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
Punchline_Lib
https://www.tradingview.com/script/IkK1CCT3-Punchline-Lib/
corny2000
https://www.tradingview.com/u/corny2000/
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/ // © corny2000 //@version=5 // @description: A collection of custom tools & utility functions commonly used with my scripts. This Library is work in progress. library("Punchline_Lib") // --- BEGIN MATH FUNCTIONS { // ----------------------------------------------------------- // ----------------------- ROUND SMART ----------------------- // ----------------------------------------------------------- // @function Truncates decimal points of a float value based on the amount of digits before the decimal point // @param float _value any number // @returns float export roundSmart(float _value) => precision = (_value < 1 ? 10000 : (_value < 10 ? 1000 : (_value < 100 ? 100 : (_value < 1000 ? 10 : 1)))) if _value < 0 _value else math.round(_value * precision) / precision // @function Returns a factor for rounding based on a sample input and a desired precision // @param float _sample sample input to give an idea for the number setup // @param string _precision desired precision (zero, max, low, high) // @returns float export fRound(float _sample, string _precision) => _precision == "zero" ? 1 : _precision == "max" ? 100000000 : _sample / close < 0.00001 ? 100000000 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1): _sample / close < 0.0001 ? 10000000 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1) : _sample / close < 0.001 ? 1000000 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1) : _sample / close < 0.01 ? 100000 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1) : _sample / close < 0.1 ? 10000 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1) : _sample / close < 1 ? 1000 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1) : _sample / close < 10 ? 100 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1) : 1 / (_precision == "low" ? 10 : 1) * (_precision == "high" ? 10 : 1) // @function Returns a suggestion for an excgabge rate based on the base currency provided as an input to the function // @param string _base symbol of the base currency to produce a quote currency against // @param float _exchangeRate alternative exchange Rate if no better can be determined // @returns float export get_exchangeRate(string _base, float _exchangeRate) => if (syminfo.currency == _base or ((_base == 'USD' or _base == 'USDT' or _base == 'USDC' or _base == 'BUSD' or _base == 'USDP' or _base == 'DAI') and (syminfo.currency == 'USDT' or syminfo.currency == 'USDC' or syminfo.currency == 'BUSD' or syminfo.currency == 'USDP' or syminfo.currency == 'DAI')) ) 1 else nz(_exchangeRate, 1.0) // @function Calculates up to 10 retracements in one go // @param float _high high value // @param float _low low value // @param float _pct_01 retracement % // @param float _pct_02 retracement % // @param float _pct_03 retracement % // @param float _pct_04 retracement % // @param float _pct_05 retracement % // @param float _pct_06 retracement % // @param float _pct_07 retracement % // @param float _pct_08 retracement % // @param float _pct_09 retracement % // @param float _pct_10 retracement % // @returns array of retracement values export get_retracement(float _high, float _low, float _pct_01, float _pct_02, float _pct_03, float _pct_04, float _pct_05, float _pct_06, float _pct_07, float _pct_08, float _pct_09, float _pct_10) => distance_ = math.max(_high, _low) - math.min(_high, _low) ret_01_L = _high - distance_ * _pct_01 ret_01_S = _high - distance_ * (1 - _pct_01) ret_02_L = _high - distance_ * _pct_02 ret_02_S = _high - distance_ * (1 - _pct_02) ret_03_L = _high - distance_ * _pct_03 ret_03_S = _high - distance_ * (1 - _pct_03) ret_04_L = _high - distance_ * _pct_04 ret_04_S = _high - distance_ * (1 - _pct_04) ret_05_L = _high - distance_ * _pct_05 ret_05_S = _high - distance_ * (1 - _pct_05) ret_06_L = _high - distance_ * _pct_06 ret_06_S = _high - distance_ * (1 - _pct_06) ret_07_L = _high - distance_ * _pct_07 ret_07_S = _high - distance_ * (1 - _pct_07) ret_08_L = _high - distance_ * _pct_08 ret_08_S = _high - distance_ * (1 - _pct_08) ret_09_L = _high - distance_ * _pct_09 ret_09_S = _high - distance_ * (1 - _pct_09) ret_10_L = _high - distance_ * _pct_10 ret_10_S = _high - distance_ * (1 - _pct_10) [ ret_01_L, ret_01_S, ret_02_L, ret_02_S, ret_03_L, ret_03_S, ret_04_L, ret_04_S, ret_05_L, ret_05_S, ret_06_L, ret_06_S, ret_07_L, ret_07_S, ret_08_L, ret_08_S, ret_09_L, ret_09_S, ret_10_L, ret_10_S ] // } END MATH FUNCTIONS // --- BEGIN STRING FUNCTIONS { // ----------------------------------------------------------- // --------------------- TO STRING SMART --------------------- // ----------------------------------------------------------- // @function converts a float to a string, intelligently cutting off decimal points // @param float _value any number // @returns string export tostring_smart(float _value) => format = (_value < 1 ? "#.####" : (_value < 10 ? "#.###" : (_value < 100 ? "#.##" : (_value < 1000 ? "#.#" : "#")))) if _value < 0 str.tostring(_value) else str.tostring(_value, format) // @function converts a string into an array of floats // @param string _string input string to be converted // @param string _separator separator to separate string by // @param float _defVal default value in case no content is found // @returns array of floats export string_to_array_float(string _string, string _separator, float _defVal) => a_str = str.split(_string, _separator) if array.size(a_str) == 0 array.push(a_str, str.tostring(_defVal)) a_float = array.new_float(0) for i = 0 to array.size(a_str)-1 array.push(a_float, str.tonumber(str.replace_all(array.get(a_str, i), " ", ""))) a_float // @function pushes 20 floats into an array and returns the array // @param float f01 float to push into the array // @param float f02 float to push into the array // @param float f03 float to push into the array // @param float f04 float to push into the array // @param float f05 float to push into the array // @param float f06 float to push into the array // @param float f07 float to push into the array // @param float f08 float to push into the array // @param float f09 float to push into the array // @param float f10 float to push into the array // @param float f11 float to push into the array // @param float f12 float to push into the array // @param float f13 float to push into the array // @param float f14 float to push into the array // @param float f15 float to push into the array // @param float f16 float to push into the array // @param float f17 float to push into the array // @param float f18 float to push into the array // @param float f19 float to push into the array // @param float f20 float to push into the array // @returns array of floats export floats_to_array_of_20( float f01, float f02, float f03, float f04, float f05, float f06, float f07, float f08, float f09, float f10, float f11, float f12, float f13, float f14, float f15, float f16, float f17, float f18, float f19, float f20 ) => lFloats = array.new_float(0) array.push(lFloats, f01) array.push(lFloats, f02) array.push(lFloats, f03) array.push(lFloats, f04) array.push(lFloats, f05) array.push(lFloats, f06) array.push(lFloats, f07) array.push(lFloats, f08) array.push(lFloats, f09) array.push(lFloats, f10) array.push(lFloats, f11) array.push(lFloats, f12) array.push(lFloats, f13) array.push(lFloats, f14) array.push(lFloats, f15) array.push(lFloats, f16) array.push(lFloats, f17) array.push(lFloats, f18) array.push(lFloats, f19) array.push(lFloats, f20) lFloats // @function pushes 20 ints into an array and returns the array // @param int i01 int to push into the array // @param int i02 int to push into the array // @param int i03 int to push into the array // @param int i04 int to push into the array // @param int i05 int to push into the array // @param int i06 int to push into the array // @param int i07 int to push into the array // @param int i08 int to push into the array // @param int i09 int to push into the array // @param int i10 int to push into the array // @param int i11 int to push into the array // @param int i12 int to push into the array // @param int i13 int to push into the array // @param int i14 int to push into the array // @param int i15 int to push into the array // @param int i16 int to push into the array // @param int i17 int to push into the array // @param int i18 int to push into the array // @param int i19 int to push into the array // @param int i20 int to push into the array // @returns array of ints export ints_to_array_of_20( int i01, int i02, int i03, int i04, int i05, int i06, int i07, int i08, int i09, int i10, int i11, int i12, int i13, int i14, int i15, int i16, int i17, int i18, int i19, int i20 ) => lInts = array.new_int(0) array.push(lInts, i01) array.push(lInts, i02) array.push(lInts, i03) array.push(lInts, i04) array.push(lInts, i05) array.push(lInts, i06) array.push(lInts, i07) array.push(lInts, i08) array.push(lInts, i09) array.push(lInts, i10) array.push(lInts, i11) array.push(lInts, i12) array.push(lInts, i13) array.push(lInts, i14) array.push(lInts, i15) array.push(lInts, i16) array.push(lInts, i17) array.push(lInts, i18) array.push(lInts, i19) array.push(lInts, i20) lInts // } END STRING FUNCTIONS // --- BEGIN FORMAT FUNCTIONS { // ----------------------------------------------------------- // ------------------------ FILL CELL ------------------------ // ----------------------------------------------------------- // @function Create a table cell based on params handed over // @param table _table Table to be edited // @param int _column column of cell to be edited // @param int _row row of cell to be edited // @param float _value value to be added into cell // @param string _text text to be added into cell // @returns table.cell export fillCell(table _table, int _column, int _row, float _value, string _text) => c_color_ = color.green transp_ = 80 cellText_ = str.tostring(_value, "#.#####") + "\n" + _text table.cell(_table, _column, _row, cellText_, bgcolor = color.new(c_color_, transp_), text_color = c_color_, width = 6) // @function Converts a string into a label size // @param string _size the desired size as string // @returns size export size(string _size) => (_size == "Huge") ? size.huge : (_size == "Large") ? size.large : (_size == "Small") ? size.small : (_size == "Tiny") ? size.tiny : (_size == "Auto") ? size.auto : size.normal // @function Converts a string into a position // @param string _position the desired position as string // @returns position export position(string _position) => (_position == "top right") ? position.top_right : (_position == "right") ? position.middle_right : (_position == "bottom right") ? position.bottom_right : (_position == "bottom") ? position.bottom_center : (_position == "bottom left") ? position.bottom_left : (_position == "left") ? position.middle_left : (_position == "top left") ? position.top_left : (_position == "top") ? position.top_center : position.bottom_right // } END FORMAT FUNCTIONS // --- BEGIN TA FUNCTIONS { // ----------------------------------------------------------------------------- // ---------------------------------- PIVOTS ----------------------------------- // ----------------------------------------------------------------------------- // { // @function detects pivots in a series of values // @param series _src source of data points // @param int _length depth for scanning // @param bool _isHigh look for high (true) or low (false) // @returns [int, float] bar index, pivot point pivots(_src, _length, _isHigh) => p_ = nz(_src[_length]) if _length == 0 [bar_index, p_] else isFound_ = true for i = 0 to _length - 1 by 1 if _isHigh and _src[i] > p_ isFound_ := false isFound_ if not _isHigh and _src[i] < p_ isFound_ := false isFound_ for i = _length + 1 to 2 * _length by 1 if _isHigh and _src[i] >= p_ isFound_ := false isFound_ if not _isHigh and _src[i] <= p_ isFound_ := false isFound_ if isFound_ and _length * 2 <= bar_index [bar_index[_length], p_] else [int(na), float(na)] // @function draws a line from previous pivot to next pivot // @param float _dev deviation // @param bool _isHigh true if to be processed coordinate is a high, false otherwise // @param int _index index of next price to process // @param float _price new price to be evaluated // @param color _color color for drawing line from one pivot to another pivot (#00000000 to draw no line) // @param int _width width of line for lines // @param bool _prev_pivot_is_a_high true if to previous pivot is a high, false otherwise // @param line _lineLast id of previous line // @param int _linesCount counter of how many lines have been drawn so far // @param float _devThreshold allowed deviation // @param int _iLast index of previous pivot point // @param float _pLast price of previous pivot point // @returns [line, bool, bool] new line (if any), high (or no high), true if new pivot is significant according to allowed deviation threshold export pivotFound(float _dev, bool _isHigh, int _index, float _price, color _color, int _width, bool _prev_pivot_is_a_high, line _lineLast, int _linesCount, float _devThreshold, int _iLast, float _pLast) => if _prev_pivot_is_a_high == _isHigh and not na(_lineLast) // same direction if _prev_pivot_is_a_high ? _price > _pLast : _price < _pLast if _linesCount <= 1 line.set_xy1(_lineLast, _index, _price) line.set_xy2(_lineLast, _index, _price) [_lineLast, _prev_pivot_is_a_high, false] else [line(na), bool(na), false] else // reverse the direction (or create the very first line) if na(_lineLast) id_ = line.new(_index, _price, _index, _price, color=_color, width=_width) [id_, _isHigh, true] else // price move is significant if math.abs(_dev) >= _devThreshold id_ = line.new(_iLast, _pLast, _index, _price, color=_color, width=_width) [id_, _isHigh, true] else [line(na), bool(na), false] // @function detects high and low pivots in a series of values // @param int _depth depth for scanning // @returns [int, float, int, float] bar index of high pivot, high pivot, bar index of low pivot, low pivot export get_pivots(int _depth) => [iH, pivot_high] = pivots(high, math.floor(_depth / 2), true) [iL, pivot_low] = pivots(low, math.floor(_depth / 2), false) [iH, pivot_high, iL, pivot_low] // } // ----------------------------------------------------------------------------- // ------------------------------ MOVING AVERAGES (MA) ------------------------- // ----------------------------------------------------------------------------- // { get_ama(src, length, fastLength, slowLength, prev_ama) => fastAlpha = 2 / (fastLength + 1) slowAlpha = 2 / (slowLength + 1) hh = ta.highest(length + 1) ll = ta.lowest(length + 1) mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0 ssc = mltp * (fastAlpha - slowAlpha) + slowAlpha ama = 0.0 ama := nz(prev_ama) + math.pow(ssc, 2) * (src - nz(prev_ama)) ama // Arnaud Legoux Moving Average manual calculation get_alma(src, windowsize, offset, sigma) => m = offset * (windowsize - 1) //m = math.floor(offset * (windowsize - 1)) // Used as m when math.floor=true s = windowsize / sigma norm = 0.0 sum = 0.0 for i = 0 to windowsize - 1 weight = math.exp(-1 * math.pow(i - m, 2) / (2 * math.pow(s, 2))) norm := norm + weight sum := sum + src[windowsize - i - 1] * weight sum / norm // @function Gets a Moving Average based on type and source // @param string _type The type of MA // @param series float _src The source for the MA // @param simple int _len The MA period // @param int _fastLength Fast EMA Length (AMA only) // @param int _slowLength Slow EMA Length (AMA only) // @param float _prev_maVal Previous MA value (AMA only) // @param simple float _offset Offset for ALMA/LSMA calculation (ALMA and LSMA only) // @param int _sigma Sigma for ALMA calculation (ALMA only) // @returns A moving average with the given parameters export get_ma(string _type, series float _src, simple int _len, int _fastLength, int _slowLength, float _prev_maVal, simple float _offset, simple int _sigma) => e = ta.ema(_src, int(_len)) switch _type // single moving average 'SMA' => ta.sma(_src, int(_len)) // exponential moving average 'EMA' => e // double exponential moving average 'DEMA' => 2 * e - ta.ema(e, int(_len)) // triple exponential moving average 'TEMA' => 3 * (e - ta.ema(e, _len)) + ta.ema(ta.ema(e, _len), _len) // adaptive moving average 'AMA' => get_ama(_src, _len, _fastLength, _slowLength, _prev_maVal) // Arnaud Legoux Moving Average 'ALMA'=> ta.alma(_src, _len, _offset, _sigma) // hull moving average 'HMA' => ta.hma(_src, _len) // 'RMA' => ta.rma(_src, _len) // weighted moving average 'WMA' => ta.wma(_src, _len) // volume-weighted moving average 'VWMA' => ta.vwma(_src, _len) // Least Squares Moving Average 'LSMA' => ta.linreg(_src, _len, int(_offset)) // Volume-weighted average price "VWAP" => ta.vwap => na // } // ----------------------------------------------------------------------------- // -------------------- EXPONENTIAL MOVING AVERAGE (OHLC) ---------------------- // ----------------------------------------------------------------------------- // { // @function calculates EMA for 4 values based on _length. Ideal in with security call // @param float _o open // @param float _h high // @param float _l low // @param float _c close // @param float _length length // @returns [float, float, float, float] export get_ema_ohlc(float _o, float _h, float _l, float _c, float _length) => [ta.ema(_o, int(_length)), ta.ema(_h, int(_length)), ta.ema(_l, int(_length)), ta.ema(_c, int(_length))] // } // ----------------------------------------------------------------------------- // ------------------------ JURIK MOVING AVERAGES (JMA) ------------------------ // ----------------------------------------------------------------------------- // { // @function calculates Jurik Moving Average // @param int _length Length // @param int _phase Phase // @param int _power Power // @returns float export jma(int _length, int _phase, int _power) => phaseRatio = _phase < -100 ? 0.5 : _phase > 100 ? 2.5 : _phase / 100 + 1.5 beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2) alpha = math.pow(beta, _power) jma = 0.0 e0 = 0.0 //e0 := (1 - alpha) * param_jma_src + alpha * nz(e0[1]) e0 := (1 - alpha) * close + alpha * nz(e0[1]) e1 = 0.0 //e1 := (param_jma_src - e0) * (1 - beta) + beta * nz(e1[1]) e1 := (close - 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]) jma // } // ----------------------------------------------------------------------------- // ------------------------------ CANDLE RATIO --------------------------------- // ----------------------------------------------------------------------------- // { // @function get ratio between current candle and candle[index] // @param int _index index of the candle you want to compare the current candle to // @returns float difference in size between current and selected candle export getRatio_singleCandle(int _index) => size_currentCandle = high - low size_prevCandle = high[_index] - low[_index] size_currentCandle / size_prevCandle // } // ----------------------------------------------------------------------------- // ----------------------------------- ADX ------------------------------------ // ----------------------------------------------------------------------------- // { dirmov(len) => up = ta.change(high) down = -ta.change(low) plusDM = na(up) ? na : up > down and up > 0 ? up : 0 minusDM = na(down) ? na : down > up and down > 0 ? down : 0 truerange = ta.rma(ta.tr, len) plus = fixnan(100 * ta.rma(plusDM, len) / truerange) minus = fixnan(100 * ta.rma(minusDM, len) / truerange) [plus, minus] // @function calculates ADX for specified Legnth and Smoothing // @param int _dilen ADX DI Length // @param int _adxlen ADX Smoothing // @returns float export adx(simple int _dilen, simple int _adxlen) => [plus, minus] = dirmov(_dilen) sum = plus + minus 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), _adxlen) //} // ----------------------------------------------------------------------------- // --------------------- HIGHEST HIGH and LOWEST LOW --------------------------- // ----------------------------------------------------------------------------- // { // @function calculates Highest High and lowest low within a specified length // @param series float h high // @param series float l low // @param series float c close // @param int _length Length to scan for values // @returns [float, float, float, float] export highestHigh_lowestLow(series float _h, series float _l, series float _c, int _length) => hh = ta.highest(_h, _length)[1] ll = ta.lowest(_l, _length)[1] hc = ta.highest(_c, _length)[1] lc = ta.lowest(_c, _length)[1] [hh, ll, hc, lc] // } // ----------------------------------------------------------------------------- // ------------------------------ ICHIMOKU CLOUD ------------------------------- // ----------------------------------------------------------------------------- // { donchian(len) => math.avg(ta.lowest(len), ta.highest(len)) // @function creates values for the Ichimoku Cloud // @param int _conversionPeriods Conversion Periods // @param int _basePeriods Base Periods // @param int _laggingSpan2Periods Lagging Span Periods // @returns [float, float, float, float] export imc(int _conversionPeriods, int _basePeriods, int _laggingSpan2Periods) => conversionLine_ = donchian(_conversionPeriods) baseLine_ = donchian(_basePeriods) leadLine1_ = math.avg(conversionLine_, baseLine_) leadLine2_ = donchian(_laggingSpan2Periods) [conversionLine_, baseLine_, leadLine1_, leadLine2_] // } // ----------------------------------------------------------------------------- // ------------------------------ WILLIAM FRACTAL ------------------------------ // ----------------------------------------------------------------------------- // { // @function Calculates William Fractals. // @param int _periods Number of periods and keep a minimum value of 2 for error handling. // @returns [bool, bool] export williamFractal(int _periods) => n = _periods // UpFractal bool upflagDownFrontier = true bool upflagUpFrontier0 = true bool upflagUpFrontier1 = true bool upflagUpFrontier2 = true bool upflagUpFrontier3 = true bool upflagUpFrontier4 = true for i = 1 to n upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n]) upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n]) upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n]) upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n]) upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n]) upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n]) flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4 upFractal = (upflagDownFrontier and flagUpFrontier) // downFractal bool downflagDownFrontier = true bool downflagUpFrontier0 = true bool downflagUpFrontier1 = true bool downflagUpFrontier2 = true bool downflagUpFrontier3 = true bool downflagUpFrontier4 = true for i = 1 to n downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n]) downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n]) downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n]) downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n]) downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n]) downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n]) flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4 downFractal = (downflagDownFrontier and flagDownFrontier) [upFractal, downFractal] // } // } END TA FUNCTIONS
ArrayOperations
https://www.tradingview.com/script/xgPQCKEG-ArrayOperations/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
42
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 Array Basic Operations. library(title='ArrayOperations') import RicardoSantos/MathExtension/1 as me import RicardoSantos/ArrayExtension/3 as ae import RicardoSantos/DebugConsole/6 as console [__T, __C] = console.init(25) // Helper method for add() process. add_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> add(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> add(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> add(): "_size_b" must be smaller or equal to _size_a') // _output = array.copy(sample_a)// defines output type for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai + _bi) _output // // @function Adds sample_b to sample_a and returns a new array. // @param sample_a values to be added to. // @param sample_b values to add. // @returns array with added results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export add(float[] sample_a, float[] sample_b) => add_method(sample_a, sample_b) export add(float[] sample_a, int[] sample_b) => add_method(sample_a, ae.to_float(sample_b)) export add(int[] sample_a, int[] sample_b) => add_method(sample_a, sample_b) export add(string[] sample_a, string[] sample_b) => add_method(sample_a, sample_b) //{ usage: console.queue_one(__C, str.format('add(): {0}', add(array.from(0, 1, 2), array.from(3, 4, 5)))) // console.queue_one(__C, str.format('add(): {0}', add(array.from(0.1, 1.1, 2.1), array.from(3, 4, 5)))) // console.queue_one(__C, str.format('add(): {0}', add(array.from('a', 'b', 'c'), array.from('3', '4')))) //}} // Helper method for subtract() process. subtract_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> subtract(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> subtract(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> subtract(): "_size_b" must be smaller or equal to _size_a') // _output = array.copy(sample_a)// defines output type for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai - _bi) _output // // @function Subtracts sample_b from sample_a and returns a new array. // @param sample_a values to be subtracted from. // @param sample_b values to subtract. // @returns array with subtracted results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export subtract(float[] sample_a, float[] sample_b) => subtract_method(sample_a, sample_b) export subtract(float[] sample_a, int[] sample_b) => subtract_method(sample_a, ae.to_float(sample_b)) export subtract(int[] sample_a, int[] sample_b) => subtract_method(sample_a, sample_b) //{ usage: console.queue_one(__C, str.format('subtract(): {0}', subtract(array.from(0, 1, 2), array.from(3, 4, 5)))) // console.queue_one(__C, str.format('subtract(): {0}', subtract(array.from(1.1, 2.2, 3.3), array.from(4, 5)))) //}} // Helper method for multiply() process. multiply_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> multiply(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> multiply(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> multiply(): "_size_b" must be smaller or equal to _size_a') // _output = array.copy(sample_a)// defines output type for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai * _bi) _output // // @function multiply sample_a by sample_b and returns a new array. // @param sample_a values to multiply. // @param sample_b values to multiply with. // @returns array with multiplied results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export multiply(float[] sample_a, float[] sample_b) => multiply_method(sample_a, sample_b) export multiply(float[] sample_a, int[] sample_b) => multiply_method(sample_a, ae.to_float(sample_b)) export multiply(int[] sample_a, int[] sample_b) => multiply_method(sample_a, sample_b) //{ usage: console.queue_one(__C, str.format('multiply(): {0}', multiply(array.from(0, 1, 2), array.from(3, 4, 5)))) // console.queue_one(__C, str.format('multiply(): {0}', multiply(array.from(1.1, 2.2, 3.3), array.from(4, 5)))) //}} // Helper method for divide() process. divide_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> divide(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> divide(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> divide(): "_size_b" must be smaller or equal to _size_a') // _output = array.copy(sample_a)// defines output type for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai / _bi) _output // // @function Divide sample_a by sample_b and returns a new array. // @param sample_a values to divide. // @param sample_b values to divide with. // @returns array with divided results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export divide(float[] sample_a, float[] sample_b) => divide_method(sample_a, sample_b) export divide(float[] sample_a, int[] sample_b) => divide_method(sample_a, ae.to_float(sample_b)) export divide(int[] sample_a, int[] sample_b) => divide_method(sample_a, sample_b) //{ usage: console.queue_one(__C, str.format('divide(): {0}', divide(array.from(0, 8, 15), array.from(3, 4, 5)))) // console.queue_one(__C, str.format('divide(): {0}', divide(array.from(1.1, 2.2, 3.3), array.from(4, 5)))) //}} // Helper method for power() process. power_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> power(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> power(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> power(): "_size_b" must be smaller or equal to _size_a') // float[] _output = array.new_float(_size_a) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=math.pow(_ai, _bi)) _output // // @function power sample_a by sample_b and returns a new array. // @param sample_a values to power. // @param sample_b values to power with. // @returns float array with power results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export power(float[] sample_a, float[] sample_b) => power_method(sample_a, sample_b) export power(float[] sample_a, int[] sample_b) => power_method(sample_a, sample_b) export power(int[] sample_a, int[] sample_b) => power_method(sample_a, sample_b) export power(int[] sample_a, float[] sample_b) => power_method(sample_a, sample_b) //{ usage: console.queue_one(__C, str.format('power(): {0}', power(array.from(0, 8, 15), array.from(3, 4, 5)))) // console.queue_one(__C, str.format('power(): {0}', power(array.from(1.1, 2.2, 3.3), array.from(4, 5)))) //}} // Helper method for log() process. log_method (sample_a) => //{ int _size_a = array.size(id=sample_a) // switch (_size_a < 1) => runtime.error('ArrayOperations -> power(): "_size_a" is invalid') // float[] _output = array.new_float(_size_a) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) array.set(id=_output, index=_i, value=math.log(_ai)) _output // // @function power sample_a by sample_b and returns a new array. // @param sample_a values to power. // @returns float array with log results. export log(float[] sample_a) => log_method(sample_a) export log(int[] sample_a) => log_method(sample_a) //{ usage: console.queue_one(__C, str.format('log(): {0}', log(array.from(0, 8, 15)))) //}} // Helper method for remainder() process. remainder_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> remainder(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> remainder(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> remainder(): "_size_b" must be smaller or equal to _size_a') // _output = array.copy(sample_a) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=me.fmod(_ai, _bi)) _output // // @function Remainder sample_a by sample_b and returns a new array. // @param sample_a values to remainder. // @param sample_b values to remainder with. // @returns array with remainder results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export remainder(float[] sample_a, float[] sample_b) => remainder_method(sample_a, sample_b) export remainder(float[] sample_a, int[] sample_b) => remainder_method(sample_a, ae.to_float(sample_b)) export remainder(int[] sample_a, int[] sample_b) => remainder_method(ae.to_float(sample_a), ae.to_float(sample_b)) export remainder(int[] sample_a, float[] sample_b) => remainder_method(ae.to_float(sample_a), sample_b) //{ usage: console.queue_one(__C, str.format('remainder(): {0}', remainder(array.from(0, 5, 22), array.from(3.0, 4.5, 5)))) // console.queue_one(__C, str.format('remainder(): {0}', remainder(array.from(1.1, 2.2, 3.3), array.from(4, 5)))) //}} // Helper method for equal() process. equal_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> equal(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> equal(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> equal(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai == _bi ? 1 : 0) _output // // @function Check element wise sample_a equals sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export equal(float[] sample_a, float[] sample_b) => equal_method(sample_a, sample_b) export equal(float[] sample_a, int[] sample_b) => equal_method(sample_a, ae.to_float(sample_b)) export equal(int[] sample_a, int[] sample_b) => equal_method(sample_a, sample_b) export equal(int[] sample_a, float[] sample_b) => equal_method(ae.to_float(sample_a), sample_b) export equal(string[] sample_a, string[] sample_b) => equal_method(sample_a, sample_b) export equal(color[] sample_a, color[] sample_b) => equal_method(sample_a, sample_b) //{ usage: console.queue_one(__C, str.format('equal(): {0}', equal(array.from(0, 5), array.from(0.0, 4)))) // console.queue_one(__C, str.format('equal(): {0}', equal(array.from('1.1', 'a', 'b'), array.from('2.2', 'a')))) // console.queue_one(__C, str.format('equal(): {0}', equal(array.from(color.red, color.blue), array.from(color.red)))) //}} // Helper method for not_equal() process. not_equal_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> not_equal(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> not_equal(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> not_equal(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai != _bi ? 1 : 0) _output // // @function Check element wise sample_a not equals sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export not_equal(float[] sample_a, float[] sample_b) => not_equal_method(sample_a, sample_b) export not_equal(float[] sample_a, int[] sample_b) => not_equal_method(sample_a, ae.to_float(sample_b)) export not_equal(int[] sample_a, int[] sample_b) => not_equal_method(sample_a, sample_b) export not_equal(int[] sample_a, float[] sample_b) => not_equal_method(ae.to_float(sample_a), sample_b) export not_equal(string[] sample_a, string[] sample_b) => not_equal_method(sample_a, sample_b) export not_equal(color[] sample_a, color[] sample_b) => not_equal_method(sample_a, sample_b) //{ usage: // console.queue_one(__C, str.format('not_equal(): {0}', not_equal(array.from(0, 5), array.from(0.0, 4)))) // console.queue_one(__C, str.format('not_equal(): {0}', not_equal(array.from('1.1', 'a', 'b'), array.from('2.2', 'a')))) console.queue_one(__C, str.format('not_equal(): {0}', not_equal(array.from(color.red, color.blue), array.from(color.red)))) //}} // Helper method for over_or_equal() process. over_or_equal_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> over_or_equal(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> over_or_equal(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> over_or_equal(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai >= _bi ? 1 : 0) _output // // @function Check element wise sample_a over or equals sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export over_or_equal(float[] sample_a, float[] sample_b) => over_or_equal_method(sample_a, sample_b) export over_or_equal(float[] sample_a, int[] sample_b) => over_or_equal_method(sample_a, ae.to_float(sample_b)) export over_or_equal(int[] sample_a, int[] sample_b) => over_or_equal_method(sample_a, sample_b) export over_or_equal(int[] sample_a, float[] sample_b) => over_or_equal_method(ae.to_float(sample_a), sample_b) //{ usage: console.queue_one(__C, str.format('over_or_equal(): {0}', over_or_equal(array.from(0, 5, 3), array.from(0.0, 4, 6)))) //}} // Helper method for under_or_equal() process. under_or_equal_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> under_or_equal(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> under_or_equal(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> under_or_equal(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai <= _bi ? 1 : 0) _output // // @function Check element wise sample_a under or equals sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export under_or_equal(float[] sample_a, float[] sample_b) => under_or_equal_method(sample_a, sample_b) export under_or_equal(float[] sample_a, int[] sample_b) => under_or_equal_method(sample_a, ae.to_float(sample_b)) export under_or_equal(int[] sample_a, int[] sample_b) => under_or_equal_method(sample_a, sample_b) export under_or_equal(int[] sample_a, float[] sample_b) => under_or_equal_method(ae.to_float(sample_a), sample_b) //{ usage: console.queue_one(__C, str.format('under_or_equal(): {0}', under_or_equal(array.from(0, 5, 3), array.from(0.0, 4, 6)))) //}} // Helper method for over() process. over_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> over(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> over(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> over(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai > _bi ? 1 : 0) _output // // @function Check element wise sample_a over sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export over(float[] sample_a, float[] sample_b) => over_method(sample_a, sample_b) export over(float[] sample_a, int[] sample_b) => over_method(sample_a, ae.to_float(sample_b)) export over(int[] sample_a, int[] sample_b) => over_method(sample_a, sample_b) export over(int[] sample_a, float[] sample_b) => over_method(ae.to_float(sample_a), sample_b) //{ usage: console.queue_one(__C, str.format('over(): {0}', over(array.from(0, 5, 3), array.from(0.0, 4, 6)))) //}} // Helper method for under() process. under_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> under(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> under(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> under(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai < _bi ? 1 : 0) _output // // @function Check element wise sample_a under sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export under(float[] sample_a, float[] sample_b) => under_method(sample_a, sample_b) export under(float[] sample_a, int[] sample_b) => under_method(sample_a, ae.to_float(sample_b)) export under(int[] sample_a, int[] sample_b) => under_method(sample_a, sample_b) export under(int[] sample_a, float[] sample_b) => under_method(ae.to_float(sample_a), sample_b) //{ usage: console.queue_one(__C, str.format('under(): {0}', under(array.from(0, 5, 3), array.from(0.0, 4, 6)))) //}} // Helper method for and_() process. and_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> and_(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> and_(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> and_(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=(_ai > 0) and (_bi > 0) ? 1 : 0) _output // // @function Check element wise sample_a and sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export and_(float[] sample_a, float[] sample_b) => and_method(sample_a, sample_b) export and_(float[] sample_a, int[] sample_b) => and_method(sample_a, ae.to_float(sample_b)) export and_(float[] sample_a, bool[] sample_b) => and_method(sample_a, ae.to_float(sample_b)) export and_(int[] sample_a, int[] sample_b) => and_method(sample_a, sample_b) export and_(int[] sample_a, float[] sample_b) => and_method(ae.to_float(sample_a), sample_b) export and_(int[] sample_a, bool[] sample_b) => and_method(sample_a, ae.to_float(sample_b)) export and_(bool[] sample_a, bool[] sample_b) => and_method(ae.to_float(sample_a), ae.to_float(sample_b)) export and_(bool[] sample_a, int[] sample_b) => and_method(ae.to_float(sample_a), ae.to_float(sample_b)) export and_(bool[] sample_a, float[] sample_b) => and_method(ae.to_float(sample_a), sample_b) //{ usage: console.queue_one(__C, str.format('and_(): {0}', and_(array.from(0, 5, 3), array.from(0.0, 4, 0)))) //}} // Helper method for or_() process. or_method (sample_a, sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) // switch (_size_a < 1) => runtime.error('ArrayOperations -> or_(): "_size_a" is invalid') (_size_b < 1) => runtime.error('ArrayOperations -> or_(): "_size_b" is invalid') (_size_a < _size_b) => runtime.error('ArrayOperations -> or_(): "_size_b" must be smaller or equal to _size_a') // int[] _output = array.new_int(_size_a, 0) for _i = 0 to _size_a - 1 _ai = array.get(id=sample_a, index=_i) _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=(_ai > 0) or (_bi > 0) ? 1 : 0) _output // // @function Check element wise sample_a or sample_b and returns a new array. // @param sample_a values to check. // @param sample_b values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export or_(float[] sample_a, float[] sample_b) => or_method(sample_a, sample_b) export or_(float[] sample_a, int[] sample_b) => or_method(sample_a, ae.to_float(sample_b)) export or_(float[] sample_a, bool[] sample_b) => or_method(sample_a, ae.to_float(sample_b)) export or_(int[] sample_a, int[] sample_b) => or_method(sample_a, sample_b) export or_(int[] sample_a, float[] sample_b) => or_method(ae.to_float(sample_a), sample_b) export or_(int[] sample_a, bool[] sample_b) => or_method(sample_a, ae.to_float(sample_b)) export or_(bool[] sample_a, bool[] sample_b) => or_method(ae.to_float(sample_a), ae.to_float(sample_b)) export or_(bool[] sample_a, int[] sample_b) => or_method(ae.to_float(sample_a), ae.to_float(sample_b)) export or_(bool[] sample_a, float[] sample_b) => or_method(ae.to_float(sample_a), sample_b) //{ usage: console.queue_one(__C, str.format('or_(): {0}', or_(array.from(0, 5, 3), array.from(0.0, 4, 0)))) //}} // Helper method for all() process. all_method (sample) => //{ int _size = array.size(id=sample) // switch (_size < 1) => runtime.error('ArrayOperations -> all(): "_size_a" is invalid') // int _output = 1 for _i = 0 to _size - 1 _ai = array.get(id=sample, index=_i) if (_ai > 0) continue else _output := 0 break _output // // @function Check element wise if all numeric samples are true (!= 0). // @param sample_a values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export all(float[] sample) => all_method(sample) export all(int[] sample) => all_method(sample) export all(bool[] sample) => all_method(ae.to_int(sample)) //{ usage: console.queue_one(__C, str.format('all(): {0}', all(array.from(0, 5, 3)))) console.queue_one(__C, str.format('all(): {0}', all(array.from(0.2, 1)))) //}} // Helper method for any() process. any_method (sample) => //{ int _size = array.size(id=sample) // switch (_size < 1) => runtime.error('ArrayOperations -> any(): "_size_a" is invalid') // int _output = 0 for _i = 0 to _size - 1 _ai = array.get(id=sample, index=_i) if (_ai > 0) _output := 1 break else continue _output // // @function Check element wise if any numeric samples are true (!= 0). // @param sample_a values to check. // @returns int array with results. // -sample_a provides type format for output. // -arrays do not need to be symmetric. // -sample_a must have same or more elements than sample_b export any(float[] sample) => any_method(sample) export any(int[] sample) => any_method(sample) export any(bool[] sample) => any_method(ae.to_int(sample)) //{ usage: console.queue_one(__C, str.format('any(): {0}', any(array.from(0, 5, 3)))) console.queue_one(__C, str.format('any(): {0}', any(array.from(0., -1)))) //}} console.update(__T, __C)
FunctionNNLayer
https://www.tradingview.com/script/ldz1Qm4Y-FunctionNNLayer/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
47
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 Generalized Neural Network Layer method. library(title='FunctionNNLayer') import RicardoSantos/MLActivationFunctions/1 as activation import RicardoSantos/FunctionNNPerceptron/1 as perceptron // reference: // https://blog.primen.dk/basic-neural-network-code-example-java/ // @function helper method to generate random weights of (A * B) size. // @param previous_size int, number of nodes on the left. // @param next_size int, number of nodes on the right. // @returns float array. generate_random_weights (int previous_size, int next_size) => //{ _weights = matrix.new<float>(next_size, previous_size) for _i = 0 to next_size-1 for _j = 0 to previous_size-1 matrix.set(_weights, _i, _j, math.random() * 2.0 - 1.0) _weights //} mprint (M, format='0.000') => //{ _rows = matrix.rows(M) _cols = matrix.columns(M) _s = '' for _i = 0 to _rows-1 _s += '[ ' for _j = 0 to _cols-1 _s += ((_j == _rows-1) ? '-> ': '') + str.tostring(matrix.get(M, _i, _j), format) + ' ' _s += ']\n' _s //} to_column_matrix (float[] a) => //{ _m = matrix.new<float>() matrix.add_col(_m, 0, a) _m //} // @function Generalized Layer. // @param inputs float array, input values. // @param weights float matrix, weight values. // @param n_nodes int, number of nodes in layer. // @param activation_function string, default='sigmoid', name of the activation function used. // @param bias float, default=1.0, bias to pass into activation function. // @param alpha float, default=na, if required to pass into activation function. // @param scale float, default=na, if required to pass into activation function. // @returns float export function (float[] inputs, matrix<float> weights, string activation_function='sigmoid', float bias=1.0, float alpha=na, float scale=na) => //{ int _size_i = array.size(inputs) int _Wrows = matrix.rows(weights) int _Wcols = matrix.columns(weights) // switch _Wrows < 1 => runtime.error('FunctionNNLayer -> layer(): "weights" must have atleast one row of values.') _size_i < 1 => runtime.error('FunctionNNLayer -> layer(): "inputs" array is empty.') _Wcols != _size_i => runtime.error(str.format('FunctionNNLayer -> layer(): number of elements in weights matrix do not match number of inputs/nodes, expecting {0}, found {1} .', _size_i, _Wcols)) // run the perceptron over the inputs and weights: float[] _outputs = array.new_float(_Wrows) for _node_i = 0 to _Wrows-1 float[] _weights = matrix.row(weights, _node_i) array.set(_outputs, _node_i, perceptron.function(inputs, _weights, activation_function, bias, alpha, scale)) _outputs //{ usage: i = array.from(0.0, 1, 2) var table T = table.new(position.bottom_right, 7, 3, bgcolor=#000000, frame_color=color.black, frame_width=2, border_width=2, border_color=color.gray) if barstate.islastconfirmedhistory // run a simple NN forward cycle once: _wh1 = generate_random_weights(3, 4) _wh2 = generate_random_weights(4, 5) _wo = generate_random_weights(5, 3) h1 = function(i, _wh1) // 1st hidden layer with 4 nodes, from inputs h2 = function(h1, _wh2) // 2nd level hidden layer with 5 nodes , from first hidden o = function(h2, _wo) // output layer with 3 nodes // label.new(bar_index, 0.0, str.tostring(matrix.mult(matrix.transpose(_wh1), i))) // table.cell(T, 0, 0, 'Input:', text_color=color.silver, text_halign=text.align_right) table.cell(T, 1, 0, 'Hidden 1:', text_color=color.silver, text_halign=text.align_right), table.cell(T, 3, 0, 'Hidden 2:', text_color=color.silver, text_halign=text.align_right) table.cell(T, 5, 0, 'output:', text_color=color.silver, text_halign=text.align_right) table.cell(T, 0, 1, '', text_color=color.silver, text_halign=text.align_right) table.cell(T, 1, 1, 'weights:', text_color=color.silver, text_halign=text.align_right), table.cell(T, 2, 1, 'node:', text_color=color.silver, text_halign=text.align_right), table.cell(T, 3, 1, 'weights:', text_color=color.silver, text_halign=text.align_right) table.cell(T, 4, 1, 'node:', text_color=color.silver, text_halign=text.align_right), table.cell(T, 5, 1, 'weights:', text_color=color.silver, text_halign=text.align_right) table.cell(T, 6, 1, 'node:', text_color=color.silver, text_halign=text.align_right), table.merge_cells(T, 1, 0, 2, 0) table.merge_cells(T, 3, 0, 4, 0) table.merge_cells(T, 5, 0, 6, 0) table.cell(T, 0, 2, str.tostring(to_column_matrix(i), '0.000'), text_color=color.silver, text_halign=text.align_left) table.cell(T, 1, 2, str.tostring(_wh1, '0.000'), text_color=color.silver, text_halign=text.align_left) table.cell(T, 2, 2, str.tostring(to_column_matrix(h1), '0.000'), text_color=color.silver, text_halign=text.align_left) table.cell(T, 3, 2, str.tostring(_wh2, '0.000'), text_color=color.silver, text_halign=text.align_left) table.cell(T, 4, 2, str.tostring(to_column_matrix(h2), '0.000'), text_color=color.silver, text_halign=text.align_left) table.cell(T, 5, 2, str.tostring(_wo, '0.000'), text_color=color.silver, text_halign=text.align_left) table.cell(T, 6, 2, str.tostring(to_column_matrix(o), '0.000'), text_color=color.silver, text_halign=text.align_left) //{ remarks: //}}}
Ichimoku Library
https://www.tradingview.com/script/7Hckqygn-Ichimoku-Library/
boitoki
https://www.tradingview.com/u/boitoki/
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/ // © boitoki //@version=5 // @description Ichimoku Kinko Hyo library library("Ichimoku", overlay=true) // Functions donchian (_periods, _high, _low) => math.avg(ta.lowest(_low, _periods), ta.highest(_high, _periods)) ichimoku (_coversion=9, _base=26, _leading_span2=52, _displacement1=26, _displacement2=26, _high = high, _low = low) => conversion = donchian(_coversion, _high, _low) base = donchian(_base, _high, _low) lead1 = math.avg(conversion, base) lead2 = donchian(_leading_span2 - 1, _high, _low) leading_offset = _displacement1 - 1 lagging_offset = -(_displacement2 + 1) [conversion, base, lead1, lead2, leading_offset, lagging_offset] // Inputs i_conversion = input.int(9, minval=1, title="Conversion Line") i_base = input.int(26, minval=1, title="Base Line") i_leading_span2 = input.int(52, minval=1, title="Leading Span 2") i_displacement1 = input.int(26, minval=1) i_displacement2 = input.int(26, minval=1) // @function: Calculate the Ichimoku Kinko Hyo values // @param conversion Conversion line' periods // @param base Base line's periods // @param lead 2nd Leading line's periods // @param displacement1 Leading line's offset // @param displacement2 Lagging line's offset // @returns [conversion_line, base_line, leading_span1, leading_span2, leading_offset, lagging_offset] export calc (int conversion, int base, int lead, int displacement1, int displacement2) => ichimoku(conversion, base, lead, displacement1, displacement2) export calc (int conversion, int base, int lead, int displacement1, int displacement2, float _high, float _low) => ichimoku(conversion, base, lead, displacement1, displacement2, _high, _low) // Calculating use_roc = input.bool(false) roc_len = input.int(1) smooth = input.int(1) use_heikin = input.bool(true) [hopen, hclose] = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, [open, close]) myhigh = use_heikin ? math.max(hopen, hclose, high) : high mylow = use_heikin ? math.min(hopen, hclose, low ) : low [conversion, base, lead1, lead2, leading_offset, lagging_offset] = calc(i_conversion, i_base, i_leading_span2, i_displacement1, i_displacement2, myhigh, mylow) roc = use_roc ? ta.sma(ta.roc(math.avg(hopen, hclose), roc_len), smooth) : 0 // Plotting plot(conversion - roc, color=color.orange, title="Conversion Line") plot(base - roc, color=color.blue, title="Base Line") plot(close, offset=lagging_offset, color=color.maroon, title="Lagging Span") p1 = plot(lead1, offset=leading_offset, color=color.green, title="Leading Span 1") p2 = plot(lead2, offset=leading_offset, color=color.red, title="Leading Span 2") //plot(lead1[leading_offset], color=color.green, title="Leading Span 1") //plot(lead2[leading_offset], color=color.red, title="Leading Span 2") fill(p1, p2, color=lead1 > lead2 ? color.new(color.green, 84) : color.new(color.red, 84), title="Cloud")
SetSessionTimes
https://www.tradingview.com/script/TfidhLVN-SetSessionTimes/
czoa
https://www.tradingview.com/u/czoa/
48
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/ // © czoa //@version=5 // @description FUNCTION TO AUTOMATICALLY SET SESSION TIMES FOR SYMBOLS AND EVENTUALLY TIMEZONE // USEFUL MAINLY FOR FUTURES CONTRACTS, TO DIFFERENTIATE BETWEEN PIT AND OVERNIGHT SESSIONS, AND FOR 24 HOURS SYMBOLS IF YOU WANT TO "CREATE" SESSIONS FOR THEM // THIS LIBRARY ONLY RETURNS CORRECT SESSION TIMES TO THE CALLING SCRIPT AND DOES NOTHING BY ITSELF ON THE CHART. THE CALLING SCRIPT MUST THEN USE THE RETURNED SESSION TIMES TO DO ANYTHING. // FOR EXAMPLE, IN THE ATTACHED CHART THIS LIBRARY IS USED BY MY INITIAL BALANCE INDICATOR, WHICH CALLS IT TO RETRIEVE THE CORRECT SESSION TIMES FOR THE SELECTED SYMBOL IN THE CHART, GIVEN // THAT DIFFERENT FUTURES CONTRACTS HAVE DIFFERENT PIT SESSION TIMES (RTH TIMES) AND TRADINGVIEW HASN'T IMPLEMENTED THAT YET. library("SetSessionTimes") // @param session_type_input: set an input.string paramenter in your script with any or all of the following possible values: ['Custom', 'FX-Tokyo', 'FX-London', 'FX-New York', 'Overnight Session (ON)', 'Day Session (RTH)'] and pass its input here // @param custom_session_times_input: set an input.session parameter in your script to be able to set the custom session times for the 'Custom' option in previous param // @param syminfo_XXX: simply pass the corresponding syminfo.XXX for the chart symbol // @returns [session times for chart symbol, session timezone for chart symbol (only useful for Forex sessions)] export SetSessionTimes(simple string session_type_input, simple string custom_session_times_input, simple string syminfo_type = syminfo.type, simple string syminfo_root = syminfo.root, simple string syminfo_timezone = syminfo.timezone)=> ret_times = if session_type_input == 'Custom' custom_session_times_input else if syminfo_type == 'stock' '' else if session_type_input == 'FX-Tokyo' '0900-1800' else if session_type_input == 'FX-London' '0800-1600' else if session_type_input == 'FX-New York' '0830-1600' else if syminfo_type == 'futures' if syminfo_root == 'FESX' or syminfo_root == 'FDXM' or syminfo_root == 'FDAX' or syminfo_root == 'FDXS' or syminfo_root == 'FSXE' if session_type_input == 'Overnight Session (ON)' '1730-0900' else '0900-1730' else if syminfo_root == 'FGBL' if session_type_input == 'Overnight Session (ON)' '1715-0900' else '0900-1715' else if syminfo_root == 'ES' or syminfo_root == 'NQ' or syminfo_root == 'YM' or syminfo_root == 'RTY' or syminfo_root == 'MES' or syminfo_root == 'MNQ' or syminfo_root == 'MRTY' if session_type_input == 'Overnight Session (ON)' '1500-0830' else '0830-1500' else if syminfo_root == 'CL' or syminfo_root == 'MCL' or syminfo_root == 'RB' or syminfo_root == 'NG' or syminfo_root == 'YF' if session_type_input == 'Overnight Session (ON)' '1430-0900' else '0900-1430' else if syminfo_root == 'GC' or syminfo_root == 'MGC' if session_type_input == 'Overnight Session (ON)' '1330-0820' else '0820-1330' else if syminfo_root == 'SI' if session_type_input == 'Overnight Session (ON)' '1325-0825' else '0825-1325' else if syminfo_root == 'PL' if session_type_input == 'Overnight Session (ON)' '1305-0820' else '0820-1305' else if syminfo_root == 'HG' if session_type_input == 'Overnight Session (ON)' '1300-0810' else '0810-1300' else if syminfo_root == 'ZN' or syminfo_root == 'ZB' or syminfo_root == 'TN' or syminfo_root == 'UB' if session_type_input == 'Overnight Session (ON)' '1400-0720' else '0720-1400' else if syminfo_root == '6B' or syminfo_root == '6C' or syminfo_root == '6E' or syminfo_root == '6J' if session_type_input == 'Overnight Session (ON)' '1400-0720' else '0720-1400' else if syminfo_root == '6A' if session_type_input == 'Overnight Session (ON)' '1400-0700' else '0700-1400' else if syminfo_root == 'ZC' or syminfo_root == 'ZW' or syminfo_root == 'ZS' or syminfo_root == 'ZL' or syminfo_root == 'ZM' if session_type_input == 'Overnight Session (ON)' '1320-0830' else '0830-1320' else if syminfo_root == 'LE' or syminfo_root == 'HE' if session_type_input == 'Overnight Session (ON)' '1300-0830' else '0830-1300' else custom_session_times_input else custom_session_times_input ret_tz = session_type_input == 'FX-Tokyo' ? 'Asia/Tokyo' : session_type_input == 'FX-London' ? 'Europe/London' : session_type_input == 'FX-New York' ? 'America/New_York' : syminfo_timezone [ret_times, ret_tz] ///******
VolatilityChecker
https://www.tradingview.com/script/ly5bbGYq-VolatilityChecker/
boitoki
https://www.tradingview.com/u/boitoki/
42
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 Volatility is judged to be high when the range of one period is greater than the ATR of another period. library("VolatilityChecker", overlay=false) f_volatility (int _periods, int _smooth) => v_top = close > open ? close : open v_bot = close > open ? open : close v_rng = ta.highest(math.avg(high, v_top), _periods) - ta.lowest(math.avg(low, v_bot), _periods) ta.ema(v_rng, _smooth) f_atr (int _atr_periods, float _atr_times) => ta.atr(_atr_periods) * _atr_times // @function Return true if the volatility is high. // @param _periods Range Period // @param _smooth Smoothes the range width. // @param _atr_periods ATR Period // @param _atr_times Amplify the calculated ATR. // @returns {Boolean} export is_high (simple int _periods = 7, simple int _smooth = 3, simple int _atr_periods = 20, simple float _atr_times = 2.0) => v_vola = f_volatility(_periods, _smooth) v_atr = ta.atr(_atr_periods) * _atr_times v_vola > v_atr export is_low (simple int _periods = 7, simple int _smooth = 3, simple int _atr_periods = 20, simple float _atr_times = 2.0) => not is_high(_periods, _smooth, _atr_periods, _atr_times) // @return return the range width value and atr value export value (simple int _periods = 7, simple int _smooth = 3, simple int _atr_periods = 20, simple float _atr_times = 2.0) => [f_volatility(_periods, _smooth), ta.atr(_atr_periods) * _atr_times] // Inputs i_periods = input.int(7, 'Periods') i_smooth = input.int(3, 'Smooth') i_atr_periods = input.int(20, 'ATR periods') i_atr_times = input.float(2.0, 'ATR times', step=.2) // Calculating v_main = f_volatility(i_periods, i_smooth) v_is_high_volatility = is_high(i_periods, i_smooth, i_atr_periods, i_atr_times) v_is_low_volatility = is_low(i_periods, i_smooth, i_atr_periods, i_atr_times) barcolor(v_is_high_volatility ? color.maroon : v_is_low_volatility ? color.purple : na) // Plotting plot(v_main, style=plot.style_columns, color=v_is_high_volatility ? color.purple : color.gray) plot(f_atr(i_atr_periods, i_atr_times), color=color.orange)
FunctionArrayNextPrevious
https://www.tradingview.com/script/qOh6zbLb-FunctionArrayNextPrevious/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
24
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 iterate through a array by a fixed anchor point. library(title='FunctionArrayNextPrevious') indexer (index=-1) => var int _s = index, _s += 1 array_next_method (array, int start_index=-1) => //{ array.get(array, indexer(start_index) % array.size(array)) // @function retrieves the next value of the internal pointer index. // @param array (any array type), array to iterate. // @param start_index int, anchor index to start indexing. export array_next (bool[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (box[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (color[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (float[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (int[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (label[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (line[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (linefill[] array, int start_index=-1)=> array_next_method(array, start_index) export array_next (string[] array, int start_index=-1) => array_next_method(array, start_index) export array_next (table[] array, int start_index=-1) => array_next_method(array, start_index) //{ usage: sample = array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) plot(array_next(sample)) plot(array_next(sample, dayofweek)) //}} array_previous_method (array, int start_index=-1) => //{ int _size = array.size(array) array.get(array, (_size - 1) - (indexer(start_index) % _size)) // @function retrieves the previous value of the internal pointer index. // @param array (any array type), array to iterate. // @param start_index int, anchor index to start indexing. export array_previous (bool[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (box[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (color[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (float[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (int[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (label[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (line[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (linefill[] array, int start_index=-1)=> array_previous_method(array, start_index) export array_previous (string[] array, int start_index=-1) => array_previous_method(array, start_index) export array_previous (table[] array, int start_index=-1) => array_previous_method(array, start_index) //{ usage: plot(array_previous(sample)) plot(array_previous(sample, dayofweek)) //}} str = '>: ' for _i = 1 to 5 str += str.tostring(array_next(sample)) str += '\n<: ' for _i = 1 to 5 str += str.tostring(array_previous(sample)) label.new(bar_index, 0.0, str)
FunctionGenerateRandomPointsInShape
https://www.tradingview.com/script/CCH4Mlzg-FunctionGenerateRandomPointsInShape/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Generate random vector points in geometric shape (parallelogram, triangle) library(title='FunctionGenerateRandomPointsInShape') // reference: https://blogs.sas.com/content/iml/2020/10/19/random-points-in-triangle.html import RicardoSantos/Vector2Operations/1 as vector // @function Generate random vector point in a parallelogram shape. // @param vector_a float array, vector of (x, y) shape. // @param vector_b float array, vector of (x, y) shape. // @returns float array, vector of (x, y) shape. export random_parallelogram (float[] vector_a, float[] vector_b) => //{ // u = [random(), random()] // >(0, 1)< vector.add(vector.scale(vector_a, math.random()), vector.scale(vector_b, math.random())) //{ usage: // a = vector.new(300.0, 200.0) // b = vector.new(100.0, -200.0) // for _i=0 to 40 // v = random_parallelogram(a, b) // label.new(int(bar_index + vector.get_x(v)), vector.get_y(v), ' ', style=label.style_circle) //}} // @function Generate random vector point in a triangle shape. // @param vector_a float array, vector of (x, y) shape. // @param vector_b float array, vector of (x, y) shape. // @returns float array, vector of (x, y) shape. export random_triangle (float[] vector_p1, float[] vector_p2, float[] vector_p3) => //{ float[] vector_a = vector.subtract(vector_p2, vector_p1) float[] vector_b = vector.subtract(vector_p3, vector_p1) // u = [random(), random()] // >(0, 1)< float _ux = math.random() float _uy = math.random() if (_ux + _uy) >= 1.0 _ux := 1.0 - _ux _uy := 1.0 - _uy vector.add(vector.scale(vector_a, _ux), vector.scale(vector_b, _uy)) //{ usage: a = vector.new(100.0, 200.0) b = vector.new(400.0, 400.0) c = vector.new(200.0, 000.0) for _i=0 to 40 v = random_triangle(a, b, c) label.new(int(bar_index + vector.get_x(v)), vector.get_y(v), ' ', style=label.style_circle) //}}
Ehlers_Super_Smoother
https://www.tradingview.com/script/u47JU3ZR-Ehlers-Super-Smoother/
KevanoTrades
https://www.tradingview.com/u/KevanoTrades/
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/ // © KevanoTrades //@version=5 // The 2 Pole and 3 Pole Super Smoother Filters were developed by John Ehlers and described in "Chapter 13: Super Smother" of his book "Cybernetic Analysis for Stocks and Futures". // The 2 Pole Smoother is described as being a better approximation of price, whereas the 3 Pole Smoother has superior smoothing. // Special thanks to Alex Orekhov (everget) for their excellent open source code for both two and three pole! // @description Provides the functions to calculate 2 Pole & 3 Pole Ehlers Super Smoother Filters library("Ehlers_Super_Smoother", true) // @function Calculates 2 Pole Ehlers Super Smoother Filter // @param _source -> Open, Close, High, Low, etc ('close' is used if no argument is supplied) // @param _length -> Ehlers Super Smoother length // @returns 2 Pole Ehlers Super Smoothing to an input source at the specified input length export twoPole(float _source = close, simple int _length) => float PI = 2 * math.asin(1) // 3.14159265 float arg = math.sqrt(2) * PI / _length float a1 = math.exp(-arg) float b1 = 2 * a1 * math.cos(arg) float coef3 = -math.pow(a1, 2) float coef2 = b1 float coef1 = 1 - coef2 - coef3 float SSF = na float sourceReplace1 = nz(_source[1], _source) float sourceReplace2 = nz(_source[2], sourceReplace1) SSF := (coef1 * (_source + sourceReplace1) / 2) + (coef2 * nz(SSF[1], sourceReplace1)) + (coef3 * nz(SSF[2], sourceReplace2)) // @function Calculates 3 Pole Ehlers Super Smoother Filter // @param _source -> Open, Close, High, Low, etc ('close' is used if no argument is supplied) // @param _length -> Ehlers Super Smoother length // @returns 3 Pole Ehlers Super Smoothing to an input source at the specified input length export threePole(float _source = close, simple int _length) => float PI = 2 * math.asin(1) // 3.14159265 float arg = 1.738 * PI / _length float a1 = math.exp(-arg) float b1 = 2 * a1 * math.cos(arg) float c1 = math.pow(a1, 2) float coef4 = math.pow(c1, 2) float coef3 = -(c1 + b1 * c1) float coef2 = b1 + c1 float coef1 = 1 - coef2 - coef3 - coef4 float SSF = na float sourceReplace1 = nz(_source[1], _source) float sourceReplace2 = nz(_source[2], sourceReplace1) float sourceReplace3 = nz(_source[2], sourceReplace2) SSF := (coef1 * (_source + sourceReplace1) / 2) + (coef2 * nz(SSF[1], sourceReplace1)) + (coef3 * nz(SSF[2], sourceReplace2)) + (coef4 * nz(SSF[3], sourceReplace3)) // plot demo plot(twoPole(close, 50), title="Ehlers Super Smoother Filter - 2 Pole", color=color.yellow) plot(threePole(close, 50), title="Ehlers Super Smoother Filter - 3 Pole", color=color.aqua)
Lukashere
https://www.tradingview.com/script/jeKpQecc/
LucasHere
https://www.tradingview.com/u/LucasHere/
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/ // © LucasHere //@version=5 // @description TODO: add library description here library("Lukashere") // @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 Percentual2nu(float a , float b) => vp_result = a < b ? ((b - a)/b) * 100 : ((a - b)/a) * 100 vp_result //iNDICADORES fUNCTION // @function Gets a Moving Average based on type // @param int _length The MA period // @param string _maType The type of MA // @returns A moving average with the given parameters // ex: basis = lib.getMA(20,'EMA') export getMA(simple int _length, string _maType , float _src) => switch _maType "EMA" => ta.ema(_src, _length) "SMA" => ta.sma(_src, _length) "HMA" => ta.hma(_src, _length) "WMA" => ta.wma(_src, _length) "VWMA" => ta.vwma(_src, _length) "VWAP" => ta.vwap => e1 = ta.ema(_src, _length) e2 = ta.ema(e1, _length) e3 = ta.ema(e2, _length) 3 * (e1 - e2) + e3 // ex: [atrup, atrdown] = lib.getStopAtr(1 , 'Max-Min' , 0.61) export getStopAtr(simple int _length, string _Type , float _mult) => atr = ta.atr(_length) atrup = _Type == "Close" ? close + atr * _mult : high + atr * _mult atrdown = _Type == "Close" ? close - atr * _mult : low - atr * _mult [atrup, atrdown] //Example use array = lib.SymbolsTopMarketcap() array.get(array, 0) = BINANCE:BTCUSDT export SymbolsTopMarketcap() => arrayExchangeSymbol = array.new_string(31) array.set(arrayExchangeSymbol, 0, "BINANCE:BTCUSDT") array.set(arrayExchangeSymbol, 1, "BINANCE:ETHUSDT") array.set(arrayExchangeSymbol, 2, "BINANCE:BNBUSDT") array.set(arrayExchangeSymbol, 3, "BINANCE:XRPUSDT") array.set(arrayExchangeSymbol, 4, "BINANCE:LUNAUSDT") array.set(arrayExchangeSymbol, 5, "BINANCE:ADAUSDT") array.set(arrayExchangeSymbol, 6, "BINANCE:SOLUSDT") array.set(arrayExchangeSymbol, 7, "BINANCE:AVAXUSDT") array.set(arrayExchangeSymbol, 8, "BINANCE:DOTUSDT") array.set(arrayExchangeSymbol, 9, "BINANCE:DOGEUSDT") array.set(arrayExchangeSymbol, 10, "BINANCE:SHIBUSDT") array.set(arrayExchangeSymbol, 11, "BINANCE:MATICUSDT") array.set(arrayExchangeSymbol, 12, "BINANCE:LTCUSDT") array.set(arrayExchangeSymbol, 13, "BINANCE:ATOMUSDT") array.set(arrayExchangeSymbol, 14, "BINANCE:NEARUSDT") array.set(arrayExchangeSymbol, 15, "BINANCE:LINKUSDT") array.set(arrayExchangeSymbol, 16, "BINANCE:BCHUSDT") array.set(arrayExchangeSymbol, 17, "BINANCE:UNIUSDT") array.set(arrayExchangeSymbol, 18, "BINANCE:TRXUSDT") array.set(arrayExchangeSymbol, 19, "BINANCE:ETCUSDT") array.set(arrayExchangeSymbol, 20, "BINANCE:FTTUSDT") array.set(arrayExchangeSymbol, 21, "BINANCE:ALGOUSDT") array.set(arrayExchangeSymbol, 22, "BINANCE:XLMUSDT") array.set(arrayExchangeSymbol, 23, "BINANCE:MANAUSDT") array.set(arrayExchangeSymbol, 24, "BINANCE:HBARUSDT") array.set(arrayExchangeSymbol, 25, "BINANCE:EGLDUSDT") array.set(arrayExchangeSymbol, 26, "BINANCE:ICPUSDT") array.set(arrayExchangeSymbol, 27, "BINANCE:SANDUSDT") array.set(arrayExchangeSymbol, 28, "BINANCE:XMRUSDT") array.set(arrayExchangeSymbol, 29, "BINANCE:WAVESUSDT") array.set(arrayExchangeSymbol, 30, "BINANCE:VETUSDT") arraySymbol = array.new_string(array.size(arrayExchangeSymbol)) for i = 0 to array.size(arrayExchangeSymbol) array.set(arraySymbol, i, str.replace_all(array.get(arrayExchangeSymbol, i), 'BINANCE:', '') ) [arrayExchangeSymbol , arraySymbol] 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 //--------------POSITION SIZE------------------ getPositionSize(EntradaPrice, Sl , riskPerTrade , accountBalance) => longDiffSL = math.abs(EntradaPrice - Sl) positionValue = accountBalance * (riskPerTrade / 100) / (longDiffSL / EntradaPrice) positionSize = positionValue / EntradaPrice // Forex getPositionSizeForex(stopLossSizePoints , riskPerTrade , accountBalance ,conversionRate) => riskAmount = accountBalance * (riskPerTrade / 100) * conversionRate riskPerPoint = stopLossSizePoints * syminfo.pointvalue positionSize = riskAmount / riskPerPoint / syminfo.mintick math.round(positionSize) // @function Gets position Size // @param float accountBalance - balance for account // @param string typeOrder - Long OR Short // @param string typePosition - 3 type (Tamanho Risco , Contrato Fixo , Value USD) // @param float inputPrice - input for price // @param float StopLoss - input for stop // @param riskPerTrade - risk for trade % // ex: basis = tradePositionSize := lib.positionSize(accountBalance, GerenciarPosicao , EntradaPrice , shortStop , riskPerTrade , conversionRate) export positionSize(float accountBalance , string typePosition , float inputPrice , float StopLoss = 0 , float riskPerTrade = 0 , float conversionRate = 1.0) => float positionSize = 0 if syminfo.type == 'crypto' if(syminfo.currency == 'USDT' or syminfo.currency == 'USD' or syminfo.currency == 'BUSD' or syminfo.currency == 'USDC') positionSize := typePosition == 'Tamanho Risco' ? getPositionSize(inputPrice, StopLoss , riskPerTrade , accountBalance) : typePosition == 'Contrato Fixo' ? riskPerTrade : typePosition == 'Value USD' ? (accountBalance / strategy.initial_capital) * (riskPerTrade / inputPrice) : 0 if syminfo.type == 'forex' or syminfo.type == 'cfd' if(syminfo.currency == 'USD') positionSize := typePosition == 'Tamanho Risco' ? getPositionSizeForex(toWhole(math.abs(inputPrice - StopLoss))* (syminfo.type == 'cfd' ? syminfo.mintick * 10000 : 10) , riskPerTrade , accountBalance , conversionRate): typePosition == 'Contrato Fixo' ? riskPerTrade : typePosition == 'Value USD' ? math.round( (accountBalance / strategy.initial_capital) * (riskPerTrade / inputPrice) * conversionRate) : 0 positionSize
Signal_transcoder_library
https://www.tradingview.com/script/AeH2FTU8-Signal-transcoder-library/
djmad
https://www.tradingview.com/u/djmad/
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/ // © djmad //@version=5 //@description // sending more than 1 value to the next indicator via plot needs encoding // via _16bit_encode() you send in 8 bit and plot out via a plot(hidden via display=display.none) // at the daisychain indicator you input that plot and send it through [x1,x2,x3,....]=_16bit_decode(plotname daisychain) so you get back your 8 bits :-) // have fun // Thanks Lonesometheblue for the assistance library("Signal_transcoder_library") export _16bit_encode(bool [] mux_array) => float mux = 0 for int x = 0 to math.min(array.size(mux_array),15) mux := mux + math.round(((array.get(mux_array,x) == true)?math.pow(2,x):0),0) export _16bit_decode(float mux) => int mux_int = math.min(math.ceil(math.round(mux,0)),65535) bool solving = true int counter = 0 demux_array = array.new_bool(16, false) for x = -15 to 0 by 1 if (math.floor(mux_int / math.pow(2,x*-1)) > 0) mux_int := mux_int - math.ceil(math.pow(2,x*-1)) array.set(demux_array,-x,true) else array.set(demux_array,-x,false) demux_array export f_remap_bits(bool [] I_B, bool [] O_B, int [] M_I,int [] M_O) => var int mapfrom = 0 var int mapto = 0 for i = 0 to 15 by 1 mapfrom := array.get(M_I, i) mapto := array.get(M_O, i) if array.get(M_O, i) > -1 and array.get(M_I, i) > -1 array.set(O_B, mapto, array.get(I_B, mapfrom)) 0 export f_bool_operations(bool [] I_B, bool [] O_B, int S_1 = -1, int S_2 = -1, int S_3 = -1, int T_1 = -1, string function = 'add') => var bool calc_1 = 0 var bool calc_2 = 0 var bool calc_3 = 0 for i = 0 to 15 by 1 array.set(O_B, i, array.get(I_B, i)) if T_1 != -1 if function == 'and' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" if S_1 != -1 calc_1 := array.get(I_B,S_1) else calc_1 := true if S_2 != -1 calc_2 := array.get(I_B,S_2) else calc_2 := true if S_3 != -1 calc_3 := array.get(I_B,S_3) else calc_3 := true if (calc_1 and calc_2 and calc_3) array.set(O_B, T_1, true) else array.set(O_B, T_1, false) if function == 'or' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if S_2 != -1 calc_2 := array.get(I_B,S_2) else if S_2 == -1 calc_2 := false if S_3 != -1 calc_3 := array.get(I_B,S_3) else if S_3 == -1 calc_3 := false if (calc_1 or calc_2 or calc_3) array.set(O_B, T_1, true) else array.set(O_B, T_1, false) if function == 'not' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" if S_1 != -1 calc_1 := not array.get(I_B,S_1) else if S_1 == -1 calc_1 := true if calc_1 array.set(O_B, T_1, true) else array.set(O_B, T_1, false) if function == 'nand' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" if S_1 != -1 calc_1 := array.get(I_B,S_1) else calc_1 := true if S_2 != -1 calc_2 := array.get(I_B,S_2) else calc_2 := true if S_3 != -1 calc_3 := array.get(I_B,S_3) else calc_3 := true if (calc_1 and calc_2 and calc_3) array.set(O_B, T_1, false) else array.set(O_B, T_1, true) if function == 'nor' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if S_2 != -1 calc_2 := array.get(I_B,S_2) else if S_2 == -1 calc_2 := false if S_3 != -1 calc_3 := array.get(I_B,S_3) else if S_3 == -1 calc_3 := false if (calc_1 or calc_2 or calc_3) array.set(O_B, T_1, false) else array.set(O_B, T_1, true) if function == 'xor' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if S_2 != -1 calc_2 := array.get(I_B,S_2) else if S_2 == -1 calc_2 := false if S_3 != -1 calc_3 := array.get(I_B,S_3) else if S_3 == -1 calc_3 := false if (calc_1 and not calc_2 and not calc_3) or (not calc_1 and calc_2 and not calc_3) or (not calc_1 and not calc_2 and calc_3) array.set(O_B, T_1, true) else array.set(O_B, T_1, false) if function == 'xnor' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if S_2 != -1 calc_2 := array.get(I_B,S_2) else if S_2 == -1 calc_2 := false if S_3 != -1 calc_3 := array.get(I_B,S_3) else if S_3 == -1 calc_3 := false if (not calc_1 and not calc_2 and not calc_3) or (calc_1 and calc_2 and calc_3) array.set(O_B, T_1, true) else array.set(O_B, T_1, false) if function == 'TP' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" var TP_active = false if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if calc_1 and TP_active array.set(O_B, T_1, false) if calc_1 and not TP_active array.set(O_B, T_1, true) TP_active := true else if not calc_1 array.set(O_B, T_1, false) TP_active := false if function == 'TPD' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" var TPD_active = false var int TPD_time = 0 if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if calc_1 and TPD_time < S_2 TPD_time := TPD_time +1 array.set(O_B, T_1, false) 0 if calc_1 and TPD_active and TPD_time >= S_2 TPD_active := true array.set(O_B, T_1, true) 0 else if not calc_1 array.set(O_B, T_1, false) TPD_active := false TPD_time := 0 0 if function == 'TON' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" var TON_active = false var int TON_time = -1 if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if calc_1 and TON_time < S_2 TON_time := TON_time +1 array.set(O_B, T_1, false) 0 if calc_1 and TON_time >= S_2 TON_active := true array.set(O_B, T_1, true) 0 else if not calc_1 array.set(O_B, T_1, false) TON_active := false TON_time := -1 0 if function == 'TOF' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP", "RATE" var TOF_active = false var int TOF_time = -2 if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if calc_1 TOF_active := true TOF_time := S_2 array.set(O_B, T_1, true) if TOF_active and TOF_time > -2 TOF_time := TOF_time -1 array.set(O_B, T_1, true) if TOF_active and TOF_time == -2 and not calc_1 array.set(O_B, T_1, false) if function == 'MDP' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP" , "RATE" var MDP_up = false var MDP_down = false var float rememberprice = close var int TOF_time = -2 if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false if not calc_1 array.set(O_B, T_1, false) if calc_1 and MDP_up and MDP_down array.set(O_B, T_1, false) if rememberprice * (S_2 / 1000) > close or rememberprice * (S_3 / 1000) < close and (MDP_up or MDP_down) array.set(O_B, T_1, false) MDP_up := false MDP_down := false// if calc_1 and (not MDP_up and not MDP_down) rememberprice := close MDP_up := true MDP_down := true array.set(O_B, T_1, true) if function == 'RATE' //"and", "or", "not", "nand", "nor", "xor", "xnor", "TP", "TPD", "TON", "TOF" ,"MDP" , "RATE" var ratecalc = 0 var Counterarray = array.new_bool(S_2,false) if S_1 != -1 calc_1 := array.get(I_B,S_1) else if S_1 == -1 calc_1 := false array.insert(Counterarray,0,array.get(I_B,S_1)) if array.size(Counterarray) > S_2 array.remove(Counterarray,array.size(Counterarray)-1) ratecalc := 0 for i = 1 to array.size(Counterarray)-1 if array.get(Counterarray, i) == true ratecalc := ratecalc +1 if ratecalc >= S_3 array.set(O_B, T_1, true) else array.set(O_B, T_1, false) infuse(bool [] M, int C, bool S) => if C > -1 and C <=15 array.set(M, C, S) M export f_infuse_signal( int CH_1, bool S_1, bool [] M_O) => infuse(M_O,CH_1, S_1) export f_infuse_signal( int CH_1, bool S_1, int CH_2, bool S_2, bool [] M_O) => infuse(M_O,CH_1, S_1) infuse(M_O,CH_2, S_2) export f_infuse_signal( int CH_1, bool S_1, int CH_2, bool S_2, int CH_3, bool S_3, bool [] M_O) => infuse(M_O,CH_1, S_1) infuse(M_O,CH_2, S_2) infuse(M_O,CH_3, S_3) export f_infuse_signal( int CH_1, bool S_1, int CH_2, bool S_2, int CH_3, bool S_3, int CH_4, bool S_4, bool [] M_O) => infuse(M_O,CH_1, S_1) infuse(M_O,CH_2, S_2) infuse(M_O,CH_3, S_3) infuse(M_O,CH_4, S_4) export f_infuse_signal( int CH_1, bool S_1, int CH_2, bool S_2, int CH_3, bool S_3, int CH_4, bool S_4, int CH_5, bool S_5, bool [] M_O) => infuse(M_O,CH_1, S_1) infuse(M_O,CH_2, S_2) infuse(M_O,CH_3, S_3) infuse(M_O,CH_4, S_4) infuse(M_O,CH_5, S_5) export f_infuse_signal( int CH_1, bool S_1, int CH_2, bool S_2, int CH_3, bool S_3, int CH_4, bool S_4, int CH_5, bool S_5, int CH_6, bool S_6, bool [] M_O) => infuse(M_O,CH_1, S_1) infuse(M_O,CH_2, S_2) infuse(M_O,CH_3, S_3) infuse(M_O,CH_4, S_4) infuse(M_O,CH_5, S_5) infuse(M_O,CH_6, S_6) export f_infuse_signal( int CH_1, bool S_1, int CH_2, bool S_2, int CH_3, bool S_3, int CH_4, bool S_4, int CH_5, bool S_5, int CH_6, bool S_6, int CH_7, bool S_7, bool [] M_O) => infuse(M_O,CH_1, S_1) infuse(M_O,CH_2, S_2) infuse(M_O,CH_3, S_3) infuse(M_O,CH_4, S_4) infuse(M_O,CH_5, S_5) infuse(M_O,CH_6, S_6) infuse(M_O,CH_7, S_7) export f_infuse_signal( int CH_1, bool S_1, int CH_2, bool S_2, int CH_3, bool S_3, int CH_4, bool S_4, int CH_5, bool S_5, int CH_6, bool S_6, int CH_7, bool S_7, int CH_8, bool S_8, bool [] M_O) => infuse(M_O,CH_1, S_1) infuse(M_O,CH_2, S_2) infuse(M_O,CH_3, S_3) infuse(M_O,CH_4, S_4) infuse(M_O,CH_5, S_5) infuse(M_O,CH_6, S_6) infuse(M_O,CH_7, S_7) infuse(M_O,CH_8, S_8) var Mapping_IN = array.new_bool(16,0) var Mapping_OUT = array.new_bool(16,0) var WorkBits1 = array.new_bool(16, false) var WorkBits2 = array.new_bool(16, false) var WorkBits3 = array.new_bool(16, false) var WorkBits4 = array.new_bool(16, false) var WorkBits5 = array.new_bool(16, false) var WorkBits6 = array.new_bool(16, false) var WorkBits7 = array.new_bool(16, false) var WorkBits8 = array.new_bool(16, false) var OutputBits = array.new_bool(16, false) int testzufall = math.ceil(math.random(0,65535,53)) Mapping_IN := _16bit_decode(testzufall) f_bool_operations( Mapping_IN, WorkBits1, 0, 1, -1, 8,"and") f_bool_operations( WorkBits1, WorkBits2, 0, 1, -1, 9,"or") f_bool_operations( WorkBits2, WorkBits3, 0, 1, -1, 10,"not") f_bool_operations( WorkBits3, WorkBits4, 0, 30, 20, 1,"RATE") f_bool_operations( WorkBits4, WorkBits5, 0, 1, -1, 12,"nor") f_bool_operations( WorkBits5, WorkBits6, 0, 3, -1, 13,"TP") f_bool_operations( WorkBits6, WorkBits7, 0, 2, -1, 14,"TON") f_bool_operations( WorkBits7, Mapping_OUT, 0, 995, 1005, 15,"MDP") plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),0)?2:1.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),1)?4:3.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),2)?6:5.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),3)?8:7.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),4)?10:9.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),5)?12:11.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),6)?14:13.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),7)?16:15.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),8)?22:21.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),9)?24:23.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),10)?26:25.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),11)?28:27.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),12)?30:29.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),13)?32:31.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),14)?34:33.5, style=plot.style_linebr) plot(array.get(_16bit_decode(_16bit_encode(Mapping_OUT)),15)?36:35.5, style=plot.style_linebr) plot(-10+_16bit_encode(_16bit_decode(testzufall))/6500,color=color.green) plot(-10+testzufall[1]/6500,color=color.yellow)
RCI Library
https://www.tradingview.com/script/imqt1T8w-RCI-Library/
boitoki
https://www.tradingview.com/u/boitoki/
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/ // © boitoki //@version=5 // @description: RCI library library("RCI") length = input.int(9, "Interval") source = input.source(close, "Source") ord (seq, idx, itv) => p = seq[idx] o = 1 s = 0 for i = 0 to itv - 1 if p < seq[i] o := o + 1 else if p == seq[i] s := s + 1 o + (s - 1) / 2.0 d (src, itv) => sum = 0.0 for i = 0 to itv - 1 sum := sum + math.pow((i + 1) - ord(src, i, itv), 2) sum rci_func (src, itv) => (1.0 - 6.0 * d(src, itv) / (itv * (itv * itv - 1.0))) * 100.0 hline(80) hline(-80) plot(rci_func(source, length)) // @function: RCI calculating // @returns: RCI value export calc (float src, int len) => rci_func(src, len)
Swiss_Pine_Libra
https://www.tradingview.com/script/XdofJ9BI-Swiss-Pine-Libra/
Exmodaus
https://www.tradingview.com/u/Exmodaus/
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/ // © Exmodaus //@version=5 // @description TODO: add library description here library("Swiss_Pine_Libra") // @function TODO: Creates an custom ADX, Di+, Di- so that a series may be used as Len // @param x TODO: iadx(len, smooth) Len = Length(lookback) Smoothing = DI Length // @returns TODO: Returns [Diplus, Diminus, ADX] export iadx(float len=21, float smooth=21) => dmp = high-nz(high[1]) > nz(low[1])-low ? math.max(high-nz(high[1]), 0): 0 dmm = nz(low[1])-low > high-nz(high[1]) ? math.max(nz(low[1])-low, 0): 0 str = 0.0 str := nz(str[1]) - (nz(str[1])/len) + ta.tr sdmp = 0.0 sdmp := nz(sdmp[1]) - (nz(sdmp[1])/len) + dmp sdmm = 0.0 sdmm := nz(sdmm[1]) - (nz(sdmm[1])/len) + dmm DIPlus = sdmp / str * 100 DIMinus = sdmm / str * 100 DX = math.abs(DIPlus-DIMinus) / (DIPlus+DIMinus)*100 ADX = ta.rma(DX, smooth) [DIPlus, DIMinus, ADX] // @function TODO: Used to find Min, Mid, Max values // @param x TODO: V1 = first value V2 = second value V3 = third value // @returns TODO: MxP(Max) MnP(Min) MdP(Mid), and the 3 numbers rounded to an int(MxPP, MnPP, MdPP) export compare(float v1,float v2,float v3) => ahv = float(v1 > v2 ? v1 : v2) // is v1 or 2 greater MxP = float(ahv > v3 ? ahv : v3) alv = float(v1 < v2 ? v1 : v2) // is v1 or 2 lesser MnP = float(alv < v3 ? alv : v3) // is alv result less then v3 MdP = if MxP == v1 //checks if MxP = v1 Value float(v2 > v3 ? v2 : v3) //if true it checks if v2 is greater then v3 and returns the higher value else if MxP == v2 // checks if MxP = v2 Value float(v1 > v3 ? v1 : v3) //if true it checks if v1 is greater then v3 and returns the higher value else float(v1 > v2 ? v1 : v2) // if both are false set MdP to greater of v1 or v2Value MnPP = int(math.round(MnP)) MdPP = int(math.round(MdP)) MxPP = int(math.round(MxP)) [MxP, MdP, MnP, MxPP, MdPP, MnPP] // @function TODO:custom function to get array averages and OHLC values // @param x TODO: ID= the array you want to use for averaging // @returns TODO: Returns a Tuple with [average, max, min] export abc(float[] id) => avg = array.avg(id) oPen = open > close[1] ? open + avg : close[1] + avg hIgh = high < high[1] ? low[1] + avg : high lOw = low > low[1] ? high[1] + avg : low cLose = open < close[1] ? close[1] + avg : open + avg average = math.avg(oPen, hIgh, lOw, cLose) max = math.max(oPen, hIgh, lOw, cLose) min = math.min(oPen, hIgh, lOw, cLose) [average, max, min]
The Divergent Library
https://www.tradingview.com/script/u5iG66IL-The-Divergent-Library/
WhiteboxSoftware
https://www.tradingview.com/u/WhiteboxSoftware/
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/ // // © WhiteboxSoftware // // @version=5 // // @description The Divergent Library contains functions that helps the development of indicators / strategies which use The Divergent indicator's Divergence Signal as an external source. library("TheDivergentLibrary", overlay = true) // Constants // 04 09 22 05 18 07 05 14 03 05 // D I V E R G E N C E var int DIVERGENCE_MAGIC_NUMBER = 4922518751435 var int EXPECTED_SIGNAL_LENGTH = 13 var int CONFIG_REGULAR_BULLISH_ENABLED = 0 var int CONFIG_HIDDEN_BULLISH_ENABLED = 1 var int CONFIG_REGULAR_BEARISH_ENABLED = 2 var int CONFIG_HIDDEN_BEARISH_ENABLED = 3 var int CONFIG_PIVOT_DETECTION_SOURCE = 4 var int CONFIG_PIVOT_DETECTION_MODE = 5 // Functions decimalToBitArray(int num) => int n = num bool[] bits = array.new_bool() while (n > 0) array.push(bits, n % 2 == 1) n := int(n / 2) array.reverse(bits) bits parseConfigFromSignal(float signal) => string[] signalParts = str.split(str.tostring(signal), ".") int encodedConfig = int(str.tonumber(array.get(signalParts, 1))) decimalToBitArray(encodedConfig) getConfig(bool[] context, int id) => int index = array.size(context) - id - 1 if index > 0 array.get(context, index) else false // @function Returns a boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent. // // @param context The context of The Divergent Library. // // @returns A boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent. export isRegularBullishEnabled(bool[] context) => getConfig(context, CONFIG_REGULAR_BULLISH_ENABLED) // @function Returns a boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent. // // @param context The context of The Divergent Library. // // @returns A boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent. export isHiddenBullishEnabled(bool[] context) => getConfig(context, CONFIG_HIDDEN_BULLISH_ENABLED) // @function Returns a boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent. // // @param context The context of The Divergent Library. // // @returns A boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent. export isRegularBearishEnabled(bool[] context) => getConfig(context, CONFIG_REGULAR_BEARISH_ENABLED) // @function Returns a boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent. // // @param context The context of The Divergent Library. // // @returns A boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent. export isHiddenBearishEnabled(bool[] context) => getConfig(context, CONFIG_HIDDEN_BEARISH_ENABLED) // @function Returns the 'Pivot Detection Source' setting of The Divergent. The returned value can be either "Oscillator" or "Price". // // @param context The context of The Divergent Library. // // @returns One of the following string values: "Oscillator" or "Price". export getPivotDetectionSource(bool[] context) => getConfig(context, CONFIG_PIVOT_DETECTION_SOURCE) ? "Price" : "Oscillator" // @function Returns the 'Pivot Detection Mode' setting of The Divergent. The returned value can be either "Bodies" or "Wicks". // // @param context The context of The Divergent Library. // // @returns One of the following string values: "Bodies" or "Wicks". export getPivotDetectionMode(bool[] context) => getConfig(context, CONFIG_PIVOT_DETECTION_MODE) ? "Wicks" : "Bodies" debugConfig(bool[] context) => str.format( "Regular Bullish enabled = {0}\nHidden Bullish Enabled = {1}\nRegular Bearish Enabled = {2}\nHidden Bearish Enabled = {3}\nPivot Detection Source = {4}\nPivot Detection Mode = {5}", str.format("{0}", isRegularBullishEnabled(context)), str.format("{0}", isHiddenBullishEnabled(context)), str.format("{0}", isRegularBearishEnabled(context)), str.format("{0}", isHiddenBearishEnabled(context)), getPivotDetectionSource(context), getPivotDetectionMode(context) ) // @function Returns a boolean value indicating the link status to The Divergent indicator. // // @param context The context of The Divergent Library. // // @returns A boolean value indicating the link status to The Divergent indicator. export isLinked(bool[] context) => array.size(context) > 0 and array.get(context, 0) == true createContext(bool linked, bool[] config) => array.concat(array.from(linked), config) printLinkStatus(bool[] context, bool debug) => var table divLinkedTable = table.new(position.bottom_left, 1, 1, border_width = 5) var bool linked = isLinked(context) table.cell(divLinkedTable, 0, 0, " The Divergent: " + (linked ? "Linked" + (debug ? "\n\n" + debugConfig(context) : "") : "Not Linked"), text_color = color.white, bgcolor = linked ? color.new(color.green, 60) : color.red, text_halign = text.align_left) // @function Initialises The Divergent Library's context with the signal produced by The Divergent on the first bar. The value returned from this function is called the "context of The Divergent Library". Some of the other functions of this library requires you to pass in this context. // // @param firstBarSignal The signal from The Divergent indicator on the first bar. // @param displayLinkStatus A boolean value indicating whether the Link Status window should be displayed in the bottom left corner of the chart. Defaults to true. // @param debug A boolean value indicating whether the Link Status window should display debug information. Defaults to false. // // @returns A bool[] array containing the context of The Divergent Library. export init(float firstBarSignal, bool displayLinkStatus = true, bool debug = false) => bool[] context = if barstate.isfirst and int(firstBarSignal) == DIVERGENCE_MAGIC_NUMBER createContext(true, parseConfigFromSignal(firstBarSignal)) else createContext(false, array.new_bool()) if displayLinkStatus printLinkStatus(context, debug) context // @function Processes a signal from The Divergent and returns a 5-tuple with the decoded signal: [int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd]. `divergenceType` can be one of the following values: na → No divergence was detected, 1 → Regular Bullish, 2 → Regular Bullish early, 3 → Hidden Bullish, 4 → Hidden Bullish early, 5 → Regular Bearish, 6 → Regular Bearish early, 7 → Hidden Bearish, 8 → Hidden Bearish early. // // @param signal The signal from The Divergent indicator. // // @returns A 5-tuple with the following values: [int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd]. export processSignal(float signal) => int length = not na(signal) ? int(math.log10(signal)) + 1 : 0 if not barstate.isfirst and length == EXPECTED_SIGNAL_LENGTH string[] chars = str.split(str.tostring(signal), "") int type = int(str.tonumber(array.get(chars, 0))) int divPriceBarIndexStartOffset = int(str.tonumber(array.get(chars, 1) + array.get(chars, 2) + array.get(chars, 3))) int divPriceBarIndexEndOffset = int(str.tonumber(array.get(chars, 4) + array.get(chars, 5) + array.get(chars, 6))) int divOscBarIndexStartOffset = int(str.tonumber(array.get(chars, 7) + array.get(chars, 8) + array.get(chars, 9))) int divOscBarIndexEndOffset = int(str.tonumber(array.get(chars, 10) + array.get(chars, 11) + array.get(chars, 12))) [ type, bar_index - divPriceBarIndexStartOffset, bar_index - divPriceBarIndexEndOffset, bar_index - divOscBarIndexStartOffset, bar_index - divOscBarIndexEndOffset ] else [na, na, na, na, na] // Usage instructions var string usageInstructions = "Usage instructions\n" + "================\n\n" + "1. Add The Divergent indicator to your chart\n\n" + "2. Create a script in which you import the library:\n\n" + " import WhiteboxSoftware/TheDivergentLibrary/1 as tdl\n\n" + "3. Add a source input to your script:\n\n" + " float divSignal = input.source(title = \"The Divergent Link\", defval = close)\n\n" + " Unfortunately there is no way to default the source to 'The Divergent: Divergence Signal',\n" + " so you will have to select 'The Divergent: Divergence Signal' as the source every time you\n" + " add the script to your chart (and every time you make changes to it).\n\n" + "4. Initialise the library (it is important to use `var` to avoid initialising on every bar!):\n\n" + " var bool[] context = tdl.init(divSignal)\n\n" + "5. Call the processSignal function on every bar to check whether a divergence was detected:\n\n" + " [divergence, priceStart, priceEnd, oscStart, oscEnd] = tdl.processSignal(divSignal)\n\n" + " // The returned `divergence` variable will have one of the following (int) values:\n" + " //\n" + " // na → No divergence was detected\n" + " // 1 → Regular Bullish\n" + " // 2 → Regular Bullish early\n" + " // 3 → Hidden Bullish\n" + " // 4 → Hidden Bullish early\n" + " // 5 → Regular Bearish\n" + " // 6 → Regular Bearish early\n" + " // 7 → Hidden Bearish\n" + " // 8 → Hidden Bearish early\n\n" + "6. Use the divergence as part of your entry condition:\n\n" + " if barstate.isconfirmed and priceAboveEma200 and ta.barssince(divergence == 1) < 5\n" + "  strategy.entry(...)" var table usageInstructionsTable = table.new(position.middle_center, 1, 1, border_width = 3, frame_width = 10, bgcolor = color.new(#1e222d, 0), frame_color = color.new(#1e222d, 0)) table.cell(usageInstructionsTable, 0, 0, usageInstructions, text_color = color.new(#b2b5be, 0), text_size = size.normal, text_halign = text.align_left)
Divergence
https://www.tradingview.com/script/TrCZ4x9h-Divergence/
DevLucem
https://www.tradingview.com/u/DevLucem/
264
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/ // © DevLucem // ( ( // )\ ) )\ ) // (()/( ( ) (()/( ( ( ) // /(_)) ))\ /(( /(_)) ))\ ( ))\ ( // (_))_ /((_)(_))\ (_)) /((_) )\ /((_) )\ ' // | \ (_)) _)((_) | | (_))( ((_)(_)) _((_)) // | |) |/ -_) \ V / | |__| || |/ _| / -_)| ' \() // |___/ \___| \_/ |____|\_,_|\__| \___||_|_|_| //@version=5 // @description Calculates a divergence between 2 series library("Divergence", overlay=true) // @function Calculates bullish divergence // @param _src Main series // @param _low Comparison series (`low` is used if no argument is supplied) // @param depth Fractal Depth (`2` is used if no argument is supplied) // @returns 2 boolean values for regular and hidden divergence export bullish(float _src, float _low=low, int depth=2) => bot_fractal = ta.lowest(_src, depth * 2 + 1) == _src[depth] prev_bot_fractal = ta.valuewhen(bot_fractal, _src[depth], 0)[depth] prev_low = ta.valuewhen(bot_fractal, _low[depth], 0)[depth] regular_bullish_div = bot_fractal and _low[depth] < prev_low and _src[depth] > prev_bot_fractal hidden_bullish_div = bot_fractal and _low[depth] > prev_low and _src[depth] < prev_bot_fractal [regular_bullish_div, hidden_bullish_div] // @function Calculates bearish divergence // @param _src Main series // @param _high Comparison series (`high` is used if no argument is supplied) // @param depth Fractal Depth (`2` is used if no argument is supplied) // @returns 2 boolean values for regular and hidden divergence export bearish(float _src, float _high=high, int depth=2) => top_fractal = ta.highest(_src, depth * 2 + 1) == _src[depth] prev_top_fractal = ta.valuewhen(top_fractal, _src[depth], 0)[depth] prev_high = ta.valuewhen(top_fractal, _high[depth], 0)[depth] regular_bearish_div = top_fractal and _high[depth] > prev_high and _src[depth] < prev_top_fractal hidden_bearish_div = top_fractal and _high[depth] < prev_high and _src[depth] > prev_top_fractal [regular_bearish_div, hidden_bearish_div] stoch = ta.sma(ta.stoch(close, high, low, 14), 3) [regular_bullish_div, hidden_bullish_div] = bullish(stoch) plotshape(regular_bullish_div or hidden_bullish_div, 'spot bottom', shape.diamond, location.belowbar, color.new(color.lime, 0), size=size.small, offset=-2) [regular_bearish_div, hidden_bearish_div] = bearish(stoch) plotshape(regular_bearish_div or hidden_bearish_div, 'spot top', shape.diamond, location.abovebar, color.new(color.red, 0), size=size.small, offset=-2) // ( ( // )\ ) )\ ) // (()/( ( ) (()/( ( ( ) // /(_)) ))\ /(( /(_)) ))\ ( ))\ ( // (_))_ /((_)(_))\ (_)) /((_) )\ /((_) )\ ' // | \ (_)) _)((_) | | (_))( ((_)(_)) _((_)) // | |) |/ -_) \ V / | |__| || |/ _| / -_)| ' \() // |___/ \___| \_/ |____|\_,_|\__| \___||_|_|_|
Dictionary/Object Library
https://www.tradingview.com/script/wBuYr4Lk-Dictionary-Object-Library/
CyberMensch
https://www.tradingview.com/u/CyberMensch/
69
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/ // © paragjyoti2012 //@version=5 // @description : This Library is aimed to mitigate the limitation of Pinescript having only one structured data type which is only arrays. // It lacks data types like Dictionaries(in Python) or Object (in JS) that are standard for other languages. Tuples do exist, but it hardly solves any problem. // Working only with Arrays could be overwhelming if your codebase is large. I looked for alternatives to arrays but couldn't find any library. // So I coded it myself and it's been working good for me. So I wanted to share it with you all. // What does it do: // ================== // If you are familiar with Python or Javascript, this library tries to immimate Object/Dictonary like structure with Key Value Pairs. // For Example: // object= {name:"John Doe", age: 28 , org: "PineCoders"} // And then it also tries to immitate the Array of Objects (I call it Stack) // like this: // stack= [{name:"John Doe", age: 28 , org: "PineCoders"}, // {name:"Adam Smith", age: 32 , org: "PineCoders"}, // {name:"Paragjyoti Deka", age: 25 , org: "PineCoders"}] // So there are basically two ideas: Objects and Stacks. // But it looks whole different in Pinescript for obvious reasons. // Limitation: // The major limitation I couldn't overcome was that, for all of the values: both input and return values for properties will be of string type. // This is due to the limiation of Pinecsript that there is no way to return a value on a if-else statement dynamically with different data types. // And as the input data type must be explicitly defined when exporting the library functions, only string inputs are allowed. // Now that doesn't mean you won't be able to use integer, float or boolens, you just need to pass the string value for it using str.tostring() method. // And the output for the getter functions will be in strings as well. But I have added some type conversion methods that you could use from this library itself. // From String to Float, String To Integer and String to Boolean: these three methods are included in this library. // So basically the whole library is based on a manipulatiion of Array of strings under the hood. // /////////////// // Usage // /////////////// // Import the library using this statement: // import paragjyoti2012/STR_Dictionary_Lib/2 as DictLib // Objects // / First define an object using this method: // for eample: // object1= DictLib.init("name=John,age=26,org=") // This is similar to // object1= {name:"John",age:"26", org:""} in JS or Python // Just like we did here in for "org", you can set initital value to "". But remember to pass string values, even for a numerical properties, like here in "age". // You can use "age="+str.tostring(age). If you find it tedious, you can always add properties later on using .set() method. // So it could also be initiated like this // object= DictLib.init("name=John") // and later on // DictLib.set(object1,"age", str.toString(age)) // DictLib.set(object1,"org", "PineCoders") // The getter function looks like this // age= DictLib.get(object1,"age") // name=DictLib.get(object1,"name") // The first argument for all methods .get, .set, and .remove is the pointer (name of the object). // /////////////////////////// // Array Of Objects (Stacks) // /////////////////////////// // As I mentioned earlier, I call the array of objects as Stack. // Here's how to initialize a Stack. // stack= DictLib.initStack(object1) // The .initStack() method takes an object pointer as argument. It simply converts the array into a string and pushes it into the newly created stack. // Rest of all the methods for Stacks, takes the stack pointer as it's first arument. // For example: // DictLib.pushStack(stack,object2) // The second argument here is the object pointer. It adds the object to it's stack. Although it might feel like a two dimentional array, it's actually an one dimentional array with string values. // Under the hood, it looks like this ["name=John,age=26,org=Pinecoders", // "name=Adam,age=35,org=Pinecoders"] // //////////////////// // Methods // //////////////////// // For Objects // ------------------- // init() : Initializes the object. // params: (string) e.g // returns: The object ([The object is actually an array of strings. So the .init() method, basically returns an array of strings]) // example: // object1=DictLib.init("name=John,age=26,org=") // ................... // get() : Returns the value for given property // params: (string[] object_pointer, string property) // returns: string // example: // age= DictLib.get(object1,"age") // ....................... // set() : Adds a new property or updates an existing property // params: (string[] object_pointer, string property, string value) // returns: void // example: // DictLib.set(object1,"age", str.tostring(29)) // ........................ // remove() : Removes a property from the object // params : (string[] object_pointer, string property) // returns: void // example: // DictLib.set(object1,"org") // ........................ // For Array Of Objects (Stacks) // ------------------------------- // initStack() : Initializes the stack. // params: (string[] object_pointer) e.g // returns: The Stack // emaple: // stack= DictLib.initStack(object1) // ................... // pushToStack() : Adds an object at at last index of the stack // params: (string[] stack_pointer, string[] object_pointer) // returns: void // example: // DictLib.pushToStack(stack,object2) // ....................... // popFromStack() : Removes the last object from the stack // params: (string[] stack_pointer) // returns: void // example: // DictLib.popFromStack(stack) // ....................... // insertToStack() : Adds an object at at the given index of the stack // params: (string[] stack_pointer, string[] object_pointer, int index) // returns: void // example: // DictLib.insertToStack(stack,object3,1) // ....................... // removeFromStack() : Removes the object from the given index of the stack // params: (string[] stack_pointer, int index) // returns: void // example: // DictLib.removeFromStack(stack,2) // ....................... // getElement () : Returns the value for given property from an object in the stack (index must be given) // params: (string[] stack_pointer, int index, string property) // returns: string // example: // ageFromObject1= DictLib.getElement(stack,0,"age") // ....................... // setElement() : Updates an existing property of an object in the stack (index must be given) // params: (string[] stack_pointer, int index, string property, string value) // returns: void // example: // DictLib.setElement(stack,0,"age", str.tostring(32)) // ........................ // includesElement() : Checks if any object exists in the stack with the given property-value pair // params : (string[] stack_pointer, string property, string value) // returns : Boolean // example: // doesExist= DictLib.includesElement(stack,"org","PineCoders") // ........................ // searchStack() : Search for a property-value pair in the stack and returns it's index // params: (stringp[] stack_pointer, string property, string value) // returns: int (-1 if doesn't exist) // example: // index= DictLib.searchElement(stack,"org","PineCoders") // Points to remember // ............... // 1. Always pass string values as arguments. // 2. The return values will be of type string, so convert them before to avoid typecasting conflict. // More Informations // ==================== // Yes, You can store this objects and stacks for persisting through the iterations of a script across successive bars. // You just need to set the variable using "var" keyword. Remember this objects and stacks are just arrays, // so any methods and properties an array have it pinescript, would be applicable for objects and stacks. // It can also be used in security functions without any issues for MTF Analysis. // If you have any suggestions or feedback, please comment on the thread, I would surely be happy to help. library("STR_Dictionary_Lib") export init(string input)=>str.split(input,",") export get(string[] object_pointer, string property)=> val="" for x=0 to array.size(object_pointer)-1 _prop= array.get(str.split(array.get(object_pointer,x),"="),0) _val= array.get(str.split(array.get(object_pointer,x),"="),1) if(_prop==property) val:=_val val _indexofElement(pointer, property)=> propindex=-1 for x=0 to array.size(pointer)-1 arr_chunk_str=array.get(pointer,x) str_chunk_arr=str.split(arr_chunk_str,'=') if(array.get(str_chunk_arr,0)==property) propindex:=x propindex export set(string[] object_pointer, string property, string val )=> index=_indexofElement(object_pointer,property) if(index!=-1) for x=0 to array.size(object_pointer)-1 _prop= array.get(str.split(array.get(object_pointer,x),"="),0) _val= array.get(str.split(array.get(object_pointer,x),"="),1) if(_prop==property) array.set(object_pointer,x, property+"="+val) else array.push(object_pointer,property+"="+val) export remove(string[] object_pointer, string property)=> for x=0 to array.size(object_pointer)-1 _prop= array.get(str.split(array.get(object_pointer,x),"="),0) if(property==_prop) array.remove(object_pointer,x) break export initStack(string[] object_pointer)=> str_arr=array.join(object_pointer,",") array.new_string(1,str_arr) export pushToStack(string[] stack_pointer, string[] object_pointer)=> str_arr=array.join(object_pointer,',') array.push(stack_pointer,str_arr) export updateStack(string[] stack_pointer, string[] object_pointer, int index)=> str_arr=array.join(object_pointer,',') array.set(stack_pointer,index,str_arr) export popFromStack(string[] stack_pointer)=> array.pop(stack_pointer) export insertToStack(string[] stack_pointer, string[] object_pointer, int index)=> str_arr=array.join(object_pointer,',') array.insert(stack_pointer,index,str_arr) export removeFromStack(string[] stack_pointer, int index)=> array.remove(stack_pointer,index) export getElement(string[] stack_pointer,int index,string property)=> str_arr=array.get(stack_pointer,index) arr_str=str.split(str_arr,',') val="" for x=0 to array.size(arr_str)-1 arr_chunk_str=array.get(arr_str,x) str_chunk_arr=str.split(arr_chunk_str,'=') if(array.get(str_chunk_arr,0)==property) val:=array.get(str_chunk_arr,1) val _indexofElement(string[] stack_pointer,int index,string property)=> str_arr=array.get(stack_pointer,index) arr_str=str.split(str_arr,',') propindex=-1 for x=0 to array.size(arr_str)-1 arr_chunk_str=array.get(arr_str,x) str_chunk_arr=str.split(arr_chunk_str,'=') if(array.get(str_chunk_arr,0)==property) propindex:=x propindex export setElement(string[] stack_pointer,int index,string property, string value)=> str_arr=array.get(stack_pointer,index) arr_str=str.split(str_arr,',') propindex=_indexofElement(stack_pointer,index,property) array.set(arr_str,propindex,property+'='+value) new_str=array.join(arr_str,',') array.set(stack_pointer,index,new_str) stack_pointer export includesElement(string[] stack_pointer,string property, string value)=> exists=false if(array.size(stack_pointer)) for x=0 to array.size(stack_pointer)-1 val=getElement(stack_pointer,x,property) if(val==value) exists:=true exists export searchStack(string[] stack_pointer,string property, string value)=> index=-1 if(array.size(stack_pointer)) for x=0 to array.size(stack_pointer)-1 val=getElement(stack_pointer,x,property) if(val==value) index:=x index strToBool(string str)=> if(str=="True" or str=="true" or str=="1") true else false export getFloat(string[] object_pointer, string property)=> str.tonumber(get(object_pointer,property)) export getInt(string[] object_pointer, string property)=> int(str.tonumber(get(object_pointer,property))) export getBool(string[] object_pointer, string property)=> strToBool(get(object_pointer,property)) export getFloatElement(string[] stack_pointer,int index,string property)=> str.tonumber(getElement(stack_pointer,index,property)) export getIntElement(string[] stack_pointer,int index,string property)=> int(str.tonumber(getElement(stack_pointer,index,property))) export getBoolElement(string[] stack_pointer,int index,string property)=> strToBool(getElement(stack_pointer,index,property)) export setFloat(string[] object_pointer, string property, float val )=> set(object_pointer,property,str.tostring(val)) export setInt(string[] object_pointer, string property, int val)=> set(object_pointer,property,str.tostring(val)) export setBool(string[] object_pointer, string property, bool val)=> set(object_pointer,property,str.tostring(val)) export setFloatElement(string[] stack_pointer,int index,string property, float value)=> setElement(stack_pointer,index,property,str.tostring(value)) export setIntElement(string[] stack_pointer,int index,string property, int value)=> setElement(stack_pointer,index,property,str.tostring(value)) export setBoolElement(string[] stack_pointer,int index,string property, bool value)=> setElement(stack_pointer,index,property,str.tostring(value))
hashmaps
https://www.tradingview.com/script/GTYSy8sD-hashmaps/
marspumpkin
https://www.tradingview.com/u/marspumpkin/
14
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 import marspumpkin/pson/7 //@version=5 // @description: Simple hashmap implementation for pinescript. It gets your string array and transforms it into a hashmap. Before using it you need to initialize your array with the size you need for your specific case. library("hashmaps") char_at(i) => str.pos(' !#$%&\()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~;', i) hashcode_to_index(arr, hashcode) => hashcode % array.size(arr) hashcode(key) => hash = 7 length = str.length(key) for i = 0 to length - 1 by 1 hash := hash * 31 + char_at(str.substring(key, i, i+1)) hash index(arr, key) => hashcode_to_index(arr, hashcode(key)) export contains(string[]arr, string key) => if array.size(arr) > 0 val = pson.get(array.get(arr, index(arr, key)), key) val != '' or val != na else false export put(string[]arr, string key, string value) => if array.size(arr) > 0 index = index(arr, key) pson_string = array.get(arr, index) if pson_string == na pson_string := '{}' // handling collisions if pson.exists(pson_string, key) pson_string := pson.set(pson_string, key, value) else pson_string := pson.add(pson_string, key, value) array.set(arr, index, pson_string) export put(string[]arr, string key, float value) => put(arr, key, str.tostring(value)) export put(string[]arr, string key, int value) => put(arr, key, str.tostring(value)) export put(string[]arr, string key, bool value) => put(arr, key, str.tostring(value)) export remove(string[]arr, string key) => if array.size(arr) > 0 index = index(arr, key) pson_string = array.get(arr, index) // collisions if pson.exists(pson_string, key) removed = pson.remove(pson_string, key) pson_string := removed == '{}' ? na : removed array.set(arr, index, pson_string) // all get methods will return NaN if key doesn't exist or if the array is empty export get(string[]arr, string key) => if array.size(arr) > 0 pson.get(array.get(arr, index(arr, key)), key) export get_float(string[]arr, string key) => if array.size(arr) > 0 str.tonumber(pson.get(array.get(arr, index(arr, key)), key)) export get_int(string[]arr, string key) => math.round(get_float(arr, key)) export get_bool(string[]arr, string key) => if array.size(arr) > 0 pson.get(array.get(arr, index(arr, key)), key) == 'true' if barstate.islast hashmap = array.new_string(100000) key = 'apple123' put(hashmap, key, 'test') before = get(hashmap, key) remove(hashmap, key) after = get(hashmap, key) after := after == na ? 'NaN' : after label.new(x=bar_index, y=high, textcolor=color.yellow, text='before removing: ' + before + ', after removing: ' + after, size=size.normal, style=label.style_none) plot(close)
pson
https://www.tradingview.com/script/LmuCoUGC-pson/
marspumpkin
https://www.tradingview.com/u/marspumpkin/
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/ // © marspumpkin //@version=5 // @description: PineScript Object Notation. // A workaround not having objects in pinescript. // This is a Json-look-alike interpreter. // Format: '{attr={a={b=c:d={e=f}}}:attr1=value1:attr3={obj=val}}' // Please only use whitespaces in the values library("pson") LINE_BREAK = ':' EQUALS = '=' OBJ_BOUNDS_0 = '{' OBJ_BOUNDS_1 = '}' valid_syntax(string pson) => // more syntax checks to be added later str.startswith(pson, OBJ_BOUNDS_0) and str.endswith(pson, OBJ_BOUNDS_1) get_pson_string(string pson) => str.substring(pson, 1, str.length(pson) - 1) char_at(string my_string, int i) => if (i < str.length(my_string)) str.substring(my_string, i, i + 1) else na export get_iterable(string pson) => itterable = array.new_string(0) if valid_syntax(pson) pson_string = get_pson_string(pson) if not (str.contains(pson_string, '{') and str.contains(pson_string, '}')) str.split(pson_string, ':') else // object within attr_start = 0 depth = 0 length = str.length(pson_string) for i = 0 to length char = char_at(pson_string, i) if char == OBJ_BOUNDS_0 depth := depth + 1 if char == OBJ_BOUNDS_1 depth := depth - 1 if depth == 0 and (char == LINE_BREAK or i == length) array.push(itterable, str.substring(pson_string, attr_start, i)) attr_start := i + 1 itterable else itterable export set(string pson, string attribute, string value) => if valid_syntax(pson) result = '' for a in get_iterable(pson) attr = str.substring(a, 0, str.pos(a, EQUALS)) val = str.substring(a, str.pos(a, EQUALS) + 1, str.length(a)) if (attribute == attr) val := value result := result + attr + EQUALS + val + LINE_BREAK result := OBJ_BOUNDS_0 + str.substring(result, 0, str.length(result) - 1) + OBJ_BOUNDS_1 result else na export set_values(string pson, string[] attributes, string[] values) => // attributes and values must have the same length if valid_syntax(pson) result = '' iterable = get_iterable(pson) for i = 0 to array.size(iterable) - 1 by 1 iterable_string = array.get(iterable, i) attr = str.substring(iterable_string, 0, str.pos(iterable_string, EQUALS)) val = str.substring(iterable_string, str.pos(iterable_string, EQUALS) + 1, str.length(iterable_string)) if (array.get(attributes, i) == attr) val := array.get(values, i) result := result + attr + EQUALS + val + LINE_BREAK result := OBJ_BOUNDS_0 + str.substring(result, 0, str.length(result) - 1) + OBJ_BOUNDS_1 result else na export add(string pson, string attr, string value) => if valid_syntax(pson) result = '' pson_string = get_pson_string(pson) if str.contains(pson, attr + EQUALS) result := set(pson, attr, value) else if pson_string == '' result := OBJ_BOUNDS_0 + attr + EQUALS + value + OBJ_BOUNDS_1 else result := OBJ_BOUNDS_0 + pson_string + LINE_BREAK + attr + EQUALS + value + OBJ_BOUNDS_1 result else na export get(string pson, string attribute) => result = '' for a in get_iterable(pson) attr = str.substring(a, 0, str.pos(a, EQUALS)) val = str.substring(a, str.pos(a, EQUALS) + 1, str.length(a)) if (attribute == attr) result := val break result // loops from the last added down to the first and removes the attribute, returns updated pson export remove(string pson, string attribute) => result = '' iterable = get_iterable(pson) for i = array.size(iterable) - 1 to 0 by 1 attr_val = array.get(iterable, i) if not str.startswith(attr_val, attribute) continue attr = str.substring(attr_val, 0, str.pos(attr_val, EQUALS)) val = str.substring(attr_val, str.pos(attr_val, EQUALS) + 1, str.length(attr_val)) if (str.contains(pson, LINE_BREAK + attr + EQUALS + val)) result := str.replace(pson, LINE_BREAK + attr + EQUALS + val, '') else result := str.replace(pson, attr + EQUALS + val, '') break result export get_values(string pson) => result = array.new_string(0) for a in get_iterable(pson) val = str.substring(a, str.pos(a, EQUALS) + 1, str.length(a)) array.push(result, val) result export get_number(string pson, string attr) => str.tonumber(get(pson, attr)) export get_int(string pson, string attr) => math.round(get_number(pson, attr)) export get_bool(string pson, string attr) => get(pson, attr) == 'true' export exists(string pson, string key) => str.contains(pson, key + EQUALS) // sample code below if barstate.islast my_object = '{attr={a={b=c:d={e=f}}}:attr1=value1:attr2={obj=val}}' output = get(my_object, 'attr') output := get(output, 'a') // {b=c:d={e=f}} output := get(output, 'd') // {e=f} arr = get_values(my_object) output := '' for v in arr output := output + v + ',' attributes = array.from('attr', 'attr1', 'attr2') values = get_values(my_object) //array.from('{a=b}', '{b=c}', '{d=e}') output := set_values(my_object, attributes, values) // output := add('{}', 'key', 'value') // {key=value} // output := add(output, 'key', 'value1') // {key=value1} // output := add(output, 'key1', 'value2') // {key=value1:key1=value2} // itter = get_iterable(my_object) // output := array.get(itter, 0) // attr={a={b=c:d={e=f}}} output := remove(output, 'attr1') label.new(x=bar_index, y=high, textcolor=color.yellow, text=output, size=size.normal, style=label.style_none) plot(close)
Points
https://www.tradingview.com/script/ogIavEUS-Points/
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 Provides functions for simplifying operations with collections of x+y coordinates. Where x is typically a bar index or time (millisecond) value. library('Points') ////////////////////////////////////////////////// // @function Creates two arrays. One for X (int[]) and another for Y (float[]). // @param size The initial size of the arrays. export new(int size = 0) => [array.new_int(size), array.new_float(size)] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Checks the size of the arrays and if they're equal returns the size. // @param xA The X array. // @param yA The Y array. export size(int[] xA, float[] yA) => if array.size(xA) != array.size(yA) runtime.error('Point arrays are out of sync.') array.size(xA) ////////////////////////////////////////////////// checkBounds(int[] xA, float[] yA, int index) => if size(xA, yA) <= index runtime.error('Requested index is greater than available.') else if index < 0 runtime.error('Index is less than zero.') ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the X and Y values of the arrays at the index. // @param xA The X array. // @param yA The Y array. // @param index The index. // @returns [x, y] export get(int[] xA, float[] yA, int index) => checkBounds(xA, yA, index) [array.get(xA, index), array.get(yA, index)] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Sets the X and Y values of the arrays at the index. // @param xA The X array. // @param yA The Y array. // @param index The index. // @param x The x value. // @param y The y value. // @returns [index, x, y] export set(int[] xA, float[] yA, int index, int x, float y) => checkBounds(xA, yA, index) array.set(xA, index, x) array.set(yA, index, y) [index, x, y] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Adds X and Y values to the end of the arrays (as the last element). // @param xA The X array. // @param yA The Y array. // @param x The x value. // @param y The y value. // @returns [index, x, y] export push(int[] xA, float[] yA, int x, float y) => index = size(xA, yA) array.push(xA, x) array.push(yA, y) [index, x, y] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Adds X and Y values to the beginning of the arrays (as the first element). // @param xA The X array. // @param yA The Y array. // @param x The x value. // @param y The y value. // @returns [index, x, y] export unshift(int[] xA, float[] yA, int x, float y) => size(xA, yA) // validate array.unshift(xA, x) array.unshift(yA, y) [0, x, y] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Inserts X and Y values to the arrays at the index. // @param xA The X array. // @param yA The Y array. // @param index The index to insert at. // @param x The x value. // @param y The y value. // @returns [index, x, y] export insert(int[] xA, float[] yA, int index, int x, float y) => checkBounds(xA, yA, index) array.insert(xA, index, x) array.insert(yA, index, y) [index, x, y] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Inserts the X and Y values into the arrays based upon the X value assuming the the arrays is ordered by X. // @param xA The X array. // @param yA The Y array. // @param x The x value. // @param y The y value. // @returns [index, x, y] export add(int[] xA, float[] yA, int x, float y) => last = size(xA, yA) - 1 if last < 0 push(xA, yA, x, y) else if array.get(xA, last) <= x push(xA, yA, x, y) else done = false last -= 1 while not done and last >= 0 if x < array.get(xA, last) last -= 1 else done := true if last < 0 unshift(xA, yA, x, y) else insert(xA, yA, last + 1, x, y) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Removes the last element from the arrays and returns their value. // @param xA The X array. // @param yA The Y array. // @returns [x, y] export pop(int[] xA, float[] yA) => if size(xA, yA) == 0 [int(na), float(na)] else [array.pop(xA), array.pop(yA)] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Removes the first element from the arrays and returns their value. // @param xA The X array. // @param yA The Y array. // @returns [x, y] export shift(int[] xA, float[] yA) => if size(xA, yA) == 0 [int(na), float(na)] else [array.shift(xA), array.shift(yA)] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Removes the element from the arrays at the index and returns their value. // @param xA The X array. // @param yA The Y array. // @returns [x, y] export remove(int[] xA, float[] yA, int index) => [x, y] = get(xA, yA, index) array.remove(xA, index) array.remove(yA, index) [x, y] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the X and Y values of the first element. // @param xA The X array. // @param yA The Y array. // @returns [x, y] export first(int[] xA, float[] yA) => len = size(xA, yA) if len == 0 [int(na), float(na)] else [array.get(xA, 0), array.get(yA, 0)] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the X and Y values of the last element. // @param xA The X array. // @param yA The Y array. // @returns [x, y] export last(int[] xA, float[] yA) => len = size(xA, yA) if len == 0 [int(na), float(na)] else last = len - 1 [array.get(xA, last), array.get(yA, last)] ////////////////////////////////////////////////// getLastIndex(int[] xA, int start) => size = array.size(xA) if not na(start) if start >= size runtime.error("Value of 'start' is greater than available.") start else size - 1 ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the indexes that have values at or above the low value and below the high value. // @param xA The X array. // @param lo The inclusive low value. // @param hi The excluded hi value. // @param start The optional index to start the backwards search. // @param ordered If true, the search ends when the first value is found that is less than the low. export allIndexesBetween(int[] xA, int lo, int hi, int start = na, bool ordered = false) => int[] indexes = array.new_int() last = na(lo) or na(hi) ? -1 : getLastIndex(xA, start) while last >= 0 x = array.get(xA, last) if x <= lo if ordered last := -1 else if x < hi array.push(indexes, last) last -= 1 array.reverse(indexes) // because unshifting is expensive indexes ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the first found from the end that has a value at or above the low value and below the high value. // @param xA The X array. // @param lo The inclusive low value. // @param hi The excluded hi value. // @param start The optional index to start the backwards search. // @param ordered If true, the search ends when the first value is found that is less than the low. export lastIndexBetween(int[] xA, int lo, int hi, int start = na, bool ordered = false) => int index = -1 last = na(lo) or na(hi) ? -1 : getLastIndex(xA, start) while index == -1 and last >= 0 x = array.get(xA, last) if x <= lo if ordered last := -1 else if x < hi index := last last -= 1 index ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the first found from the end that has a value below the high value. // @param xA The X array. // @param hi The excluded hi value. // @param start The optional index to start the backwards search. export lastIndexBelow(int[] xA, int hi, int start = na) => int index = -1 last = na(hi) ? -1 : getLastIndex(xA, start) while index == -1 and last >= 0 if array.get(xA, last) < hi index := last last -= 1 index //////////////////////////////////////////////////
eHarmonicpatterns
https://www.tradingview.com/script/9l6kN5z2-eHarmonicpatterns/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
94
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 provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations library("eHarmonicpatterns") import HeWhoMustNotBeNamed/arrayutils/20 as pa isInRange(ratio, min, max)=> ratio >= min and ratio <= max isCypherProjection(float xabRatio, float axcRatio, simple float err_min=0.92, simple float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.618 * err_max axcMin = 1.13 * err_min axcMax = 1.414 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(axcRatio, axcMin, axcMax) isCypherPattern(float xabRatio, float axcRatio, float xcdRatio, simple float err_min=0.92, simple float err_max=1.08, enable=true) => xabMin = 0.382 * err_min xabMax = 0.618 * err_max axcMin = 1.13 * err_min axcMax = 1.414 * err_max xcdMin = 0.786 * err_min xcdMax = 0.786 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(axcRatio, axcMin, axcMax) and isInRange(xcdRatio, xcdMin, xcdMax) getNumberOfSupportedPatterns()=>16 // @function Returns the list of supported patterns in order // @param patternLabelArray Supported Patterns export getSupportedPatterns()=> patternLabelArray = array.new_string() array.push(patternLabelArray, "Gartley") array.push(patternLabelArray, "Bat") array.push(patternLabelArray, "Butterfly") array.push(patternLabelArray, "Crab") array.push(patternLabelArray, "DeepCrab") array.push(patternLabelArray, "Cypher") array.push(patternLabelArray, "Shark") array.push(patternLabelArray, "NenStar") array.push(patternLabelArray, "Anti NenStar") array.push(patternLabelArray, "Anti Shark") array.push(patternLabelArray, "Anti Cypher") array.push(patternLabelArray, "Anti Crab") array.push(patternLabelArray, "Anti Butterfly") array.push(patternLabelArray, "Anti Bat") array.push(patternLabelArray, "Anti Gartley") array.push(patternLabelArray, "Navarro200") patternLabelArray // @function Checks if bcd ratio is in range of any harmonic pattern // @param bcdRatio AB/XA ratio // @param err_min minimum error threshold // @param err_max maximum error threshold // @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten. export scan_xab(float xabRatio, simple float err_min, simple float err_max, bool[] patternArray)=> if(array.includes(patternArray, true)) if(xabRatio >=0.276*err_min and xabRatio <=0.886*err_max) is_0_382_to_0_618 = isInRange(xabRatio, 0.382*err_min, 0.618*err_max) is_0_446_to_0_618 = isInRange(xabRatio, 0.446*err_min, 0.618*err_max) is_0_500_to_0_786 = isInRange(xabRatio, 0.500*err_min, 0.786*err_max) is_0_618_to_0_786 = isInRange(xabRatio, 0.618*err_min, 0.786*err_max) //Gartley array.set(patternArray, 0, array.get(patternArray, 0) and isInRange(xabRatio, 0.618*err_min, 0.618*err_max)) //Bat array.set(patternArray, 1, array.get(patternArray, 1) and isInRange(xabRatio, 0.382*err_min, 0.500*err_max)) //Butterfly array.set(patternArray, 2, array.get(patternArray, 2) and isInRange(xabRatio, 0.786*err_min, 0.786*err_max)) //Crab array.set(patternArray, 3, array.get(patternArray, 3) and is_0_382_to_0_618) //DeepCrab array.set(patternArray, 4, array.get(patternArray, 4) and isInRange(xabRatio, 0.886*err_min, 0.886*err_max)) //Cypher array.set(patternArray, 5, array.get(patternArray, 5) and is_0_382_to_0_618) //Shark array.set(patternArray, 6, array.get(patternArray, 6) and is_0_446_to_0_618) //NenStar array.set(patternArray, 7, array.get(patternArray, 7) and is_0_382_to_0_618) //Anti NenStar array.set(patternArray, 8, array.get(patternArray, 8) and is_0_500_to_0_786) //Anti Shark array.set(patternArray, 9, array.get(patternArray, 9) and is_0_446_to_0_618) //Anti Cypher array.set(patternArray, 10, array.get(patternArray, 10) and is_0_500_to_0_786) //Anti Crab array.set(patternArray, 11, array.get(patternArray, 11) and isInRange(xabRatio, 0.276*err_min, 0.446*err_max)) //Anti Butterfly array.set(patternArray, 12, array.get(patternArray, 12) and is_0_382_to_0_618) //Anti Bat array.set(patternArray, 13, array.get(patternArray, 13) and is_0_382_to_0_618) //Anti Gartley array.set(patternArray, 14, array.get(patternArray, 14) and is_0_618_to_0_786) //Navarro200 array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(xabRatio, 0.382*err_min, 0.786*err_max)) else array.fill(patternArray, false) // @function Checks if abc or axc ratio is in range of any harmonic pattern // @param abcRatio BC/AB ratio // @param axcRatio XC/AX ratio // @param err_min minimum error threshold // @param err_max maximum error threshold // @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten. export scan_abc_axc(float abcRatio, float axcRatio, simple float err_min, simple float err_max, bool[] patternArray)=> if(array.includes(patternArray, true)) is_0_382_to_0_886 = isInRange(abcRatio, 0.382*err_min, 0.886*err_max) is_0_467_to_0_707 = isInRange(abcRatio, 0.467*err_min, 0.707*err_max) is_1_128_to_2_618 = isInRange(abcRatio, 1.128*err_min, 2.618*err_max) //Gartley array.set(patternArray, 0, array.get(patternArray, 0) and is_0_382_to_0_886) //Bat array.set(patternArray, 1, array.get(patternArray, 1) and is_0_382_to_0_886) //Butterfly array.set(patternArray, 2, array.get(patternArray, 2) and is_0_382_to_0_886) //Crab array.set(patternArray, 3, array.get(patternArray, 3) and is_0_382_to_0_886) //DeepCrab array.set(patternArray, 4, array.get(patternArray, 4) and is_0_382_to_0_886) //Cypher array.set(patternArray, 5, array.get(patternArray, 5) and isInRange(axcRatio, 1.130*err_min, 1.414*err_max)) //Shark array.set(patternArray, 6, array.get(patternArray, 6) and isInRange(abcRatio, 1.130*err_min, 1.618*err_max)) //NenStar array.set(patternArray, 7, array.get(patternArray, 7) and isInRange(abcRatio, 1.414*err_min, 2.140*err_max)) //Anti NenStar array.set(patternArray, 8, array.get(patternArray, 8) and is_0_467_to_0_707) //Anti Shark array.set(patternArray, 9, array.get(patternArray, 9) and isInRange(abcRatio, 0.618*err_min, 0.886*err_max)) //Anti Cypher array.set(patternArray, 10, array.get(patternArray, 10) and is_0_467_to_0_707) //Anti Crab array.set(patternArray, 11, array.get(patternArray, 11) and is_1_128_to_2_618) //Anti Butterfly array.set(patternArray, 12, array.get(patternArray, 12) and is_1_128_to_2_618) //Anti Bat array.set(patternArray, 13, array.get(patternArray, 13) and is_1_128_to_2_618) //Anti Gartley array.set(patternArray, 14, array.get(patternArray, 14) and is_1_128_to_2_618) //Navarro200 array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(abcRatio, 0.886*err_min, 1.127*err_max)) // @function Checks if bcd ratio is in range of any harmonic pattern // @param bcdRatio CD/BC ratio // @param err_min minimum error threshold // @param err_max maximum error threshold // @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten. export scan_bcd(float bcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=> if(array.includes(patternArray, true)) is_1_618_to_2_618 = isInRange(bcdRatio, 1.618*err_min, 2.618*err_max) is_1_272_to_1_618 = isInRange(bcdRatio, 1.272*err_min, 1.618*err_max) is_1_272_to_2_000 = isInRange(bcdRatio, 1.272*err_min, 2.000*err_max) //Gartley array.set(patternArray, 0, array.get(patternArray, 0) and is_1_272_to_1_618) //Bat array.set(patternArray, 1, array.get(patternArray, 1) and is_1_618_to_2_618) //Butterfly array.set(patternArray, 2, array.get(patternArray, 2) and is_1_618_to_2_618) //Crab array.set(patternArray, 3, array.get(patternArray, 3) and isInRange(bcdRatio, 2.240*err_min, 3.618*err_max)) //DeepCrab array.set(patternArray, 4, array.get(patternArray, 4) and isInRange(bcdRatio, 2.000*err_min, 3.618*err_max)) //Shark array.set(patternArray, 6, array.get(patternArray, 6) and isInRange(bcdRatio, 1.618*err_min, 2.236*err_max)) //NenStar array.set(patternArray, 7, array.get(patternArray, 7) and is_1_272_to_2_000) //Anti NenStar array.set(patternArray, 8, array.get(patternArray, 8) and is_1_618_to_2_618) //Anti Shark array.set(patternArray, 9, array.get(patternArray, 9) and is_1_618_to_2_618) //Anti Cypher array.set(patternArray, 10, array.get(patternArray, 10) and is_1_618_to_2_618) //Anti Crab array.set(patternArray, 11, array.get(patternArray, 11) and is_1_618_to_2_618) //Anti Butterfly array.set(patternArray, 12, array.get(patternArray, 12) and isInRange(bcdRatio, 1.272*err_min, 1.272*err_max)) //Anti Bat array.set(patternArray, 13, array.get(patternArray, 13) and isInRange(bcdRatio, 2.000*err_min, 2.618*err_max)) //Anti Gartley array.set(patternArray, 14, array.get(patternArray, 14) and isInRange(bcdRatio, 1.618*err_min, 1.618*err_max)) //Navarro200 array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(bcdRatio, 0.886*err_min, 3.618*err_max)) // @function Checks if xad or xcd ratio is in range of any harmonic pattern // @param xadRatio AD/XA ratio // @param xcdRatio CD/XC ratio // @param err_min minimum error threshold // @param err_max maximum error threshold // @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten. export scan_xad_xcd(float xadRatio, float xcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=> if(array.includes(patternArray, true)) is_1_618_to_1_618 = isInRange(xadRatio, 1.618*err_min, 1.618*err_max) is_0_786_to_0_786 = isInRange(xadRatio, 0.786*err_min, 0.786*err_max) is_0_886_to_0_886 = isInRange(xadRatio, 0.886*err_min, 0.886*err_max) is_1_272_to_1_272 = isInRange(xadRatio, 1.272*err_min, 1.272*err_max) //Gartley array.set(patternArray, 0, array.get(patternArray, 0) and is_0_786_to_0_786) //Bat array.set(patternArray, 1, array.get(patternArray, 1) and is_0_886_to_0_886) //Butterfly array.set(patternArray, 2, array.get(patternArray, 2) and isInRange(xadRatio, 1.272, 1.618)) //Crab array.set(patternArray, 3, array.get(patternArray, 3) and is_1_618_to_1_618) //DeepCrab array.set(patternArray, 4, array.get(patternArray, 4) and is_1_618_to_1_618) //Cypher array.set(patternArray, 5, array.get(patternArray, 5) and isInRange(xcdRatio, 0.786*err_min, 0.786*err_max)) //Shark array.set(patternArray, 6, array.get(patternArray, 6) and is_0_886_to_0_886) //NenStar array.set(patternArray, 7, array.get(patternArray, 7) and is_1_272_to_1_272) //Anti NenStar array.set(patternArray, 8, array.get(patternArray, 8) and is_0_786_to_0_786) //Anti Shark array.set(patternArray, 9, array.get(patternArray, 9) and isInRange(xadRatio, 1.13*err_min, 1.13*err_max)) //Anti Cypher array.set(patternArray, 10, array.get(patternArray, 10) and is_1_272_to_1_272) //Anti Crab array.set(patternArray, 11, array.get(patternArray, 11) and isInRange(xadRatio, 0.618*err_min, 0.618*err_max)) //Anti Butterfly array.set(patternArray, 12, array.get(patternArray, 12) and isInRange(xadRatio, 0.618, 0.786)) //Anti Bat array.set(patternArray, 13, array.get(patternArray, 13) and isInRange(xadRatio, 1.128*err_min, 1.128*err_max)) //Anti Gartley array.set(patternArray, 14, array.get(patternArray, 14) and isInRange(xadRatio, 1.272*err_min, 1.272*err_max)) //Navarro200 array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(xadRatio, 0.886, 1.127)) // @function Checks for harmonic patterns // @param x X coordinate value // @param a A coordinate value // @param b B coordinate value // @param c C coordinate value // @param d D coordinate value // @param flags flags to check patterns. Send empty array to enable all // @param errorPercent Error threshold // @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names export isHarmonicPattern(float x, float a, float b, float c, float d, simple bool[] flags, simple bool defaultEnabled = true, simple int errorPercent = 8)=> numberOfPatterns = getNumberOfSupportedPatterns() err_min = (100 - errorPercent) / 100 err_max = (100 + errorPercent) / 100 xabRatio = (b - a) / (x - a) abcRatio = (c - b) / (a - b) axcRatio = (c - x) / (a - x) bcdRatio = (d - c) / (b - c) xadRatio = (d - a) / (x - a) xcdRatio = (d - c) / (x - c) patternArray = array.new_bool() for i=0 to numberOfPatterns-1 if(array.size(flags) > i) currentFlag = defaultEnabled? array.size(flags)<=i or array.get(flags, i) : array.size(flags)>i and array.get(flags, i) array.push(patternArray, currentFlag) else array.push(patternArray, false) scan_xab(xabRatio, err_min, err_max, patternArray) scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) scan_bcd(bcdRatio, err_min, err_max, patternArray) scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray) patternArray // @function Checks for harmonic pattern projection // @param x X coordinate value // @param a A coordinate value // @param b B coordinate value // @param c C coordinate value // @param flags flags to check patterns. Send empty array to enable all // @param errorPercent Error threshold // @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names. export isHarmonicProjection(float x, float a, float b, float c, simple bool[] flags, simple bool defaultEnabled = true, simple int errorPercent = 8)=> numberOfPatterns = getNumberOfSupportedPatterns() err_min = (100 - errorPercent) / 100 err_max = (100 + errorPercent) / 100 xabRatio = (b - a) / (x - a) abcRatio = (c - b) / (a - b) axcRatio = (c - x) / (a - x) patternArray = array.new_bool() for i=0 to numberOfPatterns-1 if(array.size(flags) > i) currentFlag = defaultEnabled? array.size(flags)<=i or array.get(flags, i) : array.size(flags)>i and array.get(flags, i) array.push(patternArray, currentFlag) else array.push(patternArray, false) scan_xab(xabRatio, err_min, err_max, patternArray) scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) patternArray export get_projection_range(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent=8, simple float start_adj=0, simple float end_adj=0)=> startRange = array.new_float(array.size(patternArray), na) endRange = array.new_float(array.size(patternArray), na) if(array.includes(patternArray, true)) //Gartley pa.getrange(x, a, 0.786, 0.786, b, c, 1.272, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0) //Bat pa.getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1) //Butterfly pa.getrange(x, a, 1.272, 1.618, b, c, 1.618, 2.618, 0, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2) //Crab pa.getrange(x, a, 1.618, 1.618, b, c, 2.240, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3) //DeepCrab pa.getrange(x, a, 1.618, 1.618, b, c, 2.000, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4) //Cypher pa.getrange(x, c, 0.786, 0.786, x, c, 0.786, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5) //Shark pa.getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6) //NenStar pa.getrange(x, a, 1.272, 1.272, b, c, 1.272, 2.000, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7) //Anti NenStar pa.getrange(x, a, 0.786, 0.786, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8) //Anti Shark pa.getrange(x, a, 1.130, 1.130, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9) //Anti Cypher pa.getrange(x, a, 1.272, 1.272, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10) //Anti Crab pa.getrange(x, a, 0.618, 0.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11) //Anti Butterfly pa.getrange(x, a, 0.618, 0.786, b, c, 1.272, 1.272, 0, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12) //Anti Bat pa.getrange(x, a, 1.128, 1.128, b, c, 2.000, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13) //Anti Gartley pa.getrange(x, a, 1.272, 1.272, b, c, 1.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14) //Navarro200 pa.getrange(x, a, 0.886, 1.127, b, c, 0.886, 3.618, 0, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15) [startRange, endRange] export get_prz_range(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent=8, simple float start_adj=0, simple float end_adj=0)=> [startRange, endRange] = get_projection_range(x,a,b,c,patternArray, errorPercent, start_adj, end_adj) dStart = b > c? array.min(startRange) : array.max(startRange) dEnd = b > c? array.max(endRange) : array.min(endRange) [dStart, dEnd] export get_prz_range_xad(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent=8, simple float start_adj=0, simple float end_adj=0)=> startRange = array.new_float(array.size(patternArray), na) endRange = array.new_float(array.size(patternArray), na) if(array.includes(patternArray, true)) //Gartley pa.getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0) //Bat pa.getrange(x, a, 0.886, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1) //Butterfly pa.getrange(x, a, 1.272, 1.618, 0, start_adj, end_adj, patternArray, startRange, endRange, 2) //Crab pa.getrange(x, a, 1.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3) //DeepCrab pa.getrange(x, a, 1.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4) //Cypher pa.getrange(x, c, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5) //Shark pa.getrange(x, a, 0.886, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6) //NenStar pa.getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7) //Anti NenStar pa.getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8) //Anti Shark pa.getrange(x, a, 1.130, 1.130, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9) //Anti Cypher pa.getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10) //Anti Crab pa.getrange(x, a, 0.618, 0.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11) //Anti Butterfly pa.getrange(x, a, 0.618, 0.786, 0, start_adj, end_adj, patternArray, startRange, endRange, 12) //Anti Bat pa.getrange(x, a, 1.128, 1.128, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13) //Anti Gartley pa.getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14) //Navarro200 pa.getrange(x, a, 0.886, 1.127, 0, start_adj, end_adj, patternArray, startRange, endRange, 15) dStart = b > c? array.min(startRange) : array.max(startRange) dEnd = b > c? array.max(endRange) : array.min(endRange) [dStart, dEnd]
StocksDeveloper_AutoTraderWeb
https://www.tradingview.com/script/q9YHSDBS-StocksDeveloper-AutoTraderWeb/
Pritesh-StocksDeveloper
https://www.tradingview.com/u/Pritesh-StocksDeveloper/
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/ // © Pritesh-StocksDeveloper //@version=5 library("StocksDeveloper_AutoTraderWeb") // IST timezone constant IST = "Asia/Kolkata" // @function Returns current time (HH:mm:ss) in Indian timezone // @returns current time (HH:mm:ss) in Indian timezone export timeIST() => tm = timenow formatted = str.tostring(hour(tm, IST), "00:") + str.tostring(minute(tm, IST), "00:") + str.tostring(second(tm, IST), "00") formatted // @function Additional properties like ticker, price, time etc. // @param comments Comments // @returns additional properties like ticker, time etc. export prepareAdditionalProperties(string comments = "") => ticker = '"ticker": "' + syminfo.ticker + '",' price = '"price": "' + str.tostring(close) + '",' tm = '"time": "' + timeIST() + '",' cm = '"comments": "' + comments + '"' ticker + price + tm + cm // @function Prepare a place order json // @param account Pseudo or Group account number // @param symbol AutoTrader Web's stock/derivative symbol // @param tradeType Trade type [BUY, SELL] // @param group Set it to true if you are using a group account (Default: false) // @param exchange Symbol's exchange [NSE, BSE, MCX] (Default: NSE) // @param quantity Quantity (Default: 1) // @param price Price (Default: 0) // @param orderType Order type [MARKET, LIMIT, STOP_LOSS, SL_MARKET] (Default: MARKET) // @param productType Product type [INTRADAY, DELIVERY, NORMAL] (Default: INTRADAY) // @param triggerPrice Trigger price (Default: 0) // @param variety Variety [REGULAR, BO, CO] (Default: REGULAR) // @param validity Validity [DAY, IOC] (Default: DAY) // @param disclosedQuantity Disclosed quantity (Default: 0) // @param target Target (for Bracket order only) (Default: 0) // @param stoploss Stoploss (for Bracket order only) (Default: 0) // @param trailingStoploss (for Bracket order only) Trailing Stoploss (Default: 0) // @param amo Set it to true for AMO (After Market Order) (Default: false) // @returns A json message for the given order data export preparePlaceOrderJson(string account, string symbol, string tradeType, bool group = false, string exchange = "NSE", int quantity = 1, float price = 0, string orderType = "MARKET", string productType = "INTRADAY", float triggerPrice = 0, string variety = "REGULAR", string validity = "DAY", int disclosedQuantity = 0, float target = 0, float stoploss = 0, float trailingStoploss = 0, bool amo = false) => acc = '"account": "' + account + '",' grp = '"group": ' + str.tostring(group) + ',' vart = '"variety": "' + variety + '",' vald = '"validity": "' + validity + '",' ex = '"exchange": "' + exchange + '",' syb = '"symbol": "' + symbol + '",' tt = '"tradeType": "' + tradeType + '",' ot = '"orderType": "' + orderType + '",' pt = '"productType": "' + productType + '",' qty = '"quantity": ' + str.tostring(quantity) + ',' dqty = '"disclosedQuantity": ' + str.tostring(disclosedQuantity) + ',' prc = '"price": ' + str.tostring(price) + ',' tprc = '"triggerPrice": ' + str.tostring(triggerPrice) + ',' tgt = '"target": ' + str.tostring(target) + ',' sl = '"stoploss": ' + str.tostring(stoploss) + ',' tsl = '"trailingStoploss": ' + str.tostring(trailingStoploss) + ',' am = '"amo": ' + str.tostring(amo) orderJson = '{' + acc + grp + ex + syb + tt + qty + prc + ot + pt + tprc + vart + vald + dqty + tgt + sl + tsl + am +'}' orderJson // @function Prepare a place order alert message using order json array // @param orderJsonArray Order json (can contain one or more orders) // @param comments Comments // @returns A complete alert message to place orders export preparePlaceOrderAlertUsingJson(string orderJsonArray, string comments = "") => props = prepareAdditionalProperties(comments) alertJson = '{ "command": "PLACE_ORDERS", "orders": [' + orderJsonArray + '],' + props + '}' alertJson // @function Prepare a place order alert json message // @param account Pseudo or Group account number // @param symbol AutoTrader Web's stock/derivative symbol // @param tradeType Trade type [BUY, SELL] // @param group Set it to true if you are using a group account (Default: false) // @param exchange Symbol's exchange [NSE, BSE, MCX] (Default: NSE) // @param quantity Quantity (Default: 1) // @param price Price (Default: 0) // @param orderType Order type [MARKET, LIMIT, STOP_LOSS, SL_MARKET] (Default: MARKET) // @param productType Product type [INTRADAY, DELIVERY, NORMAL] (Default: INTRADAY) // @param triggerPrice Trigger price (Default: 0) // @param variety Variety [REGULAR, BO, CO] (Default: REGULAR) // @param validity Validity [DAY, IOC] (Default: DAY) // @param disclosedQuantity Disclosed quantity (Default: 0) // @param target Target (for Bracket order only) (Default: 0) // @param stoploss Stoploss (for Bracket order only) (Default: 0) // @param trailingStoploss (for Bracket order only) Trailing Stoploss (Default: 0) // @param amo Set it to true for AMO (After Market Order) (Default: false) // @param comments Comments // @returns A complete alert message to place orders export preparePlaceOrderAlertMessage(string account, string symbol, string tradeType, bool group = false, string exchange = "NSE", int quantity = 1, float price = 0, string orderType = "MARKET", string productType = "INTRADAY", float triggerPrice = 0, string variety = "REGULAR", string validity = "DAY", int disclosedQuantity = 0, float target = 0, float stoploss = 0, float trailingStoploss = 0, bool amo = false, string comments = "") => orderJson = preparePlaceOrderJson(account, symbol, tradeType, group, exchange, quantity, price, orderType, productType, triggerPrice, variety, validity, disclosedQuantity, target, stoploss, trailingStoploss, amo) alertJson = preparePlaceOrderAlertUsingJson(orderJson, comments) alertJson // @function Prepare a place order alert json message for 2 orders // @param account Pseudo or Group account number // @param symbol AutoTrader Web's stock/derivative symbol // @param tradeType Trade type [BUY, SELL] // @param group Set it to true if you are using a group account (Default: false) // @param exchange Symbol's exchange [NSE, BSE, MCX] (Default: NSE) // @param quantity Quantity (Default: 1) // @param price Price (Default: 0) // @param orderType Order type [MARKET, LIMIT, STOP_LOSS, SL_MARKET] (Default: MARKET) // @param productType Product type [INTRADAY, DELIVERY, NORMAL] (Default: INTRADAY) // @param triggerPrice Trigger price (Default: 0) // @param account2 Pseudo or Group account number [for order 2] // @param symbol2 AutoTrader Web's stock/derivative symbol [for order 2] // @param tradeType2 Trade type [BUY, SELL] [for order 2] // @param group2 Set it to true if you are using a group account (Default: false) [for order 2] // @param exchange2 Symbol's exchange [NSE, BSE, MCX] (Default: NSE) [for order 2] // @param quantity2 Quantity (Default: 1) [for order 2] // @param price2 Price (Default: 0) [for order 2] // @param orderType2 Order type [MARKET, LIMIT, STOP_LOSS, SL_MARKET] (Default: MARKET) [for order 2] // @param productType2 Product type [INTRADAY, DELIVERY, NORMAL] (Default: INTRADAY) [for order 2] // @param triggerPrice2 Trigger price (Default: 0) [for order 2] // @param comments Comments // @returns A complete alert message to place 2 orders export preparePlaceOrderAlertMessageForTwoOrders(string account, string symbol, string tradeType, bool group = false, string exchange = "NSE", int quantity = 1, float price = 0, string orderType = "MARKET", string productType = "INTRADAY", float triggerPrice = 0, string account2, string symbol2, string tradeType2, bool group2 = false, string exchange2 = "NSE", int quantity2 = 1, float price2 = 0, string orderType2 = "MARKET", string productType2 = "INTRADAY", float triggerPrice2 = 0, string comments = "") => orderJson = preparePlaceOrderJson(account = account, symbol = symbol, tradeType = tradeType, group = group, exchange = exchange, quantity = quantity, price = price, orderType = orderType, productType = productType, triggerPrice = triggerPrice) orderJson2 = preparePlaceOrderJson(account = account2, symbol = symbol2, tradeType = tradeType2, group = group2, exchange = exchange2, quantity = quantity2, price = price2, orderType = orderType2, productType = productType2, triggerPrice = triggerPrice2) orderJsonArray = orderJson + ',' + orderJson2 alertJson = preparePlaceOrderAlertUsingJson(orderJsonArray, comments) alertJson // @function Prepare a square-off position json // @param account Pseudo or Group account number // @param symbol AutoTrader Web's stock/derivative symbol // @param group Set it to true if you are using a group account (Default: false) // @param exchange Symbol's exchange [NSE, BSE, MCX] (Default: NSE) // @param category Position category [NET, DAY] // @param type Position type [MIS, CNC, NRML, BO, CO] // @returns A json message for the square-off position request export prepareSqOffPositionJson(string account, string symbol, bool group = false, string exchange = "NSE", string category = "NET", string type = "MIS") => acc = '"account": "' + account + '",' syb = '"symbol": "' + symbol + '",' grp = '"group": ' + str.tostring(group) + ',' ex = '"exchange": "' + exchange + '",' cat = '"category": "' + category + '",' typ = '"type": "' + type + '"' sqOffJson = '{' + acc + syb + grp + ex + cat + typ +'}' sqOffJson // @function Prepare a square-off position alert message using positions json array // @param posJsonArray Position json (can contain one or more positions) // @param comments Comments // @returns A complete alert message to square-off position export prepareSqOffPositionAlertUsingJson(string posJsonArray, string comments = "") => props = prepareAdditionalProperties(comments) alertJson = '{ "command": "SQUARE_OFF_POSITION", "positions": [' + posJsonArray + '],' + props + '}' alertJson // @function Prepare a square-off position alert json message // @param account Pseudo or Group account number // @param symbol AutoTrader Web's stock/derivative symbol // @param group Set it to true if you are using a group account (Default: false) // @param exchange Symbol's exchange [NSE, BSE, MCX] (Default: NSE) // @param category Position category [NET, DAY] // @param type Position type [MIS, CNC, NRML, BO, CO] // @param comments Comments // @returns A complete alert message to square-off position export prepareSqOffPositionAlertMessage(string account, string symbol, bool group = false, string exchange = "NSE", string category = "NET", string type = "MIS", string comments = "") => posJson = prepareSqOffPositionJson(account, symbol, group, exchange, category, type) alertJson = prepareSqOffPositionAlertUsingJson(posJson, comments) alertJson // @function Prepare a square-off position alert json message for two positions // @param account Pseudo or Group account number // @param symbol AutoTrader Web's stock/derivative symbol // @param group Set it to true if you are using a group account (Default: false) // @param exchange Symbol's exchange [NSE, BSE, MCX] (Default: NSE) // @param category Position category [NET, DAY] // @param type Position type [MIS, CNC, NRML, BO, CO] // @param account2 Pseudo or Group account number [for order 2] // @param symbol2 AutoTrader Web's stock/derivative symbol [for order 2] // @param group2 Set it to true if you are using a group account (Default: false) [for order 2] // @param exchange2 Symbol's exchange [NSE, BSE, MCX] (Default: NSE) [for order 2] // @param category2 Position category [NET, DAY] [for order 2] // @param type2 Position type [MIS, CNC, NRML, BO, CO] [for order 2] // @param comments Comments // @returns A complete alert message to square-off of two positions export prepareSqOffPositionAlertMessageForTwoPositions(string account, string symbol, bool group = false, string exchange = "NSE", string category = "NET", string type = "MIS", string account2, string symbol2, bool group2 = false, string exchange2 = "NSE", string category2 = "NET", string type2 = "MIS", string comments = "") => posJson = prepareSqOffPositionJson(account, symbol, group, exchange, category, type) posJson2 = prepareSqOffPositionJson(account2, symbol2, group2, exchange2, category2, type2) posJsonArray = posJson + ',' + posJson2 alertJson = prepareSqOffPositionAlertUsingJson(posJsonArray, comments) alertJson // @function Prepares future symbol for AutoTrader Web // @param underlier Underlier symbol (Ex. BANKNIFTY, USDINR, CRUDEOIL) // @param expiry Expiry date in (DD-MMM-YYYY) format // @returns future symbol as per AutoTrader Web's format export prepareFutureSymbol(string underlier, string expiry) => underlier + '_' + expiry + '_FUT' // @function Prepares option symbol for AutoTrader Web // @param underlier Underlier symbol (Ex. BANKNIFTY, USDINR, CRUDEOIL) // @param expiry Expiry date in (DD-MMM-YYYY) format // @param optionType Option type [CE, PE] // @param strike Strike price // @returns option symbol as per AutoTrader Web's format export prepareOptionSymbol(string underlier, string expiry, string optionType, int strike) => underlier + '_' + expiry + '_' + optionType + '_' + str.tostring(strike) // @function Calculates the closest option strike price as per the given // underlier price // @param underlierPrice The underlier's price // @param gap The gap between option strikes // @returns the closest option strike price export calcClosestStrike(float underlierPrice, int gap) => math.round(underlierPrice / gap) * gap
Debug_Window_Library
https://www.tradingview.com/script/MePT1JFe-Debug-Window-Library/
sp2432
https://www.tradingview.com/u/sp2432/
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/ // © sp2432 //@version=5 // @description Provides a framework for logging debug information to a window on the chart. library("Debug_Window_Library", true) // @function Adds a line of text to the debug window. // @param txt - this is the text to be appended to the window // @param maxLines - Optional - size of the window in lines. Default=15 // @param textColor - Optional - color of the text. Default=color.green. export Log(string txt, int maxLines = 15, color textColor = color.green) => var txts = array.new_string(0,"") var tbl = table.new(position.top_right, 1, 1, bgcolor = color.black, frame_width = 1, frame_color = color.gray) // push it into the array array.push(txts, txt + "\n") // trim the array if needed. if array.size(txts) > maxLines array.shift(txts) table.cell(tbl, 0, 0, array.join(txts)) table.cell_set_text_size(tbl, 0, 0, size.small) table.cell_set_text_color(tbl, 0, 0, textColor) table.cell_set_text_halign(tbl, 0, 0, text.align_left)
StringtoNumber
https://www.tradingview.com/script/5FM8ZSP7-StringtoNumber/
hapharmonic
https://www.tradingview.com/u/hapharmonic/
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/ // © hapharmonic //@version=5 // @description str1 = '12340' , vv = numstrToNum(str1) library("StringtoNumber") // @function X.numstrToNum(TF) // @param x strToNum(Text) // @returns returns numX // some enumerations DECIMAL_POINT = 0.1 MINUS = -1 // error() => // a function to throw an error // label.new(0, close[-1]) // // Here goes all the magic. // // To detect that the last value is a specific digit (or a minus or a decimal point), // we should add any symbol which is definitely not in the string to the end of the string. // I use semicolon (';') for this purpose. // Then we'are trying to replace the group of the digit and semicolon with empty string. // Then we're comparing the new string to the string before replacing. // If the string changed - it means that the last value was the being checked digit. // // NOTE: we cannot try to replace just a digit with an empty string for this purpose, // because replace_all will remove all the digits in the string and we won't be able to understand // what the digit's position was. // cutLastDigit(str) => s = str + ';' r = str.replace_all(s, '1;', '') if r != s [r, 1.] else r = str.replace_all(s, '2;', '') if r != s [r, 2.] else r = str.replace_all(s, '3;', '') if r != s [r, 3.] else r = str.replace_all(s, '4;', '') if r != s [r, 4.] else r = str.replace_all(s, '5;', '') if r != s [r, 5.] else r = str.replace_all(s, '6;', '') if r != s [r, 6.] else r = str.replace_all(s, '7;', '') if r != s [r, 7.] else r = str.replace_all(s, '8;', '') if r != s [r, 8.] else r = str.replace_all(s, '9;', '') if r != s [r, 9.] else r = str.replace_all(s, '0;', '') if r != s [r, 0.] else r = str.replace_all(s, '.;', '') if r != s [r, DECIMAL_POINT] else r = str.replace_all(s, '-;', '') if r != s [r, MINUS] // else // error() // [str, -1] strToNum(str) => fractional = 0. // fractional part of the number integer = 0. // integer part of the number s_new = str position = 0.0 // handled position of the number. sign = 1 // sign of the number. 1.0 is PLUS and -1.0 is MINUS. for i = 0 to 1000 by 1 [s, digit] = cutLastDigit(s_new) // here we'll cut the digits by one from the string till the string is empty. if digit == DECIMAL_POINT // DECIMAL_POINT is found. That means the number has decimal part. order = math.pow(10, i) // convert the decimal part by shifting the accumulated value to (10^i) positions to right fractional := integer / order integer := 0. position := 0 position else if digit == MINUS // MINUS sing is found. sign := MINUS break // I expect that there's nothing after the MINUS ('-') sign. 0. // just a little workaround to help the 'if' to detect returning type. else integer += digit * math.pow(10, position) // it's just a regular digit. position += 1 position if s == '' break s_new := s // If we are here, then there are more digits in the string. Let's handle the next one! s_new sign * (integer + fractional) // We've exited from the loop. Build the returning value. // ============================================================================ // ============================ example of using=============================== // ============================================================================ // let's translate the strings below to numbers export numstrToNum(string Text) => numX = strToNum(Text) numX TF = '240' GETTF = numstrToNum(TF) L = label.new(bar_index, high, '|| numstrToNum :>> || ' + str.tostring(GETTF), style=label.style_label_down,size=size.large) label.delete(L[1])
Last Available Bar Info
https://www.tradingview.com/script/SY2NcvOD-Last-Available-Bar-Info/
CyberMensch
https://www.tradingview.com/u/CyberMensch/
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/ // © paragjyoti2012 //@version=5 // @description : This simple library is built with an aim of getting the last available bar information for the chart. This returns a constant value that doesn't change on bar change. // For backtesting with accurate results on non standard charts, it will be helpful. (Especially if you are using non standard charts like Renko Chart). library("Last_Available_Bar_Info") tf=timeframe.period // Returns Timestamp of the last available bar (Constant) export getLastBarTimeStamp()=> var t=0 bid=ta.barssince(bar_index==0) if(bid) if(t==0) t:=time t // Returns Number of Available Bars on the chart (Constant) export getAvailableBars()=> last_ts=getLastBarTimeStamp() mult=timeframe.multiplier*1000 time_factor=0 tf_str_arr=str.split(tf,"") array.reverse(tf_str_arr) res=array.get(tf_str_arr,0) if(res=="S") time_factor:=mult else if(res=="D") time_factor:=mult*60*24 else if(res=="W") time_factor:=mult*60*24*7 else if(res=="M") time_factor:=mult*60*24*30 else time_factor:=mult*60 delta_time=timenow-last_ts bars=math.floor(delta_time/time_factor) // Example // import paragjyoti2012/Last_Available_Bar_Info/v2 as LastBarInfo // last_bar_timestamp=LastBarInfo.getLastBarTimeStamp() // no_of_bars=LastBarInfo.getAvailableBars() // If you are using Renko Charts, for backtesting, it's necesary to filter out the historical bars that are not of this timeframe. // In Renko charts, once the available bars of the current timeframe (based on your Tradingview active plan) are exhausted, // previous bars are filled in with historical bars of higher timeframe. Which is detrimental for backtesting, and it leads to unrealistic results. // To get the actual number of bars available of that timeframe, you should use this security function to get the timestamp for the last (real) bar available. // tf=timeframe.period // real_available_bars = request.security(syminfo.ticker, tf , LastBarInfo.getAvailableBars() , lookahead = barmerge.lookahead_off) // last_available_bar_timestamp = request.security(syminfo.ticker, tf , LastBarInfo.getLastBarTimeStamp() , lookahead = barmerge.lookahead_off)
library TypeMovingAverages
https://www.tradingview.com/script/ltu8xy8S-library-TypeMovingAverages/
hapharmonic
https://www.tradingview.com/u/hapharmonic/
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/ // © hapharmonic //@version=5 // @description This library function returns a moving average. library("TypeMovingAverages",overlay=false) // @function TODO: add function description here // @returns TODO: MAType //****************************************************************************// //offset=input(title="Alma Offset (only for ALMA)",defval=0.85, step=0.05) offset = 0.85 //volatility_lookback =input(title="Volatility lookback (only for VAMA)",defval=12) volatility_lookback = 13 //i_fastAlpha = input(1.25,"KAMA's alpha (only for KAMA)", minval=1,step=0.25) i_fastAlpha = 1.30 fastAlpha = 2.0 / (i_fastAlpha + 1) slowAlpha = 2.0 / 31 export MA_selector(float src, simple int length, string ma_select, simple int xsmooth) => ma = 0.0 if ma_select == 'SMA' ma := ta.sma(ta.sma(src, length), xsmooth) ma if ma_select == 'EMA' ma := ta.ema(ta.ema(src, length), xsmooth) ma if ma_select == 'WMA' ma := ta.wma(ta.wma(src, length), xsmooth) ma if ma_select == 'HMA' ma := ta.hma(ta.hma(src, length), xsmooth) ma if ma_select == 'JMA' beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2) alpha = beta tmp0 = 0.0 tmp1 = 0.0 tmp2 = 0.0 tmp3 = 0.0 tmp4 = 0.0 tmp0 := (1 - alpha) * src + alpha * nz(tmp0[1]) tmp1 := (src - tmp0[0]) * (1 - beta) + beta * nz(tmp1[1]) tmp2 := tmp0[0] + tmp1[0] tmp3 := (tmp2[0] - nz(tmp4[1])) * (1 - alpha) * (1 - alpha) + alpha * alpha * nz(tmp3[1]) tmp4 := nz(tmp4[1]) + tmp3[0] ma := tmp4 ma if ma_select == 'KAMA' momentum = math.abs(ta.change(src, length)) volatility = math.sum(math.abs(ta.change(src)), length) efficiencyRatio = volatility != 0 ? momentum / volatility : 0 smoothingConstant = math.pow(efficiencyRatio * (fastAlpha - slowAlpha) + slowAlpha, 2) var kama = 0.0 kama := nz(kama[1], src) + smoothingConstant * (src - nz(kama[1], src)) ma := kama ma if ma_select == 'TMA' ma := ta.sma(ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1), xsmooth) ma if ma_select == 'VMA' valpha = 2 / (length + 1) vud1 = src > src[1] ? src - src[1] : 0 vdd1 = src < src[1] ? src[1] - src : 0 vUD = math.sum(vud1, 9) vDD = math.sum(vdd1, 9) vCMO = nz((vUD - vDD) / (vUD + vDD)) VAR = 0.0 VAR := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(VAR[1]) ma := VAR ma if ma_select == 'WWMA' wwalpha = 1 / length WWMA = 0.0 WWMA := wwalpha * src + (1 - wwalpha) * nz(WWMA[1]) ma := WWMA ma if ma_select == 'EMA_NO_LAG' EMA1 = ta.ema(ta.ema(src, length), xsmooth) EMA2 = ta.ema(ta.ema(EMA1, length), xsmooth) Difference = EMA1 - EMA2 ma := EMA1 + Difference ma if ma_select == 'TSF' lrc = ta.linreg(src, length, 0) lrc1 = ta.linreg(src, length, 1) lrs = lrc - lrc1 TSF = ta.linreg(src, length, 0) + lrs ma := TSF ma if ma_select == 'VAMA' // Volatility Adjusted from @fractured mid = ta.ema(ta.ema(src, length), xsmooth) dev = src - mid vol_up = ta.highest(dev, volatility_lookback) vol_down = ta.lowest(dev, volatility_lookback) ma := mid + math.avg(vol_up, vol_down) ma if ma_select == 'SMMA' smma = float(0.0) smaval = ta.sma(ta.sma(src, length), xsmooth) smma := na(smma[1]) ? smaval : (smma[1] * (length - 1) + src) / length ma := smma ma if ma_select == 'DEMA' e1 = ta.ema(ta.ema(src, length), xsmooth) e2 = ta.ema(ta.ema(e1, length), xsmooth) ma := 2 * e1 - e2 ma if ma_select == 'ALMA' ma := ta.alma(src, length, offset, 6) ma ma /////////////////////////////////////////////////////// ////////////////////////Example//////////////////////// /////////////////////////////////////////////////////// // // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // // © hapharmonic // //@version=5 // indicator("Test MATYPE", overlay=true) // import hapharmonic/TypeMovingAverages/3 as MAType // xprd1 = input(title='   💉Fast EMA period', defval=12) // ma_select1 = input.string(title='   ⚖️Fast moving average Type', defval='EMA', options=['SMA', 'EMA', 'WMA', 'HMA', 'JMA', 'KAMA', 'TMA', 'VAMA', 'SMMA', 'DEMA', 'VMA', 'WWMA', 'EMA_NO_LAG', 'TSF', 'ALMA']) // xprd2 = input(title='   💉Fast EMA period', defval=26) // ma_select2 = input.string(title='   ⚖️Fast moving average Type', defval='EMA', options=['SMA', 'EMA', 'WMA', 'HMA', 'JMA', 'KAMA', 'TMA', 'VAMA', 'SMMA', 'DEMA', 'VMA', 'WWMA', 'EMA_NO_LAG', 'TSF', 'ALMA']) // xsmooth = input.int(title='🏄‍♂️Smoothing period (1 = no smoothing)', minval=1, defval=1) // ma_fast = MAType.MA_selector(close, xprd1, ma_select1,xsmooth) // ma_slow = MAType.MA_selector(close, xprd2, ma_select2,xsmooth) // plot(ma_fast, "INDICATOR",color.green) // plot(ma_slow, "INDICATOR",color.red) // /////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////
ConverterTF
https://www.tradingview.com/script/hgJXbapf-ConverterTF/
hapharmonic
https://www.tradingview.com/u/hapharmonic/
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/ // © hapharmonic //@version=5 // @description I have found a bug Regarding the timeframe display, on the chart I have found that the display is numeric, for example 4Hr timeframe instead of '4H', but it turns out to be '240', which I want it to be displayed in abbreviated form. And in all other timeframes it's the same. So this library was created to solve those problems. It converts a timeframe from a numeric string type to an integer type by selecting a timeframe manually and displaying it on the chart. library("ConverterTF") // @function X.GetTF(TF) // @returns String Timeframe >> 1s....1m .... 4h... /// TFCVmulti() => tf = timeframe.multiplier tfstr = "" if timeframe.isseconds tfstr := "s" else if timeframe.isminutes if tf >= 60 tf := tf / 60 tfstr := "h" else tfstr := "m" else if timeframe.isdaily tfstr := "D" else if timeframe.isweekly tfstr := "W" else if timeframe.ismonthly tfstr := "M" [tfstr, str.tostring(tf)] TFCVcustom(float TF , string DWM) => tf = float(na) tfstr = "" if DWM == "D" or DWM == "W" or DWM == "M" tf := TF tfstr := DWM else if TF >= 60 and TF <= 1380 tf := TF / 60 tfstr := "h" else if TF <= 59 tf := TF tfstr := "m" [tfstr, str.tostring(tf)] export CTF(string str) => newStr = str st = str.split(str, '') // SUBtextarray sizeTF = array.size(st)-1 //MAXSIZE typetf = str.replace_all(newStr, array.get(st,sizeTF), "") //= remove DWM //= num DMW = array.get(st,sizeTF) //= DWM if DMW == 'D' or DMW == 'W' or DMW == 'M' newStr := typetf TF = str.tonumber(newStr) tf = string(na) , period = string(na) if str != '' [tf1, period1] = TFCVcustom(TF,DMW) tf:=tf1,period:=period1 else [tf2, period2] = TFCVmulti() tf:=tf2,period:=period2 TimeF = period+tf TimeF str = input.timeframe(title='Time frame', defval='240') TimeF = CTF(str) L=label.new(bar_index, high, 'Before>> Timeframe '+str+'\nAfter>> Timeframe '+TimeF,style=label.style_label_down,size=size.large) label.delete(L[1])
DailyDeviation
https://www.tradingview.com/script/T6yLe3eZ-DailyDeviation/
Electrified
https://www.tradingview.com/u/Electrified/
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/ // © Electrified // @version=5 // @description Helps in determining the relative deviation from the open of the day compared to the high or low values. library("DailyDeviation") import Electrified/SessionInfo/10 as Session import Electrified/DailyLevels/9 as Daily import Electrified/DataCleaner/2 as Data ////////////////////////////////////////////////// // @function Returns a set of arrays representing the daily deviation of price for a given number of days. // @param daysPrior Number of days back to get the close from. // @param maxDeviation Maximum deviation before a value is considered an outlier. A value of 0 will not filter results. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns [OH, OL, OC] Where OH = Open vs High, OL = Open vs Low, and OC = Open vs Close export hlcDeltaArrays( simple int days, simple float maxDeviation = 3, simple string spec = session.regular, simple string res = '1440') => Dopen = Daily.openArray(days, spec, res) Dhigh = Daily.highArray(days, spec, res) Dlow = Daily.lowArray(days, spec, res) Dclose = Daily.closeArray(days, spec, res) OH = array.new_float(days + 1) OL = array.new_float(days + 1) OC = array.new_float(days + 1) int d = 0 while d < days d += 1 o = array.get(Dopen, d) h = array.get(Dhigh, d) l = array.get(Dlow, d) c = array.get(Dclose, d) array.set(OH, d, h - o) array.set(OL, d, o - l) array.set(OC, d, c - o) if maxDeviation == 0 [OH, OL, OC] else [Data.cleanArray(OH, maxDeviation), Data.cleanArray(OL, maxDeviation), Data.cleanArray(OC, maxDeviation)] ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns a value representing the deviation from the open (to the high or low) of the current day given number of days to measure from. // @param daysPrior Number of days back to get the close from. // @param maxDeviation Maximum deviation before a value is considered an outlier. A value of 0 will not filter results. // @param comparison The value use in comparison to the current open for the day. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). export fromOpen( simple int days, simple float maxDeviation = 3, float comparison = close, simple string spec = session.regular, simple string res = '1440') => if na(comparison) or not Session.isIn(spec, res) na else oD = Daily.O() [OH, OL, OC] = hlcDeltaArrays(days, maxDeviation, spec, res) if comparison > oD OHbase = oD + array.avg(OH) Hstdev = array.stdev(OH) d = OHbase + Hstdev if comparison < d (comparison - oD) / (d - oD) else d2 = d + Hstdev 1 + (comparison - d) / Hstdev else if comparison < oD OLbase = oD - array.avg(OL) Lstdev = array.stdev(OL) d = OLbase - Lstdev if comparison > d (comparison - oD) / (oD - d) else d2 = d - Lstdev (comparison - d) / Lstdev - 1 else 0 ////////////////////////////////////////////////// days = input.int(50, "Days to Measure Deviation", minval=2) max = input.float(3, "Data Cleaning: Maximum Deviation", minval=0) dev = fromOpen(days, max) plot(dev, "Deviation From Open", dev<0 ? color.blue : color.yellow, style=plot.style_area) hline(1) hline(2) hline(3) hline(-1) hline(-2) hline(-3)
options_expiration_and_strike_price_calculator
https://www.tradingview.com/script/C5MaWmNv-options-expiration-and-strike-price-calculator/
natronix
https://www.tradingview.com/u/natronix/
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/ // © natronix //@version=5 // @description TODO: add library description here library("options_expiration_and_strike_price_calculator") // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns //plot(datemonth,"exp date") monthexp = month(time) + input(1) dayexp = dayofmonth(time) + input(1) yearexp = year(time) - 2000 plot(yearexp,"expyear") plot(monthexp,"expmonth") plot(dayexp,"expday") //price rounded to nearest whole plus input(1) for strike price //input.symbol(input(QQQ),"ticker", tooltip, inline, group, confirm) symbol =request.security(input("QQQ"),"1",close) strikeprice = math.round(symbol + input(1)) plot(strikeprice,"strike") export fun(float x) => //TODO : add function body and return value here x
Time
https://www.tradingview.com/script/yPDvbkBs-Time/
Electrified
https://www.tradingview.com/u/Electrified/
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/ // © Electrified // @version=5 // @description Utilities for measuring time. library("Time") /////////////////////////////////////////////////// // @function Gets the number of milliseconds per bar. export bar() => var int msPerDay = 1000 * 60 * 60 * 24 var int m = switch timeframe.isdaily => msPerDay timeframe.isweekly => msPerDay * 7 timeframe.ismonthly => msPerDay * 30 timeframe.isseconds => 1000 timeframe.isminutes => 1000 * 60 => na var value = m * timeframe.multiplier value /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Gets the start of the day for the provided time value. // @param datetime The date/time to acquire the date from. // @returns The number of milliseconds representing the date for the given value. export date(int datetime = time) => timestamp(year(datetime), month(datetime), dayofmonth(datetime)) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Gets milliseconds from the start of the day. // @param datetime The date/time to acquire the time of day from. // @returns The number of milliseconds representing time of day. export timeOfDay(int datetime = time) => datetime - date(datetime) /////////////////////////////////////////////////// // Normalizes timespan and timeframe values. adjustTimeframe(simple float timespan, simple string type) => var typeLower = str.lower(type) var ts = switch typeLower 'bar' => 'bars' 'second' => 'seconds' 'minute' => 'minutes' 'day' => 'days' 'week' => 'weeks' 'month' => 'months' 'year' => 'years' => typeLower var dayMultiple = switch ts 'weeks' => 7 'months' => 30 'years' => 365 => 1 var t = dayMultiple == 1 ? ts : 'days' var s = timespan * dayMultiple [s,t] /////////////////////////////////////////////////// // @function Returns the number (float) bars that represents the timespan provided. // @param timespan The number of units to convert to bar count. // @param type The type of units to measure. ('Bar', 'Bars', 'Minute', 'Minutes', 'Day' or 'Days') // @param sessionMinutes Optional override for the number of minutes per session. (Default: Regular = 390, Extended = 1440) // @returns The number bars that represents the timespan provided. export spanToLen(simple float timespan, simple string type, simple int sessionMinutes = na) => var sess_minutes = na(sessionMinutes) ? syminfo.session == session.regular ? 390 : 1440 : sessionMinutes var float minutesPerBar = switch timeframe.isminutes => timeframe.multiplier timeframe.isseconds => timeframe.multiplier / 60 timeframe.isdaily => sess_minutes timeframe.isweekly => sess_minutes * 7 timeframe.ismonthly => sess_minutes * 30 => na [s, t] = adjustTimeframe(timespan, type) switch t 'bars' => s 'seconds' => s / minutesPerBar 'minutes' => s / minutesPerBar 'days' => timeframe.isintraday ? (sess_minutes * s / minutesPerBar) : timeframe.isdaily ? s : timeframe.isweekly ? s / 7 : timeframe.ismonthly ? s / 30 : na => na /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the number (int) bars that represents the timespan provided. // @param timespan The number of units to convert to bar count. // @param type The type of units to measure. ('Bar', 'Minute' or 'Day') // @returns The number bars that represents the timespan provided. export spanToIntLen(simple float timespan, simple string type) => math.ceil(spanToLen(timespan, type)) /////////////////////////////////////////////////// plot(bar())
lib_Indicators_v2_DTU
https://www.tradingview.com/script/IoBwXTJ0-lib-Indicators-v2-DTU/
dturkuler
https://www.tradingview.com/u/dturkuler/
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/ // © dturkuler s_lib_version="2.1" //Version 2.1 //This library includes indicators, snippets from tradingview builtin library, @Rodrigo, @midtownsk8rguy, @Lazybear Special thanks to all of the Pine wizards and others for their contribution with their indicators //You can see the demo of the library by directly adding to the chart //ADD: 23 new indicators added. Most of them are TR builtin indicators (see description in TV builtin Indicators). Newly added indicators are listed below //ADD: New Indicator 'pivothigh(src,BarsLeft,BarsRight=2)' //Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2 //ADD: New Indicator 'pivotlow(src,BarsLeft,BarsRight=2)' //Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2 //ADD: New Indicator 'ranges(src,upper=len, lower=-5)', //ranges of the source. return -1 source<lower, return 1 source>upper otherwise return 0 //ADD: New Indicator 'aroon(len,dir=0)', //aroon indicator. Aroon's major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower //ADD: New Indicator 'adx(dilen=len, adxlen=14)' //adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0) //ADD: New Indicator 'awesome(fast=len=5,slow=34,type=0)' //Awesome Oscilator (AO) is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference //ADD: New Indicator 'cmf(len=20)' //Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20 //ADD: New Indicator 'eom(len=14,div=10000)', //Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default) //ADD: New Indicator 'efi(len)' //Elder's Force Index (EFI) measures the power behind a price movement using price and volume. //ADD: New Indicator 'fn_fisher(len)' //Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data //ADD: New Indicator 'fn_histvol(len)', //Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time. //ADD: New Indicator 'dpo(len)', //Detrended Price Oscilator is used to remove trend from price. //ADD: New Indicator 'klinger(type=len)', //Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal //ADD: New Indicator 'msi(len=10)', //Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time //ADD: New Indicator 'mcginley(src, len)' //McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines //ADD: New Indicator 'sar(start=len, inc=0.02, max=0.02)' //Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02) //ADD: New Indicator 'rvi(src,len)', //The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price. //ADD: New Indicator 'ultimateOsc(len)' //Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes //ADD: New Indicator 'volstop(src,len,atrfactor=2)' //Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1 //ADD: New Indicator 'vwap(src_)', //Volume Weighted Average Price (VWAP) is used to measure the average price weighted by volume //ADD: New Indicator 'cti(src,len)', //Ehler s Correlation Trend Indicator by @midtownsk8rguy. //ADD: New Indicator 'stc(src,len,fast=23,slow=50)', //Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from @lazybear's (thanks) Schaff Trend Cycle script. //ADD: New Indicator 'Original Value', //Return input source value as output //UPD: constants and inputs (ind_src) are updated with new indicators //UPD: indicators descriptions updated //UPD: function outputs with "na" converted to 0 //UPD: input (len:) converted int to float and function codes updated accordingly //UPD: calculation error on fn_factor() corrected //@version=5 //START library Description { //@description This library functions returns included Moving averages, indicators with factorization, functions candles, function heikinashi and more. //Created it to feed as backend of my other indicators/strategies and feel free the use/modify the source. //This is replacement of my previous indicator (lib_indicators_DT) //Additionally library will be updated with more indicators in the future //---------------------- //NOTES: //---------------------- //Indicator functions returns only one series :-( //plotcandle function returns candle [open,high,low,close] series //---------------------- //INDICATOR LIST: //---------------------- //OVERLAY INDICATORS //hide = 'DONT DISPLAY', //Dont display & calculate the indicator. (For my framework usage) //org = 'Original Value', //Return input source value as output //alma = 'alma(src,len,offset=0.85,sigma=6)', //Arnaud Legoux Moving Average //ama = 'ama(src,len,fast=14,slow=100)', //Adjusted Moving Average //acdst = 'accdist()', //Accumulation/distribution index. //cma = 'cma(src,len)', //Corrective Moving average //dema = 'dema(src,len)', //Double EMA (Same as EMA with 2 factor) //ema = 'ema(src,len)', //Exponential Moving Average //gmma = 'gmma(src,len)', //Geometric Mean Moving Average //hghst = 'highest(src,len)', //Highest value for a given number of bars back. //hl2ma = 'hl2ma(src,len)', //higest lowest moving average //hma = 'hma(src,len)', //Hull Moving Average. //lgAdt = 'lagAdapt(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter //lgAdV = 'lagAdaptV(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter variation //lguer = 'laguerre(src,len)', //Ehler's Laguerre filter //lsrcp = 'lesrcp(src,len)', //lowest exponential esrcpanding moving line //lexp = 'lexp(src,len)', //lowest exponential expanding moving line //linrg = 'linreg(src,len,loffset=1)', //Linear regression //lowst = 'lowest(src,len)', //Lovest value for a given number of bars back. //mgi = 'mcginley(src, len)' //McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines //pcnl = 'percntl(src,len)', //percentile nearest rank. Calculates percentile using method of Nearest Rank. //pcnli = 'percntli(src,len)', //percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks. //prev = 'previous(src,len)', //Previous n (len) value of the source //pvth = 'pivothigh(src,BarsLeft=len,BarsRight=2)' //Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2 //pvtl = 'pivotlow(src,BarsLeft=len,BarsRight=2)' //Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2 //rema = 'rema(src,len)', //Range EMA (REMA) //rma = 'rma(src,len)', //Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length. //sar = 'sar(start=len, inc=0.02, max=0.02)' //Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02) //sma = 'sma(src,len)', //Smoothed Moving Average //smma = 'smma(src,len)', //Smoothed Moving Average //supr2 = 'super2(src,len)', //Ehler's super smoother, 2 pole //supr3 = 'super3(src,len)', //Ehler's super smoother, 3 pole //strnd = 'supertrend(src,len,period=3)', //Supertrend indicator //swma = 'swma(src,len)', //Sine-Weighted Moving Average //tema = 'tema(src,len)', //Triple EMA (Same as EMA with 3 factor) //tma = 'tma(src,len)', //Triangular Moving Average //vida = 'vida(src,len)', //Variable Index Dynamic Average //vstop = 'volstop(src,len,atrfactor=2)' //Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1 //vwap = 'vwap(src_)', //Volume Weighted Average Price (VWAP) is used to measure the average price weighted by volume //vwma = 'vwma(src,len)', //Volume Weigted Moving Average //wma = 'wma(src,len)', //Weigted Moving Average // //NON OVERLAY INDICATORS //adx = 'adx(dilen=len, adxlen=14, adxtype=0)' //adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0) //angle = 'angle(src,len)', //angle of the series (Use its Input as another indicator output) //aroon = 'aroon(len,dir=0)', //aroon indicator. Aroon's major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower //atr = 'atr(src,len)', //average true range. RMA of true range. //awsom = 'awesome(fast=len=5,slow=34,type=0)', //Awesome Oscilator is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference //bbr = 'bbr(src,len,mult=1)', //bollinger %% //bbw = 'bbw(src,len,mult=2)', //Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band. //cci = 'cci(src,len)', //commodity channel index //cctbb = 'cctbbo(src,len)', //CCT Bollinger Band Oscilator //chng = 'change(src,len)', //A.K.A. Momentum. Difference between current value and previous, source - source[length]. is most commonly referred to as a rate and measures the acceleration of the price and/or volume of a security //cmf = 'cmf(len=20)', //Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20 //cmo = 'cmo(src,len)', //Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period. //cog = 'cog(src,len)', //The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio. //cpcrv = 'copcurve(src,len)', //Coppock Curve. was originally developed by Edwin "Sedge" Coppock (Barron's Magazine, October 1962). //corrl = 'correl(src,len)', //Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values. //count = 'count(src,len)', //green avg - red avg //cti = 'cti(src,len)', //Ehler s Correlation Trend Indicator by @midtownsk8rguy. //dev = 'dev(src,len)', //ta.dev() Measure of difference between the series and it's ta.sma //dpo = 'dpo(len)', //Detrended Price OScilator is used to remove trend from price. //efi = 'efi(len)', //Elder's Force Index (EFI) measures the power behind a price movement using price and volume. //eom = 'eom(len=14,div=10000)', //Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default) //fall = 'falling(src,len)', //ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output) //fit = 'fisher(len)', //Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data //hvo = 'histvol(len)', //Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time. //kcr = 'kcr(src,len,mult=2)', //Keltner Channels Range //kcw = 'kcw(src,len,mult=2)', //ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel. //kli = 'klinger(type=len)', //Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal //macd = 'macd(src,len)', //MACD (Moving Average Convergence/Divergence) //mfi = 'mfi(src,len)', //Money Flow Index s a tool used for measuring buying and selling pressure //msi = 'msi(len=10)', //Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time //nvi = 'nvi()', //Negative Volume Index //obv = 'obv()', //On Balance Volume //pvi = 'pvi()', //Positive Volume Index //pvt = 'pvt()', //Price Volume Trend //rangs = 'ranges(src,upper=len, lower=-5)', //ranges of the source. src=src, upper=len, v1:lower=upper . returns: -1 source<lower, 1 source>=upper otherwise 0 //rise = 'rising(src,len)', //ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output) //roc = 'roc(src,len)', //Rate of Change //rsi = 'rsi(src,len)', //Relative strength Index //rvi = 'rvi(src,len)', //The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price. //smosc = 'smi_osc(src,len,fast=5, slow=34)', //smi Oscillator //smsig = 'smi_sig(src,len,fast=5, slow=34)', //smi Signal //stc = 'stc(src,len,fast=23,slow=50)', //Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from @lazybear's (thanks) Schaff Trend Cycle script. //stdev = 'stdev(src,len)', //Standart deviation //trix = 'trix(src,len)' , //the rate of change of a triple exponentially smoothed moving average. //tsi = 'tsi(src,len)', //The True Strength Index indicator is a momentum oscillator designed to detect, confirm or visualize the strength of a trend. //ulos = 'ultimateOsc(len)' //Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes //vari = 'variance(src,len)', //ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean. //wilpc = 'willprc(src,len)', //Williams %R //wad = 'wad()', //Williams Accumulation/Distribution. //wvad = 'wvad()' //Williams Variable Accumulation/Distribution. // //} library("lib_Indicators_v2_DTU", overlay = false) //-------------------------- //--------Constants--------- //--------------------------{ hide = 'DONT DISPLAY', //Dont display/calculate the indicator. (For my framework usage) org = 'Original Value', //Return input source value as output ovrly = '▼▼▼ OVERLAY ▼▼▼', //(Not used as indicator, info Only)Just used to separate input options of overlayable indicators alma = 'alma(src,len,offset=0.85,sigma=6)', //Arnaud Legoux Moving Average ama = 'ama(src,len,fast=14,slow=100)', //Adjusted Moving Average acdst = 'accdist()', //Accumulation/distribution index. cma = 'cma(src,len)', //Corrective Moving average dema = 'dema(src,len)', //Double EMA (Same as EMA with 2 factor) ema = 'ema(src,len)', //Exponential Moving Average gmma = 'gmma(src,len)', //Geometric Mean Moving Average hghst = 'highest(src,len)', //Highest value for a given number of bars back. hl2ma = 'hl2ma(src,len)', //higest lowest moving average hma = 'hma(src,len)', //Hull Moving Average. lgAdt = 'lagAdapt(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter lgAdV = 'lagAdaptV(src,len,perclen=5,fperc=50)', //Ehler's Adaptive Laguerre filter variation lguer = 'laguerre(src,len)', //Ehler's Laguerre filter lsrcp = 'lesrcp(src,len)', //lowest exponential esrcpanding moving line lexp = 'lexp(src,len)', //lowest exponential expanding moving line linrg = 'linreg(src,len,loffset=1)', //Linear regression lowst = 'lowest(src,len)', //Lovest value for a given number of bars back. mgi = 'mcginley(src, len)' //McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines pcnl = 'percntl(src,len)', //percentile nearest rank. Calculates percentile using method of Nearest Rank. pcnli = 'percntli(src,len)', //percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks. prev = 'previous(src,len)', //Previous n (len) value of the source pvth = 'pivothigh(src,BarsLeft=len,BarsRight=2)' //Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2 pvtl = 'pivotlow(src,BarsLeft=len,BarsRight=2)' //Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2 rema = 'rema(src,len)', //Range EMA (REMA) rma = 'rma(src,len)', //Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length. sar = 'sar(start=len, inc=0.02, max=0.02)' //Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02) sma = 'sma(src,len)', //Smoothed Moving Average smma = 'smma(src,len)', //Smoothed Moving Average supr2 = 'super2(src,len)', //Ehler's super smoother, 2 pole supr3 = 'super3(src,len)', //Ehler's super smoother, 3 pole strnd = 'supertrend(src,len,period=3)', //Supertrend indicator swma = 'swma(src,len)', //Sine-Weighted Moving Average tema = 'tema(src,len)', //Triple EMA (Same as EMA with 3 factor) tma = 'tma(src,len)', //Triangular Moving Average vida = 'vida(src,len)', //Variable Index Dynamic Average vstop = 'volstop(src,len,atrfactor=2)' //Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1 vwma = 'vwma(src,len)', //Volume Weigted Moving Average wma = 'wma(src,len)', //Weigted Moving Average vwap = 'vwap(src_)', //Volume Weighted Average Price (VWAP) is used to measure the average price weighted by volume nvrly = '▼▼▼ NON OVERLAY ▼▼▼' //(Not used as indicator, info Only)Just used to separate input options of non overlayable indicators adx = 'adx(dilen=len, adxlen=14, adxtype=0)' //adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0) angle = 'angle(src,len)', //angle of the series (Use its Input as another indicator output) aroon = 'aroon(len,dir=0)', //aroon indicator. Aroon's major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower atr = 'atr(src,len)', //average true range. RMA of true range. awsom = 'awesome(fast=len=5,slow=34,type=0)', //Awesome Oscilator is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference bbr = 'bbr(src,len,mult=1)', //bollinger %% bbw = 'bbw(src,len,mult=2)', //Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band. cci = 'cci(src,len)', //commodity channel index cctbb = 'cctbbo(src,len)', //CCT Bollinger Band Oscilator chng = 'change(src,len)', //A.K.A. Momentum. Difference between current value and previous, source - source[length]. is most commonly referred to as a rate and measures the acceleration of the price and/or volume of a security cmf = 'cmf(len=20)', //Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20 cmo = 'cmo(src,len)', //Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period. cog = 'cog(src,len)', //The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio. cpcrv = 'copcurve(src,len)', //Coppock Curve. was originally developed by Edwin "Sedge" Coppock (Barron's Magazine, October 1962). corrl = 'correl(src,len)', //Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values. count = 'count(src,len)', //green avg - red avg cti = 'cti(src,len)', //Ehler s Correlation Trend Indicator by @midtownsk8rguy. dev = 'dev(src,len)', //ta.dev() Measure of difference between the series and it's ta.sma dpo = 'dpo(len)', //Detrended Price OScilator is used to remove trend from price. efi = 'efi(len)', //Elder's Force Index (EFI) measures the power behind a price movement using price and volume. eom = 'eom(len=14,div=10000)', //Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default) fall = 'falling(src,len)', //ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output) fit = 'fisher(len)', //Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data hvo = 'histvol(len)', //Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time. kcr = 'kcr(src,len,mult=2)', //Keltner Channels Range kcw = 'kcw(src,len,mult=2)', //ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel. kli = 'klinger(type=len)', //Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal macd = 'macd(src,len)', //MACD (Moving Average Convergence/Divergence) mfi = 'mfi(src,len)', //Money Flow Index s a tool used for measuring buying and selling pressure msi = 'msi(len=10)', //Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time nvi = 'nvi()', //Negative Volume Index obv = 'obv()', //On Balance Volume pvi = 'pvi()', //Positive Volume Index pvt = 'pvt()', //Price Volume Trend rangs = 'ranges(src,upper=len, lower=-5)', //ranges of the source. src=src, upper=len, v1:lower=upper . returns: -1 source<lower, 1 source>=upper otherwise 0 rise = 'rising(src,len)', //ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output) roc = 'roc(src,len)', //Rate of Change rsi = 'rsi(src,len)', //Relative strength Index rvi = 'rvi(src,len)', //The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price. smosc = 'smi_osc(src,len,fast=5, slow=34)', //smi Ergodic Oscillator smsig = 'smi_sig(src,len,fast=5, slow=34)', //smi Ergodic Signal stc = 'stc(src,len,fast=23,slow=50)', //Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from @lazybear's (thanks) Schaff Trend Cycle script. stdev = 'stdev(src,len)', //Standart deviation trix = 'trix(src,len)' , //TRIX rate of change of a triple exponentially smoothed moving average. tsi = 'tsi(src,len)', //True Strength Index indicator is a momentum oscillator designed to detect, confirm or visualize the strength of a trend. ulos = 'ultimateOsc(len)' //Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes vari = 'variance(src,len)', //ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean. wilpc = 'willprc(src,len)', //Williams %R wad = 'wad()', //Williams Accumulation/Distribution. wvad = 'wvad()' //Williams Variable Accumulation/Distribution. //-------------------------} //-------------------------- //--------Functions--------- //--------------------------{ //--------------------------------------------------------------------------------------------------- //FUNCTIONS WITH EXTENDED PARAMETERS //--------------------------------------------------------------------------------------------------- fn_stc(src, len=10, fast=23, slow=50,factor_=0.5) => // float f1=0,float f2=0, float pf=0, float pff=0 fastMA = ta.ema(src, fast) slowMA = ta.ema(fast, slow) m = fastMA - slowMA v1 = ta.lowest(m, len) v2 = ta.highest(m, len) - v1 f1 := (v2 > 0 ? ((m - v1) / v2) * 100 : nz(f1[1])) pf := (na(pf[1]) ? f1 : pf[1] + (factor_ * (f1 - pf[1]))) v3 = ta.lowest(pf, len) v4 = ta.highest(pf, len) - v3 f2 := (v4 > 0 ? ((pf - v3) / v4) * 100 : nz(f2[1])) pff := (na(pff[1]) ? f2 : pff[1] + (factor_ * (f2 - pff[1]))) pff fn_volStop(src, atrlen, atrfactor=2) => var max = src var min = src var uptrend = true var stop = 0.0 atrM = nz(ta.atr(atrlen) * atrfactor, ta.tr) max := math.max(max, src) min := math.min(min, src) stop := nz(uptrend ? math.max(stop, max - atrM) : math.min(stop, min + atrM), src) uptrend := src - stop >= 0.0 if uptrend != nz(uptrend[1], true) max := src min := src stop := uptrend ? max - atrM : min + atrM // [stop, uptrend] stop average(bp, tr_, length) => math.sum(bp, length) / math.sum(tr_, length) fn_ultimateOsc(len_=7)=> length2 = len_*2 length3 = len_*3 high_ = math.max(high, close[1]) low_ = math.min(low, close[1]) bp = close - low_ tr_ = high_ - low_ avg7 = average(bp, tr_, len_) avg14 = average(bp, tr_, length2) avg28 = average(bp, tr_, length3) out = 100 * (4*avg7 + 2*avg14 + avg28)/7 fn_klinger(type_=0) => //type: 0=klinger, 1=signal var cumVol = 0. cumVol += nz(volume) if barstate.islast and cumVol == 0 runtime.error("No volume is provided by the data vendor.") sv = ta.change(hlc3) >= 0 ? volume : -volume kvo = ta.ema(sv, 34) - ta.ema(sv, 55) sig = ta.ema(kvo, 13) result=type_==0?kvo:sig fn_eom(len=14,div=10000) => var cumVol = 0. cumVol += nz(volume) if barstate.islast and cumVol == 0 runtime.error("No volume is provided by the data vendor.") result = ta.sma(div * ta.change(hl2) * (high - low) / volume, len) fn_cmf(len) => var cumVol = 0. cumVol += nz(volume) if barstate.islast and cumVol == 0 runtime.error("No volume is provided by the data vendor.") ad = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume mf = math.sum(ad, len) / math.sum(volume, len) dirmov(len) => up = ta.change(high) down = -ta.change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) truerange = ta.rma(ta.tr, len) plus = fixnan(100 * ta.rma(plusDM, len) / truerange) minus = fixnan(100 * ta.rma(minusDM, len) / truerange) [plus, minus] fn_adx(dilen_=14, adxlen_=14, adxtype_=0) => [plus, minus] = dirmov(dilen_) sum = plus + minus adx_ = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen_) result=adxtype_==0?adx_:adxtype_==1?plus:minus fn_awesome(fast_=5,slow_=34,type_=0) => ao = ta.sma(hl2,5) - ta.sma(hl2,34) diff = ao - ao[1] result=type_==0?ao:diff fn_aroon(length_,dir_=0) => upper_ = 100 * (ta.highestbars(high, length_+1) + length_)/length_ lower_ = 100 * (ta.lowestbars(low, length_+1) + length_)/length_ mid_ = (upper_+lower_)/2-50 float result=0. result:=dir_==1?upper_:dir_==2?lower_:mid_ //bollinger %% fn_bbr(src_, length_,mult_=1) => dev_ = mult_ * ta.stdev(src_, length_) (src_ - ta.sma(src_, length_) + dev_) / (2 * dev_) fn_alma(src_, length_, AlmaOffset_=0.85, AlmaSigma_=6)=> ta.alma(src_, length_, AlmaOffset_, AlmaSigma_) fn_linreg(src_, length_, LOffset_=1)=> ta.linreg(src_, length_, int(LOffset_)) fn_kcw(src_, length_, mult_=2)=> ta.kcw(src_, length_, mult_) fn_kcr(src_, length_, mult_=2) => range_1 = mult_ * ta.ema(ta.tr, length_) (src_ - ta.ema(src_, length_) - range_1) / (2 * range_1) fn_bbw(src_, length_, mult_=2)=> ta.bbw(src_, length_, mult_) fn_ama(src_, length_, fastLength_=14,slowLength_=100)=> fastAlpha = 2 / (fastLength_ + 1) slowAlpha = 2 / (slowLength_ + 1) hh = ta.highest(length_ + 1) ll = ta.lowest(length_ + 1) mltp = hh - ll != 0 ? math.abs(2 * src_ - ll - hh) / (hh - ll) : 0 ssc_ = mltp * (fastAlpha - slowAlpha) + slowAlpha ama_ = 0.0 ama_ := nz(ama_[1]) + math.pow(ssc_, 2) * (src_ - nz(ama_[1])) fn_supertrend(length_,atrPeriod_=3)=> [sp_,dir_] = ta.supertrend(length_,atrPeriod_) sp_ fn_smiSignal(src_, length_, fastlength_=5, slowlength_=34) => erg = ta.tsi(src_, fastlength_, slowlength_) //indicaot sig = ta.ema(erg, length_) //Signal sig fn_smiOscillator(src_, length_, fastlength_=5, slowlength_=34) => erg = ta.tsi(src_, fastlength_, slowlength_) //indicaot sig = ta.ema(erg, length_) //Signal osc = erg - sig //Oscillator osc //Ehler's Adaptive Laguerre filter fn_lagAdapt(src_, length_,LAPercLen_=5,FPerc_=50) => y = float(na) alpha = float(na) error = math.abs(src_ - nz(y[1])) le_=ta.lowest(error, length_) he_=ta.highest(error, length_) range_2 = he_ - le_ perc = range_2 != 0 ? (error - le_) / range_2 : nz(alpha[1]) alpha := ta.percentile_nearest_rank(perc, int(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 y //Ehler's Adaptive Laguerre filter variation fn_lagAdaptV(src_, length_,LAPercLen_=5,FPerc_=50) => y = float(na) alpha = float(na) error = math.abs(src_ - nz(y[1])) le_=ta.lowest(error, length_) he_=ta.highest(error, length_) range_3 = he_- le_ perc = range_3 != 0 ? (error - le_) / range_3 : nz(alpha[1]) alpha := ta.percentile_linear_interpolation(perc, int(LAPercLen_), int(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 y //--------------------------------------------------------------------------------------------------- //FUNCTIONS WITHOUT EXTENDED PARAMETERS //--------------------------------------------------------------------------------------------------- fn_VWAP(src) => 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] // sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1] _vwap = sumSrcVol / sumVol variance = sumSrcSrcVol / sumVol - math.pow(_vwap, 2) variance := variance < 0 ? 0 : variance stDev = math.sqrt(variance) // lowerBand = _vwap - stDev * stDevMultiplier // upperBand = _vwap + stDev * stDevMultiplier _vwap fn_cti(src_, length_) => // Ehler's Correlation Trend Function by @midtownsk8rguy period = math.max(2, int(length_)) Ex = 0.0, Ey = 0.0, Ex2 = 0.0, Ey2 = 0.0, Exy = 0.0 for i=0 to length_-1 X = nz(src_[i]) Y = -i Ex := Ex + X Ex2 := Ex2 + X * X Exy := Exy + X * Y Ey2 := Ey2 + Y * Y Ey := Ey + Y denominator = (length_ * Ex2 - Ex * Ex) * (length_ * Ey2 - Ey * Ey) denominator==0.0 or bar_index==0 ? 0.0 : (length_ * Exy - Ex * Ey) / math.sqrt(denominator) fn_massIndex(len=10)=> span = high - low mi = math.sum(ta.ema(span, 9) / ta.ema(ta.ema(span, 9), 9), len) fn_rvi(src_, length_) => len = 14 stddev = ta.stdev(src_, length_) upper = ta.ema(ta.change(src_) <= 0 ? 0 : stddev, len) lower = ta.ema(ta.change(src_) > 0 ? 0 : stddev, len) rvi_ = upper / (upper + lower) * 100 fn_mcGinley(src_, length_) => mg = 0.0 mg := na(mg[1]) ? ta.ema(src_, length_) : mg[1] + (src_ - mg[1]) / (length_ * math.pow(src_/mg[1], 4)) fn_dpo(len=14) => barsback = len/2 + 1 ma = ta.sma(close, len) dpo_ = close - ma[barsback] fn_histvol(length_)=> annual = 365 per = timeframe.isintraday or timeframe.isdaily and timeframe.multiplier == 1 ? 1 : 7 hv = 100 * ta.stdev(math.log(close / close[1]), length_) * math.sqrt(annual / per) fn_round_(val) => val > .99 ? .999 : val < -.99 ? -.999 : val fn_fisher(length_=9)=> high_ = ta.highest(hl2, length_) low_ = ta.lowest(hl2, length_) value = 0.0 value := fn_round_(.66 * ((hl2 - low_) / (high_ - low_) - .5) + .67 * nz(value[1])) fish1 = 0.0 fish1 := .5 * math.log((1 + value) / (1 - value)) + .5 * nz(fish1[1]) fn_efi(length_=13)=> var cumVol = 0. cumVol += nz(volume) if barstate.islast and cumVol == 0 runtime.error("No volume is provided by the data vendor.") result = ta.ema(ta.change(close) * volume, length_) fn_count(src_, length_) => red_count = 0 red_src = 0.0 green_count = 0 green_src = 0.0 for i = 0 to length_ by 1 if close[i] < open[i] red_count := red_count + 1 red_src := red_src + src_[i] red_src if close[i] > open[i] green_count := green_count + 1 green_src := green_src + src_[i] green_src green_ave = green_src / green_count red_ave = red_src / red_count green_ave - red_ave fn_dema(src_, length_) => ema1 = ta.ema(src_, length_) ema2 = ta.ema(ema1, length_) 2 * ema1 - ema2 fn_tema(src_, length_) => ema1 = ta.ema(src_, length_) ema2 = ta.ema(ema1, length_) ema3 = ta.ema(ema2, length_) 3 * (ema1 - ema2) + ema3 fn_cctbbo(src_, length_) => deviation = ta.stdev(src_, length_) smooth = ta.sma(src_, length_) (src_ + 2 * deviation - smooth) / (4 * deviation) - 0.4 //Ehler's super smoother, 2 pole fn_super2(src_, length_) => y = float(na) PI_=3.145926 a1 = math.exp(-math.sqrt(2) * PI_ / length_) b1 = 2 * a1 * math.cos(math.sqrt(2) * PI_ / length_) coef2 = b1 coef3 = -math.pow(a1, 2) coef1 = 1 - coef2 - coef3 y := coef1 * (src_ + nz(src_[1], src_)) / 2 + coef2 * nz(y[1]) + coef3 * nz(y[2]) y //Ehler's super smoother, 3 pole fn_super3(src_, length_) => y = float(na) PI_=3.145926 a1 = math.exp(-PI_ / length_) b1 = 2 * a1 * math.cos(1.738 * PI_ / length_) c1 = math.pow(a1, 2) coef2 = b1 + c1 coef3 = -c1 * (1 + b1) coef4 = c1 * c1 coef1 = 1 - coef2 - coef3 - coef4 y := coef1 * (src_ + nz(src_[1], src_)) / 2 + coef2 * nz(y[1]) + coef3 * nz(y[2]) + coef4 * nz(y[3]) y fn_willprc(src_, length_) => max = ta.highest(length_) min = ta.lowest(length_) 100 * (src_ - max) / (max - min) fn_trix(src_, length_) => 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(src_), length_), length_), length_)) //lowest exponential expanding moving line fn_lexp(src_, length_) => y = float(na) y := na(y[1]) ? src_ : src_ <= y[1] ? src_ : y[1] + (src_ - y[1]) / length_ y //Ehler's Laguerre filter fn_laguerre(src_, length_) => y = float(na) alpha = math.exp((1 - length_) / 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 y //lowest exponential esrcpanding moving line fn_lesrcp(src_, length_) => y = float(na) y := na(y[1]) ? src_ : src_ <= y[1] ? src_ : y[1] + (src_ - y[1]) / length_ y //---Smoothed Moving Average (SMMA) fn_smma(src,l)=> smmaMA = 0.0 sma_=ta.sma(src, l) smmaMA := na(smmaMA[1]) ? sma_ : (smmaMA[1] * (l - 1) + src) / l smmaMA //---Sine-Weighted Moving Average (SW-MA) fn_swma(src,l) => PI_ = 2 * math.asin(1) sum = 0.0 weightSum = 0.0 for i = 0 to l - 1 weight = math.sin((i + 1) * PI_ / (l + 1)) sum := sum + nz(src[i]) * weight weightSum := weightSum + weight sineWeightMA = sum / weightSum sineWeightMA //---Triangular Moving Average (TMA) fn_tma(src,l) => triMA = ta.sma(ta.sma(src, math.ceil(l / 2)), math.floor(l / 2) + 1) triMA //Geometric Mean Moving Average (GMMA) fn_gmma(src,l) => lmean = math.log(src) smean = math.sum(lmean,l) geoMA = math.exp(smean/l) geoMA //---Variable Index Dynamic Average (VIDA) fn_vida(src,l) => mom_ = ta.change(src) upSum = math.sum(math.max(mom_, 0), l) downSum = math.sum(-math.min(mom_, 0), l) cmo_ = math.abs((upSum - downSum) / (upSum + downSum)) F = 2/(l+1) vida_ = 0.0 vida_ := src * F * cmo_ + nz(vida_[1]) * (1 - F * cmo_) vida_ //---Corrective Moving average (CMA) fn_cma(src,l) => sma_ = ta.sma(src, l) cma_ = sma_ v1 = ta.variance(src, l) 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 if err > tolerance k := v3 * kPrev * (2 - kPrev) err := kPrev - k kPrev := k cma_ := nz(cma_[1], src) + k * (sma_ - nz(cma_[1], src)) cma_ //---Range EMA (REMA) fn_range_ema (src,l) => alpha = 2/(1 + l) 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]) ma = num/den ma fn_angle(_src1,_src2) => rad2degree=180/3.14159265359 //pi float ang=(rad2degree*math.atan((_src1 - _src2)/ta.atr(14)) ) result=ang //--------------------------} //-------------------------- //--------Exported Functions //--------------------------{ // @function f_func Return selected indicator value with different parameters. New version. Use extra parameters for available indicators // @param string FuncType_ indicator from the indicator list // @param float src_ close, open, high, low,hl2, hlc3, ohlc4 or any [series] // @param simple int length_ indicator length // @param float p1 extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p2 extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p3 extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param simple int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators // @returns float [series] Return calculated indicator value export f_func(simple string function_, float src_, simple float length_, simple float p1_=0, simple float p2_=0, simple float p3_=0, simple int version_=1) => float a=p1_*p2_*p3_*0 //used for passing the TV error: argument is not used. All args should be used. int length__=int(length_) float y = switch function_ stc => version_!=2?fn_stc(src_, length__):fn_stc(src=src_, len=length__, fast=int(p1_), slow=int(p2_),factor_=0.5) cti => fn_cti(src_, length__) vwap => fn_VWAP(src_) vstop => version_!=2?fn_volStop(src_, length__):fn_volStop(src_, length__, atrfactor=p1_) ulos => fn_ultimateOsc(length__) rvi => fn_rvi(src_, length__) sar => version_!=2?ta.sar(start=length_, inc=0.02, max=0.02):ta.sar(start=length_, inc=p1_, max=p2_) mgi => fn_mcGinley(src_, length__) msi => fn_massIndex(len=length__) kli => fn_klinger(type_=length__) dpo => fn_dpo(len=length__) hvo => fn_histvol(length__) fit => fn_fisher(length__) efi => fn_efi(length__) eom => version_!=2?fn_eom(length__):fn_eom(length__,div=p1_) cmf => fn_cmf(length__) awsom => version_!=2?fn_awesome(fast_=length__):fn_awesome(fast_=length__,slow_=int(p1_),type_=int(p2_)) adx => version_!=2?fn_adx(length__):fn_adx(length__,int(p1_),int(p2_)) aroon => version_!=2?fn_aroon(length__):fn_aroon(length__,p1_) rangs => version_!=2?(src_>=length_?1:src_<length_?-1:0):(src_>=length_?1:src_<p1_?-1:0) pvth => version_!=2?ta.pivothigh(src_,length_,2):ta.pivothigh(src_,length_,p1_) pvtl => version_!=2?ta.pivotlow(src_,length_, 2):ta.pivotlow(src_,length_, p1_) acdst => ta.accdist alma => version_!=2?fn_alma(src_, length__) : fn_alma(src_, length__,p1_, p2_) ama => version_!=2?fn_ama(src_, length__):fn_ama(src_, length__, int(p1_), int(p2_)) angle => fn_angle(src_, src_[length_]) atr => ta.atr(length__) bbr => version_!=2?fn_bbr(src_, length__):fn_bbr(src_, length__,p1_) bbw => version_!=2?fn_bbw(src_, length__): fn_bbw(src_, length__, p1_) cci => ta.cci(src_, length__) cctbb => fn_cctbbo(src_, length__) chng => ta.change(src_, length__) cma => fn_cma(src_, length__) cmo => ta.cmo(src_, length__) cog => ta.cog(src_, length__) corrl => version_!=2?ta.correlation(src_, src_[1], length__):ta.correlation(src_, src_[int(p1_)], length__) count => fn_count(src_, length_) cpcrv => version_!=2?ta.wma(ta.roc(src_, 34) + ta.roc(src_, 5), length__):ta.wma(ta.roc(src_, int(p2_)) + ta.roc(src_, int(p1_)), length__) dema => fn_dema(src_, length__) dev => ta.dev(src_, length__) ema => ta.ema(src_, length__) fall => ta.falling(src_, length__)?1:-1 gmma => fn_gmma(src_, length__) hghst => ta.highest(src_,length__) hide => src_ + a hl2ma => (ta.highest(src_, length__) + ta.lowest(src_, length__)) / 2 hma => ta.hma(src_, length__) kcr => version_!=2?fn_kcr(src_, length__) : fn_kcr(src_, length__,p1_) kcw => version_!=2?fn_kcw(src_, length__) : fn_kcw(src_, length__,p1_) lexp => fn_lexp(src_, length_) lgAdV => version_!=2?fn_lagAdaptV(src_, length__):fn_lagAdaptV(src_, length__, p1_, p2_) lgAdt => version_!=2?fn_lagAdapt(src_, length__):fn_lagAdapt(src_, length__, p1_, p2_) lguer => fn_laguerre(src_, length_) linrg => version_!=2?fn_linreg(src_, length__) : fn_linreg(src_, length__,p1_) lowst => ta.lowest(src_,length__) lsrcp => fn_lesrcp(src_, length_) macd => ta.sma(src_, length__) - ta.sma(src_, 2 * length__) mfi => ta.mfi(src_, length__) nvi => ta.nvi obv => ta.obv pcnl => version_!=2?ta.percentile_nearest_rank(src_, length__, 50):ta.percentile_nearest_rank(src_, length__, p1_) pcnli => version_!=2?ta.percentile_linear_interpolation(src_, length__, 50):ta.percentile_linear_interpolation(src_, length__, p1_) prev => src_[length_] pvi => ta.pvi pvt => ta.pvt rema => fn_range_ema(src_, length_) rise => ta.rising(src_, length__)?1:-1 rma => ta.rma(src_, length__) roc => ta.roc(src_, length__) rsi => ta.rsi(src_, length__) sma => ta.sma(src_, length__) smma => fn_smma(src_, length__) smosc => version_!=2?fn_smiOscillator(src_, length__):fn_smiOscillator(src_, length__, int(p1_), int(p2_)) smsig => version_!=2?fn_smiSignal(src_, length__):fn_smiSignal(src_, length__, int(p1_), int(p2_)) stdev => ta.stdev(src_, length__) strnd => version_!=2?fn_supertrend(length_):fn_supertrend(length_,int(p1_)) supr2 => fn_super2(src_, length_) supr3 => fn_super3(src_, length_) swma => fn_swma(src_, length_) tema => fn_tema(src_, length__) tma => fn_tma(src_, length_) trix => fn_trix(src_, length__) tsi => version_!=2?ta.tsi(src_, 5, 34):ta.tsi(src_, int(p1_), int(p2_)) vari => ta.variance(src_, length__) vida => fn_vida(src_, length__) vwma => ta.vwma(src_, length__) wad => ta.wad wilpc => fn_willprc(src_, length__) wma => ta.wma(src_, length__) wvad => ta.wvad org => src_ => na y:=na(y)?0:y y // @function fn_heikin Return given src data (open, high,low,close) as heikin ashi candle values // @param float o_ open value // @param float h_ high value // @param float l_ low value // @param float c_ close value // @returns float [series, series,series,series] heikin ashi open, high,low,close vlues that will be used with plotcandle export fn_heikin(float o_=open, float h_=high, float l_=low, float c_=close) => Close = math.avg(o_,h_,l_,c_) Open = float(na) Open := na(Open[1]) ? (o_ + c_) / 2 : (nz(Open[1]) + nz(Close[1])) / 2 High = math.max(h_, math.max(Open, Close)) Low = math.min(l_, math.min(Open, Close)) Open := math.round(Open / syminfo.mintick) * syminfo.mintick High := math.round(High / syminfo.mintick) * syminfo.mintick Low := math.round(Low / syminfo.mintick) * syminfo.mintick Close := math.round(Close / syminfo.mintick) * syminfo.mintick [Open, High, Low, Close] // @function fn_plotFunction Return input src data with different plotting options // @param float src_ indicator src_data or any other series..... // @param string plotingType Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)'] // @param simple int stochlen_ length for plotingType for stochastic and PercentRank options // @param bool plotSWMA Use SWMA for smoothing Ploting // @returns float [series] export fn_plotFunction(float src_, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false) => f_plot_= switch plotingType_ "Stochastic" => ta.stoch(src_, src_, src_, stochlen_) / 50 - 1 "PercentRank" => ta.percentrank(src_, stochlen_) / 50 - 1 "Original" => src_ "Org. Range (-1,1)" => src_ => src_ if plotSWMA_ f_plot_:= ta.swma(f_plot_) f_plot_ // @function fn_funcPlotV2 Return selected indicator value with different parameters. New version. Use extra parameters fora available indicators // @param string FuncType_ indicator from the indicator list // @param float src_data_ close, open, high, low,hl2, hlc3, ohlc4 or any [series] // @param simple int length_ indicator length // @param float p1 extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p2 extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p3 extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param simple int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators // @param string plotingType Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)'] // @param simple int stochlen_ length for plotingType for stochastic and PercentRank options // @param bool plotSWMA Use SWMA for smoothing Ploting // @param bool log_ Use log on function entries // @returns float [series] Return calculated indicator value export fn_funcPlotV2(simple string FuncType_="Hide", float src_data_=close, simple float length_=14, simple float p1=0, simple float p2=0, simple int version_=2, simple float p3=0, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false, simple string log_="None") => src_data__=log_=="Simple" ? math.log(src_data_) : log_=="Log10" ? math.log10(src_data_) : src_data_ src_=f_func(FuncType_, src_data__, length_,p1,p2,p3,version_=version_) f_plot_=fn_plotFunction(src_=src_, plotingType_=plotingType_, stochlen_=stochlen_, plotSWMA_ = plotSWMA_) // @function fn_factor Return selected indicator's factorization with given arguments // @param string FuncType_ indicator from the indicator list // @param float src_data_ close, open, high, low,hl2, hlc3, ohlc4 or any [series] // @param simple int length_ indicator length // @param float p1 parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p2 parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p3 parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param simple int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators // @param simple int fact_ Add double triple, Quatr factor to selected indicator (like converting EMA to 2-DEMA, 3-TEMA, 4-QEMA...) // @param string plotingType Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)'] // @param simple int stochlen_ length for plotingType for stochastic and PercentRank options // @param bool plotSWMA Use SWMA for smoothing Ploting // @param bool log_ Use log on function entries // @returns float [series] Return result of the function export fn_factor(simple string FuncType_="Hide", float src_data_=close, simple float length_=14, simple float p1=0, simple float p2=0, simple float p3=0, simple int version_=2, simple int fact_=1, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false, simple string log_="None")=> float result=0 if FuncType_!=hide float xIND1 = 0, float xIND2 = 0,float xIND3 = 0, float xIND4 = 0, float xIND5 = 0 xIND1 := fn_funcPlotV2(FuncType_, src_data_,length_=length_, p1=p1, p2=p2, p3=p3, version_=version_) if fact_>1 xIND2 := fn_funcPlotV2(FuncType_,xIND1, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_) if fact_>2 xIND3 := fn_funcPlotV2(FuncType_,xIND2, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_) if fact_>3 xIND4 := fn_funcPlotV2(FuncType_,xIND3, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_) xIND5 := fn_funcPlotV2(FuncType_,xIND4, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_) indfact_ = switch fact_ 1 => xIND1 2 => (2 * xIND1) - xIND2 3 => 3 * (xIND1 - xIND2) + xIND3 4 => 5 * xIND1 - 10 * xIND2 + 10 * xIND3 - 5 * xIND4 + xIND5 result := fn_funcPlotV2(org, indfact_,length_=length_, version_=1, plotingType_=plotingType_, stochlen_=stochlen_, plotSWMA_=plotSWMA_, log_=log_) result // @function fn_plotCandles Return selected indicator's candle values with different parameters also heikinashi is available // @param string FuncType_ indicator from the indicator list // @param simple int length_ indicator length // @param float p1 parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p2 parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param float p3 parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) // @param simple int version_ indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators // @param string plotingType Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)'] // @param simple int stochlen_ length for plotingType for stochastic and PercentRank options // @param bool plotSWMA Use SWMA for smoothing Ploting // @param bool log_ Use log on function entries // @param bool plotheikin_ Use Heikin Ashi on Plot // @returns float [series] export fn_plotCandles(simple string FuncType_,simple float len_, simple float p1=0, simple float p2=0, simple float p3=0, simple int version_=2, simple int fact_=1, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false, simple string log_="None", bool plotheikin_=false,float oIn_=open,float hIn_=high, float lIn_=low, float cIn_=close )=> oOut_=0.0, hOut_=0.0, lOut_=0.0, cOut_=0.0 bool palette_=false if FuncType_!=hide oOut_:=fn_factor(FuncType_=FuncType_, src_data_=oIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_, plotSWMA_=plotSWMA_, log_=log_) hOut_:=fn_factor(FuncType_=FuncType_, src_data_=hIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_, plotSWMA_=plotSWMA_, log_=log_) lOut_:=fn_factor(FuncType_=FuncType_, src_data_=lIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_, plotSWMA_=plotSWMA_, log_=log_) cOut_:=fn_factor(FuncType_=FuncType_, src_data_=cIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_, plotSWMA_=plotSWMA_, log_=log_) palette_ := cOut_[1] <= cOut_ ? true : false if plotheikin_ [oOut__,hOut__,lOut__,cOut__]=fn_heikin(o_=oOut_, h_=hOut_, l_=lOut_, c_=cOut_) oOut_:=oOut__, hOut_:=hOut__, lOut_:=lOut__, cOut_:=cOut__ [oOut_,hOut_,lOut_,cOut_, palette_] //--------------------------} //---------------------------------------------------------------------------------------------------------------------------------- //--------DEMO---------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------{ //Indicators that returned plot function values float f_indicator1=0 float f_indicator2=0 float ext_data = input.source( defval=close, title='External Indicator') //Function returns source values from given input //Ex: ind_data =input.string(defval="close", title='',options=["close", "open", "high", "low","hl2", "hlc3", "ohlc4","IND1"]) fn_get_source(string source_) => result = switch source_ "close" => close "open" => open "high" => high "low" => low "hl2" => hl2 "hlc3" => hlc3 "ohlc4" => ohlc4 "volume" => volume "EXT" => ext_data "IND1" => f_indicator1 //ex:return calculated indicator or another source entry for using in new calculation "IND2" => f_indicator2 //ex:return calculated indicator or another source entry for using in new calculation =>na result //--------------------------} //---------------------------------------------------------------------------------------------------------------------------------------- //INDICATOR 1----------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------- s_grp_indicator1="════════════ INDICATOR 1 ════════════" s_ind1_src= input.string( defval=ema, title='IND1:', options=[hide, org, ovrly, alma, ama , acdst, cma, dema, ema, gmma, hghst, hl2ma, hma, lgAdt, lgAdV, lguer, lsrcp, lexp, linrg, lowst, mgi,pcnl, pcnli, prev , pvth, pvtl, rema, rma, sar, sma, smma, supr2, supr3, strnd, swma, tema, tma, vida, vwma, vstop, wma, vwap, nvrly, adx, angle, aroon, atr, awsom, bbr, bbw, cci, cctbb, chng, cmf, cmo, cog, cpcrv, corrl, count, cti, dev, dpo, efi, eom, fall, fit, hvo, kcr, kcw, kli, macd, mfi, msi, nvi, obv, pvi, pvt, rangs, rise, roc, rsi, rvi, smosc, smsig, stc, stdev, trix, tsi, vari, wilpc, wad, wvad] , group=s_grp_indicator1, inline="ind1") s_ind1_data = input.string( defval="close", title='', options=["close", "open", "high", "low","hl2", "hlc3", "ohlc4", "volume", "EXT"] , group= s_grp_indicator1, inline="ind1") f_ind1_len = input.float( defval=14, title='Len', group=s_grp_indicator1, inline="ind1") i_ind1_ver = input.int( defval=1, title='V', group=s_grp_indicator1, inline="ind2", minval=1, maxval=2) f_ind1_p1 = input.float( defval=0, title='P1', group=s_grp_indicator1, inline="ind2") f_ind1_p2 = input.float( defval=0, title='P2', group=s_grp_indicator1, inline="ind2") i_ind1_fact = input.int( defval=1, title='factor', group=s_grp_indicator1, inline="ind4", minval=1,maxval=4) s_ind1_log = input.string( defval="None", title='Log', group=s_grp_indicator1, inline="ind4", options=['None', 'Simple', 'Log10']) s_ind1_pType = input.string( defval="Original", title="PType", group=s_grp_indicator1, inline="ind3", options=['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)']) i_ind1_stlen = input.int( defval=50, title='St/% val', group=s_grp_indicator1, inline="ind3") b_ind1_pSWMA= input.bool( defval=false, title="Smooth", group=s_grp_indicator1, inline="ind3") c_ind1_color = input( defval=color.green, title="", group=s_grp_indicator1, inline="ind3") b_plt1_candle = input.bool( defval=true, title='Plot Candle',group=s_grp_indicator1, inline="plt") b_plt1_ind = input.bool( defval=true, title='Plot Ind', group=s_grp_indicator1, inline="plt") b_plt1_heikin = input.bool( defval=false, title='HeikinAshi', group=s_grp_indicator1, inline="plt") //f_ind1_p3 = input.float( defval=0, title='P3', group=s_grp_indicator1, inline="ind2") //to be activated in the future oOut1=0.0, hOut1=0.0, lOut1=0.0, cOut1=0.0 palette1=color.green //PLOT INDICATOR 1 if s_ind1_src!=hide and b_plt1_ind!=false s_ind1_data_=fn_get_source(s_ind1_data) f_indicator1:=fn_factor(FuncType_=s_ind1_src, src_data_=s_ind1_data_, length_=f_ind1_len, p1=f_ind1_p1, p2=f_ind1_p2, version_=i_ind1_ver, fact_=i_ind1_fact, plotingType_=s_ind1_pType, stochlen_=i_ind1_stlen, plotSWMA_=b_ind1_pSWMA, log_=s_ind1_log) plot(s_ind1_src==hide or b_plt1_ind==false ?na:f_indicator1, color=c_ind1_color, title='indicator1', linewidth=2) //PLOT FUNCTION CANDLES 1 if s_ind1_src!=hide and b_plt1_candle!=false [oOut_, hOut_, lOut_, cOut_, palette_] = fn_plotCandles(FuncType_=s_ind1_src,len_=f_ind1_len, p1=f_ind1_p1, p2=f_ind1_p2, version_=i_ind1_ver,fact_=i_ind1_fact, plotingType_=s_ind1_pType, stochlen_=i_ind1_stlen, plotSWMA_=b_ind1_pSWMA, log_=s_ind1_log, plotheikin_=b_plt1_heikin ) oOut1:=oOut_, hOut1:=hOut_, lOut1:=lOut_, cOut1:=cOut_ palette1 := palette_ ? color.green : color.red pc1_=s_ind1_src==hide or b_plt1_candle==false plotcandle(pc1_?na:oOut1, pc1_?na:hOut1, pc1_?na:lOut1, pc1_?na:cOut1, color=palette1, title='Filter Candles 1') //---------------------------------------------------------------------------------------------------------------------------------------- //INDICATOR 2----------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------- s_grp_indicator2="════════════ INDICATOR 2 ════════════" s_ind2_src= input.string( defval=ema, title='IND2:', options=[hide, org, ovrly, alma, ama , acdst, cma, dema, ema, gmma, hghst, hl2ma, hma, lgAdt, lgAdV, lguer, lsrcp, lexp, linrg, lowst, mgi,pcnl, pcnli, prev , pvth, pvtl, rema, rma, sar, sma, smma, supr2, supr3, strnd, swma, tema, tma, vida, vwma, vstop, wma, vwap, nvrly, adx, angle, aroon, atr, awsom, bbr, bbw, cci, cctbb, chng, cmf, cmo, cog, cpcrv, corrl, count, cti, dev, dpo, efi, eom, fall, fit, hvo, kcr, kcw, kli, macd, mfi, msi, nvi, obv, pvi, pvt, rangs, rise, roc, rsi, rvi, smosc, smsig, stc, stdev, trix, tsi, vari, wilpc, wad, wvad] , group=s_grp_indicator2, inline="ind1") //ind2_data = input.source( defval=close, title='', group=s_grp_indicator2, inline="ind1") s_ind2_data = input.string( defval="close", title='', options=["close", "open", "high", "low","hl2", "hlc3", "ohlc4", "volume", "EXT", "IND1"] , group= s_grp_indicator2, inline="ind1") f_ind2_len = input.float( defval=48, title='Len', group=s_grp_indicator2, inline="ind1") i_ind2_ver = input.int( defval=1, title='V', group=s_grp_indicator2, inline="ind2", minval=1, maxval=2) f_ind2_p1 = input.float( defval=0, title='P1', group=s_grp_indicator2, inline="ind2") f_ind2_p2 = input.float( defval=0, title='P2', group=s_grp_indicator2, inline="ind2") i_ind2_fact = input.int( defval=1, title='factor', group=s_grp_indicator2, inline="ind4", minval=1,maxval=4) s_ind2_log = input.string( defval="None", title='Log', group=s_grp_indicator2, inline="ind4", options=['None', 'Simple', 'Log10']) s_ind2_pType = input.string( defval="Original", title="PType", group=s_grp_indicator2, inline="ind3", options=['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)']) i_ind2_stlen = input.int( defval=50, title='St/% val', group=s_grp_indicator2, inline="ind3") b_ind2_pSWMA= input.bool( defval=false, title="Smooth", group=s_grp_indicator2, inline="ind3") c_ind2_color = input( defval=color.red, title="", group=s_grp_indicator2, inline="ind3") b_plt2_candle = input.bool( defval=true, title='Plot Candle',group=s_grp_indicator2, inline="plt") b_plt2_ind = input.bool( defval=true, title='Plot Ind', group=s_grp_indicator2, inline="plt") b_plt2_heikin = input.bool( defval=false, title='HeikinAshi', group=s_grp_indicator2, inline="plt") //ind2_p3 = input.float( defval=0, title='P3', group=s_grp_indicator2, inline="ind2") //to be activated in the future oOut2=0.0, hOut2=0.0, lOut2=0.0, cOut2=0.0 palette2=color.green //PLOT INDICATOR 2 if s_ind2_src!=hide and b_plt2_ind!=false s_ind2_data_=fn_get_source(s_ind2_data) f_indicator2:=fn_factor(FuncType_=s_ind2_src, src_data_=s_ind2_data_, length_=f_ind2_len, p1=f_ind2_p1, p2=f_ind2_p2, version_=i_ind2_ver, fact_=i_ind2_fact, plotingType_=s_ind2_pType, stochlen_=i_ind2_stlen, plotSWMA_=b_ind2_pSWMA, log_=s_ind2_log) plot(s_ind2_src==hide or b_plt2_ind==false ?na:f_indicator2, color=c_ind2_color, title='indicator2', linewidth=2) //PLOT FUNCTION CANDLES 2 if s_ind2_src!=hide and b_plt2_candle!=false [oOut_, hOut_, lOut_, cOut_, palette_] = fn_plotCandles(FuncType_=s_ind2_src,len_=f_ind2_len, p1=f_ind2_p1, p2=f_ind2_p2, version_=i_ind2_ver,fact_=i_ind2_fact, plotingType_=s_ind2_pType, stochlen_=i_ind2_stlen, plotSWMA_=b_ind2_pSWMA, log_=s_ind2_log, plotheikin_=b_plt2_heikin ) oOut2:=oOut_, hOut2:=hOut_, lOut2:=lOut_, cOut2:=cOut_ palette2 := palette_ ? color.green : color.red pc2_=s_ind2_src==hide or b_plt2_candle==false plotcandle(pc2_?na:oOut2, pc2_?na:hOut2, pc2_?na:lOut2, pc2_?na:cOut2, color=palette2, title='Filter Candles 2') //---------------------------------------------------------------------------------------------------------------------------------- //--------END DEMO------------------------------------------------------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------}
arsenal
https://www.tradingview.com/script/bGdqd0a5-arsenal/
yourtradingbuddy
https://www.tradingview.com/u/yourtradingbuddy/
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/ // © doppelgunner //@version=5 // @description This library is a collection of weapons that will help us win the war against different markets. library("arsenal", overlay=true) //CONSTANTS LINE_STYLE_SOLID = "Solid" LINE_STYLE_DOTTED = "Dotted" LINE_STYLE_DASHED = "Dashed" LABEL_STYLE_NONE = "None" LABEL_STYLE_XCROSS = "X cross" LABEL_STYLE_CROSS = "Cross" LABEL_STYLE_TRIANGLEUP = "Triangle up" LABEL_STYLE_TRIANGLEDOWN = "Triangle down" LABEL_STYLE_FLAG = "Flag" LABEL_STYLE_CIRCLE = "Circle" LABEL_STYLE_ARROWUP = "Arrow up" LABEL_STYLE_ARROWDOWN = "Arrow down" LABEL_STYLE_SQUARE = "Square" LABEL_STYLE_DIAMOND = "Diamond" LABEL_STYLE_LABELUP = "Label up" LABEL_STYLE_LABELDOWN = "Label down" LABEL_STYLE_LABELLEFT = "Label left" LABEL_STYLE_LABELRIGHT = "Label right" LABEL_STYLE_LABELLOWERLEFT = "Label lower left" LABEL_STYLE_LABELLOWERRIGHT = "Label lower right" LABEL_STYLE_LABELUPPERLEFT = "Label upper left" LABEL_STYLE_LABELUPPERRIGHT = "Label upper right" LABEL_STYLE_LABELCENTER = "Label center" // @function Fix timeframe // @param _inputTF - input timeframe export fixTimeframe(simple string _inputTF) => inputTF = str.upper(_inputTF) inputTF := switch(inputTF) "S" => "1S" "D" => "1D" "W" => "1W" "M" => "1M" => inputTF inputTF // @function Compares if the2 input timeframes are the same... // @param _inputTF - input timeframe // @param _inputTF2 - input timeframe 2 export isSameTimeframe(simple string _inputTF, simple string _inputTF2) => fixTimeframe(_inputTF) == fixTimeframe(_inputTF2) // @function Is input timeframe equal to current timeframe // @param _inputTF - input timeframe export isEqualToCurrentTF(simple string _inputTF) => isSameTimeframe(_inputTF, timeframe.period) // @function Gets the unit of time // @param _tf - timeframe in string // @returns unit of time export getTimeUnit_timeframe(simple string _tf)=> tf = str.upper(_tf) timeframe = str.replace_all(tf, "S","") timeframe := str.replace_all(timeframe, "H","") timeframe := str.replace_all(timeframe, "D","") timeframe := str.replace_all(timeframe, "W","") timeframe := str.replace_all(timeframe, "M","") timeframeInNumber = str.tonumber(timeframe) if (na(timeframeInNumber)) timeframeInNumber := 1 timeframeInNumber // @function Gets the unit of time // @returns unit of time export getTimeUnit()=> timeframe = str.replace_all(timeframe.period, "S","") timeframe := str.replace_all(timeframe, "H","") timeframe := str.replace_all(timeframe, "D","") timeframe := str.replace_all(timeframe, "W","") timeframe := str.replace_all(timeframe, "M","") timeframeInNumber = str.tonumber(timeframe) if (na(timeframeInNumber)) timeframeInNumber := 1 timeframeInNumber // @function Gets the label of unit of time based on current timeframe on chart // @returns unit of time export getTimeUnitLabelRaw()=> toReturn = "" if (timeframe.isseconds) toReturn := "s" if (timeframe.isminutes) toReturn := "" else if (timeframe.isdaily) toReturn := "D" else if (timeframe.isweekly) toReturn := "W" else if (timeframe.ismonthly) toReturn := "M" toReturn // @function Multiply the current chart's timeframe // @returns new timeframe export multiplyTimeframe(int mult)=> str.tostring(getTimeUnit() * mult) + getTimeUnitLabelRaw() // @function Gets the label of unit of time based on current timeframe on chart // @returns unit of time export getTimeUnitLabel()=> toReturn = "" timeframeInNumber = str.tonumber(timeframe.period) if (timeframe.isseconds) toReturn := "s" if (timeframe.isminutes) if (timeframeInNumber < 60) toReturn := "m" else if ((timeframeInNumber % 60) > 0.0) toReturn := "m" else toReturn := "H" else if (timeframe.isdaily) toReturn := "D" else if (timeframe.isweekly) toReturn := "W" else if (timeframe.ismonthly) toReturn := "M" toReturn // @function Converts to unit based on bar // @param count - in float // @returns unit of time export convertToTimeUnit(float bar)=> string toReturn = na timeframeInNumber = getTimeUnit() if (timeframe.isminutes and timeframeInNumber >= 60) if (timeframeInNumber % 60 > 0) newTimeframe = timeframeInNumber * bar toReturn := str.tostring(math.floor(newTimeframe / 60)) + "H " + str.tostring(newTimeframe % 60) + "m" else newTimeframe = timeframeInNumber * bar toReturn := str.tostring(math.floor(newTimeframe / 60)) + "H" else toReturn := str.tostring(getTimeUnit() * bar) + getTimeUnitLabel() toReturn // @function Converts timeframe into human readable string // @param string - timeframe // @returns timeframe in human readable string export timeframeToString(string timeframe)=> timeframeInNumber = str.tonumber(timeframe) toReturn = timeframe if (timeframe.isseconds) if (timeframe.period == 'S') toReturn := '1s' toReturn := str.replace_all(toReturn, "S", "s") if (timeframe.isminutes) if (timeframeInNumber < 60) toReturn := timeframe + "m" else toReturn := str.tostring(math.floor(timeframeInNumber / 60)) + "H" if ((timeframeInNumber % 60) > 0.0) toReturn += ' ' + str.tostring(timeframeInNumber % 60) + "m" if (timeframe.period == 'D' or timeframe.period == 'W' or timeframe.period == 'M') toReturn := '1' + timeframe.period toReturn // @function Gets the average of all the values from the array // @param array - in float[] // @returns the avarage mean export getAverageFromArray(float[] array)=> float sum = 0 for i = 0 to array.size(array) - 1 sum := sum + array.get(array, i) sum / array.size(array) // @function Gets the highest of all the values from the array // @param array - in float[] // @returns the highest value from the array export getHighestFromArray(float[] array)=> float highest = na for i = 0 to array.size(array) - 1 value = array.get(array, i) if (na(highest) or value > highest) highest := value highest // @function Gets the lowest of all the values from the array // @param array - in float[] // @returns the lowest value from the array export getLowestFromArray(float[] array)=> float lowest = na for i = 0 to array.size(array) - 1 value = array.get(array, i) if (na(lowest) or value < lowest) lowest := value lowest // @function Counts the number of digits before decimal point // @param number - in float // @returns number of digits export numberBeforeDecimalPoint(float number) => c=1 c:=number==0?1:1+math.floor(math.log10(math.abs(number))) c // @function Counts the number of digits after decimal point // @param number - in float // @returns number of digits export numberAfterDecimalPoint(float number) => c=0 d=0.0 d:=math.abs(number) d:=d-math.floor(d) for i=0 to 42 if ( d==0 ) break d:=d*10 d:=d-math.floor(math.round(d)) c:=c+1 c // @function Rounds number to same decimals of mintick // @param number - in float, number to round // @param minTick - in float, decimals to use // @returns rounded number export roundToMinTick(float number, float minTick)=> math.round(number, numberAfterDecimalPoint(minTick)) // @function Rounds number to price format (same decimals as the current asset) // @param price - the number to format // @returns formatted price export toPriceFormat(float price)=> roundToMinTick(price, numberAfterDecimalPoint(syminfo.mintick)) // @function Rounds number to price format (same decimals as the current asset) // @param price - the number to format // @returns formatted price to string export toPriceFormatString(float price)=> decimals = '' for i = 0 to numberAfterDecimalPoint(syminfo.mintick) - 1 decimals := decimals + '0' str.format('{0,number,0.' + decimals + '}', price) // @function Show an alert based on the bar's close // @param title - title of the alert // @returns label export showAlerts(simple string title) => label.new(bar_index, close, style=label.style_label_right, color=color.blue, textcolor=color.white, text="⏰ " + title) // @function Converts % change // @param prev - previous value // @param new - new value // @returns float: - % change in float export percentChange(float prev, float new)=> (new - prev) / (prev * 1.0) // @function Converts the number into a human readable % format // @param number - number in float // @returns string: - number in % that is readable to human export toPercentString(float number)=> str.replace_all(str.format("{0,number,currency}%", number * 100), '$', '') // @function Converts the number into a human readable format // @param number - number in float // @returns string: - number in human readable format export toNumberString(float number)=> str.replace_all(str.format("{0,number,currency}", number), '$', '') // @function Converts the number into a human readable format but also dropping decimals // @param number - number in float // @returns string: - number in human readable format export toNumberStringWithoutDecimal(float number)=> s = str.replace_all(str.format("{0,number,currency}", math.floor(number)), '$', '') s := str.replace_all(s, '.00', '') // // @function Checks if the res is in new bar using request.security // // @param res - resolution of the bar to check if new // // @returns ch: - true, false // export isNewbarSecurity(simple string res)=> // c = request.security(syminfo.ticker, res, close, barmerge.gaps_on, barmerge.lookahead_on) // not na(c) // @function Checks if the res is in new bar at the current timeframe // @param res - resolution of the bar to check if new // @param timezone - timezone of the resolution // @returns ch: - 1=true, 0=false export isNewbar(simple string res, simple string timezone) => ch = 0 if(res == '12M') t = year(time('D', "", timezone)) ch := ta.change(t) != 0 ? 1 : 0 else t = time(res,"", timezone) ch := ta.change(t) != 0 ? 1 : 0 ch // @param src - source to normalize like macd histogram // @param min - minimum value // @param max - maximum value // @returns normalized value export normalize(float _src, float _min, float _max) => // Normalizes series with unknown min/max using historical min/max. // _src: series to rescale. // _min: minimum value of rescaled series. // _max: maximum value of rescaled series. var _historicMin = +10e10 var _historicMax = -10e10 _historicMin := math.min(nz(_src, _historicMin), _historicMin) _historicMax := math.max(nz(_src, _historicMax), _historicMax) _min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 10e-10) // @function Gets the ms equivalent of the given timeframe period // @param _tf - timeframe in string // @returns float in ms get_ms_timeframe(_tf)=> tf = str.upper(_tf) float toReturn = na if (str.contains(tf, "s")) toReturn := 1000 else if (str.contains(tf, "H")) toReturn := 1000 * 60 * 60 else if (str.contains(tf, "D")) toReturn := 1000 * 60 * 60 * 24 else if (str.contains(tf, "W")) toReturn := 1000 * 60 * 60 * 24 * 7 else if (str.contains(tf, "M")) toReturn := 1000 * 60 * 60 * 24 * 7 * 30 else //minutes if no label toReturn := 1000 * 60 toReturn // @function Gets the ms value equivalent of the given timeframe // @param _tf - timeframe in string // @returns float in ms export get_ms_timeframe_value(simple string _tf)=> get_ms_timeframe(_tf) * getTimeUnit_timeframe(_tf) // @function Gets the ratio of 2 timeframes (tf1 / tf2) // @param tf_1 - timeframe in string // @param tf_2 - timeframe in string // @returns ratio in float export get_ms_timeframes_ratio(simple string tf_1, simple string tf_2)=> get_ms_timeframe_value(tf_1) / get_ms_timeframe_value(tf_2) // @function Gets the line styles in string // @returns line styles in string export get_line_styles_string()=> [LINE_STYLE_SOLID, LINE_STYLE_DOTTED, LINE_STYLE_DASHED] // @function Gets the symbol-label styles in string // @returns symbol-label styles in string export get_label_styles_symbol_string()=> [LABEL_STYLE_NONE, LABEL_STYLE_XCROSS, LABEL_STYLE_CROSS, LABEL_STYLE_TRIANGLEUP, LABEL_STYLE_TRIANGLEDOWN, LABEL_STYLE_FLAG, LABEL_STYLE_CIRCLE, LABEL_STYLE_ARROWUP, LABEL_STYLE_ARROWDOWN, LABEL_STYLE_SQUARE, LABEL_STYLE_DIAMOND] // @function Gets the text-label styles in string // @returns text-label styles in string export get_label_styles_text_string()=> [LABEL_STYLE_NONE, LABEL_STYLE_LABELUP, LABEL_STYLE_LABELDOWN, LABEL_STYLE_LABELLEFT, LABEL_STYLE_LABELRIGHT, LABEL_STYLE_LABELLOWERLEFT, LABEL_STYLE_LABELLOWERRIGHT, LABEL_STYLE_LABELUPPERLEFT, LABEL_STYLE_LABELUPPERRIGHT, LABEL_STYLE_LABELCENTER] // @function Get's the equivalent value of line.style_x string // @param type - line_style type in string // @returns corresponding line.style_x export get_line_styles_value(simple string type)=> switch(type) LINE_STYLE_SOLID => line.style_solid LINE_STYLE_DOTTED => line.style_dotted LINE_STYLE_DASHED => line.style_dashed // @function Get's the equivalent value of label.style_x symbol string // @param type - label_style symbol type in string // @returns corresponding label.style_x symbol export get_label_styles_symbol_value(simple string type)=> switch(type) LABEL_STYLE_NONE => label.style_none LABEL_STYLE_XCROSS => label.style_xcross LABEL_STYLE_CROSS => label.style_cross LABEL_STYLE_TRIANGLEUP => label.style_triangleup LABEL_STYLE_TRIANGLEDOWN => label.style_triangledown LABEL_STYLE_FLAG => label.style_flag LABEL_STYLE_CIRCLE => label.style_circle LABEL_STYLE_ARROWUP => label.style_arrowup LABEL_STYLE_ARROWDOWN => label.style_arrowdown LABEL_STYLE_SQUARE => label.style_square LABEL_STYLE_DIAMOND => label.style_diamond // @function Get's the equivalent value of label.style_x text string // @param type - label_style text type in string // @returns corresponding label.style_x text export get_label_styles_text_value(simple string type)=> switch(type) LABEL_STYLE_NONE => label.style_none LABEL_STYLE_LABELUP => label.style_label_up LABEL_STYLE_LABELDOWN => label.style_label_down LABEL_STYLE_LABELLEFT => label.style_label_left LABEL_STYLE_LABELRIGHT => label.style_label_right LABEL_STYLE_LABELLOWERLEFT => label.style_label_lower_left LABEL_STYLE_LABELLOWERRIGHT => label.style_label_lower_right LABEL_STYLE_LABELUPPERLEFT => label.style_label_upper_left LABEL_STYLE_LABELUPPERRIGHT => label.style_label_upper_right LABEL_STYLE_LABELCENTER => label.style_label_center LABEL_STYLE_DIAMOND => label.style_diamond // @function Get the time to exit from timenow + minutes // @param type - minutes // @returns time to exit export timetoexit_in_minutes(int _minutes)=> upto = 1000 * 60 * _minutes result = time + upto // @function Get the time to exit from timenow + hours // @param type - hours // @returns time to exit export timetoexit_in_hours(int _hours)=> upto = 1000 * 60 * 60 * _hours result = time + upto // @function Check if condition is valid // @param numstring - bar indices separated by pipe (|) // @returns if condition is valid on given indices export is_valid(simple string numstring, bool cond) => valid = true nums = str.split(numstring, '|') length = array.size(nums) count = 0 i = 0 while (count < length) if (array.indexof(nums, str.tostring(i)) != -1) if (not cond[i]) valid := false break count += 1 i += 1 valid timezone = input.string("GMT+8", "Timezone") res = input.timeframe("1D", "Timeframe") //highlight each new daily bar newbar = isNewbar(res, timezone) bgcolor(newbar ? color.new(color.blue, 90) : na) var label labelholder = na if barstate.islast label.delete(labelholder) labelholder := label.new(bar_index, high, text=fixTimeframe("1W") + "|" + fixTimeframe(timeframe.period) + "|" + (isSameTimeframe("1W", "W") ? "YES" : "NO") + "|" + (is_valid('0|1', open > close) ? "YES" : "NO"), textcolor=color.white)
Momentum
https://www.tradingview.com/script/bIrAWhxL-Momentum/
Electrified
https://www.tradingview.com/u/Electrified/
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/ // © Electrified (electrifiedtrading) // @version=5 // @description Contains utilities varying algorithms for measuring momentum. library('Momentum') import Electrified/MovingAverages/10 as MA import Electrified/DataCleaner/7 as Data /////////////////////////////////////////////////// // @function Returns the 'change' (current - previous) in value normalized by standard deviation measured by the provided length. // @param src The series to measure changes. // @param len The number of bars to measure the standard deviation. export changeNormalized(series float src, int len) => Data.normalize(ta.change(src) / src, len) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Derives momentum from two moving averages of different lengths. // @param fast The length of the fast moving average. // @param slow The length of the slow moving average. // @param src The series to measure from. Default is 'close'. // @param fastType The type of moving average the fast should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @param slowType The type of moving average the slow should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. export simple( simple int fast, simple int slow, series float src = close, simple string fastType = "SMA", simple string slowType = "SMA") => if fast > slow runtime.error("A fast length that is greater than the slow length will cause inverted momentum results.") MA.get(fastType, fast, src) - MA.get(slowType, slow, src) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the K and D values of a Stochastic RSI. Allows for different moving averages to produce the K value. // @param smoothK The length to average the stochastic. // @param smoothD The length to smooth out K and produce D. // @param rsiLen The length of the RSI. // @param stochLen The length of stochastic. // @param src The series to measure from. Default is 'close'. // @param kmode The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @returns [K, D] export stochRSI( simple int smoothK, simple int smoothD, simple int rsiLen, simple int stochLen, series float src = close, simple string kmode = "SMA") => rsi1 = ta.rsi(src, rsiLen) stoch = ta.stoch(rsi1, rsi1, rsi1, stochLen) k = MA.get(kmode, smoothK, stoch) d = ta.sma(k, smoothD) [k, d] /////////////////////////////////////////////////// // @function Same as well-known MACD formula but allows for different moving averages types to be used. // @param fast The length of the fast moving average. // @param slow The length of the slow moving average. // @param signal The length of average to applied to smooth out the signal. // @param src The series to measure from. Default is 'close'. // @param fastType The type of moving average the fast should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @param slowType The type of moving average the slow should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @param slowType The type of moving average the signal should use. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @returns [macd, signal, histogram] export macd( simple int fast = 12, simple int slow = 26, simple int signal = 9, series float src = close, simple string fastType = "EMA", simple string slowType = "EMA", simple string signalType = "SMA") => macdValue = simple(fast, slow, src, fastType, slowType) signalValue = MA.get(signalType, signal, macdValue) hist = macdValue - signalValue [macdValue, signalValue, hist] /////////////////////////////////////////////////// // Example: [m, s, h] = macd() plot(m, "MACD", color.blue) plot(s, "Signal", color.yellow) plot(h, "Histogram", color.gray, style=plot.style_histogram)
MomentumSignals
https://www.tradingview.com/script/jq8b0tOh-MomentumSignals/
Electrified
https://www.tradingview.com/u/Electrified/
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/ // © Electrified (electrifiedtrading) // @version=5 // @description Contains utilities varying algorithms for detecting key changes in momentum. Note: Momentum is not velocity and should be used in conjunction with other indicators. A change in momentum does not mean a reversal of velocity or trend. library('MomentumSignals') import Electrified/Momentum/5 quantize(float value, simple int up = 1, simple int dn = -1) => na(value) ? na : value > 0 ? up : value < 0 ? dn : 0 signalOnly( series float s, int len = 1) => quantize(ta.change(s, 1)) // Changes in direction at the key. reverseSignalOnly( series float s, simple int len = 2) => c = ta.change(s, len) if c > 0 and s < 0 +1 else if c < 0 and s > 0 -1 else 0 // Simplified super-trend algo trend(series float h, series float d, int len, float m = 1) => var lo = h var hi = h var direction = 0 if na(lo) lo := h if na(hi) hi := h std = ta.stdev(d, len) if h > hi direction := +1 hi := h lo := h - std * m else if h < lo direction := -1 lo := h hi := h + std * m [direction, std] //// /////////////////////////////////////////////////// // @function Compares two series for changes in momentum to derive signal values. // @param primary The primary series (typically a moving average) to look for changes in momentum. // @param secondary The secondary series (typically derived moving average of the primary) to use as a comparison value. // @param len The number of bars to measure the change in momentum. export simple( series float primary, series float secondary) => p = signalOnly(primary) s = signalOnly(secondary) h = primary - secondary // similar to the histogram in MACD. d = ta.change(h) x = quantize(d) p + s + x /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Compares two series for changes in momentum to derive signal values. Uses statistics to filter out changes in momentum. // @param primary The primary series (typically a moving average) to look for changes in momentum. // @param secondary The secondary series (typically derived moving average of the primary) to use as a comparison value. // @param len The number of bars to measure the change in momentum. // @param stdlen The number of bars to measure the change in momentum for filtering. // @param stdMultiple The multiple of the change in momentum to use before reversiing. export filtered( series float primary, series float secondary, simple int stdlen = 200, simple float stdMultiple = 3.5) => p = signalOnly(primary) s = signalOnly(secondary) h = primary - secondary // similar to the histogram in MACD. d = ta.change(h) [t, std] = trend(h, d, stdlen, stdMultiple) x = t > 0 and d < 0 or t < 0 and d > 0 ? 0 : quantize(d) p + s + x /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Compares two series for changes in momentum to derive signal values. Uses statistics to filter out changes in momentum. Does not signal when likely overbought or oversold. // @param primary The primary series (typically a moving average) to look for changes in momentum. // @param secondary The secondary series (typically derived moving average of the primary) to use as a comparison value. // @param stdlen The number of bars to measure the change in momentum for filtering. // @param stdMultiple The multiple of the change in momentum to use before reversiing. export special( series float primary, series float secondary, simple int stdlen = 200, simple float stdMultiple = 3.5) => p = signalOnly(primary) s = signalOnly(secondary) h = primary - secondary // similar to the histogram in MACD. d = ta.change(h) [t, std] = trend(h, d, stdlen, stdMultiple) x = t > 0 and d < 0 or t < 0 and d > 0 ? 0 : quantize(d) r = p + s + x accelleration = ta.change(d) aStd = ta.stdev(accelleration, stdlen) accP = accelleration[1] a = signalOnly(accelleration) if a>aStd or accP>aStd or a<-aStd or accP<-aStd if primary < h and a > 0 or primary > h and a < 0 r += a if r < -1 and d > 0 r := -1 else if r > +1 and d < 0 r := +1 // When the signal level has exceeded the histogram, signals become more risky. r := primary > secondary and secondary > h or primary < secondary and secondary < h ? x : r // Filter out noise. r > 0 and primary > 0 and primary < secondary or r < 0 and primary < 0 and primary > secondary ? 0 : r /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns a signal value representing the stage of where the RSI is in its cycle. // @param smoothK The length to average the stochastic. // @param smoothD The length to smooth out K and produce D. // @param rsiLen The length of the RSI. // @param stochLen The length of stochastic. // @param src The series to measure from. Default is 'close'. // @param kmode The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @param upper The upper band of the range. // @param lower The lower band of the range. // @returns [signal, stage] Where stage is: +1 is oversold and rising, +2 rising above lower bound but less than mid. +3 rising above mid. +4 is overbought. Negative numbers are the reverse. export stochRSI( simple int smoothK = 3, simple int smoothD = 3, simple int rsiLen = 14, simple int stochLen = 14, series float src = close, simple string kmode = "SMA", simple float upper = 80, simple float lower = 20, simple float mid = 50) => [k, d] = Momentum.stochRSI(smoothK, smoothD, rsiLen, stochLen, src, kmode) k_c = quantize(ta.change(k)) d_c = quantize(ta.change(d)) // Where are we? var stage = 0 if stage != -1 and k > d and k > upper stage := +4 // overbought if stage != +1 and k < d and k < lower stage := -4 // oversold if stage == +4 and k < d and d_c < 0 stage := -1 // overbought and falling if stage == -4 and k > d and d_c > 0 stage := +1 // oversold and rising if stage == +1 and k > lower stage := +2 // rising up if stage == -1 and k < upper stage := -2 // falling down if stage == +2 and k > mid stage := +3 // rising up high if stage == -2 and k < mid stage := -3 // falling down low if stage == +3 and k < d and d < mid or stage == -3 and k > d and d > mid stage := 0 // indeterminate stage_c = ta.change(stage) // Avoid noisy alignment... signal = if k_c != d_c or k_c != quantize(k - d) 0 else if stage == +2 (k_c + 1) * (stage_c > 0 ? 2 : 1) else if stage == -2 (k_c - 1) * (stage_c < 0 ? 2 : 1) else if d < lower k_c < 0 ? 0 : k_c else if d > upper k_c > 0 ? 0 : k_c else k_c [signal, stage] /////////////////////////////////////////////////// // Example: SMA = 'SMA', EMA = 'EMA', WMA = 'WMA', VWMA = 'VWMA', VAWMA = 'VAWMA' [m, s, h] = Momentum.macd( input.int(24, "MACD Length", minval=1), input.int(52, "Signal Length", minval=1), input.int(12, "Signal Smoothing", minval=1), input.source(hlc3, "Source"), input.string(WMA, "MACD MA Type", options=[SMA,EMA,WMA,VWMA,VAWMA]), input.string(WMA, "Signal MA Type", options=[SMA,EMA,WMA,VWMA,VAWMA])) stdLen = input.int(200, "StdDev Length", minval=1, tooltip="Length of standard deviation measurement of historgram change") stdM = input.float(3.5, "StdDev Multiple", minval=0, step=0.5, tooltip="The number of standard deviations before momentum may have reversed") plot(m, "MACD", color.blue) plot(s, "Signal", color.yellow) plot(h, "Histogram", color.gray, style=plot.style_columns) signal = special(m, s, stdLen, stdM) //plot(signal, "Signal", color.orange) color signalColor = switch signal +4 => color.new(color.green, 20) +3 => color.new(color.green, 40) +2 => color.new(color.green, 60) +1 => color.new(color.green, 80) -1 => color.new(color.red, 80) -2 => color.new(color.red, 60) -3 => color.new(color.red, 40) -4 => color.new(color.red, 20) => na bgcolor(signalColor)
UnicodeReplacementFunction
https://www.tradingview.com/script/3wOXfbuT-UnicodeReplacementFunction/
wlhm
https://www.tradingview.com/u/wlhm/
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/ // © wlhm //{ // DESCRIPTION // // This script is a continuation from Duyck's Unicode font function // A different approach made on this function to able change font type on a string. // Now you can call it as a function to change the font type on every string that you need, // // Shoutout to @Duyck for his amazing works on this function. // Thanks to Pine Script Community who made this library function exist on Pine script. // // Greets, // wlhm // //} //@version=5 // @description Unicode Characters Replacement function for strings. library("UnicodeReplacementFunction") ////////////////////////////////////////////////////////////////////////////////////////////////////// // Font Selector copypasta // ["Pine Default", "Sans", "Sans Italic", "Sans Bold", "Sans Bold Italic", "Sans-Serif", "Sans-Serif Italic", "Sans-Serif Bold", "Sans-Serif Bold Italic", "Fraktur", "Fraktur Bold", "Script", "Script Bold", "Double-Struck", "Monospace", "Regional Indicator", "Full Width", "Circled"] ////////////////////////////////////////////////////////////////////////////////////////////////////// //// UNICODE REPLACEMENT FUNCTIONS //// //{ // @function Unicode Character Replace Function // @param _str String input // @param _fontType Font Type Selector // @returns Replaced Char String with any custom font type choosed export replaceFont(string _str, string _fontType) => //// STANDARD PINESCRIPT FONT //// //{ Pine_std_LC = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z" Pine_std_UC = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z" Pine_std_DG = "0,1,2,3,4,5,6,7,8,9" Pine_font_std_LC = str.split(Pine_std_LC, ",") Pine_font_std_UC = str.split(Pine_std_UC, ",") Pine_font_std_DG = str.split(Pine_std_DG, ",") //} //// CUSTOM FONT //// // (a different font can be copy-pasted here, from the listed website or another source) //{ var string cust_select_LC = " " var string cust_select_UC = " " var string cust_select_DG = " " if _fontType == "Sans" cust_select_LC := "𝖺,𝖻,𝖼,𝖽,𝖾,𝖿,𝗀,𝗁,𝗂,𝗃,𝗄,𝗅,𝗆,𝗇,𝗈,𝗉,𝗊,𝗋,𝗌,𝗍,𝗎,𝗏,𝗐,𝗑,𝗒,𝗓" cust_select_UC := "𝖠,𝖡,𝖢,𝖣,𝖤,𝖥,𝖦,𝖧,𝖨,𝖩,𝖪,𝖫,𝖬,𝖭,𝖮,𝖯,𝖰,𝖱,𝖲,𝖳,𝖴,𝖵,𝖶,𝖷,𝖸,𝖹" cust_select_DG := "𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫" else if _fontType == "Sans Italic" cust_select_LC := "𝘢,𝘣,𝘤,𝘥,𝘦,𝘧,𝘨,𝘩,𝘪,𝘫,𝘬,𝘭,𝘮,𝘯,𝘰,𝘱,𝘲,𝘳,𝘴,𝘵,𝘶,𝘷,𝘸,𝘹,𝘺,𝘻" cust_select_UC := "𝘈,𝘉,𝘊,𝘋,𝘌,𝘍,𝘎,𝘏,𝘐,𝘑,𝘒,𝘓,𝘔,𝘕,𝘖,𝘗,𝘘,𝘙,𝘚,𝘛,𝘜,𝘝,𝘞,𝘟,𝘠,𝘡" cust_select_DG := "𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫" else if _fontType == "Sans Bold" cust_select_LC := "𝗮,𝗯,𝗰,𝗱,𝗲,𝗳,𝗴,𝗵,𝗶,𝗷,𝗸,𝗹,𝗺,𝗻,𝗼,𝗽,𝗾,𝗿,𝘀,𝘁,𝘂,𝘃,𝘄,𝘅,𝘆,𝘇" cust_select_UC := "𝗔,𝗕,𝗖,𝗗,𝗘,𝗙,𝗚,𝗛,𝗜,𝗝,𝗞,𝗟,𝗠,𝗡,𝗢,𝗣,𝗤,𝗥,𝗦,𝗧,𝗨,𝗩,𝗪,𝗫,𝗬,𝗭" cust_select_DG := "𝟬,𝟭,𝟮,𝟯,𝟰,𝟱,𝟲,𝟳,𝟴,𝟵" else if _fontType == "Sans Bold Italic" cust_select_LC := "𝙖,𝙗,𝙘,𝙙,𝙚,𝙛,𝙜,𝙝,𝙞,𝙟,𝙠,𝙡,𝙢,𝙣,𝙤,𝙥,𝙦,𝙧,𝙨,𝙩,𝙪,𝙫,𝙬,𝙭,𝙮,𝙯" cust_select_UC := "𝘼,𝘽,𝘾,𝘿,𝙀,𝙁,𝙂,𝙃,𝙄,𝙅,𝙆,𝙇,𝙈,𝙉,𝙊,𝙋,𝙌,𝙍,𝙎,𝙏,𝙐,𝙑,𝙒,𝙓,𝙔,𝙕" cust_select_DG := "𝟬,𝟭,𝟮,𝟯,𝟰,𝟱,𝟲,𝟳,𝟴,𝟵" else if _fontType == "Sans-Serif" cust_select_LC := "𝚊,𝚋,𝚌,𝚍,𝚎,𝚏,𝚐,𝚑,𝚒,𝚓,𝚔,𝚕,𝚖,𝚗,𝚘,𝚙,𝚚,𝚛,𝚜,𝚝,𝚞,𝚟,𝚠,𝚡,𝚢,𝚣" cust_select_UC := "𝙰,𝙱,𝙲,𝙳,𝙴,𝙵,𝙶,𝙷,𝙸,𝙹,𝙺,𝙻,𝙼,𝙽,𝙾,𝙿,𝚀,𝚁,𝚂,𝚃,𝚄,𝚅,𝚆,𝚇,𝚈,𝚉" cust_select_DG := "𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿" else if _fontType == "Sans-Serif Italic" cust_select_LC := "𝘢,𝘣,𝘤,𝘥,𝘦,𝘧,𝘨,𝘩,𝘪,𝘫,𝘬,𝘭,𝘮,𝘯,𝘰,𝘱,𝘲,𝘳,𝘴,𝘵,𝘶,𝘷,𝘸,𝘹,𝘺,𝘻" cust_select_UC := "𝘈,𝘉,𝘊,𝘋,𝘌,𝘍,𝘎,𝘏,𝘐,𝘑,𝘒,𝘓,𝘔,𝘕,𝘖,𝘗,𝘘,𝘙,𝘚,𝘛,𝘜,𝘝,𝘞,𝘟,𝘠,𝘡" cust_select_DG := "𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿" else if _fontType == "Sans-Serif Bold" cust_select_LC := "𝐚,𝐛,𝐜,𝐝,𝐞,𝐟,𝐠,𝐡,𝐢,𝐣,𝐤,𝐥,𝐦,𝐧,𝐨,𝐩,𝐪,𝐫,𝐬,𝐭,𝐮,𝐯,𝐰,𝐱,𝐲,𝐳" cust_select_UC := "𝐀,𝐁,𝐂,𝐃,𝐄,𝐅,𝐆,𝐇,𝐈,𝐉,𝐊,𝐋,𝐌,𝐍,𝐎,𝐏,𝐐,𝐑,𝐒,𝐓,𝐔,𝐕,𝐖,𝐗,𝐘,𝐙" cust_select_DG := "𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗" else if _fontType == "Sans-Serif Bold Italic" cust_select_LC := "𝒂,𝒃,𝒄,𝒅,𝒆,𝒇,𝒈,𝒉,𝒊,𝒋,𝒌,𝒍,𝒎,𝒏,𝒐,𝒑,𝒒,𝒓,𝒔,𝒕,𝒖,𝒗,𝒘,𝒙,𝒚,𝒛" cust_select_UC := "𝑨,𝑩,𝑪,𝑫,𝑬,𝑭,𝑮,𝑯,𝑰,𝑱,𝑲,𝑳,𝑴,𝑵,𝑶,𝑷,𝑸,𝑹,𝑺,𝑻,𝑼,𝑽,𝑾,𝑿,𝒀,𝒁" cust_select_DG := "𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗" else if _fontType == "Fraktur" cust_select_LC := "𝔞,𝔟,𝔠,𝔡,𝔢,𝔣,𝔤,𝔥,𝔦,𝔧,𝔨,𝔩,𝔪,𝔫,𝔬,𝔭,𝔮,𝔯,𝔰,𝔱,𝔲,𝔳,𝔴,𝔵,𝔶,𝔷" cust_select_UC := "𝔄,𝔅,ℭ,𝔇,𝔈,𝔉,𝔊,ℌ,ℑ,𝔍,𝔎,𝔏,𝔐,𝔑,𝔒,𝔓,𝔔,ℜ,𝔖,𝔗,𝔘,𝔙,𝔚,𝔛,𝔜,ℨ" cust_select_DG := "𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫" else if _fontType == "Fraktur Bold" cust_select_LC := "𝖆,𝖇,𝖈,𝖉,𝖊,𝖋,𝖌,𝖍,𝖎,𝖏,𝖐,𝖑,𝖒,𝖓,𝖔,𝖕,𝖖,𝖗,𝖘,𝖙,𝖚,𝖛,𝖜,𝖝,𝖞,𝖟" cust_select_UC := "𝕬,𝕭,𝕮,𝕯,𝕰,𝕱,𝕲,𝕳,𝕴,𝕵,𝕶,𝕷,𝕸,𝕹,𝕺,𝕻,𝕼,𝕽,𝕾,𝕿,𝖀,𝖁,𝖂,𝖃,𝖄,𝖅" cust_select_DG := "𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗" else if _fontType == "Script" cust_select_LC := "𝒶,𝒷,𝒸,𝒹,ℯ,𝒻,ℊ,𝒽,𝒾,𝒿,𝓀,𝓁,𝓂,𝓃,ℴ,𝓅,𝓆,𝓇,𝓈,𝓉,𝓊,𝓋,𝓌,𝓍,𝓎,𝓏" cust_select_UC := "𝒜,ℬ,𝒞,𝒟,ℰ,ℱ,𝒢,ℋ,ℐ,𝒥,𝒦,ℒ,ℳ,𝒩,𝒪,𝒫,𝒬,ℛ,𝒮,𝒯,𝒰,𝒱,𝒲,𝒳,𝒴,𝒵" cust_select_DG := "𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫" else if _fontType == "Script Bold" cust_select_LC := "𝓪,𝓫,𝓬,𝓭,𝓮,𝓯,𝓰,𝓱,𝓲,𝓳,𝓴,𝓵,𝓶,𝓷,𝓸,𝓹,𝓺,𝓻,𝓼,𝓽,𝓾,𝓿,𝔀,𝔁,𝔂,𝔃" cust_select_UC := "𝓐,𝓑,𝓒,𝓓,𝓔,𝓕,𝓖,𝓗,𝓘,𝓙,𝓚,𝓛,𝓜,𝓝,𝓞,𝓟,𝓠,𝓡,𝓢,𝓣,𝓤,𝓥,𝓦,𝓧,𝓨,𝓩" cust_select_DG := "𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗" else if _fontType == "Double-Struck" cust_select_LC := "𝕒,𝕓,𝕔,𝕕,𝕖,𝕗,𝕘,𝕙,𝕚,𝕛,𝕜,𝕝,𝕞,𝕟,𝕠,𝕡,𝕢,𝕣,𝕤,𝕥,𝕦,𝕧,𝕨,𝕩,𝕪,𝕫" cust_select_UC := "𝔸,𝔹,ℂ,𝔻,𝔼,𝔽,𝔾,ℍ,𝕀,𝕁,𝕂,𝕃,𝕄,ℕ,𝕆,ℙ,ℚ,ℝ,𝕊,𝕋,𝕌,𝕍,𝕎,𝕏,𝕐,ℤ" cust_select_DG := "𝟘,𝟙,𝟚,𝟛,𝟜,𝟝,𝟞,𝟟,𝟠,𝟡" else if _fontType == "Monospace" cust_select_LC := "𝚊,𝚋,𝚌,𝚍,𝚎,𝚏,𝚐,𝚑,𝚒,𝚓,𝚔,𝚕,𝚖,𝚗,𝚘,𝚙,𝚚,𝚛,𝚜,𝚝,𝚞,𝚟,𝚠,𝚡,𝚢,𝚣" cust_select_UC := "𝙰,𝙱,𝙲,𝙳,𝙴,𝙵,𝙶,𝙷,𝙸,𝙹,𝙺,𝙻,𝙼,𝙽,𝙾,𝙿,𝚀,𝚁,𝚂,𝚃,𝚄,𝚅,𝚆,𝚇,𝚈,𝚉" cust_select_DG := "𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿" else if _fontType == "Regional Indicator" cust_select_LC := " 🇦, 🇧, 🇨, 🇩, 🇪, 🇫, 🇬, 🇭, 🇮, 🇯, 🇰, 🇱, 🇲, 🇳, 🇴, 🇵, 🇶, 🇷, 🇸, 🇹, 🇺, 🇻, 🇼, 🇽, 🇾, 🇿" cust_select_UC := " 🇦, 🇧, 🇨, 🇩, 🇪, 🇫, 🇬, 🇭, 🇮, 🇯, 🇰, 🇱, 🇲, 🇳, 🇴, 🇵, 🇶, 🇷, 🇸, 🇹, 🇺, 🇻, 🇼, 🇽, 🇾, 🇿" cust_select_DG := "𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿" else if _fontType == "Full Width" cust_select_LC := "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z" cust_select_UC := "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z" cust_select_DG := "0,1,2,3,4,5,6,7,8,9" else if _fontType == "Circled" cust_select_LC := "🅐,🅑,🅒,🅓,🅔,🅕,🅖,🅗,🅘,🅙,🅚,🅛,🅜,🅝,🅞,🅟,🅠,🅡,🅢,🅣,🅤,🅥,🅦,🅧,🅨,🅩" cust_select_UC := "🅐,🅑,🅒,🅓,🅔,🅕,🅖,🅗,🅘,🅙,🅚,🅛,🅜,🅝,🅞,🅟,🅠,🅡,🅢,🅣,🅤,🅥,🅦,🅧,🅨,🅩" cust_select_DG := "⓿,❶,❷,❸,❹,❺,❻,❼,❽,❾" else cust_select_LC := "𝚊,𝚋,𝚌,𝚍,𝚎,𝚏,𝚐,𝚑,𝚒,𝚓,𝚔,𝚕,𝚖,𝚗,𝚘,𝚙,𝚚,𝚛,𝚜,𝚝,𝚞,𝚟,𝚠,𝚡,𝚢,𝚣" cust_select_UC := "𝙰,𝙱,𝙲,𝙳,𝙴,𝙵,𝙶,𝙷,𝙸,𝙹,𝙺,𝙻,𝙼,𝙽,𝙾,𝙿,𝚀,𝚁,𝚂,𝚃,𝚄,𝚅,𝚆,𝚇,𝚈,𝚉" cust_select_DG := "𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿" //} //// UNICODE CHARACTER REPLACEMENT //// //{ _custom_font_LC = str.split(cust_select_LC, ",") _custom_font_UC = str.split(cust_select_UC, ",") _custom_font_DG = str.split(cust_select_DG, ",") _char_str = _str for _i = 0 to array.size(Pine_font_std_LC) - 1 _char_str := str.replace_all(_char_str, array.get(Pine_font_std_LC, _i), array.get(_custom_font_LC, _i)) _char_str := str.replace_all(_char_str, array.get(Pine_font_std_UC, _i), array.get(_custom_font_UC, _i)) _digit_str = _char_str for _i = 0 to array.size(Pine_font_std_DG) - 1 _digit_str := str.replace_all(_digit_str, array.get(Pine_font_std_DG, _i), array.get(_custom_font_DG, _i)) _digit_str //} //}
TableColorTheme
https://www.tradingview.com/script/39NI1l6h-TableColorTheme/
boitoki
https://www.tradingview.com/u/boitoki/
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/ // © boitoki //@version=5 // @description TODO: This library provides the color for the table. library("TableColorTheme") GREEN__ = #1bbd96 BLUE___ = #2400ee ORANGE_ = #fdbd08 RED____ = #fb003e BLACK__ = #02223c WHITE__ = #F3F3F3 GRAY___ = #292A2B TVBLACK = #131722 TVGRAY_ = #20222b DFGRAY_ = color.new(color.gray, 30) // @function theme: Provides the colors of monokai. // @param name TODO: The name of the color group. // @returns TODO: Returns an array of colors. // https://kolormark.com/brands/monokai export monokai (string name) => switch name 'purple' => #AE81FF 'blue' => #66D9EF 'green' => #A6E22E 'yellow' => #E6DB74 'orange' => #FD971F 'pink' => #F92672 'black' => #272822 => #272822 // @function theme: Provides the colors of monokai pro. // @param name TODO: The name of the color group. // @returns TODO: Returns an array of colors. export monokaipro (string name) => switch name 'purple' => #AB9DF2 'blue' => #78DCE8 'green' => #A9DC76 'yellow' => #FFD866 'orange' => #FC9867 'pink' => #FF6188 'black' => #2D2A2E => #2D2A2E // [Table] // border_color = color.gray // border_width = 1 // frame_color = color.gray // frame_width = 2 // // [Cell] // text_color = color.black // text_size = size.normal // bgcolor = color.white // // [Head] // head_text_color = color.white // head_text_size = size.normal // head_bgcolor = color.black // @function theme This function provides the color for the table. // @param name TODO: The name of the color group. // @returns TODO: Returns an array of colors. export theme(string name) => switch name 'green' => [GREEN__, 1, GREEN__, 1, BLACK__, size.normal, WHITE__, WHITE__, size.normal, GREEN__] 'blue' => [BLUE___, 1, BLUE___, 1, BLACK__, size.normal, WHITE__, WHITE__, size.normal, BLUE___] 'orange' => [ORANGE_, 1, ORANGE_, 1, BLACK__, size.normal, WHITE__, #392a00, size.normal, ORANGE_] 'red' => [RED____, 1, RED____, 1, BLACK__, size.normal, WHITE__, WHITE__, size.normal, RED____] 'black' => [BLACK__, 1, BLACK__, 1, BLACK__, size.normal, WHITE__, WHITE__, size.normal, BLACK__] 'white' => [WHITE__, 1, BLACK__, 1, BLACK__, size.normal, WHITE__, BLACK__, size.normal, WHITE__] 'dark' => [DFGRAY_, 1, DFGRAY_, 1, #ffffff, size.normal, TVBLACK, #a3a6b0, size.normal, TVBLACK] 'night' => [#343640, 1, #343640, 1, WHITE__, size.normal, TVBLACK, #b2b5be, size.normal, #343640] 'carbon' => [GRAY___, 1, GRAY___, 1, WHITE__, size.normal, GRAY___, WHITE__, size.normal, GRAY___] 'monokai'=> [#252328, 1, #252328, 1, #d5ced4, size.normal, #211e23, #66D9EF, size.normal, #211e23] 'multi' => [GREEN__, 0, GREEN__, 0, WHITE__, size.normal, GREEN__, WHITE__, size.normal, GREEN__] => [color.gray, 1, color.gray, 2, color.black, size.normal, color.white, color.white, size.normal, color.black] [border_color, border_width, frame_color, frame_width, text_color, text_size, bgcolor, head_text_color, head_text_size, head_bgcolor] = theme(input.string(defval="green", options=['green', 'blue', 'orange', 'red', 'black', 'white', 'dark', 'night', 'carbon', 'monokai', 'multi'])) var table panel = table.new(position.top_right, 3, 4, border_color=border_color, border_width=border_width, frame_color=frame_color, frame_width=frame_width) table.cell(panel, 0, 0, "h", bgcolor=head_bgcolor, text_color=head_text_color, text_size=head_text_size) table.cell(panel, 1, 0, "name", bgcolor=bgcolor, text_color=text_color, text_size=text_size) table.cell(panel, 2, 0, "value", bgcolor=bgcolor, text_color=text_color, text_size=text_size) table.cell(panel, 0, 1, "h", bgcolor=head_bgcolor, text_color=head_text_color, text_size=head_text_size) table.cell(panel, 1, 1, "open", bgcolor=bgcolor, text_color=text_color, text_size=text_size) table.cell(panel, 2, 1, str.format('{0,number,#.#}', open), bgcolor=bgcolor, text_color=text_color, text_size=text_size) table.cell(panel, 0, 2, "h", bgcolor=head_bgcolor, text_color=head_text_color, text_size=head_text_size) table.cell(panel, 1, 2, "close", bgcolor=bgcolor, text_color=text_color, text_size=text_size) table.cell(panel, 2, 2, str.format('{0,number,#.#}', close), bgcolor=bgcolor, text_color=text_color, text_size=text_size)
LocalLimit
https://www.tradingview.com/script/U7zSlZR1-LocalLimit/
Electrified
https://www.tradingview.com/u/Electrified/
28
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 Calculates the local upper or local lower limit for a given series. Applying multiple passes produces what appears like support or resistance levels. library('LocalLimit', true) export type Limit float value int trend export type Level Limit upper Limit lower /////////////////////////////////////////////////// // @function Produces the recent local upper limit for a given series. // @param src The source series to derive from. // @param padding Gives some extra room when lowering the level. export upper( series float src, float padding = 0) => value = src[0] valuePrev = src[1] var limit = value var int trend = 0 var int phase = 0 phase := if not na(value) and (value > limit or na(limit)) trend := +1 limit := value 0 else switch phase 0 => 1 1 => value > valuePrev ? 2 : 1 2 => if value < valuePrev trend := -1 limit := math.min(limit, valuePrev + nz(padding)) 0 else 2 limit /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Produces the recent local lower limit for a given series. // @param src The source series to derive from. // @param padding Gives some extra room when raising the level. export lower( series float src, float padding = 0) => value = src[0] valuePrev = src[1] var limit = value var int trend = 0 var int phase = 0 phase := if not na(value) and (value < limit or na(limit)) trend := -1 limit := value 0 else switch phase 0 => 1 1 => value < valuePrev ? 2 : 1 2 => if value > valuePrev trend := +1 limit := math.max(limit, valuePrev - nz(padding)) 0 else 2 limit /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @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 Creates a Limit object that contains the value and the trend. // @param src The source series to derive from. export valueAndTrend(series float src) => Limit.new(src, trend(src)) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Creates a Level object representing the local upper and lower limits. // @param hiSrc The source to discover the upper limit from. // @param loSrc The source to discover the lower limit from. // @param padding Gives some extra room when raising the lower level and lowering the upper level. export of( series float hiSrc = high, series float loSrc = low, float padding = 0) => hi = valueAndTrend(upper(hiSrc, padding)) lo = valueAndTrend(lower(loSrc, padding)) Level.new(hi, lo) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Creates a Level object representing the local upper and lower limits. // @param level The source levels to expand of. // @param padding Gives some extra room when raising the lower level and lowering the upper level. export of( series Level level, float padding = 0) => hi = valueAndTrend(upper(level.upper.value, padding)) lo = valueAndTrend(lower(level.lower.value, padding)) Level.new(hi, lo) /////////////////////////////////////////////////// limit0 = of() limit1 = of(limit0, 0.1) limit2 = of(limit1, 0.5) hColor = color.yellow lColor = color.blue plot(limit0.upper.value, "H0", hColor, 1) plot(limit1.upper.value, "H1", hColor, 2) plot(limit2.upper.value, "H2", hColor, 3) plot(limit0.lower.value, "L0", lColor, 1) plot(limit1.lower.value, "L1", lColor, 2) plot(limit2.lower.value, "L3", lColor, 3)
ma_function
https://www.tradingview.com/script/N9jcsItr-ma-function/
boitoki
https://www.tradingview.com/u/boitoki/
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/ // © boitoki //@version=5 // @description: This library is a package of various MAs. // @sample: // import boitoki/ma_function/{version} as ma // // ma.calc('SMA', close, 10) // library("ma_function") export sma (float x, int y) => sum = 0.0 for i = 0 to y - 1 sum := sum + x[i] / y sum export ema (float src, int length) => alpha = 2 / (length + 1) sum = 0.0 sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1]) export kama (float xPrice, int Length)=> xvnoise = math.abs(xPrice - xPrice[1]) nfastend = 0.666 nslowend = 0.0645 nsignal = math.abs(xPrice - xPrice[Length]) nnoise = math.sum(xvnoise, Length) nefratio = (nnoise != 0 ? nsignal / nnoise : 0) nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2) nAMA = 0.0 nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1])) export zlema (float src, int length) => zxLag = length/2==math.round(length/2) ? length/2 : (length - 1) / 2 zxEMAData = (src + (src - src[zxLag])) ZLEMA = ema(zxEMAData, length) export mav (float source, int length) => ((ta.sma(source, length)[1]*(length-1)) + source) / length export dema (float src, int len) => e = ema(src, len) 2 * e - ema(e, len) export tema (float src, int len) => e = ema(src, len) 3 * (e - ema(e, len)) + ema(ema(e, len), len) export hma (float src, int len) => ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) export tma (float source, int length) => ta.sma(ta.sma(source, math.ceil(length / 2)), math.floor(length / 2) + 1) export ama (float source, int length, int fast, int slow) => fastAlpha = 2 / (fast + 1) slowAlpha = 2 / (slow + 1) hh = ta.highest(length + 1) ll = ta.lowest(length + 1) mltp = hh - ll != 0 ? math.abs(2 * source - ll - hh) / (hh - ll) : 0 ssc = mltp * (fastAlpha - slowAlpha) + slowAlpha ama = 0.0 ama := nz(ama[1]) + math.pow(ssc, 2) * (source - nz(ama[1])) ama export rma (float src, int length) => alpha = 1 / length sum = 0.0 sum := na(sum[1]) ? sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1]) export bwma (float src, int length, int beta, int alpha) => var b = array.new_float(0) if barstate.isfirst for i = 0 to length-1 x = i / (length-1) w = math.pow(x, alpha-1) * math.pow(1-x, beta-1) array.push(b,w) den = array.sum(b) sum = 0. for i = 0 to length-1 sum := sum + src[i]*array.get(b,i) filt = sum/den // @function This function provides the MA specified in the argument. // @param name MA's name // @param source Source value // @param length Look back periods // @returns MA value export ma_function (simple string name, float source, int length) => switch name 'ALMA' => ta.alma(source, length,0.85, 6) 'AMA' => ama(source, length, 2, 30) 'BWMA' => bwma(source, length, 3, 3) 'DEMA' => dema(source, length) 'EMA' => ema(source, length) 'HMA' => hma(source, length) 'KAMA' => kama(source, length) 'LSMA' => ta.linreg(source, length, 0) 'MAV' => mav(source, length) 'RMA' => rma(source, length) 'SMA' => ta.sma(source, length) 'SWMA' => ta.swma(source) 'TEMA' => tema(source, length) 'TMA' => tma(source, length) 'VWMA' => ta.vwma(source, length) 'WMA' => ta.wma(source, length) 'ZLEMA' => zlema(source, length) // This function is a syntax sugar of `ma_function` export calc (simple string name, float source, int length) => ma_function(str.upper(name), source, length) i_source = input.source(close, 'Source') i_type = input.string('SMA', 'Type', options=['ALMA', 'AMA', 'BWMA', 'DEMA', 'EMA', 'HMA', 'KAMA', 'LSMA', 'MAV', 'RMA', 'SMA', 'SWMA', 'TEMA', 'TMA', 'VWMA', 'WMA', 'ZLEMA']) i_len = input.int(10, 'Length') i_color = input.color(color.blue, 'Color') plot(calc(i_type, i_source, i_len), 'MA', color=i_color)
SgjoeLibrary
https://www.tradingview.com/script/gFVeZuzY-SgjoeLibrary/
The_Brit
https://www.tradingview.com/u/The_Brit/
7
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/ // © The_Brit // Last updated 15th November, 2021 //@version=5 // @description Custom functions library("SgjoeLibrary", true) // Custom Functions { // @function Permits a condition to be used with highest(high,condition) // @param float _high_series The High for the condition // @param float _when The condition such as close > high[1] // @returns The high(s) at the point(s) the condition was true export highest_when(float _high_series, bool _when) => var float _high = na _high := _high_series > _high or _when ? _high_series : _high _high // @function Permits a condition to be used with lowest(low,condition) // @param float _low_series The Low for the condition // @param float _when The condition such as close < low[1] // @returns The low(s) at the point(s) the condition was true export lowest_when(float _low_series, bool _when) => var float _low = na _low := _low_series < _low or _when ? _low_series : _low _low // Breakouts can be achieved using [1] on the end // or can keep within boundaries by removing [1] on end // Example highest_when(high, close > high[1])[1] // or lowest_when(low, close < low[1])[1] // USE FUNCTION EXAMPLE hw = highest_when(high, close > high[1])[1] lw = lowest_when(low, close < low[1])[1] plot(hw, title='Conditional Highest Highs', color=color.new(color.green, 0), linewidth=1, style=plot.style_linebr) plot(lw, title='Conditional Lowest Lows', color=color.new(color.red, 0), linewidth=1, style=plot.style_linebr) // }
AwesomeColor
https://www.tradingview.com/script/0USIQREJ-AwesomeColor/
boitoki
https://www.tradingview.com/u/boitoki/
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/ // © boitoki //@version=5 // @description The following functions all provide different sets of colors. library("AwesomeColor", overlay=false) // The name of the function indicates the color scheme. // The usage of arguments for all functions is the same. // @function {Color group name} // @param _color The name of the color group. // @returns Returns a color code. // Logical properties // - Up // - Down // - Neutral // - Buy // - Sell // - Take profit // - Stop loss // monokai // https://kolormark.com/brands/monokai export monokai (string _color) => switch _color 'purple' => #AE81FF 'blue' => #66D9EF 'green' => #A6E22E 'yellow' => #E6DB74 'orange' => #FD971F 'black' => #272822 'red' => #F92472 // Originally pink, but changed to red to add another pink 'pink' => #FB71A3 // added 'white' => #ffffff // added 'gray' => #74756F // added // Logical properties 'up' => #A6E22E 'down' => #F92472 'neutral' => #66D9EF 'buy' => #66D9EF 'sell' => #F92472 'tp' => #FD971F 'sl' => #AE81FF => na // monokai pro // https://kolormark.com/brands/monokai export monokaipro (string _color) => switch _color 'purple' => #AB9DF2 'blue' => #78DCE8 'green' => #A9DC76 'yellow' => #FFD866 'orange' => #FC9867 'red' => #FE6188 // Originally pink, but changed to red to add another pink 'pink' => #FFADC2 // added 'black' => #2D2A2E 'white' => #ffffff // added 'gray' => #7A7A7A // added 'up' => #A9DC76 'down' => #FE6188 'neutral' => #78DCE8 'buy' => #78DCE8 'sell' => #FE6188 'tp' => #FC9867 'sl' => #AB9DF2 => na // Panda // http://panda.siamak.me/ export panda (string _color) => switch _color 'verylightgray' => #E6E6E6 'lightergray' => #cdcdcd 'lightgray' => #757575 'gray' => #373b41 'darkgray' => #2e2f30 'verydarkgray' => #292A2B 'black' => #292A2B 'white' => #f3f3f3 'lightmidnight' => #676B79 'blue' => #45A9F9 'bluelight' => #6FC1FF 'purple' => #B084EB 'green' => #19f9d8 'red' => #FF2C6D 'orange' => #FFB86C 'lightorange' => #ffcc95 'pink' => #FF75B5 'lightpink' => #FF9AC1 'yellow' => #FFF145 // added 'up' => #19f9d8 'down' => #FF2C6D 'neutral' => #45A9F9 'buy' => #45A9F9 'sell' => #FF2C6D 'tp' => #FFB86C 'sl' => #B084EB => na // TradingView export tradingview (string _color) => switch _color 'blue' => #2962ff 'red' => #f23645 // #f23645 // #f44336 'green' => #22ab94 // #22ab94 // #089981 'orange' => #ff9800 // #FF9850 // #F57C00 'yellow' => #FFCA3B 'purple' => #673ab7 'lightgray' => #9598a1 'gray' => #5d606b 'black' => #131722 'white' => #b2b5be 'pink' => #F47F89 // added 'buy' => #1f44ff 'sell' => #e21e34 'up' => #22ab94 'down' => #f23645 'neutral' => #2962ff 'buy' => #2962ff 'sell' => #f23645 'tp' => #ff9800 'sl' => #673ab7 => #131722 // TradingView flag export tradingview_flag (string _color) => switch _color 'red' => #ff5252 'blue' => #2979ff 'green' => #4caf50 'orange' => #ff9100 'purple' => #ab47bc 'cyan' => #00e5ff 'pink' => #ff80ab 'black' => #131722 'white' => #b2b5be 'up' => #4caf50 'down' => #ff5252 'neutral' => #00e5ff 'buy' => #2979ff 'sell' => #ff5252 'tp' => #ff9100 'sl' => #ab47bc => na // https://github.com/nashamri/spacemacs-theme/blob/master/spacemacs-common.el export spacemacs_dark (string _color) => switch _color 'aqua' => #2d9574 'aqua-bg' => #293235 'green' => #67b11d 'green-bg' => #293235 'green-bg-s' => #29422d 'cyan' => #28def0 'red' => #f2241f 'red-bg' => #3c2a2c 'red-bg-s' => #512e31 'blue' => #4f97d7 'blue-bg' => #293239 'blue-bg-s' => #2d4252 'magenta' => #a31db1 'purple' => #a31db1 // copied magenta 'yellow' => #b1951d 'yellow-bg' => #32322c 'black' => #1e2023 'gray' => #808777 // added 'pink' => #EF74C3 // added 'orange' => #F2692C // added 'white' => #dcd6d5 'up' => #67b11d 'down' => #f2241f 'neutral' => #b1951d 'buy' => #4f97d7 'sell' => #f2241f 'tp' => #F2692C 'sl' => #a31db1 => na export spacemacs_light (string _color) => switch _color 'aqua' => #2d9574 'aqua-bg' => #edf2e9 'green' => #67b11d 'green-bg' => #edf2e9 'green-bg-s' => #dae6d0 'cyan' => #21b8c7 'red' => #f2241f 'red-bg' => #faede4 'red-bg-s' => #eed9d2 'blue' => #3a81c3 'blue-bg' => #edf1ed 'blue-bg-s' => #d1dcdf 'magenta' => #a31db1 'purple' => #a31db1 // added 'yellow' => #b1951d 'yellow-bg' => #f6f1e1 'black' => #0e0a10 'white' => #f9f7fb 'gray' => #796384 // added 'orange' => #F95B14 // added 'pink' => #F46B69 // added 'up' => #2d9574 'down' => #f2241f 'neutral' => #3a81c3 'buy' => #3a81c3 'sell' => #f2241f 'tp' => #F95B14 'sl' => #a31db1 => na // https://github.com/morhetz/gruvbox/blob/master/colors/gruvbox.vim export gruvbox (string _color) => switch _color 'bright_red' => #fb4934 'bright_green' => #b8bb26 'bright_yellow' => #fabd2f 'bright_blue' => #83a598 'bright_purple' => #d3869b 'bright_aqua' => #8ec07c 'bright_orange' => #fe8019 'neutral_red' => #cc241d 'neutral_green' => #98971a 'neutral_yellow' => #d79921 'neutral_blue' => #458588 'neutral_purple' => #b16286 'neutral_aqua' => #689d6a 'neutral_orange' => #d65d0e 'faded_red' => #9d0006 'faded_green' => #79740e 'faded_yellow' => #b57614 'faded_blue' => #076678 'faded_purple' => #8f3f71 'faded_aqua' => #427b58 'faded_orange' => #af3a03 'red' => #cc241d 'pink' => #D5615E // added 'green' => #98971a 'yellow' => #d79921 'blue' => #458588 'purple' => #b16286 'aqua' => #689d6a 'orange' => #d65d0e 'black' => #1D2021 'verydarkgray' => #282828 'darkgray' => #32302F 'gray' => #928374 'white' => #f9f5d7 'veryrightgray' => #FBF1C7 'lightergray' => #f2e5bc 'lightgray' => #ebdbb2 'up' => #98971a 'down' => #cc241d 'neutral' => #458588 'buy' => #458588 'sell' => #cc241d 'tp' => #d65d0e 'sl' => #b16286 => na // https://jakesheadwarning.tumblr.com/image/87096028457 // https://diariesofanessexgirl.com/guardians-of-the-galaxy-color-palette/ export guardians (string _color) => switch _color 'green' => #41802A 'red' => #75091e 'purple' => #8C5094 // #a35fd1 'orange' => #E17431 // added 'blue' => #385A99 // #2061c8 'yellow' => #dac23a 'black' => #000000 'white' => #ffffff 'pink' => #C7207A // added 'gray' => #493D52 // added 'up' => #385A99 'down' => #75091e 'neutral' => #8C5094 'buy' => #385A99 'sell' => #75091e 'tp' => #E17431 'sl' => #8C5094 => na // https://i.pinimg.com/originals/b8/36/6e/b8366e9f276a9fc63055f3187945247a.png export st3 (string _color) => switch _color 'black' => #090922 'white' => #E0DFE5 'navy' => #080247 'blue' => #096EBF //#0f0085 'darkpurple' => #382895 'purple' => #8768e0 'cyan' => #30bae3 'green' => #12B083 'pink' => #C70A95 'red' => #b1002a 'yellow' => #B0A612 'orange' => #E34417 'brown' => #694e2b 'darkbrown' => #51363b 'gray' => #5A595E 'up' => #12B083 'down' => #b1002a 'neutral' => #B0A612 'buy' => #096EBF 'sell' => #b1002a 'tp' => #E34417 'sl' => #8768e0 => na export st4 (string _color) => switch _color 'black' => #0D0D0D 'white' => #E0DFE5 'blue' => #0578A6 'purple' => #9632A6 //#BA07AB 'green' => #0DA667 'pink' => #F25093 'red' => #D93611 'yellow' => #F2A341 'orange' => #FC5E35 'gray' => #5C504D 'up' => #0DA667 'down' => #D93611 'neutral' => #0578A6 'buy' => #0578A6 'sell' => #D93611 'tp' => #FC5E35 'sl' => #9632A6 => na // Van Gogh // Van Gogh’s "The Painter on the Road to Tarascon" (1888) // https://commons.wikimedia.org/wiki/File:Vincent_Van_Gogh_0013.jpg export gogh_tarascon (string _color) => switch _color 'lightgreen' => #75b27f 'green' => #4c7b3d 'yellow' => #d39e2e 'blue' => #27749a 'black' => #2e3428 'up' => #4c7b3d 'down' => #d39e2e 'neutral' => #27749a 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Van Gogh’s "Wheatfield with Crows" (1890) // https://commons.wikimedia.org/wiki/File:Vincent_Van_Gogh_-_Wheatfield_with_Crows.jpg export gogh_crows (string _color) => switch _color 'navy' => #072945 'blue' => #2e68b1 'maroon' => #5f292a 'yellow' => #e7bb3c 'green' => #4e683d 'up' => #e7bb3c 'down' => #2e68b1 'neutral' => #4e683d 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Van Gogh’s "Café Terrace on the Place du Forum, Arles" (1888) // https://commons.wikimedia.org/wiki/File:Van_Gogh_-_Terrasse_des_Caf%C3%A9s_an_der_Place_du_Forum_in_Arles_am_Abend1.jpeg export gogh_cafeterrace (string _color) => switch _color 'blue' => #1f3fa0 'lightblue' => #5581c6 'orange' => #dd862e 'yellow' => #f7da44 'black' => #172128 'up' => #dd862e 'down' => #5581c6 'neutral' => #f7da44 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Helen Frankenthaler // Helen Frankenthaler’s "Flood" (1967) // https://whitney.org/collection/works/2879 export frankenthaler_flood (string _color) => switch _color 'maroon' => #2c0f0c 'red' => #88231a 'green' => #2b371f 'yellow' => #f59009 'blue' => #0a1467 'up' => #0a1467 'down' => #88231a 'neutral' => #f59009 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Helen Frankenthaler’s "The Bay" (1963) // https://www.khanacademy.org/humanities/ap-art-history/later-europe-and-americas/modernity-ap/a/frankenthaler-the-bay export frankenthaler_thebay (string _color) => switch _color 'lilac' => #949bcd 'green' => #5f7660 'purple' => #443d8e 'white' => #fef8cb 'black' => #03000e 'up' => #5f7660 'down' => #443d8e 'neutral' => #949bcd 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Georgia O’Keeffe // Georgia O’Keeffe’s "Music, Pink and Blue, №2" (1918) // https://prints.okeeffemuseum.org/detail/461218/okeeffe-music-pink-and-blue-ii-1919 export okeeffe_music (string _color) => switch _color 'green' => #9ec6be 'icegreen' => #9ec6be 'cyan' => #359bc9 'blue' => #0e6ca5 'pink' => #d890cc 'peach' => #fdc7ae 'down' => #359bc9 'up' => #d890cc 'neutral' => #fdc7ae 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Georgia O’Keeffe’s "Lake George (formerly Reflection Seascape)" (1922) // https://prints.okeeffemuseum.org/detail/493483/okeeffe-lake-george-formerly-reflection-seascape-1922 export okeeffe_lake (string _color) => switch _color 'skyblue' => #99b6d0 'horizonblue' => #6d8bac 'jayblue' => #41628a 'smalt' => #203e62 'indigo' => #10214c 'up' => #203e62 'down' => #6d8bac 'neutral' => #41628a 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Georgia O’Keeffe’s "Lake George Reflection" (1921–1922) // https://commons.wikimedia.org/wiki/File:Georgia_O%27Keeffe_-_Lake_George_Reflection.jpg export okeeffe_reflection (string _color) => switch _color 'black' => #060c09 'red' => #8f0a11 'cyan' => #4086c5 'lightblue' => #d0f1e4 'blue' => #2415c1 'up' => #4086c5 'down' => #2415c1 'neutral' => #8f0a11 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na // Georgia O’Keeffe’s "Sun Water Maine" (1922) // http://www.artnet.com/artists/georgia-okeeffe/sun-water-maine-lXkLXUE90Y-4KwWQdW2L7A2 export okeeffe_sun (string _color) => switch _color 'yellow' => #e5d67c 'blue' => #94c4d1 'lightgreen' => #8bb48f 'green' => #1a413a 'pink' => #fce7d9 'up' => #e5d67c 'down' => #94c4d1 'neutral' => #8bb48f 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => na export grayscale (string _color) => switch _color 'black' => panda('black') 'white' => panda('verylightgray') 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => color.from_gradient(50, 0, 100, panda('gray'), panda('lightgray')) export grayscale_light (string _color) => switch _color 'black' => panda('black') 'white' => panda('white') 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => panda('gray') export blackscale (string _color) => switch _color 'black' => panda('black') 'white' => panda('white') 'buy' => tradingview('blue') 'sell' => tradingview('red') 'tp' => tradingview('orange') 'sl' => tradingview('purple') => panda('black') // // red green blue orange yellow purple black white export package (string _name, string _color, color _fallback = na) => switch str.lower(_name) 'monokai' => monokai(_color) 'monokaipro' => monokaipro(_color) 'panda' => panda(_color) 'tradingview' => tradingview(_color) 'spacemacs_dark' => spacemacs_dark(_color) 'spacemacs_light' => spacemacs_light(_color) 'gruvbox' => gruvbox(_color) 'guardians' => guardians(_color) 'st3' => st3(_color) 'st4' => st4(_color) 'grayscale' => grayscale(_color) 'grayscale_dark' => grayscale(_color) 'grayscale_light' => grayscale_light(_color) 'blackscale' => blackscale(_color) 'okeeffe_sun' => okeeffe_sun(_color) 'okeeffe_reflection' => okeeffe_reflection(_color) 'okeeffe_lake' => okeeffe_lake(_color) 'okeeffe_music' => okeeffe_music(_color) 'frankenthaler_thebay' => frankenthaler_thebay(_color) 'frankenthaler_flood' => frankenthaler_flood(_color) 'gogh_cafeterrace' => gogh_cafeterrace(_color) 'gogh_crows' => gogh_crows(_color) 'gogh_tarascon' => gogh_tarascon(_color) => _fallback TRANSPARENT = color.new(#000000, 100) ////////// // TEST // i_show_colors = input.bool(true, 'Colors') i_color = input.string('Guardians', 'Color', options=['TradingView', 'monokai', 'monokaipro', 'panda', 'Gruvbox', 'Spacemacs_light', 'Spacemacs_dark', 'Guardians', 'st3', 'st4']) i_bar_color = input.string('TradingView', 'Barcolor', options=[ 'TradingView', 'monokai', 'monokaipro', 'panda', 'Gruvbox', 'Spacemacs_light', 'Spacemacs_dark', 'Guardians', 'st3', 'st4', 'gogh_tarascon', 'gogh_crows', 'gogh_cafeterrace', 'frankenthaler_flood', 'frankenthaler_thebay', 'okeeffe_sun', 'okeeffe_reflection', 'okeeffe_lake', 'okeeffe_music', 'grayscale', 'grayscale_light' ]) i_candle_hollow = input.bool(false, 'Hollow') if i_show_colors and barstate.islast a_colors = array.from('red', 'pink', 'orange', 'yellow', 'green', 'blue', 'purple', 'gray', 'black', 'white') for i = 0 to array.size(a_colors) - 1 line.new(bar_index, i * -10, bar_index + 10, i * -10, extend=extend.both, color=package(i_color, array.get(a_colors, i)), width=10) bar_color = close > open ? package(str.lower(i_bar_color), 'up') : package(str.lower(i_bar_color), 'down') ma_color = package(str.lower(i_bar_color), 'neutral') buy_color = package(str.lower(i_bar_color), 'buy') sell_color = package(str.lower(i_bar_color), 'sell') //barcolor() plotcandle(i_show_colors ? na : open, i_show_colors ? na : high, i_show_colors ? na : low, i_show_colors ? na : close, bordercolor=bar_color, wickcolor=bar_color, color=(close > open and i_candle_hollow) ? TRANSPARENT : bar_color) plot(i_show_colors ? na : ta.sma(close, 34), color=ma_color) if (ta.crossover(ta.sma(close, 10), ta.sma(close, 34))) label.new(bar_index, na, 'Buy', yloc=yloc.belowbar, style=label.style_label_up, color=buy_color, textcolor=color.white, size=size.small) if (ta.crossunder(ta.sma(close, 10), ta.sma(close, 34))) label.new(bar_index, na, 'Buy', yloc=yloc.abovebar, style=label.style_label_down, color=sell_color, textcolor=color.white, size=size.small) // (ColorLisa)[http://colorlisa.com/] // (ColorSnap)[http://snapyourcolors.com/] // (Coolors)[https://coolors.co/image-picker] // (unDraw)[https://undraw.co/] // (References)[https://uxplanet.org/the-4-master-artists-who-used-nature-inspired-color-palettes-c10441c1c7d2]
arrayutils
https://www.tradingview.com/script/9IzpUieD-arrayutils/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
59
library
5
CC-BY-NC-SA-4.0
// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © Trendoscope Pty Ltd // ░▒ // ▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒ // ▒▒▒▒▒▒▒░ ▒ ▒▒ // ▒▒▒▒▒▒ ▒ ▒▒ // ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ // ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒ // ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒ ▒▒▒▒▒ // ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗ // ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗ // ▒▒ ▒ // //@version=5 // @description Library contains utility functions using arrays. library("arrayutils") 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 // @function remove an item from array at specific index. Also deletes the item // @param arr - array from which the item needs to be deleted // @param index - index of item to be deleted // @returns void 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) // @function remove the last item from array. Also deletes the item // @param arr - array from which the last item needs to be removed and deleted // @returns void 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 // @function remove an item from array at index 0. Also deletes the item // @param arr - array from which the first item needs to be removed and deleted // @returns void 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 // @function add an item to the beginning of an array with max items cap // @param arr - array to which the item needs to be added at the beginning // @param val - value of item which needs to be added // @param maxItems - max items array can hold. After that, items are removed from the other end // @returns resulting array 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) // @function remove and delete all items in an array // @param arr - array which needs to be cleared // @returns void 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) // @function add an item to the end of an array with max items cap // @param arr - array to which the item needs to be added at the beginning // @param val - value of item which needs to be added // @param maxItems - max items array can hold. After that, items are removed from the starting index // @returns resulting array 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) // @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 a, float b, float c, float[] pivots, int[] barArray)=> cBar = array.get(barArray, 0) aBar = array.get(barArray, array.size(barArray)-1) ln = line.new(aBar, a, cBar, c) overflow = false dir = c > b? 1 : -1 for i = 1 to array.size(barArray)-2 currentBar = array.get(barArray, i) peak = array.get(pivots, i) linePrice = line.get_price(ln, 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 calculates sma for elements in array // @param source source array // @returns float sma export sma(float[] source) => array.avg(source) // @function calculates ema for elements in array // @param source source array // @param length ema length // @returns float ema export ema(float[] source, simple int length) => var ma = close last = nz(array.get(source, 0)) k = 2 / (length + 1) ma := last * k + (1 - k) * ma ma // @function calculates rma for elements in array // @param source source array // @param length rma length // @returns float rma export rma(float[] source, simple int length) => var ma = close last = nz(array.get(source, 0)) ma := (ma * (length - 1) + last) / length ma // @function calculates wma for elements in array // @param source source array // @param length wma length // @returns float wma export wma(float[] source, simple int length) => masum = 0.0 for i = 0 to length - 1 by 1 masum := masum + array.get(source, i) * (length - i) masum lenSum = length * (length + 1) / 2 masum / lenSum // @function calculates hma for elements in array // @param source source array // @param length hma length // @returns float hma export hma(float[] source, simple int length) => wma1 = wma(source, length / 2) wma2 = wma(source, length) var hmaRange = array.new_float(0) push(hmaRange, 2 * wma1 - wma2, length) float hma = na if array.size(hmaRange) == length hma := wma(hmaRange, math.round(math.sqrt(length))) hma hma // @function wrapper for all moving averages based on array // @param source source array // @param matype moving average type. Valud values are: sma, ema, rma, wma, hma, high, low, median, medianHigh, medianLow // @param length moving average length length // @returns float moving average export ma(float[] source, simple string matype, simple int length) => var float ma = ta.tr if array.size(source) >= length sliced = array.slice(source, 0, length) ma := matype == 'sma' ? sma(sliced): matype == 'ema'? ema(sliced, length): matype == 'rma'? rma(sliced, length): matype == 'wma'? wma(sliced, length): matype == 'hma'? hma(sliced, length): matype == 'high'? array.max(sliced): matype == 'low'? array.min(sliced): matype == 'median'? array.median(sliced): matype == 'medianHigh'? array.median(sliced): matype == 'medianLow'? array.median(sliced): na if(matype == 'medianHigh') ma := ta.highest(ma, length) if(matype == 'medianLow') ma := ta.lowest(ma, length) ma // @function gets fib series in array // @param numberOfFibs number of fibs // @param start starting number // @returns float[] fibArray export getFibSeries(simple int numberOfFibs, simple int start=0)=> var fibArray = array.new<int>() if(array.size(fibArray) == 0) next = 1 prev = 1 while(array.size(fibArray) < numberOfFibs) fib = next+prev prev := next next := fib if(fib >= start) array.push(fibArray, fib) fibArray
harmonicpatterns
https://www.tradingview.com/script/t1rxQm9k-harmonicpatterns/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
98
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 harmonicpatterns: methods required for calculation of harmonic patterns library("harmonicpatterns") isInRange(ratio, min, max)=> ratio >= min and ratio <= max // @function isGartleyPattern: Checks for harmonic pattern Gartley // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Gartley. False otherwise. export isGartleyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.618 * err_min xabMax = 0.618 * err_max abcMin = 0.382 * err_min abcMax = 0.886 * err_max bcdMin = 1.272 * err_min bcdMax = 1.618 * err_max xadMin = 0.786 * err_min xadMax = 0.786 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isBatPattern: Checks for harmonic pattern Bat // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Bat. False otherwise. export isBatPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.50 * err_max abcMin = 0.382 * err_min abcMax = 0.886 * err_max bcdMin = 1.618 * err_min bcdMax = 2.618 * err_max xadMin = 0.886 * err_min xadMax = 0.886 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isButterflyPattern: Checks for harmonic pattern Butterfly // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Butterfly. False otherwise. export isButterflyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.786 * err_min xabMax = 0.786 * err_max abcMin = 0.382 * err_min abcMax = 0.886 * err_max bcdMin = 1.618 * err_min bcdMax = 2.618 * err_max xadMin = 1.272 xadMax = 1.618 enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isCrabPattern: Checks for harmonic pattern Crab // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Crab. False otherwise. export isCrabPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.618 * err_max abcMin = 0.382 * err_min abcMax = 0.886 * err_max bcdMin = 2.24 * err_min bcdMax = 3.618 * err_max xadMin = 1.618 * err_min xadMax = 1.618 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isDeepCrabPattern: Checks for harmonic pattern DeepCrab // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is DeepCrab. False otherwise. export isDeepCrabPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.886 * err_min xabMax = 0.886 * err_max abcMin = 0.382 * err_min abcMax = 0.886 * err_max bcdMin = 2.00 * err_min bcdMax = 3.618 * err_max xadMin = 1.618 * err_min xadMax = 1.618 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isCypherPattern: Checks for harmonic pattern Cypher // @param xabRatio AB/XA // @param axcRatio XC/AX // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Cypher. False otherwise. export isCypherPattern(float xabRatio, float axcRatio, float xcdRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.618 * err_max axcMin = 1.13 * err_min axcMax = 1.414 * err_max xcdMin = 0.786 * err_min xcdMax = 0.786 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(axcRatio, axcMin, axcMax) and isInRange(xcdRatio, xcdMin, xcdMax) // @function isSharkPattern: Checks for harmonic pattern Shark // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Shark. False otherwise. export isSharkPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.446 * err_min xabMax = 0.618 * err_max abcMin = 1.13 * err_min abcMax = 1.618 * err_max bcdMin = 1.618 * err_min bcdMax = 2.236 * err_max xadMin = 0.886 * err_min xadMax = 0.886 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isNenStarPattern: Checks for harmonic pattern Nenstar // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Nenstar. False otherwise. export isNenStarPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.618 * err_max abcMin = 1.414 * err_min abcMax = 2.140 * err_max bcdMin = 1.272 * err_min bcdMax = 2.0 * err_max xadMin = 1.272 * err_min xadMax = 1.272 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isAntiNenStarPattern: Checks for harmonic pattern Anti NenStar // @param xabRatio - AB/XA // @param abcRatio - BC/AB // @param bcdRatio - CD/BC // @param xadRatio - AD/XA // @param err_min - Minumum error threshold // @param err_max - Maximum error threshold // @returns True if the pattern is Anti NenStar. False otherwise. export isAntiNenStarPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.5 * err_min xabMax = 0.786 * err_max abcMin = 0.467 * err_min abcMax = 0.707 * err_max bcdMin = 1.618 * err_min bcdMax = 2.618 * err_max xadMin = 0.786 * err_min xadMax = 0.786 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isAntiSharkPattern: Checks for harmonic pattern Anti Shark // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Anti Shark. False otherwise. export isAntiSharkPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.446 * err_min xabMax = 0.618 * err_max abcMin = 0.618 * err_min abcMax = 0.886 * err_max bcdMin = 1.618 * err_min bcdMax = 2.618 * err_max xadMin = 1.13 * err_min xadMax = 1.13 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isAntiCypherPattern: Checks for harmonic pattern Anti Cypher // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Anti Cypher. False otherwise. export isAntiCypherPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.5 * err_min xabMax = 0.786 * err_max abcMin = 0.467 * err_min abcMax = 0.707 * err_max bcdMin = 1.618 * err_min bcdMax = 2.618 * err_max xadMin = 1.272 * err_min xadMax = 1.272 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isAntiCrabPattern: Checks for harmonic pattern Anti Crab // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Anti Crab. False otherwise. export isAntiCrabPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.276 * err_min xabMax = 0.446 * err_max abcMin = 1.128 * err_min abcMax = 2.618 * err_max bcdMin = 1.618 * err_min bcdMax = 2.618 * err_max xadMin = 0.618 * err_min xadMax = 0.618 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isAntiButterflyPattern: Checks for harmonic pattern Anti Butterfly // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Anti Butterfly. False otherwise. isAntiButterflyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.618 * err_max abcMin = 1.127 * err_min abcMax = 2.618 * err_max bcdMin = 1.272 * err_min bcdMax = 1.272 * err_max xadMin = 0.618 xadMax = 0.786 enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isAntiBatPattern: Checks for harmonic pattern Anti Bat // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Anti Bat. False otherwise. export isAntiBatPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.618 * err_max abcMin = 1.128 * err_min abcMax = 2.618 * err_max bcdMin = 2.0 * err_min bcdMax = 2.618 * err_max xadMin = 1.128 * err_min xadMax = 1.128 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isAntiGartleyPattern: Checks for harmonic pattern Anti Gartley // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Anti Gartley. False otherwise. export isAntiGartleyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.618 * err_min xabMax = 0.786 * err_max abcMin = 1.127 * err_min abcMax = 2.618 * err_max bcdMin = 1.618 * err_min bcdMax = 1.618 * err_max xadMin = 1.272 * err_min xadMax = 1.272 * err_max enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isNavarro200Pattern: Checks for harmonic pattern Navarro200 // @param xabRatio AB/XA // @param abcRatio BC/AB // @param bcdRatio CD/BC // @param xadRatio AD/XA // @param err_min Minumum error threshold // @param err_max Maximum error threshold // @returns True if the pattern is Navarro200. False otherwise. export isNavarro200Pattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) => xabMin = 0.382 * err_min xabMax = 0.786 * err_max abcMin = 0.886 * err_min abcMax = 1.127 * err_max bcdMin = 0.886 * err_min bcdMax = 3.618 * err_max xadMin = 0.886 xadMax = 1.127 enable and isInRange(xabRatio, xabMin, xabMax) and isInRange(abcRatio, abcMin, abcMax) and isInRange(bcdRatio, bcdMin, bcdMax) and isInRange(xadRatio, xadMin, xadMax) // @function isHarmonicPattern: Checks for harmonic patterns // @param x X coordinate value // @param a A coordinate value // @param c B coordinate value // @param c C coordinate value // @param d D coordinate value // @param flags flags to check patterns. Send empty array to enable all // @param errorPercent Error threshold // @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names export isHarmonicPattern(float x, float a, float b, float c, float d, simple bool[] flags, simple int errorPercent = 8)=> ignoreFlags = array.size(flags) == 0 err_min = (100 - errorPercent) / 100 err_max = (100 + errorPercent) / 100 xabRatio = math.abs(b - a) / math.abs(x - a) abcRatio = math.abs(c - b) / math.abs(a - b) bcdRatio = math.abs(d - c) / math.abs(b - c) xadRatio = math.abs(d - a) / math.abs(x - a) axcRatio = math.abs(c - x) / math.abs(a - x) xcdRatio = math.abs(c - d) / math.abs(x - c) patternArray = array.new_bool() patternLabelArray = array.new_string() array.push(patternArray, isGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 0))) array.push(patternArray, isCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 1))) array.push(patternArray, isDeepCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 2))) array.push(patternArray, isBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 3))) array.push(patternArray, isButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 4))) array.push(patternArray, isSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 5))) array.push(patternArray, isCypherPattern(xabRatio, axcRatio, xcdRatio, err_min, err_max, ignoreFlags or array.get(flags, 6))) array.push(patternArray, isNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 7))) array.push(patternArray, isAntiNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 8))) array.push(patternArray, isAntiSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 9))) array.push(patternArray, isAntiCypherPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 10))) array.push(patternArray, isAntiCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 11))) array.push(patternArray, isAntiButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 12))) array.push(patternArray, isAntiBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 13))) array.push(patternArray, isAntiGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 14))) array.push(patternArray, isNavarro200Pattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 15))) array.push(patternLabelArray, "Gartley") array.push(patternLabelArray, "Crab") array.push(patternLabelArray, "DeepCrab") array.push(patternLabelArray, "Bat") array.push(patternLabelArray, "Butterfly") array.push(patternLabelArray, "Shark") array.push(patternLabelArray, "Cypher") array.push(patternLabelArray, "NenStar") array.push(patternLabelArray, "Anti NenStar") array.push(patternLabelArray, "Anti Shark") array.push(patternLabelArray, "Anti Cypher") array.push(patternLabelArray, "Anti Crab") array.push(patternLabelArray, "Anti Butterfly") array.push(patternLabelArray, "Anti Bat") array.push(patternLabelArray, "Anti Gartley") array.push(patternLabelArray, "Navarro200") [patternArray, patternLabelArray]
customcandles
https://www.tradingview.com/script/lxLlA0Xg-customcandles/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
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/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description customcandles: Contains methods which can send custom candlesticks based on the input library("customcandles", overlay=false) import HeWhoMustNotBeNamed/enhanced_ta/10 as eta percentb(float source, float upper, float lower)=> 100*(source-lower)/(upper-lower) percentbands(simple string btype = "bb", float source, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool useTrueRange=true, simple bool sticky=false)=> switch btype "bb" => eta.bpercentb(source, maType, length, multiplier, sticky) "kc" => eta.kpercentk(source, maType, length, multiplier, useTrueRange, sticky) => eta.dpercentd(length, true, source, sticky) // @function macandles: Provides OHLC of moving average candles // @param maType - Moving average Type. Can be sma, ema, hma, rma, wma, vwma, swma, linreg, median // @param length - Defaulted to 20. Can chose custom length // @param o - Optional different open source. By default is set to open // @param h - Optional different high source. By default is set to high // @param l - Optional different low source. By default is set to low // @param c - Optional different close source. By default is set to close // @returns [maOpen, maHigh, maLow, maClose]: Custom Moving Average based OHLC values export macandles(simple string maType="sma", simple int length=20, float o=open, float h=high, float l=low, float c=close) => maOpen = eta.ma(o, maType, length) maHigh = eta.ma(h, maType, length) maLow = eta.ma(l, maType, length) maClose = eta.ma(c, maType, length) [maOpen, maHigh, maLow, maClose] // @function hacandles: Provides Heikin Ashi OHLC values // @returns [haOpen, haHigh, haLow, haClose]: Custom Heikin Ashi OHLC values export hacandles() => haOpen = (open[1]+close[1])/2 haClose = ohlc4 haHigh = math.max(haOpen, haClose, high) haLow = math.min(haOpen, haClose, low) [haOpen, haHigh, haLow, haClose] // @function macandles: Provides OHLC of moving average candles // @param type - Oscillator Type. Can be cci, cmo, cog, mfi, roc, rsi, tsi, mfi // @param length - Defaulted to 14. Can chose custom length // @param shortLength - Used only for TSI. Default is 13 // @param longLength - Used only for TSI. Default is 25 // @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 // @param percentCandles - candles are generated based on percent with respect to high/low instead of actual oscillator values // @returns [maOpen, maHigh, maLow, maClose]: Custom Moving Average based OHLC values export ocandles(simple string type="rsi", simple int length=14, simple int shortLength = 13, simple int longLength = 25, simple string method="highlow", simple int highlowLength=50, simple bool sticky=false, simple bool percentCandles=false)=> [oOpen, oOverbought, oOversold] = eta.oscillator(source = open, type=type, length=length, shortLength=shortLength, longLength=longLength, method=method, highlowLength=highlowLength, sticky=sticky) [oHigh, hOverbought, hOversold] = eta.oscillator(source = high, type=type, length=length, shortLength=shortLength, longLength=longLength, method=method, highlowLength=highlowLength, sticky=sticky) [oLow, lOverbought, lOversold] = eta.oscillator(source = low, type=type, length=length, shortLength=shortLength, longLength=longLength, method=method, highlowLength=highlowLength, sticky=sticky) [oClose, cOverbought, cOversold] = eta.oscillator(source = close, type=type, length=length, shortLength=shortLength, longLength=longLength, method=method, highlowLength=highlowLength, sticky=sticky) if(percentCandles) oOpen := percentb(oOpen, oOverbought, oOversold) oHigh := percentb(oHigh, hOverbought, hOversold) oLow := percentb(oLow, lOverbought, lOversold) oClose := percentb(oClose, cOverbought, cOversold) [oOpen, oHigh, oLow, oClose] // @function bcandles returns candlestick made of percent range of bands - bollinger bands, keltner channel and donchian channel // @param btype Band Type. Valid options bb, kc and dc // @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 or ATR multiplier. Not applicable for Donchian Channel // @param useTrueRange - if set to false, uses high-low. Only applicable for Keltener Channel // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns [bOpen, bHigh, bLow, bClose] OHLC of band percentage export bcandles(simple string btype = "bb", simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool useTrueRange=true, simple bool sticky=false)=> bOpen = percentbands(btype, open, maType, length, multiplier, useTrueRange, sticky) bHigh = percentbands(btype, high, maType, length, multiplier, useTrueRange, sticky) bLow = percentbands(btype, low, maType, length, multiplier, useTrueRange, sticky) bClose = percentbands(btype, close, maType, length, multiplier, useTrueRange, sticky) [bOpen, bHigh, bLow, bClose] candleType = input.string("ma", "Candle Tyle", options=["ma", "ha", "osc", "bands"]) matype = input.string("sma", title="Moving Average", group="MA Candles", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"], inline="m") malength = input.int(20, step=5, title="", group="MA Candles", inline="m") oscType = input.string("cci", title="Oscillator Type", group="Oscillator", options=["cci", "cmo", "cog", "mfi", "roc", "rsi", "tsi"]) oLength = input.int(14, title="Length", group="Oscillator") shortLength = input.int(13, title="Short Length (TSI)", group="Oscillator") longLength = input.int(25, 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(false, title="Sticky", group="Oscillator") percentCandles = input.bool(false, title="Percent Candles", group="Oscillator") bandType = input.string("bb", title="Type", group="Bands/Bandwidth/BandPercent", options=["bb", "kc", "dc"]) 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") bsticky = input.bool(true, title="Sticky", group="Bands/Bandwidth/BandPercent") nOpen = 0.0 nHigh = 0.0 nLow = 0.0 nClose = 0.0 if(candleType == "ma") [maOpen, maHigh, maLow, maClose] = macandles(matype, malength) nOpen := maOpen nHigh := maHigh nLow := maLow nClose := maClose if(candleType == "ha") [haOpen, haHigh, haLow, haClose] = hacandles() nOpen := haOpen nHigh := haHigh nLow := haLow nClose := haClose if(candleType == "osc") [oOpen, oHigh, oLow, oClose] = ocandles(oscType, oLength, shortLength, longLength, method, highlowlength, osticky, percentCandles) nOpen := oOpen nHigh := oHigh nLow := oLow nClose := oClose if(candleType == "bands") [bOpen, bHigh, bLow, bClose] = bcandles(bandType, bmatype, bmalength, multiplier, useTrueRange, bsticky) nOpen := bOpen nHigh := bHigh nLow := bLow nClose := bClose wickColor = nOpen < nClose ? color.green : color.red candleColor = nClose < nClose[1]? wickColor : color.new(wickColor, 100) plotcandle(nOpen, nHigh, nLow, nClose, "Custom Candles", candleColor, wickColor, true, bordercolor=wickColor)
FunctionArrayMaxSubKadanesAlgorithm
https://www.tradingview.com/script/DUR26Nbz-FunctionArrayMaxSubKadanesAlgorithm/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
25
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 Implements Kadane's maximum sum sub array algorithm. library("FunctionArrayMaxSubKadanesAlgorithm") // reference: // https://en.wikipedia.org/wiki/Maximum_subarray_problem // https://javabypatel.blogspot.com/2015/08/find-largest-sum-contiguous-subarray-using-Kadane-algorithm.html import RicardoSantos/DebugConsole/3 as console [__T, __C] = console.init(20) // @function Kadanes algorithm. // @param samples float array, sample data values. // @returns float. export size (float[] samples) => //{ int _size_s = array.size(samples) // switch (_size_s < 1) => runtime.error('FunctionArrayMaxSubKadanesAlgorithm -> size(): "samples" has the wrong size.') // float _max_sum = array.get(samples, 0) float _current_sum = _max_sum for _i = 1 to _size_s-1 float _si = array.get(samples, _i) _current_sum := math.max(_current_sum + _si, _si) _max_sum := math.max(_max_sum, _current_sum) _max_sum //{ usage: console.queue_one(__C, str.format('maximum sum sub array size:{0}', size(array.from(-2.0, 1, -3, 4, -1.5, 2, 1, -5, -2, 5)))) console.queue_one(__C, str.format('maximum sum sub array size:{0}', size(array.from(-2.0, 1, 3, -2, 1, 4, -5, 1)))) //}} // @function Kadane's algorithm with indices. // @param samples float array, sample data values. // @returns tuple with format [float, int, int]. export indices (float[] samples) => int _size_s = array.size(samples) // switch (_size_s < 1) => runtime.error('FunctionArrayMaxSubKadanesAlgorithm -> indices(): "samples" has the wrong size.') // float _max_sum = array.get(samples, 0) float _current_sum = _max_sum int _start = 0, int _end = 0, int _s = 0 for _i = 1 to _size_s-1 float _si = array.get(samples, _i) _current_sum := math.max(_current_sum + _si, _si) if _current_sum > _max_sum _max_sum := _current_sum _start := _s _end := _i if _current_sum < 0 _current_sum := 0 _s := _i + 1 [_max_sum, _start, _end] //{ usage: [ki_0, kistart_0, kiend_0] = indices(array.from(-2.0, 1, -3, 4, -1, 2, 1, -5, -2, 5)) [ki_1, kistart_1, kiend_1] = indices(array.from(-2.0, 1, 3, -2, 1, 4, -5, 1)) console.queue_one(__C, str.format('maximum sum sub array size: {0} start:{1} end:{2}', ki_0, kistart_0, kiend_0)) console.queue_one(__C, str.format('maximum sum sub array size: {0} start:{1} end:{2}', ki_1, kistart_1, kiend_1)) //}} console.update(__T, __C)
LabelHelper
https://www.tradingview.com/script/K20wKTOs-LabelHelper/
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 Utility for managing active labels on the chart. library('LabelHelper', true) import Electrified/Time/1 ////////////////////////////////////////////////// // @function Refreshes the x position of label. // @param lbl The label to update. // @param offset A positive value will push label one bar to the right and a negative value to the left. // @returns The time value that was used. export refreshXPos( label lbl, int offset = 0) => var barLength = Time.bar() t = time + offset * barLength label.set_x(lbl, t) t ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function For creating a label at the last bar. // @param level The value to display the label at. // @param txt The text to show on the label. // @param labelColor The background color of the label. // @param textColor The text color of the label. // @param size The size of the text. Default is large. // @param textAlign The alignment of the text. Default is left. // @param offset A positive value will push label to the right and a negative to the left. // @param tooltip The optional tooltip of the label. // @returns The label that was created. export create( float level, string txt, color labelColor = color.gray, color textColor = color.white, string size = size.large, string textAlign = text.align_left, int offset = 0, string tooltip = '') => t = time + offset * Time.bar() label.new(t, level, txt, xloc.bar_time, yloc.price, labelColor, label.style_label_left, textColor, size, textAlign, tooltip) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function [DEPRECATED use .manage(…) instead] For displaying a label at the last bar. // @param level The value to display the label at. // @param txt The text to show on the label. // @param labelColor The background color of the label. // @param textColor The text color of the label. // @param size The size of the text. Default is large. // @param textAlign The alignment of the text. Default is left. // @param offset A positive value will push label to the right and a negative to the left. // @param tooltip The optional tooltip of the label. // @returns The label being managed. export add( float level, string txt, color labelColor = color.gray, color textColor = color.white, string size = size.large, string textAlign = text.align_left, int offset = 0, string tooltip = '') => // Create label on the first bar. lbl = create(level, txt, labelColor, textColor, size, textAlign, offset, tooltip) label.delete(lbl[1]) lbl ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function For displaying a label at the last bar. // @param src The existing label to manage. // @param txt The text to show on the label. // @param labelColor The background color of the label. // @param textColor The text color of the label. // @param size The size of the text. Default is large. // @param textAlign The alignment of the text. Default is left. // @param offset A positive value will push label to the right and a negative to the left. // @param tooltip The optional tooltip of the label. // @returns The active label (or 'na' if no text was provided). export manage( series label src, float level, string txt, color labelColor = color.gray, color textColor = color.white, string size = size.large, string textAlign = text.align_left, int offset = 0, string tooltip = '') => label result = na if not na(src) // possible difference duing live session. label.delete(src) if not na(src[0]) label.delete(src[0]) if not na(src[1]) label.delete(src[1]) if not na(txt) and txt != "" result := create(level, txt, labelColor, textColor, size, textAlign, offset, tooltip) result ////////////////////////////////////////////////// // Demo var label lbl = na lbl := manage(lbl, close, "CLOSE", offset = 1, tooltip = "This is\nthe close.")
cache
https://www.tradingview.com/script/f2ibenEK-cache/
GeoffHammond
https://www.tradingview.com/u/GeoffHammond/
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/ // © Geoff Hammond //@version=5 // @description A simple cache library to store key value pairs library("cache") // █▀▀ ▄▀█ █▀▀ █ █ █▀▀ █ █ █▄▄ █▀█ ▄▀█ █▀█ █▄█ // █▄▄ █▀█ █▄▄ █▀█ ██▄ █▄▄ █ █▄█ █▀▄ █▀█ █▀▄ █ // @TODO: Expiry. // ██╗ ███╗ ███╗ ██████╗ █████╗ ██████╗ ████████╗ ██████╗ // ██║ ████╗ ████║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ╚══██╔══╝ ██╔════╝ // ██║ ██╔████╔██║ ██████╔╝ ██║ ██║ ██████╔╝ ██║ ╚█████╗ // ██║ ██║╚██╔╝██║ ██╔═══╝ ██║ ██║ ██╔══██╗ ██║ ╚═══██╗ // ██║ ██║ ╚═╝ ██║ ██║ ╚█████╔╝ ██║ ██║ ██║ ██████╔╝ // ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ import GeoffHammond/assert/3 // ██╗ ██╗███████╗██╗ ██████╗ ███████╗██████╗ ██████╗ // ██║ ██║██╔════╝██║ ██╔══██╗██╔════╝██╔══██╗██╔════╝ // ███████║█████╗ ██║ ██████╔╝█████╗ ██████╔╝╚█████╗ // ██╔══██║██╔══╝ ██║ ██╔═══╝ ██╔══╝ ██╔══██╗ ╚═══██╗ // ██║ ██║███████╗███████╗██║ ███████╗██║ ██║██████╔╝ // ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═════╝ // COPY THESE HELPERS INTO YOUR SCRIPT // [__CACHE_KEYS, __CACHE_VALUES] = cache.init() // cache_set(key, value) => cache.set(__CACHE_KEYS, __CACHE_VALUES, key, value) // cache_has(key) => cache.has(__CACHE_KEYS, __CACHE_VALUES, key) // cache_get(key) => cache.get(__CACHE_KEYS, __CACHE_VALUES, key) // cache_remove(key) => cache.remove(__CACHE_KEYS, __CACHE_VALUES, key) // cache_count() => cache.count(__CACHE_KEYS, __CACHE_VALUES) // cache_loop() => cache.loop(__CACHE_KEYS, __CACHE_VALUES) // cache_next() => cache.next(__CACHE_KEYS, __CACHE_VALUES) // cache_clear() => cache.clear(__CACHE_KEYS, __CACHE_VALUES) // cache_debug() => // while cache_loop() // [k, v] = cache_next() // debug(k, v) // see log library for this function // ███████╗ ██╗ ██╗ ███╗ ██╗ █████╗ ████████╗ ██╗ █████╗ ███╗ ██╗ ██████╗ // ██╔════╝ ██║ ██║ ████╗ ██║ ██╔══██╗ ╚══██╔══╝ ██║ ██╔══██╗ ████╗ ██║ ██╔════╝ // █████╗ ██║ ██║ ██╔██╗██║ ██║ ╚═╝ ██║ ██║ ██║ ██║ ██╔██╗██║ ╚█████╗ // ██╔══╝ ██║ ██║ ██║╚████║ ██║ ██╗ ██║ ██║ ██║ ██║ ██║╚████║ ╚═══██╗ // ██║ ╚██████╔╝ ██║ ╚███║ ╚█████╔╝ ██║ ██║ ╚█████╔╝ ██║ ╚███║ ██████╔╝ // ╚═╝ ╚═════╝ ╚═╝ ╚══╝ ╚════╝ ╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚══╝ ╚═════╝ check_integrity(string[] keys, float[] values) => if array.size(keys) != array.size(values) runtime.error('Cache: Keys and values array sizes are not equal!') // ██╗ ██╗██████╗ ██████╗ █████╗ ██████╗ ██╗ ██╗ // ██║ ██║██╔══██╗██╔══██╗██╔══██╗██╔══██╗╚██╗ ██╔╝ // ██║ ██║██████╦╝██████╔╝███████║██████╔╝ ╚████╔╝ // ██║ ██║██╔══██╗██╔══██╗██╔══██║██╔══██╗ ╚██╔╝ // ███████╗██║██████╦╝██║ ██║██║ ██║██║ ██║ ██║ // ╚══════╝╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ // @function Initialises the syncronised cache key and value arrays // @param persistant bool, toggles data persistance between bars and ticks // @returns [string[], float[]], a tuple of both arrays export init(bool persistant = false) => varip keys = array.new_string() varip values = array.new_float() [persistant ? keys : array.new_string(), persistant ? values : array.new_float()] // @function Sets a value into the cache // @param keys string[], the array of cache keys // @param values float[], the array of cache values // @param key string, the cache key to create or update // @param value float, the value to set export set(string[] keys, float[] values, string key, float value) => check_integrity(keys, values) index = array.indexof(keys, key) if index > -1 array.set(values, index, value) else array.push(keys, key) array.push(values, value) // @function Checks if the cache has a key // @param keys string[], the array of cache keys // @param values float[], the array of cache values // @param key string, the cache key to check // @returns bool, true only if the key is found export has(string[] keys, float[] values, string key) => check_integrity(keys, values) array.includes(keys, key) // @function Gets a keys value from the cache // @param keys string[], the array of cache keys // @param values float[], the array of cache values // @param key string, the cache key to get // @returns float, the stored value export get(string[] keys, float[] values, string key) => check_integrity(keys, values) index = array.indexof(keys, key) index > -1 ? array.get(values, index) : float(na) // @function Removes a key and value from the cache // @param keys string[], the array of cache keys // @param values float[], the array of cache values // @param key string, the cache key to remove export remove(string[] keys, float[] values, string key) => check_integrity(keys, values) index = array.indexof(keys, key) if index > -1 array.remove(keys, index) array.remove(values, index) // @function Counts how many key value pairs in the cache // @returns int, the total number of pairs export count(string[] keys, float[] values) => check_integrity(keys, values) array.size(values) // @function Returns true for each value in the cache (use as the while loop expression) // @param keys string[], the array of cache keys // @param values float[], the array of cache values export loop(string[] keys, float[] values) => check_integrity(keys, values) varip i = 0 if i < array.size(values) i += 1 true else i := 0 false // @function Returns each key value pair on successive calls (use in the while loop) // @param keys string[], the array of cache keys // @param values float[], the array of cache values // @returns [string, float], tuple of each key value pair export next(string[] keys, float[] values) => check_integrity(keys, values) size = array.size(values) varip i = 0 if size == 0 [string(na), float(na)] else offset = i i := i + 1 == size ? 0 : i + 1 [array.get(keys, offset), array.get(values, offset)] // @function Clears all key value pairs from the cache // @param keys string[], the array of cache keys // @param values float[], the array of cache values export clear(string[] keys, float[] values) => array.clear(keys) array.clear(values) // ██╗ ██╗ ███╗ ██╗ ██╗ ████████╗ ████████╗ ███████╗ ██████╗ ████████╗ ██████╗ // ██║ ██║ ████╗ ██║ ██║ ╚══██╔══╝ ╚══██╔══╝ ██╔════╝ ██╔════╝ ╚══██╔══╝ ██╔════╝ // ██║ ██║ ██╔██╗██║ ██║ ██║ ██║ █████╗ ╚█████╗ ██║ ╚█████╗ // ██║ ██║ ██║╚████║ ██║ ██║ ██║ ██╔══╝ ╚═══██╗ ██║ ╚═══██╗ // ╚██████╔╝ ██║ ╚███║ ██║ ██║ ██║ ███████╗ ██████╔╝ ██║ ██████╔╝ // ╚═════╝ ╚═╝ ╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ // @function Cache module unit tests, for inclusion in parent script test suite. Usage: log.unittest_cache(__ASSERTS) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) export unittest_cache(string[] case) => assert.new_case(case, 'Cache:init') [ks, vs] = init() assert.is_false(has(ks, vs, 'test'), case, 'has false') assert.new_case(case, 'Cache:set #1') set(ks, vs, 'test', 1) assert.equal(array.size(ks), 1, case, 'keys size') assert.equal(array.size(vs), 1, case, 'values size') assert.is_true(has(ks, vs, 'test'), case, 'has') assert.equal(get(ks, vs, 'test'), 1, case, 'get') assert.new_case(case, 'Cache:set #2') set(ks, vs, 'test', 2) assert.equal(array.size(ks), 1, case, 'keys size') assert.equal(array.size(vs), 1, case, 'values size') assert.is_true(has(ks, vs, 'test'), case, 'has') assert.equal(get(ks, vs, 'test'), 2, case, 'get') assert.new_case(case, 'Cache:set #3') set(ks, vs, 'test2', 1.1) assert.equal(array.size(ks), 2, case, 'keys size') assert.equal(array.size(vs), 2, case, 'values size') assert.is_true(has(ks, vs, 'test2'), case, 'has') assert.equal(get(ks, vs, 'test2'), 1.1, case, 'get') assert.new_case(case, 'Cache:remove') remove(ks, vs, 'test') assert.equal(array.size(ks), 1, case, 'keys size') assert.equal(array.size(vs), 1, case, 'values size') assert.is_false(has(ks, vs, 'test'), case, 'has') assert.nan(get(ks, vs, 'test'), case, 'get') assert.is_true(has(ks, vs, 'test2'), case, 'has test2') assert.equal(get(ks, vs, 'test2'), 1.1, case, 'get test2') assert.new_case(case, 'Cache:clear') clear(ks, vs) assert.equal(array.size(ks), 0, case, 'keys size') assert.equal(array.size(vs), 0, case, 'values size') assert.is_false(has(ks, vs, 'test'), case, 'has test') assert.is_false(has(ks, vs, 'test2'), case, 'has test2') assert.new_case(case, 'Cache:count') assert.equal(count(ks, vs), 0, case, 'count is 0') set(ks, vs, 'test', 1) assert.equal(count(ks, vs), 1, case, 'count is 1') set(ks, vs, 'test2', 2) assert.equal(count(ks, vs), 2 , case, 'count is 2') assert.new_case(case, 'Cache:loop') i = 0 while loop(ks, vs) i += 1 assert.equal(i, 2, case, 'loop') // These static calls of next are only valid on the first bar and should not be used outside a while loop assert.new_case(case, 'Cache:next') [key1, value1] = next(ks, vs) assert.str_equal(key1, 'test', case, 'key1') assert.equal(value1, 1, case, 'value1') [key2, value2] = next(ks, vs) assert.str_equal(key2, 'test', case, 'key2') assert.equal(value2, 1, case, 'value2') i := 0 while loop(ks, vs) i += 1 [k, v] = next(ks, vs) assert.str_equal(k, i == 1 ? 'test' : i == 2 ? 'test2' : 'unknown', case, 'loop key' + str.tostring(i)) assert.equal(v, i, case, 'loop value' + str.tostring(i)) // @function Run the cache module unit tests as a stand alone. Usage: cache.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_cache(__ASSERTS) assert.report(__ASSERTS, verbose) // ██████╗ ██╗ ██╗ ███╗ ██╗ // ██╔══██╗ ██║ ██║ ████╗ ██║ // ██████╔╝ ██║ ██║ ██╔██╗██║ // ██╔══██╗ ██║ ██║ ██║╚████║ // ██║ ██║ ╚██████╔╝ ██║ ╚███║ // ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══╝ unittest() // _.-'~~`~~'-._ // .'` B E R `'. // / I T \ // /` .-'~"-. `\ // ; L / `- \ Y ; // ; /> `. -.| ; // | /_ '-.__) | // | |- _.' \ | | // ; `~~; \\ ; // ; INGODWE / \\)P ; // \ TRUST '.___.-'`" / // `\ /` // '._ 1 9 9 7 _.' // `'-..,,,..-'` - No! No! No! That's not what I meant!
SessionInfo
https://www.tradingview.com/script/bSBICQeV-SessionInfo/
Electrified
https://www.tradingview.com/u/Electrified/
38
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 Utility functions for session specific information like the bar index of the session. library('SessionInfo', false) // Note: The following are already provided by PineScript 5. // session.ismarket https://www.tradingview.com/pine-script-reference/v5/#var_session{dot}ismarket // session.ispremarket https://www.tradingview.com/pine-script-reference/v5/#var_session{dot}ispremarket // session.ispostmarket https://www.tradingview.com/pine-script-reference/v5/#var_session{dot}ispostmarket /////////////////////////////////////////////////// // Session Info /////////////////////////////////// /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns true if the current bar is in the session specification. // @param spec session.regular (default), session.extended or other time spec. // @returns True if the current is in session; otherwise false. export isIn( simple string spec = session.regular, simple string res = timeframe.period) => not na(time(res, spec)) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns true if the bar is before before the session (default = regular) opens. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = timeframe.period). // @returns True if before the session. export isBefore( simple string spec = session.regular, simple string res = timeframe.period) => if not timeframe.isintraday false else var y = year var m = month var d = dayofmonth var bool start = false if y != year or m != month or d != dayofmonth y := year m := month d := dayofmonth start := true if isIn(spec, res) start := false false else start /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns true if the bar is before before the session (default = regular) opens. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = timeframe.period). // @returns True if before the session. export isAfter( simple string spec = session.regular, simple string res = timeframe.period) => if not timeframe.isintraday false else var y = year var m = month var d = dayofmonth var int phase = na if y != year or m != month or d != dayofmonth y := year m := month d := dayofmonth phase := 0 if isIn(spec, res) phase := 1 false else phase == 1 /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Converts the number of minutes to a length to be used with indicators. // @param minutes The number of minutes. // @param multiple The length multiplier. // @returns math.ceil(minutes * multiple / timeframe.multiplier) export minutesToLen( simple int minutes, simple float multiple = 1) => math.ceil(minutes * multiple / timeframe.multiplier) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the intraday bar index. May not always map directly to time as a bars can be skipped. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The integer index of the bar of the session. export bar( simple string spec = session.regular, simple string res = '1440') => var int notYet = na if timeframe.isdaily 0 else if not timeframe.isintraday notYet else var barCount = -1 barCount += 1 var y = year var m = month var d = dayofmonth var int firstBar = na t = time(res, spec) if na(t) or y != year or m != month or d != dayofmonth y := year m := month d := dayofmonth firstBar := na(t) ? na : barCount else if na(firstBar) and (na(t[1]) and not na(t) or t[1] < t) firstBar := barCount barCount - firstBar /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the number bars in the past to find the first bar of the session of a given day. // @param daysPrior The number of days in the past to count the bars. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The number bars in the past to find the first bar of the session of a given day. export firstBarOfDay( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => var int notYet = na if daysPrior < 0 runtime.error('firstBarOfDay(daysPrior) must be (>=0) at least zero.') notYet else if timeframe.isdaily 0 else if not timeframe.isintraday notYet else var days = daysPrior + 1 var dayRecord = array.new_int() var dayCount = 0 var barCount = -1 barCount += 1 var y = year var m = month var d = dayofmonth var int firstBar = na t = time(res, spec) if y != year or m != month or d != dayofmonth y := year m := month d := dayofmonth if not na(t) array.push(dayRecord, barCount) dayCount += 1 if dayCount > days array.shift(dayRecord) dayCount -= 1 else if na(t[1]) and not na(t) or t[1] < t array.push(dayRecord, barCount) dayCount += 1 if dayCount > days array.shift(dayRecord) dayCount -= 1 dayCount == 0 ? notYet : barCount - array.get(dayRecord, 0) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns true if the current bar is the first one of the session. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns True if the current bar is the first one of the session. export isFirstBar( simple string spec = session.regular, simple string res = '1440') => bar(spec, res) == 0 /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns Returns true if the previous bar was the last of the session. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns True if was the last bar of the session. export wasLastBar( simple string spec = session.regular, simple string res = '1440') => var bool notYet = na if timeframe.isdaily true else if not timeframe.isintraday notYet else var int b = na bb = bar(spec, res) wasLast = bb < b or na(bb) and not na(b) b := bb wasLast /////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns maximum (usual) number of bars per day. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The max (usual) number of bars per day. export maxBars( simple string spec = session.regular, simple string res = '1440') => var int notYet = na if timeframe.isdaily 1 else if not timeframe.isintraday notYet else var int max = na var int b = 0 var int count = 0 b += 1 if wasLastBar(spec, res) count += 1 if na(max) or b > max max := b if isFirstBar(spec, res) b := 0 count > 3 ? max : na /////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns maximum (usual) number of minutes per day. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The max (usual) number of minutes per day. export maxMinutes( simple string spec = session.regular, simple string res = '1440') => maxBars(spec, res) * timeframe.multiplier /////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns the number of bars equal to the number of days based upon usual session length. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The number of bars representing the number of days. export daysToBars( simple int days, simple string spec = session.regular, simple string res = '1440') => var int notYet = na if timeframe.isdaily days else if not timeframe.isintraday notYet else days * maxBars(spec, res) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the number bars in the past to find the last bar of the session of a given day. // @param daysPrior The number of days in the past to count the bars. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The number bars in the past to find the last bar of the session of a given day. export lastBarOfDay( simple int daysPrior = 1, simple string spec = session.regular, simple string res = '1440') => var int notYet = na if daysPrior < 1 runtime.error('lastBarOfDay(daysPrior) must be (>=1) at least one.') notYet else if timeframe.isdaily daysPrior else if not timeframe.isintraday notYet else var dayRecord = array.new_int() var dayCount = 0 var barCount = -1 barCount += 1 if wasLastBar(spec, res) array.push(dayRecord, barCount - 1) dayCount += 1 if dayCount > daysPrior array.shift(dayRecord) dayCount -= 1 dayCount == 0 ? notYet : barCount - array.get(dayRecord, 0) /////////////////////////////////////////////////// bos = bar() plot(bos, 'Bar of the Standard Session', color=color.green, style=plot.style_stepline) bose = bar(session.extended) plot(bose, 'Bar of the Extended Session', style=plot.style_stepline)
Moments
https://www.tradingview.com/script/PgteBq8S-Moments/
nolantait
https://www.tradingview.com/u/nolantait/
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/ // © dontspamnolan //@version=5 // @description: Calculates the moments of a source based on Moments (Mean,Variance,Skewness,Kurtosis) [pig] library("Moments") // --- Constants centerLine = 0 zScoreSmallSample = 1.96 // Absolute zscore for N < 50 95% confidence zScoreLargeSample = 3.29 // Absolute zscore for N > 50 95% confidence skewReferenceValue = 2.0 // Skewness reference value for N > 300 kurtosisReferenceValue = 10.0 // Excess Kurtosis reference value for N > 300 (value for kurtosis is 7, excess kurtosis = 7 + 3) // @function Calculates log returns of a series (e.g log percentage change) // @param src Source to use for the returns calculation (e.g. close). // @returns Log percentage returns of a series export logReturns(float src = close) => returns = src / src[1] math.log(returns) // @function Calculates the mean of a series using ta.sma // @param src Source to use for the mean calculation (e.g. close). // @param length Length to use mean calculation (e.g. 14). // @returns The sma of the source over the length provided. export mean(float src, int length) => ta.sma(src, length) // @function Calculates the variance of a series // @param src Source to use for the variance calculation (e.g. close). // @param length Length to use for the variance calculation (e.g. 14). // @returns The variance of the source over the length provided. export variance(float src, int length) => sample = array.new_float(0) sampleMean = mean(src, length) for i=0 to length-1 array.push(sample, math.pow(src[i] - sampleMean, 2)) sum = array.sum(sample) sum / (length-1) // @function Calculates the standard deviation of a series // @param src Source to use for the standard deviation calculation (e.g. close). // @param length Length to use for the standard deviation calculation (e.g. 14). // @returns The standard deviation of the source over the length provided. export standardDeviation(float src, int length) => math.sqrt(variance(src, length)) // @function Calculates the skewness of a series // @param src Source to use for the skewness calculation (e.g. close). // @param length Length to use for the skewness calculation (e.g. 14). // @returns The skewness of the source over the length provided. export skewness(float src, int length) => stdev = standardDeviation(src, length) sampleMean = mean(src, length) sample = array.new_float(0) for i=0 to length-1 array.push(sample, math.pow(src[i] - sampleMean, 3)) sum = array.sum(sample) a = sum * length b = (length-1) * (length-2) * math.pow(stdev, 3) a / b // @function Calculates the kurtosis of a series // @param src Source to use for the kurtosis calculation (e.g. close). // @param length Length to use for the kurtosis calculation (e.g. 14). // @returns The kurtosis of the source over the length provided. export kurtosis(float src, int length) => stdev = standardDeviation(src, length) sampleMean = mean(src, length) sample = array.new_float(0) for i=0 to length-1 array.push(sample, math.pow(src[i] - sampleMean, 4)) sum = array.sum(sample) a = length * (length+1) * sum b = (length-1) * (length-2) * (length-3) * math.pow(stdev, 4) (a / b) - (3 * math.pow((length-1), 2)) / ((length-2) * (length-3)) // @function Estimates the standard error of skewness based on sample size // @param sampleSize The number of samples used for calculating standard error. // @returns The standard error estimate for skewness based on the sample size provided. export skewnessStandardError(int sampleSize) => math.sqrt((6 * sampleSize * (sampleSize - 1)) / ((sampleSize - 2) * (sampleSize + 1) * (sampleSize + 3))) // @function Estimates the standard error of kurtosis based on sample size // @param sampleSize The number of samples used for calculating standard error. // @returns The standard error estimate for kurtosis based on the sample size provided. export kurtosisStandardError(int sampleSize) => skewnessError = skewnessStandardError(sampleSize) 2 * skewnessError * math.sqrt((math.pow(sampleSize, 2) - 1) / ((sampleSize - 3) * (sampleSize + 5))) // @function Estimates the critical value of skewness based on sample size // @param sampleSize The number of samples used for calculating critical value. // @returns The critical value estimate for skewness based on the sample size provided. export skewnessCriticalValue(int sampleSize) => if sampleSize > 300 skewReferenceValue else if sampleSize > 50 zScoreLargeSample * skewnessStandardError(sampleSize) else zScoreSmallSample * skewnessStandardError(sampleSize) // @function Estimates the critical value of kurtosis based on sample size // @param sampleSize The number of samples used for calculating critical value. // @returns The critical value estimate for kurtosis based on the sample size provided. export kurtosisCriticalValue(int sampleSize) => if sampleSize > 300 kurtosisReferenceValue else if sampleSize > 50 zScoreLargeSample * kurtosisStandardError(sampleSize) else zScoreSmallSample * kurtosisStandardError(sampleSize) // Example returns = logReturns(close) * 100 length = 14 plot(returns, "Log Returns", color=color.green) plot(variance(returns, length), "Variance", color=color.blue) plot(standardDeviation(returns, length), "Stdev", color=color.purple) plot(skewness(returns, length), "Skewness", color=color.lime) plot(kurtosis(returns, length), "Kurtosis", color=color.red) plot(skewnessCriticalValue(length), "Skewness Critical Value", color=color.white) plot(kurtosisCriticalValue(length), "Kurtosis Critical Value", color=color.black)
DailyLevels
https://www.tradingview.com/script/njlelywY-DailyLevels/
Electrified
https://www.tradingview.com/u/Electrified/
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/ // © Electrified (electrifiedtrading) // @version=5 // @description Functions for acquiring daily timeframe data by number of prior days. library('DailyLevels', true) import Electrified/SessionInfo/9 as Session _open( simple int daysPrior, simple string spec = session.regular, simple string res = '1440') => var float result = na if daysPrior < 0 runtime.error('DailyLevels._open(daysPrior) cannot be at less than zero.') result if timeframe.isdaily result := open[daysPrior] else if not timeframe.isintraday result else if daysPrior == 0 // Current day does not have a valid value until session is open. if Session.isBefore(spec, res) result := na else if Session.isFirstBar(spec, res) or na(result) result := open // this could be na else result else d = daysPrior + 1 // need +1 to skip current day. var days = array.new_float() if Session.isFirstBar(spec, res) or na(result) result := open array.push(days, result) if array.size(days)>d array.shift(days) array.size(days) < d ? na : array.get(days, 0) //// _high( series float src, simple int daysPrior, simple string spec = session.regular, simple string res = '1440') => var float result = na if daysPrior < 0 runtime.error('DailyLevels._high(daysPrior) cannot be at less than zero.') result else if timeframe.isdaily result := src[daysPrior] else if not timeframe.isintraday result else if daysPrior == 0 var today = src if Session.isFirstBar(spec, res) or src > today and Session.isIn(spec, res) today := src result := today else var days = array.new_float() if Session.isIn(spec, res) and (na(result) or src > result) result := src if Session.wasLastBar(spec, res) and not na(result) array.push(days, result[1]) result := na if array.size(days)>daysPrior array.shift(days) array.size(days) < daysPrior ? na : array.get(days, 0) //// _low( series float src, simple int daysPrior, simple string spec = session.regular, simple string res = '1440') => var float result = na if daysPrior < 0 runtime.error('DailyLevels._low(daysPrior) cannot be at less than zero.') result else if timeframe.isdaily result := src[daysPrior] else if not timeframe.isintraday result else if daysPrior == 0 var today = src if Session.isFirstBar(spec, res) or src < today and Session.isIn(spec, res) today := src result := today else var days = array.new_float() if Session.isIn(spec, res) and (na(result) or src < result) result := src if Session.wasLastBar(spec, res) and not na(result) array.push(days, result[1]) result := na if array.size(days)>daysPrior array.shift(days) array.size(days) < daysPrior ? na : array.get(days, 0) //// _close( simple int daysPrior, simple string spec = session.regular, simple string res = '1440') => max_bars_back(close, 9999) var float result = na if daysPrior < 0 runtime.error('DailyLevels._close(daysPrior) cannot be at less than zero.') result if timeframe.isdaily result := close[daysPrior] else if not timeframe.isintraday result else if daysPrior == 0 // Current day does not have a valid value until session is open. if Session.isBefore(spec, res) result := na else if not na(close) and Session.isIn(spec, res) result := close // this could be na else result else var days = array.new_float() if Session.wasLastBar(spec, res) or na(result) result := close[1] array.push(days, result) if array.size(days)>daysPrior array.shift(days) array.size(days) < daysPrior ? na : array.get(days, 0) //// ////////////////////////////////////////////////// // @type Simple type for holding high and low values. export type HighLow float high float low ////////////////////////////////////////////////// // @type Simple type for holding OHLC values. export type OpenHighLowClose float open float high float low float close ////////////////////////////////////////////////// // @function Gets the open for the number of days prior. // @param daysPrior Number of days back to get the open from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The open for the number of days prior. export O( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => _open(daysPrior, spec, res) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the highest value for the number of days prior. // @param src The series to use for values. // @param daysPrior Number of days back to get the high from. // @param extraForward Number of extra days forward to include. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The high for the number of days prior. export highOf( series float src, simple int daysPrior = 0, simple int extraForward = 0, simple string spec = session.regular, simple string res = '1440') => var int notYet = na if extraForward < 0 runtime.error('DailyLevels.highOf(extraForward) must be at least zero.') notYet else if extraForward > daysPrior runtime.error('DailyLevels.highOf(extraForward) has not enough days back to meet the requested extra.') notYet else hi = _high(src, daysPrior, spec, res) e = extraForward while e > 0 v = _high(src, daysPrior - e, spec, res) if v > hi hi := v e -= 1 hi ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the highest value for the number of days prior. // @param daysPrior Number of days back to get the high from. // @param extraForward Number of extra days forward to include. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The high for the number of days prior. export H( simple int daysPrior = 0, simple int extraForward = 0, simple string spec = session.regular, simple string res = '1440') => highOf(high, daysPrior, extraForward, spec, res) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the lowest value for the number of days prior. // @param src The series to use for values. // @param daysPrior Number of days back to get the low from. // @param extraForward Number of extra days forward to include. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The low for the number of days prior. export lowOf( series float src, simple int daysPrior = 0, simple int extraForward = 0, simple string spec = session.regular, simple string res = '1440') => var int notYet = na if extraForward < 0 runtime.error('DailyLevels.lowOf(extraForward) must be at least zero.') notYet else if extraForward > daysPrior runtime.error('DailyLevels.lowOf(extraForward) has not enough days back to meet the requested extra.') notYet else lo = _low(src, daysPrior, spec, res) e = extraForward while e > 0 v = _low(src, daysPrior - e, spec, res) if v < lo lo := v e -= 1 lo ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the lowest value for the number of days prior. // @param daysPrior Number of days back to get the low from. // @param extraForward Number of extra days forward to include. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The low for the number of days prior. export L( simple int daysPrior = 0, simple int extraForward = 0, simple string spec = session.regular, simple string res = '1440') => lowOf(low, daysPrior, extraForward, spec, res) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the close for the number of days prior. // @param daysPrior Number of days back to get the close from. 0 produces the current close. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The close for the number of days prior. export C( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => _close(daysPrior, spec, res) ////////////////////////////////////////////////// _hlc3( simple int daysPrior, simple int extraForward = 0, simple string spec = session.regular, simple string res = '1440') => var float result = na if daysPrior < 0 runtime.error('DailyLevels._hlc3(daysPrior) cannot be at less than zero.') result else hi = H(daysPrior, extraForward, spec, res) lo = L(daysPrior, extraForward, spec, res) c = _close(daysPrior - extraForward, spec, res) (hi + lo + c) / 3 //// ////////////////////////////////////////////////// // @function Gets the HLC3 value for the number of days prior. // @param daysPrior Number of days back to get the HLC3 from. // @param extraForward Number of extra days forward to include. Determines the closing value. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The HLC3 for the number of days prior. export HLC3( simple int daysPrior = 0, simple int extraForward = 0, simple string spec = session.regular, simple string res = '1440') => _hlc3(daysPrior, extraForward, spec, res) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the high and low values for the number of days prior. // @param daysPrior Number of days back to get the high and low from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The high and low for the number of days prior. export HL( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => HighLow.new(_high(high, daysPrior, spec, res), _low(low, daysPrior, spec, res)) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the OHLC values for the number of days prior. // @param daysPrior Number of days back to get the OHLC from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns The OHLC for the number of days prior. export OHLC( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => OpenHighLowClose.new( _open(daysPrior, spec, res), _high(high, daysPrior, spec, res), _low(low, daysPrior, spec, res), _close(daysPrior, spec, res)) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // Array Helpers ///////////////////////////////// // Use these when repeated access to the daily data is needed. ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets all the open values for the number of days prior. // @param daysPrior Number of days back to get the open from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns An array of the previous open values. export openArray( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => var result = array.new_float(daysPrior + 1) if Session.isFirstBar(spec, res) array.unshift(result, open[0]) array.pop(result) result ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets all the close values for the number of days prior. // @param daysPrior Number of days back to get the close from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns An array of the previous close values. export closeArray( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => var result = array.new_float(daysPrior + 1) v = _close(0, spec, res) if Session.isFirstBar(spec, res) array.unshift(result, v) array.pop(result) 0 else if Session.isIn(spec, res) array.set(result, 0, v) 0 result ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the highest value for the number of days prior for each day as an array. // @param src The series to use for values. // @param daysPrior Number of days back to get the high from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns An array of the values. export highOfArray( series float src, simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => var result = array.new_float(daysPrior + 1) v = _high(src, 0, spec, res) if Session.isFirstBar(spec, res) array.unshift(result, v) array.pop(result) 0 else if Session.isIn(spec, res) array.set(result, 0, v) 0 result ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the highest value for the number of days prior for each day as an array. // @param daysPrior Number of days back to get the high from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns An array of the values. export highArray( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => highOfArray(high, daysPrior, spec, res) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the lowest value for the number of days prior for each day as an array. // @param src The series to use for values. // @param daysPrior Number of days back to get the high from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns An array of the values. export lowOfArray( series float src, simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => var result = array.new_float(daysPrior + 1) v = _low(src, 0, spec, res) if Session.isFirstBar(spec, res) array.unshift(result, v) array.pop(result) 0 else if Session.isIn(spec, res) array.set(result, 0, v) 0 result ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the lowest value for the number of days prior for each day as an array. // @param daysPrior Number of days back to get the high from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns An array of the values. export lowArray( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => lowOfArray(low, daysPrior, spec, res) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the hlc3 value for the number of days prior for each day as an array. // @param daysPrior Number of days back to get the high from. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @returns An array of the values. export hlc3Array( simple int daysPrior = 0, simple string spec = session.regular, simple string res = '1440') => var result = array.new_float(daysPrior + 1) v = _hlc3(0, 0, spec, res) if Session.isFirstBar(spec, res) array.unshift(result, v) array.pop(result) 0 else if Session.isIn(spec, res) array.set(result, 0, v) 0 result ////////////////////////////////////////////////// days = input(1, "Days Prior") plot(O(days), 'Previous Open', color=color.yellow) plot(H(days), 'Previous High', color=color.red, style=plot.style_circles) plot(L(days), 'Previous Low', color=color.green, style=plot.style_circles) plot(C(days), 'Previous Close', color=color.blue)
PivotPointsDailyTraditional
https://www.tradingview.com/script/lsnmCmBf-PivotPointsDailyTraditional/
Electrified
https://www.tradingview.com/u/Electrified/
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/ // © Electrified (electrifiedtrading) // @version=5 // @description Provides the traditional daily pivot values and a pivot vacinity function. library('PivotPointsDailyTraditional', true) import Electrified/DailyLevels/9 as Daily // https://www.tradingview.com/support/solutions/43000521824-pivot-points-standard/ // Traditional // PP = (HIGHprev + LOWprev + CLOSEprev) / 3 // R1 = PP * 2 - LOWprev // S1 = PP * 2 - HIGHprev // R2 = PP + (HIGHprev - LOWprev) // S2 = PP - (HIGHprev - LOWprev) // R3 = PP * 2 + (HIGHprev - 2 * LOWprev) // S3 = PP * 2 - (2 * HIGHprev - LOWprev) // R4 = PP * 3 + (HIGHprev - 3 * LOWprev) // S4 = PP * 3 - (3 * HIGHprev - LOWprev) // R5 = PP * 4 + (HIGHprev - 4 * LOWprev) // S5 = PP * 4 - (4 * HIGHprev - LOWprev) /////////////////////////////////////////////////// // @function Returns the P value. // @param level The level to caclulate. // @param daysPrior The number of days in the past to do the calculation. export P( simple int daysPrior = 0) => Daily.HLC3(daysPrior + 1) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Calculates the R value for a given pivot level. // @param level The level to caclulate. // @param daysPrior The number of days in the past to do the calculation. export R( int level, simple int daysPrior = 0) => day = daysPrior + 1 switch level 1 => P(daysPrior) * 2 - Daily.L(day) 2 => P(daysPrior) + Daily.H(day) - Daily.L(day) => if level < 1 runtime.error('"level" must be at least one.') na else ratio = level - 1 P(daysPrior) * ratio + Daily.H(day) - ratio * Daily.L(day) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Calculates the S value for a given pivot level. // @param level The level to caclulate. // @param daysPrior The number of days in the past to do the calculation. export S( int level, simple int daysPrior = 0) => day = daysPrior + 1 switch level 1 => P(daysPrior) * 2 - Daily.H(day) 2 => P(daysPrior) - Daily.H(day) + Daily.L(day) => if level < 1 runtime.error('"level" must be at least one.') na else ratio = level - 1 P(daysPrior) * ratio + Daily.L(day) - ratio * Daily.H(day) /////////////////////////////////////////////////// levelsUp( simple int daysPrior, simple int maxLevel = 3) => levels = array.new_float(maxLevel + 1) array.set(levels, 0, P(daysPrior)) for i = 1 to maxLevel array.set(levels, i, R(i, daysPrior)) levels //// levelsDn( simple int daysPrior, simple int maxLevel = 3) => levels = array.new_float(maxLevel + 1) array.set(levels, 0, P(daysPrior)) for i = 1 to maxLevel array.set(levels, i, S(i, daysPrior)) levels //// /////////////////////////////////////////////////// // @function Returns a value representing where the provided value is in relation to each pivot level. // @param value The value to compare against. // @param daysPrior The number of days in the past to do the calculation. // @param maxLevel The maximum number of pivot levels to include. export vacinity( float value, simple int daysPrior = 0, simple int maxLevel = 3) => level = 0 levelBounds = 2 UP = levelsUp(daysPrior, maxLevel) DN = levelsDn(daysPrior, maxLevel) p = array.get(UP, 0) if value == p 0 else if value > p levels = UP lo = p hi = array.get(levels, 1) while(levelBounds < maxLevel and value > hi) levelNext = level + 1 levelBounds := levelNext + 1 lo := hi hi := array.get(levels, levelBounds) level := levelNext (value - lo) / (hi - lo) + level else if value < p levels = DN hi = p lo = array.get(levels, 1) while(levelBounds < maxLevel and value < lo) levelNext = level + 1 levelBounds := levelNext + 1 hi := lo lo := array.get(levels, levelBounds) level := levelNext (value - hi) / (hi - lo) - level else na /////////////////////////////////////////////////// /////////////////////////////////////////////////// // Pivot Levels Example /////////////////////////// p = P() plot(p, "P") plot(R(1), "R1", color.red) plot(R(2), "R2", color.red) plot(S(1), "S1", color.green) plot(S(2), "S2", color.green) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // Vacinity Testing /////////////////////////////// // hline(2) // hline(1) // hline(0) // hline(-1) // hline(-2) // c = close > p ? color.green : color.red // plot(vacinity(close), color=c) ///////////////////////////////////////////////////
debugger
https://www.tradingview.com/script/NeDnFMpG-debugger/
ed56
https://www.tradingview.com/u/ed56/
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/ // // SUMMARY // DEBUGGER is a library to help print debug messages to a console. // // DESCRIPTION // This library provides an easy-to-use interface to print your debugging messages // to a console in the chart. Special attention has been given to printing series // and arrays easily. // // A debugger is a valuable tool when working on scripts and getting into trouble. // Unfortunately, TradingView does not provide an interactive debugger, and does // not provide a console to use the oldest trick in the debugging book: print statements. // This library provides you with the latter tool, print statements. // // As a bonus, the library also provides a way to show labels in the chart next // to the pricing action. // // INTERFACE OVERVIEW // These are the main interface functions: // debugger (consoleSize=20) -> [c, f] Returns a debugger containing the console and the window frame // print (c, f, message, condition) Prints a debug message as string // print_series (c, f, message, series, condition) Prints a debug message for a float/int series // print_series_bool(c, f, message, series, condition) Prints a debug message for a bool series // print_array (c, f, message, array, condition) Prints a debug message for an array of float/int // print_array_bool (c, f, message, array, condition) Prints a debug message for an array of bool // show_label (message, condition) Shows a new debug message as a label // show_bar_index () Shows bar indexes on the chart // // EXAMPLES // This is how you define and use a debug console and some usages. The console will // show on the left hand side of the chart. // // import ed56/debugger/2 as db // [c, f] = db.debugger() // // // Print a simple message for each bar // db.print(c, f, "Print a debug message") // // // Print a message every 100 bars // db.print(c, f, str.format("Processed bar {0}", bar_index), bar_index % 100 == 0) // // // Print the last 20 prices of a series as [1, 2, 3, ...] // db.print_series(c, f, "Close prices", close, size=20) // // // Print the last 5 prices of an array as [1, 2, 3, ...] // db.print_array(c, f, "Array values", my_array, size=5) // // This is how you define a label console, so we show messages in labels instead of the text console. // // // Show a label above the price bar // db.show_label("Print a debug message") // // // Show a label below the price bar with an alternative color // db.show_label("Low" + str.tostring(low), (bar_index + 5) % 10 == 0, // aboveBar=false, textColor=color.maroon, bgColor=color.red) // // And you can easily show the bar indexes on the chart as follows // // db.show_bar_index() // // REMARKS // Ideally debugger() should just return the console, and there should be no need // to return the underlying table. The table should be available from the chart DOM using // table.all. The issue is that Pine Script v5 does not provide any way to access // the contents or properties of the table to ensure we can identify the console table. // //@version=5 library(title='debugger', overlay=true) // **************************************************************************************************************** // **************************************************************************************************************** // // DEBUGGER CONSOLE METHODS // // **************************************************************************************************************** // **************************************************************************************************************** // @function debugger Returns a debugger containing the console and the window frame // // You can declare and use a debugger as follows // // import ed56/Debugger/1 as db // [c, f] = db.debugger() // db.print(c, f, "Print a debug message") // db.print_series(c, f, "Print the last 10 close prices", close, size=10) // // @param consoleSize The maximum number of lines in the debugger console // @returns dbConsole The console containing debug messages // dbFrame The window frame that will show the console export debugger(simple int consoleSize=20) => var int calls = 1 var string[] dbConsole = array.new_string(consoleSize, '') var table dbFrame = table.new( position=position.bottom_left, columns=1, rows=1, frame_color=na, frame_width=1, border_color=na, border_width=1) if calls == 1 table.cell( table_id=dbFrame, column=0, row=0, text="", width=100, height=100, text_color=chart.fg_color, text_halign=text.align_left, text_valign=text.align_bottom, text_size=size.normal) calls += 1 [dbConsole, dbFrame] // @function print Prints a debug message as string // // @param dbConsole The debugger console as returned by the debugger() method // dbFrame The debugger frame as returned by the debugger() method // message The message to print as string // condition If true (default) then print the message to the console; if false then ignore the message // showBarIndex If true (default) shows the current bar_index export print(series string[] dbConsole, series table dbFrame, series string message, series bool condition = true, bool showBarIndex = true) => if condition visibleMessage = message if showBarIndex visibleMessage := str.format("{0}: {1}", str.tostring(bar_index), message) array.shift(dbConsole) array.push(dbConsole, visibleMessage) debugText = array.join(dbConsole, '\n') table.cell_set_text(dbFrame, 0, 0, debugText) // @function print_series Prints a debug message for a float/int series. // The message and series are only printed if the condition is true. // The series is printed using the format [1, 2, 3, ...]. // The size parameter limits the values to print from the series. // // @param dbConsole The debugger console as returned by the debugger() method // dbFrame The debugger frame as returned by the debugger() method // message The message to print as string, before the series // source The float/int series to print // condition If true (default) then print the message to the console; if false then ignore the message // size The max number of values to print from the series (default 10) // showBarIndex If true (default) shows the current bar_index export print_series(series string[] dbConsole, series table dbFrame, series string message, series float source, series bool condition = true, simple int size = 10, simple bool showBarIndex = true) => visibleMessage = message if condition itemsStr = "" numItems = bar_index > size ? size : bar_index if numItems > 0 for i = 0 to numItems - 1 itemsStr := itemsStr + (i > 0 ? ", " : "") + str.tostring(source[i]) visibleMessage := str.format("{0}: [{1}]", message, itemsStr) print(dbConsole, dbFrame, visibleMessage, condition, showBarIndex) // @function print_series_bool Prints a debug message for a bool series. // The message and series are only printed if the condition is true. // The series is printed using the format [true, false, true, ...]. // The size parameter limits the values to print from the series. // // @param dbConsole The debugger console as returned by the debugger() method // dbFrame The debugger frame as returned by the debugger() method // message The message to print as string, before the series // source The bool series to print // condition If true (default) then print the message to the console; if false then ignore the message // size The max number of values to print from the series (default 10) // showBarIndex If true (default) shows the current bar_index export print_series_bool(series string[] dbConsole, series table dbFrame, series string message, series bool source, series bool condition = true, simple int size = 10, simple bool showBarIndex = true) => visibleMessage = message if condition itemsStr = "" numItems = bar_index > size ? size : bar_index if numItems > 0 for i = 0 to numItems - 1 itemsStr := itemsStr + (i > 0 ? ", " : "") + str.tostring(source[i]) visibleMessage := str.format("{0}: [{1}]", message, itemsStr) print(dbConsole, dbFrame, visibleMessage, condition, showBarIndex) // @function print_array Prints a debug message for an array of float/int. // The message and array values are only printed if the condition is true. // The array is printed using the format [1, 2, 3, ...]. // The size parameter limits the values to print from the array. // // @param dbConsole The debugger console as returned by the debugger() method // dbFrame The debugger frame as returned by the debugger() method // message The message to print as string, before the array // source The float/int array to print // condition If true (default) then print the message to the console; if false then ignore the message // size The max number of values to print from the array (default 10) // showBarIndex If true (default) shows the current bar_index export print_array(series string[] dbConsole, series table dbFrame, series string message, series float[] source, series bool condition = true, simple int size = 10, simple bool showBarIndex = true) => visibleMessage = message if condition itemsStr = "" numItems = array.size(source) > size ? size : array.size(source) if numItems > 0 for i = 0 to numItems - 1 itemsStr := itemsStr + (i > 0 ? ", " : "") + str.tostring(array.get(source, i)) visibleMessage := str.format("{0}: (size={1}) [{2}]", message, array.size(source), itemsStr) print(dbConsole, dbFrame, visibleMessage, condition, showBarIndex) // @function print_array_bool Prints a debug message for an array of bool. // The message and array values are only printed if the condition is true. // The array is printed using the format [true, false, true, ...]. // The size parameter limits the values to print from the array. // // @param dbConsole The debugger console as returned by the debugger() method // dbFrame The debugger frame as returned by the debugger() method // message The message to print as string, before the array // source The bool array to print // condition If true (default) then print the message to the console; if false then ignore the message // size The max number of values to print from the array (default 10) // showBarIndex If true (default) shows the current bar_index export print_array_bool(series string[] dbConsole, series table dbFrame, series string message, series bool[] source, series bool condition = true, simple int size = 10, simple bool showBarIndex = true) => visibleMessage = message if condition itemsStr = "" numItems = array.size(source) > size ? size : array.size(source) if numItems > 0 for i = 0 to numItems - 1 itemsStr := itemsStr + (i > 0 ? ", " : "") + str.tostring(array.get(source, i)) visibleMessage := str.format("{0}: (size={1}) [{2}]", message, array.size(source), itemsStr) print(dbConsole, dbFrame, visibleMessage, condition, showBarIndex) // **************************************************************************************************************** // **************************************************************************************************************** // // LABEL MESSAGES // // **************************************************************************************************************** // **************************************************************************************************************** // @function show_label Shows a new debug message as a label // The value of the label will be shown either above or below the current price bar (default above) // // @param message The message to print as string, // @param condition If true (default) then print the message to the console; if false then ignore the message // @param aboveBar If true (default) show the message above the price bar; if falst then show it below the price bar // @param simpleStyle If true, we show the label as a text message on the chart using the color provided. // If false, we decorate the label with a background of the color provided, and black foreground. // @param color The color of the label export show_label(series string message, series bool condition = true, simple bool aboveBar = true, simple bool simpleStyle = true, simple color color = color.yellow) => if condition ylocation = aboveBar ? yloc.abovebar : yloc.belowbar labelStyle = aboveBar ? label.style_label_down : label.style_label_up bgColor = simpleStyle ? na : color textColor = simpleStyle ? color : color.black labelMessage = not simpleStyle ? message : aboveBar ? str.format("{0}\n▼", message) : str.format("▲\n{0}", message) newLabel = label.new(x = bar_index, y = 0, yloc = ylocation, text = labelMessage, textcolor = textColor, textalign = text.align_center, color = bgColor, size = size.normal, style = labelStyle) //} // **************************************************************************************************************** // **************************************************************************************************************** // // BAR_INDEX // // **************************************************************************************************************** // **************************************************************************************************************** // @function show_bar_index Shows bar indexes in the chart // // Sometimes when debugging or refining your strategies over a specific date range, // when you want quickly find out the bar range in terms of bar_index. // // @param step Step determines the separation between bars identified in the chart. // For example, step=10 will show every 1 in every 10 bars indexes. // @param from Show bars from this index // @param until Show bars until this index. // The default until=0 will show all bars // @param color The color of the bar index text on the chart // @param size The size of the text export show_bar_index(simple int step=10, simple int from=0, simple int until=0, simple color color = color.gray, simple string size = size.small) => bar_until = until == 0 ? bar_index : until show = (bar_index % step == 0) and (bar_index >= from) and (bar_index <= bar_until) if show label.new(x = bar_index, y = 0, yloc = yloc.abovebar, text = str.format("{0}\n▼", bar_index), tooltip = str.format("Bar Index = {0}", bar_index), textcolor = color, size = size, color = na, style = label.style_none) // **************************************************************************************************************** // // EXAMPLES // // **************************************************************************************************************** show_text_conditional = input.bool(true, title="Debug text message conditionally", group="Console Message") show_text_if_block = input.bool(true, title="Debug text message from IF block", group="Console Message") show_text_spam = input.bool(false, title="Write a lot of messages, cap to console size", group="Console Message") show_float_series = input.bool(true, title="Debug float/int series", group="Series") show_float_series_start = input.bool(false, title="Debug float/int series for first few bars", group="Series") show_bool_series = input.bool(true, title="Debug bool series", group="Series") show_float_array = input.bool(false, title="Debug float/int array", group="Arrays") show_float_array_start = input.bool(false, title="Debug float/int array for first few bars", group="Arrays") show_bool_array = input.bool(true, title="Debug bool array", group="Arrays") show_label_above = input.bool(true, title="Show labels above price line", group="Labels") show_label_below = input.bool(false, title="Show labels below price line", group="Labels") _show_simple_style = input.string("Simple", title="Style", group="Labels", options=["Simple", "Background"]) show_simple_style = "Simple" == _show_simple_style show_barindex = input.bool(false, title="Show bar index", group="Bar Index") barindex_step = input.int(10, title="Step", group="Bar Index") barindex_from = input.int(0, title="From", group="Bar Index") barindex_until = input.int(0, title="Until", group="Bar Index", tooltip="Use 0 to show until last bar") barindex_color = input.color(color.gray, "Style", group="Bar Index", inline="BI") barindex_size = input.string(size.small, "", group="Bar Index", inline="BI", options=[size.small, size.normal, size.large]) //****************************************************************************** // Declare the debugger // [c, f] = debugger() //****************************************************************************** // Print message according to a condition // if show_text_conditional print(c, f, "Only show for first bar", barstate.isfirst) print(c, f, "Only show for last bar", barstate.islast) //****************************************************************************** // Print messages within a conditional block // if show_text_if_block var numPrintsLeft = 3 if numPrintsLeft > 0 print(c, f, "We will print this debug message " + str.tostring(numPrintsLeft) + " times") numPrintsLeft -= 1 // Print debug message from an conditional block if barstate.islast print(c, f, "This is the last bar printed from conditional block") //****************************************************************************** // Print a lot of messages, cap it to debugger size limit // if show_text_spam if bar_index % 10 == 0 print(c, f, "Bar Index=" + str.tostring(bar_index)) //****************************************************************************** // Print float/int series // if show_float_series print_series(c, f, "Print float series", close, barstate.islast) print_series(c, f, "Print int series", bar_index, barstate.islast, size=5) print_series(c, f, "Print High Prices every 2000 bars", high, bar_index % 2000 == 0, size=5) //****************************************************************************** // Print float/int series from bar_index=0 (just a few bars) // if show_float_series_start print_series(c, f, "Print float series for first few bars", close, bar_index < 7) //****************************************************************************** // Print bool series // if show_bool_series var bool_series = true bool_series := bar_index % 2 == 0 ? true : false print_series_bool(c, f, "Print bool series", bool_series, barstate.islast, size=5) //****************************************************************************** // Print float/int array // if show_float_array // Print float array var float_array = array.new_float() if (array.size(float_array) >= 20) array.pop(float_array) array.unshift(float_array, close[0]) print_array(c, f, "Print float array", float_array, barstate.islast, size=10) // Print int array var int_array = array.new_int() if (array.size(int_array) >= 20) array.pop(int_array) array.unshift(int_array, bar_index) print_array(c, f, "Print int array", int_array, barstate.islast, size=10) //****************************************************************************** // Print float/int array from the start (just a few elements in the array) // if show_float_array_start var float_array = array.new_float() if (array.size(float_array) >= 20) array.pop(float_array) array.unshift(float_array, close[0]) print_array(c, f, "Print float array", float_array, bar_index < 8, size=10) //****************************************************************************** // Print bool array // if show_bool_array var bool_array = array.new_bool() if (array.size(bool_array) >= 20) array.pop(bool_array) array.unshift(bool_array, bar_index % 2 == 0) print_array_bool(c, f, "Print bool array", bool_array, barstate.islast, size=10) //****************************************************************************** // Declare label debugger // //****************************************************************************** // Show labels above price bars // if show_label_above show_label("Close = " + str.tostring(close), bar_index % 40 == 0, simpleStyle = show_simple_style) //****************************************************************************** // Show labels below price bars, and some customisation of the label // if show_label_below show_label("Low Price = " + str.tostring(low), (bar_index + 5) % 40 == 0, simpleStyle = show_simple_style, aboveBar = false, color = color.red) //****************************************************************************** // Show bar index // if show_barindex show_bar_index(step = barindex_step, from = barindex_from, until = barindex_until, color = barindex_color, size = barindex_size)
HurstExponent
https://www.tradingview.com/script/LsW08uRb-HurstExponent/
nolantait
https://www.tradingview.com/u/nolantait/
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/ // © nolantait //@version=5 // @description Library to calculate Hurst Exponent refactored from Hurst Exponent - Detrended Fluctuation Analysis [pig] library("HurstExponent") import nolantait/Moments/1 as moments // @function Calculates a series subtracted from the series mean. // @param src The series used to calculate the difference from the mean (e.g. log returns). // @returns The series subtracted from the series mean export demean(float src, int length) => src - moments.mean(src, length) // @function Calculates a cumulated sum from the series. // @param src The series used to calculate the cumulative sum (e.g. demeaned log returns). // @param length The length used to calculate the cumulative sum (e.g. 100). // @returns The cumulative sum of the series as an array export cumsum(float src, int length) => csum = array.new_float(length) sum = 0.0 for i=0 to length-1 sum := src[i] + sum array.set(csum, i, sum) csum // @function Calculates an aproximated log scale. Used to save sample size // @param scale The scale to aproximate. // @param length The length used to aproximate the expected scale. // @returns The aproximated log scale of the value export aproximateLogScale(int scale, int length, int minScale = 8, int maxScale = 2) => aproximation = math.pow(length / (minScale * maxScale), 0.1111111111) math.round(minScale * math.pow(aproximation, scale)) // @function Calculates linear trend to determine error between linear trend and cumulative sum // @param cumulativeSum The cumulative sum array to regress. // @param barId The barId for the slice // @param numberOfSegments The total number of segments used for the regression calculation // @returns The error between linear trend and cumulative sum export rootMeanSum(float[] cumulativeSum, int barId, int numberOfSegements = 10) => sequence = array.new_float(numberOfSegements) count = 0 for i=0 to numberOfSegements-1 count := count + 1 array.set(sequence, i, count) y = array.slice(cumulativeSum, barId, barId + numberOfSegements) xStandardDeviation = array.stdev(sequence) * math.sqrt(numberOfSegements / (numberOfSegements - 1)) yStandardDeviation = array.stdev(y) * math.sqrt(numberOfSegements / (numberOfSegements - 1)) covariance = array.covariance(sequence, y) * (numberOfSegements / (numberOfSegements - 1)) regression = math.pow(covariance / (xStandardDeviation * yStandardDeviation), 2) math.sqrt(1 - regression) * yStandardDeviation // @function Calculates the Root Mean Sum Measured for each block (e.g the aproximated log scale) // @param cumulativeSum The cumulative sum array to regress and determine the average of. // @param barId The barId for the slice // @param length The length used for finding the average // @returns The average root mean sum error of the cumulativeSum export averageRootMeanSum(float[] cumulativeSum, int barId, int length) => calculatedLength = math.floor(length / barId) sum = 0.0 for i=0 to calculatedLength-1 sum := sum + rootMeanSum(cumulativeSum, i * barId, barId) math.log10(sum / calculatedLength) // @function Calculates the critical values for a hurst exponent for a given length // @param length The length used for finding the average // @returns The critical value, upper critical value and lower critical value for a hurst exponent export criticalValues(int length) => critical = 1.645 * (0.3912 / math.pow(length, 0.3)) upper = 0.5 + critical lower = 0.5 - critical [critical, upper, lower] // @function Calculates the hurst exponent slope measured from root mean sum, scaled to log log plot using linear regression // @param cumulativeSum The cumulative sum array to regress and determine the average of. // @param length The length used for the hurst exponent sample size // @returns The slope of the hurst exponent export slope(float[] cumulativeSum, int length) => fluxes = array.new_float(10) scales = array.new_float(10) for i=0 to 9 logScale = aproximateLogScale(i, length) array.set(fluxes, i, averageRootMeanSum(cumulativeSum, logScale, length)) array.set(scales, i, math.log10(logScale)) array.covariance(scales, fluxes) / array.variance(scales) // @function Smooths input using advanced linear regression // @param src The series to smooth (e.g. hurst exponent slope) // @param length The length used to smooth // @returns The src smoothed according to the given length export smooth(float src, int length) => pi = 2.0 * math.asin(1.0) sqrt2 = math.sqrt(2.0) lambda = pi * sqrt2 / length a1 = math.exp(-lambda) coeffecient2 = 2.0 * a1 * math.cos(lambda) coeffecient3 = -math.pow(a1, 2.0) coeffecient1 = 1.0 - coeffecient2 - coeffecient3 filter = 0.0 filter := coeffecient1 * (src + nz(src[1])) * 0.5 + coeffecient2 * nz(filter[1]) + coeffecient3 * nz(filter[2]) filter // @function Wrapper function to calculate the hurst exponent slope // @param src The series used for returns calculation (e.g. close) // @param hurstLength The length used to calculate the hurst exponent (should be greater than 50) // @returns The src smoothed according to the given length export exponent(float src, int hurstLength = 100) => returns = moments.logReturns(src) demeanedReturns = demean(returns, hurstLength) cumulativeSum = cumsum(demeanedReturns, hurstLength) slope(cumulativeSum, hurstLength) // Example hurstExponent = exponent(close) smoothedHurstExponent = smooth(hurstExponent, 18) plot(hurstExponent, "Hurst Exponent") plot(smoothedHurstExponent, "Smoothed Hurst Exponent", color=color.yellow)
log
https://www.tradingview.com/script/Lpq08i08-log/
GETpacman
https://www.tradingview.com/u/GETpacman/
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/ // © GETpacman //@version=5 // @description A dual logging library for developers. library("log") export type log matrix<string> mqx matrix<int> hqx matrix<color> cqx array<int> intDB array<bool> boolDB array<string> stringDB matrix<color> colorDB array<string> levelDB color HeaderColor color HeaderColorBG color StatusColor color StatusColorBG color TextColor color TextColorBG color FrameColor int FrameSize = 1 int CellBorderSize = 0 color CellBorderColor color SeparatorColor = color.gray table tbx bool IsConsole = true string HeaderQbarIndex = 'Bar#' string HeaderQdateTime = 'Date' string HeaderQerrorCode = 'eCode' string HeaderQlogLevel = 'State' string HeaderQ1 = 'h.Q1' string HeaderQ2 = 'h.Q2' string HeaderQ3 = 'h.Q3' string HeaderQ4 = 'h.Q4' string HeaderQ5 = 'h.Q5' string HeaderQ6 = 'h.Q6' string Status = '' int PageHistory = 0 bool PageOnEveryBar = false bool MoveLogUp = true bool ShowStatusBar = true bool StatusBarAtBottom = true bool ColorText = true bool HighlightText = false bool ShowMetaStatus = true bool ShowBarIndex = false bool ShowDateTime = false bool ShowLogLevels = false bool ReplaceWithErrorCodes=false bool RestrictLevelsToKey7 = false bool MarkNewBar = true int MinWidth = 40 bool ShowHeader = true bool HeaderAtTop = true bool ShowQ1 = true bool ShowQ2 = true bool ShowQ3 = true bool ShowQ4 = true bool ShowQ5 = true bool ShowQ6 = true bool AutoMerge = true int TabSizeQ1 = 0 int TabSizeQ2 = 0 int TabSizeQ3 = 0 int TabSizeQ4 = 0 int TabSizeQ5 = 0 int TabSizeQ6 = 0 bool PrefixLogLevel = false _consolePosition(int position) => _position=switch position 1 => 'top' 2 => 'right' 4 => 'left' => 'bottom' _consolePosition(string position='anywhere') => _position = switch str.lower(position) 'top' => 1 'right' => 2 'left' => 4 => 3 _position method _resetLocations(log this) => this.intDB.set(17,0),this.intDB.set(18,0),this.intDB.set(19,1),this.intDB.set(20,8) this.intDB.set(13,0),this.intDB.set(14,10),this.intDB.set(15,this.intDB.get(1)-1+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0)),this.intDB.set(16,18) this.intDB.set(11,3) method _switchMode(log this) => if not this.boolDB.get(1) and this.IsConsole for x=0 to this.mqx.rows()>0 ? (this.mqx.rows()-1) : na _toLog= (this.ShowBarIndex ? (str.tostring(this.hqx.get(x,1))+', ') : '') + (this.ShowDateTime ? (str.format('{0,date,'+this.stringDB.get(4)+'}',this.hqx.get(x,2))+'  ') : '') + ((this.TabSizeQ1>0 and this.hqx.get(x,0)>1)? str.substring(this.stringDB.get(3),0,(math.min(7,this.hqx.get(x,0))-1)*this.TabSizeQ1):'') + ( (this.PrefixLogLevel and this.hqx.get(x,0)>=1 and this.hqx.get(x,0)<=7 and (this.hqx.get(x,0)+1)<=this.levelDB.size())? (this.levelDB.get(this.hqx.get(x,0)+1) +':  ' ):'') + this.mqx.get(x,0) this.mqx.set(x,5,this.mqx.get(x,0)) this.mqx.set(x,0,_toLog) this.hqx.set(x,4,0) this.hqx.set(x,3,str.length(_toLog)) if this.boolDB.get(1) and not this.IsConsole for x=0 to this.mqx.rows()>0?(this.mqx.rows()-1) : na this.mqx.set(x,0,this.mqx.get(x,5)) this.mqx.set(x,5,'') this.hqx.set(x,3,str.length(this.mqx.get(x,0))) this.hqx.set(x,4,this.hqx.get(x,3)+str.length(this.mqx.get(x,1))+str.length(this.mqx.get(x,2))+str.length(this.mqx.get(x,3))+str.length(this.mqx.get(x,4))+str.length(this.mqx.get(x,5))) this.boolDB.set(1, this.IsConsole) // @function Clears all the queue, including bar_index and time queues, of existing messages export method clear (log this) => this.mqx.fill( '', 0, this.mqx.rows(), 0, this.mqx.columns()) this.hqx.fill( -1, 0, this.hqx.rows(), 0, this.hqx.columns()) this.intDB.set(7,0) // @function Resizes the message queues. If size is decreased then removes the oldest messages // @param rows The new size needed for the queues. Default value is 40. export method resize (log this, int rows=40) => int _txn = this.intDB.get(0) int _qsize = this.intDB.get(1) int _qc = (_txn<=-1 or _qsize<1) ? na : (_txn%_qsize) int _qn = (_txn<=-1 or _qsize<1) ? na : ((_txn+1)%_qsize) if rows<=0 this.clear() else if _qsize > rows and _qsize != rows for x = 1 to (_qsize - rows) this.mqx.remove_row(_qn),this.hqx.remove_row(_qn),this.cqx.remove_row(_qn) _qn := (_txn<=-1) ? na : ((_txn+1)%_qsize) if _qn>_qc _qn := (_qc+1 > (_qsize-1-x)) ? 0 : _qn else _qc -= 1 if _qsize < rows and _qsize != rows for x =1 to (rows - _qsize) this.mqx.add_row(_qn,array.new_string(this.mqx.columns(),'')),this.hqx.add_row(_qn,array.new_int(this.hqx.columns(),-1)),this.cqx.add_row(_qn,array.new_color(this.cqx.columns(),na)) this.intDB.set(1, rows) _txn := (_txn+1) < _qsize ? _txn : (rows-1+_qn) this.intDB.set(0, _txn) this.intDB.set(15, rows-1+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0) + (this.intDB.get(11)==1 ? 2 : 0)) // @function Re/set the date time format used for displaying date and time. Default resets to dd.MMM.yy HH:mm export method dateTimeFormat(log this, string format='') => this.stringDB.set(4, format==''?'dd.MMM.yy HH:mm':format) // @function Resets the text color of the log to library default. export method resetTextColor(log this) => this.TextColor := color.new(chart.fg_color,60) // @function Resets the background color of the log to library default. export method resetTextColorBG(log this) => this.TextColorBG := chart.bg_color // @function Resets the color used for Headers, to library default. export method resetHeaderColor(log this) => this.TextColor := color.new(chart.fg_color,30) // @function Resets the background color used for Headers, to library default. export method resetHeaderColorBG(log this) => this.HeaderColorBG := color.new(#434651,80) // @function Resets the text color of the status row, to library default. export method resetStatusColor(log this) => this.StatusColor := color.new(#9598a1,50) // @function Resets the background color of the status row, to library default. export method resetStatusColorBG(log this) => this.StatusColorBG := color.new(#434651,70) // @function Resets the color used for the frame around the log table, to library default. export method resetFrameColor(log this) => this.FrameColor := chart.bg_color // @function Resets the color used for the highlighting when Highlight Text option is used, to library default export method resetColorsHC(log this) => if this.colorDB.rows()<37 for x=1 to 37-this.colorDB.rows() this.colorDB.add_row(0) this.colorDB.set(1, 2,color.new(color.white,10)),this.colorDB.set(2, 2,color.new(color.white,10)),this.colorDB.set(3, 2,color.new(color.white,10)),this.colorDB.set(4, 2,color.new(color.white,10)),this.colorDB.set(5, 2,color.new(color.black,10)),this.colorDB.set(6, 2,color.new(color.black,10)),this.colorDB.set(7, 2,color.new(color.white,10)) this.colorDB.set(8, 2,color.new(color.white,10)),this.colorDB.set(9, 2,color.new(color.white,10)),this.colorDB.set(10,2,color.new(color.white,10)),this.colorDB.set(11,2,color.new(color.white,10)),this.colorDB.set(12,2,color.new(color.white,10)),this.colorDB.set(13,2,color.new(color.white,10)),this.colorDB.set(14,2,color.new(color.black,10)) this.colorDB.set(15,2,color.new(color.white,10)),this.colorDB.set(16,2,color.new(color.white,10)),this.colorDB.set(17,2,color.new(color.white,10)),this.colorDB.set(18,2,color.new(color.white,10)),this.colorDB.set(19,2,color.new(color.white,10)),this.colorDB.set(20,2,color.new(color.white,10)),this.colorDB.set(21,2,color.new(color.black,10)) this.colorDB.set(22,2,color.new(color.black,10)),this.colorDB.set(23,2,color.new(color.white,10)),this.colorDB.set(24,2,color.new(color.white,10)),this.colorDB.set(25,2,color.new(color.white,10)),this.colorDB.set(26,2,color.new(color.black,10)),this.colorDB.set(27,2,color.new(color.white,10)),this.colorDB.set(28,2,color.new(color.white,10)) this.colorDB.set(29,2,color.new(color.white,10)),this.colorDB.set(30,2,color.new(color.white,10)),this.colorDB.set(31,2,color.new(color.white,10)),this.colorDB.set(32,2,color.new(color.white,10)),this.colorDB.set(33,2,color.new(color.white,10)),this.colorDB.set(34,2,color.new(color.black,10)),this.colorDB.set(35,2,color.new(color.black,10)) this.colorDB.set(36,2,color.new(color.white,10)) // @function Resets the background color used for setting the background color, when the Color Text option is used, to library default export method resetColorsBG(log this) => if this.colorDB.rows()<37 for x=1 to 37-this.colorDB.rows() this.colorDB.add_row(0) for x=0 to this.colorDB.rows()-1 this.colorDB.set(x,1,chart.bg_color) // @function Resets the color used for respective error codes, when the Color Text option is used, to library default export method resetColors(log this) => if this.colorDB.rows()<37 for x=1 to 37-this.colorDB.rows() this.colorDB.add_row(0) this.colorDB.set(1, 0, color.new(#2196f3,10)),this.colorDB.set(2, 0, color.new(#4caf50,10)),this.colorDB.set(3, 0, color.new(#9598a1,20)),this.colorDB.set(4, 0, color.new(#c29857,20)),this.colorDB.set(5, 0, color.new(#fbc02d,10)),this.colorDB.set(6, 0, color.new(#f57f17,00)),this.colorDB.set(7, 0, color.new(#f44336,10)) this.colorDB.set(8, 0, color.new(color.aqua,10)),this.colorDB.set(9, 0, color.new(color.blue,10)),this.colorDB.set(10,0, color.new(color.red,10)),this.colorDB.set(11,0, color.new(color.fuchsia,10)),this.colorDB.set(12,0, color.new(color.gray,10)),this.colorDB.set(13,0, color.new(color.green,10)),this.colorDB.set(14,0, color.new(color.lime,10)) this.colorDB.set(15,0, color.new(color.maroon,10)),this.colorDB.set(16,0, color.new(color.navy,10)),this.colorDB.set(17,0, color.new(color.olive,10)),this.colorDB.set(18,0, color.new(color.purple,10)),this.colorDB.set(19,0, color.new(color.silver,10)),this.colorDB.set(20,0, color.new(color.teal,10)),this.colorDB.set(21,0, color.new(color.white,10)) this.colorDB.set(22,0, color.new(color.yellow,10)),this.colorDB.set(23,0, color.new(#9C6E1B,00)),this.colorDB.set(24,0, color.new(#AA00FF,10)),this.colorDB.set(25,0, color.new(#673ab7,10)),this.colorDB.set(26,0, color.new(#CCCC00,10)),this.colorDB.set(27,0, color.new(#c29857,10)),this.colorDB.set(28,0, color.new(#5d606b,00)) this.colorDB.set(29,0, color.new(#fc5d07,10)),this.colorDB.set(30,0, color.new(#004d40,10)),this.colorDB.set(31,0, color.new(#b71c1c,10)),this.colorDB.set(32,0, color.new(#7e57c2,50)),this.colorDB.set(33,0, color.new(#388e3c,20)),this.colorDB.set(34,0, color.new(#ffeb3b,00)),this.colorDB.set(35,0, color.new(#fbc02d,00)) this.colorDB.set(36,0, color.new(#ff9850,10)) this.resetColorsHC(),this.resetColorsBG() // @function Sets the colors corresponding to error codes // Index 0 of input array c is color is reserved for future use. // Index 1 of input array c is color for debug code 1. // Index 2 of input array c is color for debug code 2. // There are 2 modes of coloring // 1 . Using the Foreground color // 2 . Using the Foreground color as background color and a white/black/gray color as foreground color //     This is denoting or highlighting. Which effectively puts the foreground color as background color // @param c Array of colors to be used for corresponding error codes. If the corresponding code is not found, then text color is used export method setColors(log this, color[] c) => sc=c.size() sq=this.colorDB.rows() if sq<sc trow=this.colorDB.row(0) for x=1 to sc-sq this.colorDB.add_row(0) if sq>sc and sc>0 for x=1 to sq-sc this.colorDB.remove_row(0) for x=0 to (sc > 0 ? sc-1 : na) this.colorDB.set(x,0,c.get(x)) this.intDB.set(21,this.colorDB.rows()) // @function Sets the highlight colors corresponding to error codes // Index 0 of input array c is color is reserved for future use. // Index 1 of input array c is color for debug code 1. // Index 2 of input array c is color for debug code 2. // There are 2 modes of coloring // 1 . Using the Foreground color // 2 . Using the Foreground color as background color and a white/black/gray color as foreground color //     This is denoting or highlighting. Which effectively puts the foreground color as background color // @param c Array of highlight colors to be used for corresponding error codes. If the corresponding code is not found, then text color BG is used export method setColorsHC(log this, color[] c) => sc=c.size() sq=this.colorDB.rows() if sq<sc trow=this.colorDB.row(0) for x=1 to sc-sq this.colorDB.add_row(0) if sq>sc and sc>0 for x=1 to sq-sc this.colorDB.remove_row(0) for x=0 to (sc > 0 ? sc-1 : na) this.colorDB.set(x,2,c.get(x)) this.intDB.set(21,this.colorDB.rows()) // @function Sets the highlight colors corresponding to debug codes // Index 0 of input array c is color is reserved for future use. // Index 1 of input array c is color for debug code 1. // Index 2 of input array c is color for debug code 2. // There are 2 modes of coloring // 1 . Using the Foreground color // 2 . Using the Foreground color as background color and a white/black/gray color as foreground color //     This is denoting or highlighting. Which effectively puts the foreground color as background color // @param c Array of background colors to be used for corresponding error codes. If the corresponding code is not found, then text color BG is used export method setColorsBG(log this, color[] c) => sc=c.size() sq=this.colorDB.rows() if sq<sc trow=this.colorDB.row(0) for x=1 to sc-sq this.colorDB.add_row(0) if sq>sc and sc>0 for x=1 to sq-sc this.colorDB.remove_row(0) for x=0 to (sc > 0 ? sc-1 : na) this.colorDB.set(x,1,c.get(x)) this.intDB.set(21,this.colorDB.rows()) // @function Resets the log level names used for corresponding error codes // With prefix/suffix, the default Level name will be like => prefix + Code + suffix // @param prefix Prefix to use when resetting level names // @param suffix Suffix to use when resetting level names export method resetLevelNames(log this, string prefix='Level ', string suffix='') => this.levelDB.clear() this.levelDB:=array.new_string(this.colorDB.rows()<8 ? 8 : (this.colorDB.rows())) this.levelDB.set(0,''),this.levelDB.set(1,'TRACE'),this.levelDB.set(2,'DEBUG'),this.levelDB.set(3,'INFO'),this.levelDB.set(4,'WARNING'),this.levelDB.set(5,'ERROR'),this.levelDB.set(6,'CRITICAL'),this.levelDB.set(7,'FATAL') for x=8 to this.levelDB.size() > 8 ? (this.levelDB.size()-1) : na this.levelDB.set(x,prefix+str.tostring(x)+suffix) // @function Resets the log level names used for corresponding error codes // Index 0 of input array names is reserved for future use. // Index 1 of input array names is name used for error code 1. // Index 2 of input array names is name used for error code 2. // @param names Array of log level names be used for corresponding error codes. If the corresponding code is not found, then an empty string is used export method setLevelNames(log this, string[] names) => if names.size()>0 this.levelDB.clear(),this.levelDB:=array.new_string(names.size()<8 ? 8 : names.size()) this.levelDB.set(0,''),this.levelDB.set(1,''),this.levelDB.set(2,''),this.levelDB.set(3,''),this.levelDB.set(4,''),this.levelDB.set(5,''),this.levelDB.set(6,''),this.levelDB.set(7,'') for x=0 to names.size()-1 this.levelDB.set(x+1,names.get(x)) // @function Sets up data for logging. It consists of 6 separate message queues, and 3 additional queues for bar index, time and log level/error code. Do not directly alter the contents, as library could break. // @param rows Log size, excluding the header/status. Default value is 50. // @param isConsole Whether to init the log as console or logx. True= as console, False = as Logx. Default is true, hence init as console. export method init(log this, int rows=50, bool isConsole=true) => var bool _init = false if not _init and barstate.isfirst and barstate.isnew this.IsConsole:=isConsole this.mqx:= matrix.new<string> (rows,7,'') this.hqx:= matrix.new<int> (rows,6,-1) this.cqx:= matrix.new<color> (rows,2) this.intDB := array.new<int> (30,0) this.boolDB := array.new<bool> (10,false) this.stringDB := array.new<string> (10,'') this.colorDB := matrix.new<color> (37,3) this.levelDB := array.new<string> (37,'') this.intDB.set(21,this.colorDB.rows()) this.resetColors() this.dateTimeFormat() this.resetLevelNames('ec <','>') this.HeaderColor := color.new(chart.fg_color,30) this.HeaderColorBG := color.new(#434651,80) this.StatusColor := color.new(#9598a1,50) this.StatusColorBG := color.new(#434651,70) this.TextColor := color.new(chart.fg_color,60) this.TextColorBG := chart.bg_color this.FrameColor := chart.bg_color this.CellBorderColor:= chart.bg_color this.stringDB.set(0,'                                                                                                                                                                                                                                                                                                                                                                                                                ') this.stringDB.set(1,'______________'),this.intDB.set(22,str.length(this.stringDB.get(0))),this.intDB.set(23,str.length(this.stringDB.get(1))),this.stringDB.set(3,'                            ') this.intDB.set(0,-1),this.intDB.set(1,math.max(0,rows)),this.intDB.set(2,-1),this.intDB.set(3,-1),this.intDB.set(4,-1),this.intDB.set(6,0),this.intDB.set(5,0),this.intDB.set(7,0) this.boolDB.set(1,this.IsConsole) this.boolDB.set(2,false) this.boolDB.set(3,false) this.stringDB.set(4,'dd.MMM.yy HH:mm') this.stringDB.set(5,position.top_right) this.intDB.set(24,80) this.intDB.set(25,40) this._resetLocations() _init:=true this.boolDB.set(0,_init) // @function Logs messages to the queues , including, time/date, bar_index, and error code // @param ec Error/Code to be assigned. // @param m1 Message needed to be logged to Q1, or for console. // @param m2 Message needed to be logged to Q2. Not used/ignored when in console mode // @param m3 Message needed to be logged to Q3. Not used/ignored when in console mode // @param m4 Message needed to be logged to Q4. Not used/ignored when in console mode // @param m5 Message needed to be logged to Q5. Not used/ignored when in console mode // @param m6 Message needed to be logged to Q6. Not used/ignored when in console mode // @param tv Time to be used. Default value is time, which logs the start time of bar. // @param log Whether to log the message or not. Default is true. export method log (log this, int ec=0, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int tv=time, bool log=true) => this.PageHistory:=this.PageHistory < 0 ? 0 : this.PageHistory if this.PageOnEveryBar and bar_index-this.intDB.get(3) > this.PageHistory if this.PageHistory==0 this.clear() else if this.intDB.get(1)>0 for x=0 to this.intDB.get(1)-1 this.hqx.set(x,1,(bar_index-this.hqx.get(x,1)) > this.PageHistory ? -1 : this.hqx.get(x,1)) this.hqx.set(x,3,(bar_index-this.hqx.get(x,1)) > this.PageHistory ? 0 : this.hqx.get(x,3)) this.hqx.set(x,4,(bar_index-this.hqx.get(x,1)) > this.PageHistory ? 0 : this.hqx.get(x,4)) this.intDB.set(3,bar_index-this.PageHistory) if this.IsConsole!=this.boolDB.get(1) this._switchMode() int _txn = this.intDB.get(0) int _qn = ((_txn+1)%this.intDB.get(1)) if log if (this.MarkNewBar and this.intDB.get(4)!=bar_index) _logMark='#.'+str.tostring(bar_index)+' '+this.stringDB.get(1) _markLen=str.length(_logMark) this.hqx.set(_qn,0, ec),this.hqx.set(_qn,1, bar_index),this.hqx.set(_qn,2, tv),this.hqx.set(_qn,3, _markLen),this.hqx.set(_qn,4, _markLen),this.hqx.set(_qn,5, this.intDB.get(6)) this.mqx.set(_qn,0, _logMark),this.mqx.set(_qn,1, ''),this.mqx.set(_qn,2, ''),this.mqx.set(_qn,3, ''),this.mqx.set(_qn,4, ''),this.mqx.set(_qn,5, ''),this.mqx.set(_qn,6, '') this.cqx.set(_qn,0,(ec<1 or ec>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ec,0) : this.HighlightText ? this.colorDB.get(ec, 2) : this.TextColor) this.cqx.set(_qn,1,(ec<1 or ec>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ec,1) : this.HighlightText ? this.colorDB.get(ec, 0) : this.TextColorBG) _txn+=1 _qn := ((_txn+1)%this.intDB.get(1)) _toLog =this.IsConsole?'' : (( (this.TabSizeQ1>0 and ec>1 and ec<=7 and str.length(m1)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,ec)-1)*math.min(4,this.TabSizeQ1)):'') + m1) _mq2 =this.IsConsole?'' : (( (this.TabSizeQ2>0 and ec>1 and ec<=7 and str.length(m2)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,ec)-1)*math.min(4,this.TabSizeQ2)):'') + m2) _mq3 =this.IsConsole?'' : (( (this.TabSizeQ3>0 and ec>1 and ec<=7 and str.length(m3)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,ec)-1)*math.min(4,this.TabSizeQ3)):'') + m3) _mq4 =this.IsConsole?'' : (( (this.TabSizeQ4>0 and ec>1 and ec<=7 and str.length(m4)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,ec)-1)*math.min(4,this.TabSizeQ4)):'') + m4) _mq5 =this.IsConsole?'' : (( (this.TabSizeQ5>0 and ec>1 and ec<=7 and str.length(m5)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,ec)-1)*math.min(4,this.TabSizeQ5)):'') + m5) _mq6 =this.IsConsole?m1 : (( (this.TabSizeQ6>0 and ec>1 and ec<=7 and str.length(m6)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,ec)-1)*math.min(4,this.TabSizeQ6)):'') + m6) if this.IsConsole _totalLen=array.sum(this.hqx.col(3)) _toLog:= (this.ShowBarIndex ? (str.tostring(bar_index)+', ') : '') + (this.ShowDateTime ? (str.format('{0,date,'+this.stringDB.get(4)+'}',tv)+'  ') : '') + ((this.TabSizeQ1>0 and ec>1 and ec<=7)? str.substring(this.stringDB.get(3),0,(math.min(7,ec)-1)*math.min(4,this.TabSizeQ1)):'') + ( (this.PrefixLogLevel and ec>=0 and ec<=this.levelDB.size())? (this.levelDB.get(ec) +': ' ):'') + m1 int _mLen=str.length(_toLog) _overflow=(_totalLen+_mLen+this.intDB.get(1)-1)>4096?true:false _freeup=_overflow?_totalLen+_mLen+this.intDB.get(1)-1-4096:0 _rowsout=1 while _freeup > 0 and _rowsout <= this.intDB.get(1) _qn:=((_txn+_rowsout)%this.intDB.get(1)) _freeup -= this.hqx.get(_qn,3) this.hqx.set(_qn,0,0),this.hqx.set(_qn,1,0),this.hqx.set(_qn,2,0),this.hqx.set(_qn,3,0),this.hqx.set(_qn,4,0) this.mqx.set(_qn,0,''),this.mqx.set(_qn,1,''),this.mqx.set(_qn,2,''),this.mqx.set(_qn,3,''),this.mqx.set(_qn,4,''),this.mqx.set(_qn,5,'') _rowsout+=1 _qn := ((_txn+1)%this.intDB.get(1)) _totalLen:=array.sum(this.hqx.col(3)) this.intDB.set(5, _totalLen) this.stringDB.set(2, ' ='+str.tostring(4096-_totalLen)+(this.PageOnEveryBar ? ' ● ' : ' ')+(_overflow ? 'x' : '') ) this.hqx.set(_qn,0, ec),this.hqx.set(_qn,1, bar_index),this.hqx.set(_qn,2, tv),this.hqx.set(_qn,3, str.length(_toLog)),this.hqx.set(_qn,4, str.length(_mq2)+str.length(_mq3)+str.length(_mq4)+str.length(_mq5)+str.length(_mq6)+this.hqx.get(_qn,3)),this.hqx.set(_qn,5, this.intDB.get(6)) this.cqx.set(_qn,0,(ec<1 or ec>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ec,0) : this.HighlightText ? this.colorDB.get(ec, 2) : this.TextColor) this.cqx.set(_qn,1,(ec<1 or ec>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ec,1) : this.HighlightText ? this.colorDB.get(ec, 0) : this.TextColorBG) this.mqx.set(_qn,0, _toLog),this.mqx.set(_qn,1, _mq2),this.mqx.set(_qn,2, _mq3),this.mqx.set(_qn,3, _mq4),this.mqx.set(_qn,4, _mq5),this.mqx.set(_qn,5, _mq6),this.mqx.set(_qn,6, (ec<0 or ec>this.levelDB.size())?'':this.levelDB.get(ec)) this.intDB.set(4,bar_index) this.intDB.set(0, _txn+1) else if not log and this.IsConsole this.stringDB.set(2, ' ='+str.tostring(4096-this.intDB.get(5)) + (this.PageOnEveryBar ? ' ● ' : ' ') + '◼︎' ) // @function Logs messages to the queues , including, time/date, bar_index, and error code. All messages from previous bars are cleared // @param ec Error/Code to be assigned. // @param m1 Message needed to be logged to Q1, or for console. // @param m2 Message needed to be logged to Q2. Not used/ignored when in console mode // @param m3 Message needed to be logged to Q3. Not used/ignored when in console mode // @param m4 Message needed to be logged to Q4. Not used/ignored when in console mode // @param m5 Message needed to be logged to Q5. Not used/ignored when in console mode // @param m6 Message needed to be logged to Q6. Not used/ignored when in console mode // @param tv Time to be used. Default value is time, which logs the start time of bar. // @param page Whether to log the message or not. Default is true. export method page (log this, int ec, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int tv=time, bool page=true) => if this.intDB.get(3)!=bar_index and page this.clear() this.intDB.set(3, bar_index ) this.log(ec,m1,m2,m3,m4,m5,m6,tv,log=page) // @function Set the messages to be on a new page, clearing messages from previous page. // This is not dependent on PageHisotry option, as this method simply just clears all the messages, like turning old pages to a new page. export method turnPage (log this, bool turn=true) => this.intDB.set(6, this.intDB.get(6)+1) for x=0 to (turn and this.intDB.get(1)>0)?(this.intDB.get(1)-1):na this.hqx.set(x,1, (this.intDB.get(6)-this.hqx.get(x,5)) > this.PageHistory ? -1 : this.hqx.get(x,1)) _display (table tt, log this, string hhalign=text.align_left, string hvalign=text.align_top, string hsize=size.auto, string thalign=text.align_left, string tvalign=text.align_top, string tsize=size.auto) => if barstate.islast int _txn = this.intDB.get(0) int _qsize = this.intDB.get(1) int _txnS = (_txn<=-1 or _qsize<1) ? na : _txn<_qsize ? 0 : (_txn - _qsize + 1) int _txnLen = (_txn<=-1 or _qsize<1) ? na : _txn<_qsize ? _txn : _qsize - 1 int _qS = this.MoveLogUp ? _txnS :_txn int _dx = this.MoveLogUp ? 1 : -1 int _qc = (_qS%_qsize) //From Left int _hqcolBar = this.intDB.get(14)-1+(this.ShowBarIndex?1:0) int _hqcolDateTime = _hqcolBar+(this.ShowDateTime?1:0) int _hqcolEC = _hqcolDateTime+(this.ShowLogLevels?1:0) this.ShowLogLevels and this.ReplaceWithErrorCodes int _mqcolQ1 = _hqcolEC+(this.ShowQ1?1:0) int _mqcolQ2 = _mqcolQ1+(this.ShowQ2?1:0) int _mqcolQ3 = _mqcolQ2+(this.ShowQ3?1:0) int _mqcolQ4 = _mqcolQ3+(this.ShowQ4?1:0) int _mqcolQ5 = _mqcolQ4+(this.ShowQ5?1:0) int _mqcolQ6 = _mqcolQ5+(this.ShowQ6?1:0) int _logx_headerRowDelta = this.intDB.get(13) + ((this.ShowHeader and this.HeaderAtTop) ? 1 : 0) + ((this.ShowStatusBar and not this.StatusBarAtBottom) ? 1 : 0) int _hrow = 0 int _totalFGc = this.colorDB.rows() int _ec = 0 string _toShow='' if this.ShowHeader and not this.IsConsole _hrow := this.intDB.get(13) + (this.HeaderAtTop ? (this.ShowStatusBar ? (this.StatusBarAtBottom ? 0 : 1) : 0) : (this.intDB.get(1) + (this.ShowStatusBar ? (this.StatusBarAtBottom ? 0 : 1 ) : 0))) if this.ShowBarIndex tt.cell(column=_hqcolBar, row=_hrow, text=this.HeaderQbarIndex, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowDateTime tt.cell(column=_hqcolDateTime, row=_hrow, text=this.HeaderQdateTime, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowLogLevels and this.ReplaceWithErrorCodes tt.cell(column=_hqcolEC, row=_hrow, text=this.HeaderQerrorCode, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowLogLevels and not this.ReplaceWithErrorCodes tt.cell(column=_hqcolEC, row=_hrow, text=this.HeaderQlogLevel, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowQ1 tt.cell(column=_mqcolQ1, row=_hrow, text=this.HeaderQ1, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowQ2 tt.cell(column=_mqcolQ2, row=_hrow, text=this.HeaderQ2, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowQ3 tt.cell(column=_mqcolQ3, row=_hrow, text=this.HeaderQ3, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowQ4 tt.cell(column=_mqcolQ4, row=_hrow, text=this.HeaderQ4, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowQ5 tt.cell(column=_mqcolQ5, row=_hrow, text=this.HeaderQ5, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if this.ShowQ6 tt.cell(column=_mqcolQ6, row=_hrow, text=this.HeaderQ6, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG) if _mqcolQ6<this.intDB.get(16) tt.merge_cells(start_column=_mqcolQ6, start_row=_hrow, end_column=this.intDB.get(16), end_row=_hrow) for x=0 to _txnLen _qc := (_qS%_qsize) _qS += _dx _toShow+=(this.hqx.get(_qc,1)>=0?(this.mqx.get(_qc,0)+(x==_txnLen?'':'\n')):'') if this.hqx.get(_qc,1) >=0 and not this.IsConsole if this.ShowBarIndex tt.cell(column=_hqcolBar, row=x+_logx_headerRowDelta, text=str.tostring( this.hqx.get(_qc,1)), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowDateTime tt.cell(column=_hqcolDateTime, row=x+_logx_headerRowDelta, text=str.format('{0,date,'+this.stringDB.get(4)+'}',this.hqx.get(_qc,2)), bgcolor=this.cqx.get(_qc,1), text_color=this.cqx.get(_qc,0), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowLogLevels and this.ReplaceWithErrorCodes tt.cell(column=_hqcolEC, row=x+_logx_headerRowDelta, text=str.tostring(this.hqx.get(_qc,0)), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowLogLevels and not this.ReplaceWithErrorCodes tt.cell(column=_hqcolEC, row=x+_logx_headerRowDelta, text=((this.RestrictLevelsToKey7 and this.hqx.get(_qc,0) >=0 and this.hqx.get(_qc,0) <=7) or not this.RestrictLevelsToKey7)? this.mqx.get(_qc,6) : '' , text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowQ1 tt.cell(column=_mqcolQ1, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,0), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowQ2 tt.cell(column=_mqcolQ2, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,1), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowQ3 tt.cell(column=_mqcolQ3, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,2), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowQ4 tt.cell(column=_mqcolQ4, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,3), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowQ5 tt.cell(column=_mqcolQ5, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,4), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.ShowQ6 tt.cell(column=_mqcolQ6, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,5), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize) if this.AutoMerge if str.length(this.mqx.get(_qc,5))==0 if str.length(this.mqx.get(_qc,4))==0 if str.length(this.mqx.get(_qc,3))==0 if str.length(this.mqx.get(_qc,2))==0 if str.length(this.mqx.get(_qc,1))==0 tt.merge_cells( start_column = _mqcolQ1, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta) else tt.merge_cells( start_column = _mqcolQ2, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta) else tt.merge_cells( start_column = _mqcolQ3, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta) else tt.merge_cells( start_column = _mqcolQ4, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta) else tt.merge_cells( start_column = _mqcolQ5, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta) else if _mqcolQ6<this.intDB.get(16) tt.merge_cells( start_column = _mqcolQ6, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta) else if _mqcolQ6<this.intDB.get(16) tt.merge_cells(start_column=_mqcolQ6, start_row=x+_logx_headerRowDelta, end_column=this.intDB.get(16), end_row=x+_logx_headerRowDelta) if this.IsConsole int _crowUP = this.intDB.get(17) + (this.ShowStatusBar ? (this.StatusBarAtBottom? 0 : 1) : 0) int _crowDN = this.intDB.get(19) - (this.ShowStatusBar ? (this.StatusBarAtBottom? 1 : 0) : 0) tt.merge_cells(start_column=this.intDB.get(18), end_column=this.intDB.get(20),start_row=_crowUP,end_row =_crowDN) tt.cell(column=this.intDB.get(18), row=_crowUP, text=_toShow, text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign,text_valign=tvalign, text_size=tsize) if this.ShowStatusBar and not this.IsConsole int _srow = this.intDB.get(13) + (this.StatusBarAtBottom ? (this.intDB.get(1) + (this.ShowHeader?1:0)) : 0) int _endMerge=this.ShowMetaStatus ? ((this.ShowBarIndex?1:0) + (this.ShowDateTime?1:0) + (this.ShowLogLevels?1:0) ) : 0 _minStatusLen=math.max(this.intDB.get(24),this.MinWidth)-(this.ShowMetaStatus?11:0) _status=this.Status + (str.length(this.Status)>_minStatusLen ? '': str.substring(this.stringDB.get(0),0,_minStatusLen-str.length(this.Status))) if _endMerge >1 tt.merge_cells(start_column=this.intDB.get(14), start_row=_srow, end_column=this.intDB.get(14)+_endMerge-1, end_row=_srow) tt.merge_cells(start_column=this.intDB.get(14)+_endMerge, start_row=_srow, end_column=this.intDB.get(16), end_row=_srow) tt.cell(column=this.intDB.get(14), row=_srow, text=(this.PageOnEveryBar?'●':'')+' @'+str.tostring(bar_index)+(this.StatusBarAtBottom?' ▲':' ▼'), text_halign=text.align_left, text_valign=text.align_center, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG) tt.cell(column=this.intDB.get(14)+_endMerge, row=_srow, text=_status, text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG) else tt.merge_cells(start_column=this.intDB.get(14)+(this.ShowMetaStatus?1:0), start_row=_srow, end_column=this.intDB.get(16), end_row=_srow) if this.ShowMetaStatus tt.cell(column=this.intDB.get(14), row=_srow, text=(this.PageOnEveryBar?'●':'')+' @'+str.tostring(bar_index)+(this.StatusBarAtBottom?' ▲':' ▼'), text_halign=text.align_left, text_valign=text.align_center, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG) tt.cell(column=this.intDB.get(14)+(this.ShowMetaStatus?1:0), row=_srow, text=_status, text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG) if this.ShowStatusBar and this.IsConsole int _srow = this.StatusBarAtBottom? this.intDB.get(19) : this.intDB.get(17) _hideECmeta= (this.hqx.get(_qc,0)<=0 or (not this.ShowLogLevels) or (this.ShowLogLevels and this.hqx.get(_qc,0)>this.levelDB.size()) or (this.ShowLogLevels and this.RestrictLevelsToKey7 and this.hqx.get(_qc,0)>7)) _minStatusLen=math.max(this.intDB.get(25),this.MinWidth)-(this.ShowMetaStatus?20:0) if _hideECmeta _status=this.Status + (str.length(this.Status)>_minStatusLen ? '': str.substring(this.stringDB.get(0),0,_minStatusLen-str.length(this.Status))) tt.merge_cells(start_column=this.intDB.get(18),start_row=_srow, end_column=this.intDB.get(20)-(this.ShowMetaStatus?1:0),end_row=_srow) if this.ShowMetaStatus tt.cell(column=this.intDB.get(20), row=_srow, text=(this.StatusBarAtBottom?'▲':'▼')+' @'+str.tostring(bar_index)+this.stringDB.get(2) , text_halign=text.align_right, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG) tt.cell(column=this.intDB.get(18), row=_srow, text=_status , text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG) else string _ecText = this.levelDB.get(this.hqx.get(_qc,0)) color _ecColor = this.hqx.get(_qc,0)<=this.colorDB.rows() ? this.colorDB.get(this.hqx.get(_qc,0),0) : this.StatusColorBG color _ecColorHC = this.hqx.get(_qc,0)<=this.colorDB.rows() ? this.colorDB.get(this.hqx.get(_qc,0),2) : this.StatusColor _minStatusLen-=str.length(_ecText) _status=this.Status + (str.length(this.Status)>_minStatusLen ? '': str.substring(this.stringDB.get(0),0,_minStatusLen-str.length(this.Status))) tt.cell(column=this.intDB.get(18), row=_srow, text=_ecText, text_halign=text.align_center, text_valign=text.align_top, text_size=tsize, text_color=_ecColorHC, bgcolor=_ecColor) tt.merge_cells(start_column=this.intDB.get(18)+1,start_row=_srow, end_column=this.intDB.get(20)-(this.ShowMetaStatus?1:0),end_row=_srow) if this.ShowMetaStatus tt.cell(column=this.intDB.get(20), row=_srow, text=(this.StatusBarAtBottom?'▲':'▼')+' @'+str.tostring(bar_index)+this.stringDB.get(2) , text_halign=text.align_right, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG) tt.cell(column=this.intDB.get(18)+1, row=_srow, text=_status, text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG) // @function Display Message Q, Index Q, Time Q, and Log Levels // All options for postion/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc. // @param position Position of the table used for displaying the messages. Default is Bottom Right. // @param hhalign Horizontal alignment of Header columns // @param hvalign Vertical alignment of Header columns // @param hsize Size of Header text Options // @param thalign Horizontal alignment of all messages // @param tvalign Vertical alignment of all messages // @param tsize Size of text across the table // @param show Whether to display the logs or not. Default is true. // @param attach Console that has been attached via attach method. If na then console will not be shown export method show (log this, string position=position.bottom_right, string hhalign=text.align_left, string hvalign=text.align_top, string hsize=size.auto, string thalign=text.align_left, string tvalign=text.align_top, string tsize=size.auto, bool show=true, log attach=na) => this.stringDB.set(5,position) if barstate.islast if this.IsConsole!=this.boolDB.get(1) this._switchMode() if barstate.islast and not show and not na(this.tbx) this.tbx.delete() if barstate.islast and show and not this.boolDB.get(3) this._resetLocations() if barstate.islast and show and not this.boolDB.get(2) this.tbx := table.new(frame_color=this.FrameColor,border_color=this.CellBorderColor,position=position,columns=19,rows=5+this.intDB.get(1),frame_width=this.FrameSize,border_width=this.CellBorderSize) if not na(attach) if attach.intDB.get(2)!=-1 attach.resize(this.intDB.get(1)) if this.boolDB.get(3) and not na(this.SeparatorColor) this.tbx.merge_cells(start_column=this.intDB.get(11)==1?this.intDB.get(14):this.intDB.get(11)==2?this.intDB.get(16)+1:this.intDB.get(11)==4?this.intDB.get(14)-1:this.intDB.get(14),start_row=this.intDB.get(11)==1?this.intDB.get(13)-1:this.intDB.get(11)==2?this.intDB.get(13):this.intDB.get(11)==4?this.intDB.get(13):this.intDB.get(15)+1,end_column=this.intDB.get(11)==1?this.intDB.get(16):this.intDB.get(11)==2?this.intDB.get(16)+1:this.intDB.get(11)==4?this.intDB.get(14)-1:this.intDB.get(16),end_row=this.intDB.get(11)==1?this.intDB.get(13)-1:this.intDB.get(11)==2?this.intDB.get(15):this.intDB.get(11)==4?this.intDB.get(15):this.intDB.get(15)+1) this.tbx.cell(text=' ',bgcolor=this.SeparatorColor, text_color=this.SeparatorColor,row=this.intDB.get(11)==1?this.intDB.get(13)-1:this.intDB.get(11)==2?this.intDB.get(13) :this.intDB.get(11)==4?this.intDB.get(13) :this.intDB.get(15)+1,column=this.intDB.get(11)==1?this.intDB.get(14):this.intDB.get(11)==2?this.intDB.get(16)+1:this.intDB.get(11)==4?this.intDB.get(14)-1:this.intDB.get(14)) if attach.boolDB.get(2) _display(this.tbx, attach, hhalign=hhalign, hvalign=hvalign, hsize=hsize, thalign=thalign, tvalign=tvalign, tsize=tsize) _display(this.tbx, this, hhalign=hhalign, hvalign=hvalign, hsize=hsize, thalign=thalign, tvalign=tvalign, tsize=tsize) // @function Attaches a console to Logx, or moves already attached console around Logx // All options for position/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc. // @param attach Console object that has been previously attached. // @param position Position of Console in relation to Logx. Can be Top, Right, Bottom, Left. Default is Bottom. If unknown specified then defaults to bottom. export method attach(log this,log attach, string position='anywhere') => if not this.boolDB.get(3) if (this.intDB.get(11)%2==0) attach.intDB.set(2,attach.intDB.get(1)) attach.resize(this.intDB.get(1)) else attach.intDB.set(2,-1) if this.boolDB.get(3) if _consolePosition(position)%2!=this.intDB.get(11)%2 if attach.intDB.get(2)==-1 attach.intDB.set(2,attach.intDB.get(1)) attach.resize(this.intDB.get(1)) else attach.resize(attach.intDB.get(2)) attach.intDB.set(2,-1) attach.tbx.delete() this.intDB.set(11,_consolePosition(position)) this.IsConsole:=false,attach.IsConsole:=true this.boolDB.set(2,false),this.boolDB.set(3,true) attach.boolDB.set(2,true),attach.boolDB.set(3,false) _ate=not(na(this.SeparatorColor)) int _czeroRow = this.intDB.get(11)==3 ? (this.intDB.get(1)+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0) + (_ate?1:0) ) : 0 int _czeroCol = this.intDB.get(11)==2 ? (9 + (_ate?1:0)) : 0 int _clastCol = _czeroCol + 8 int _clastRow = _czeroRow + (this.intDB.get(11)%2==1?1:this.intDB.get(1)-1+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0)) int _lzeroRow = this.intDB.get(11)==1 ? (_clastRow+1+(_ate?1:0)) : 0 int _lzeroCol = this.intDB.get(11)==4? (_clastCol+1+(_ate?1:0)): 0 int _llastRow = _lzeroRow + this.intDB.get(1)-1+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0) int _llastCol = _lzeroCol + 8 this.intDB.set(14,_lzeroCol),this.intDB.set(16,_llastCol),this.intDB.set(13,_lzeroRow),this.intDB.set(15,_llastRow) attach.intDB.set(18,_czeroCol),attach.intDB.set(20,_clastCol),attach.intDB.set(17,_czeroRow),attach.intDB.set(19,_clastRow) attach.intDB.set(14,_lzeroCol),attach.intDB.set(16,_llastCol),attach.intDB.set(13,_lzeroRow),attach.intDB.set(15,_llastRow) // @function Detaches the attached console from Logx. // All options for position/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc. // @param attach Console object that has been previously attached. export method detach(log this,log attach) => this.boolDB.set(2,false),this.boolDB.set(3,false) attach.boolDB.set(2,false),attach.boolDB.set(3,false) this._resetLocations(),attach._resetLocations() if attach.intDB.get(2)!=-1 attach.resize(attach.intDB.get(2)) // libhs.log.alpha.57 dev.143
FunctionSMCMC
https://www.tradingview.com/script/1wSximNI-FunctionSMCMC/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Methods to implement Markov Chain Monte Carlo Simulation (MCMC) library(title='FunctionSMCMC') import RicardoSantos/FunctionProbabilityDistributionSampling/1 as dist // @function a basic implementation of the markov chain algorithm // @param weights float array, weights of the Markov Chain. // @param actions float array, actions of the Markov Chain. // @param target_path float array, target path array. // @param position int, index of the path. // @param last_value float, base value to increment. // @returns void, updates target array export markov_chain (float[] weights, float[] actions, float[] target_path, int position, float last_value) => //{ int _size_t = array.size(target_path) int _size_w = array.size(weights) int _size_a = array.size(actions) // switch (_size_t < 1) => runtime.error('FunctionSMCMC -> markov_chain(): "target_path" has the wrong size.') (_size_w < 1) => runtime.error('FunctionSMCMC -> markov_chain(): "weights" has the wrong size.') (_size_w != _size_a) => runtime.error('FunctionSMCMC -> markov_chain(): "weights" and "actions" size must match.') // if _size_w > 1 array.set(target_path, position, last_value + array.get(actions, dist.sample(weights))) else array.set(target_path, position, last_value + array.get(actions, 0)) //} // @function uses a monte carlo algorithm to simulate a markov chain at each step. // @param weights float array, weights of the Markov Chain. // @param actions float array, actions of the Markov Chain. // @param start_value float, base value to start simulation. // @param n_iterations integer, number of iterations to run. // @returns float array with path. export mcmc (float[] weights, float[] actions, float start_value, int n_iterations) => //{ int _size_w = array.size(weights) int _size_a = array.size(actions) float _sum_w = array.sum(weights) // switch na(start_value) => runtime.error('FunctionSMCMC -> markov_chain(): "start_value" is undefined.') (n_iterations < 1) => runtime.error('FunctionSMCMC -> markov_chain(): "n_iterations" must be a positive integer > 0.') (_size_w < 1) => runtime.error('FunctionSMCMC -> markov_chain(): "weights" has the wrong size.') (_size_w != _size_a) => runtime.error('FunctionSMCMC -> markov_chain(): "weights" and "actions" size must match.') (_sum_w != 1.0) => runtime.error(str.format('FunctionSMCMC -> markov_chain(): "weights" must sum 1, found: {0}.', _sum_w)) // float[] _T = array.new_float(n_iterations, 0.0) array.set(_T, 0, start_value) for _i = 1 to n_iterations - 1 by 1 float _current = array.get(_T, _i - 1) markov_chain(weights, actions, _T, _i, _current) _T // @references: // https://stephens999.github.io/fiveMinuteStats/MH-examples1.html // https://ml-cheatsheet.readthedocs.io/en/latest/activation_functions.html //} i_iterations = input(100) i_start = input(500.) weights = array.from(0.3, 0.3, 0.4) actions = array.from(1.0, -1.0, 0.0) var float[] M = array.new_float(0) if barstate.isfirst M := mcmc(weights, actions, i_start, i_iterations) M float output = na if bar_index < i_iterations output := array.get(M, bar_index) output plot(output)
amibroker
https://www.tradingview.com/script/iVEFGCrR-amibroker/
yourtradingbuddy
https://www.tradingview.com/u/yourtradingbuddy/
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/ // © doppelgunner //@version=5 // @description This library consists of functions from amibroker that doesn't exist on tradingview pinescript. The example of these are the ExRem and Flip. // In the example below, I used ExRem to remove the excessive buy and sell signals. Meanwhile, I used the Flip to highlight the bg color when there is an open position. library("amibroker", overlay=true) // @function Removes excessive signals. Pinescript version of ExRem in Amibroker (http://www.amibroker.com/guide/afl/exrem.html) // @param series1 boolean // @param series2 boolean // @returns boolean export exrem(bool series1, bool series2) => result = false series1_index = ta.valuewhen(series1 == true, bar_index, 1) series2_index = ta.valuewhen(series2 == true, bar_index, 0) series1_current_index = ta.valuewhen(series1 == true, bar_index, 0) if (series1 and series2_index > series1_index) or (series1 and not na(series1_current_index) and na(series1_index)) result := true result // @function works as a flip/flop device or "latch". Pinescript version of Flip in Amibroker: (https://www.amibroker.com/guide/afl/flip.html) // @param series1 boolan // @param series2 boolean // @returns boolean. export flip(bool series1, bool series2) => result = series1 series1_index = ta.valuewhen(series1, bar_index, 0) series2_index = ta.valuewhen(series2, bar_index, 0) if (series1_index > series2_index) result := true result buy = close >= ta.highest(close, 50) sell = close <= ta.lowest(close, 50) buy := exrem(buy, sell) sell := exrem(sell, buy) var hasPosition = false hasPosition := flip(buy, sell) bgcolor(hasPosition ? color.new(color.green, 90) : na) plotshape(buy, "Buy", color=color.green, textcolor=color.white, text="Buy", location=location.belowbar, style=shape.labelup) plotshape(sell, "Sell", color=color.red, textcolor=color.white, text="Sell", location=location.abovebar, style=shape.labeldown)
FunctionCompoundInterest
https://www.tradingview.com/script/woq6TTda-FunctionCompoundInterest/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Method for compound interest. library("FunctionCompoundInterest") import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(20) // @function Computes compound interest for given duration. // @param principal float, the principal or starting value. // @param rate float, the rate of interest. // @param duration float, the period of growth. // @returns float. export simple_compound (float principal, float rate, float duration) => //{ principal * math.pow(1.0 + rate / 100.0, duration) // usage: console.queue_one(__C, str.format('Compound interest for the principal (${0}) with interest rate ({1}%) for a duration ({2} periods) = total ${3}', 10000.0, 3.6, 12.0, simple_compound(10000.0, 3.6, 12.0))) //{ remarks: //}}} // @function Computes variable compound interest for given duration. // @param principal float, the principal or starting value. // @param rates float array, the rates of interest. // @param duration int, the period of growth. // @returns float array. export variable_compound (float principal, float[] rates, int duration) => //{ int _size_r = array.size(rates) float _accretion = principal for _i = 1 to duration _accretion := simple_compound(_accretion, array.get(rates, (_i - 1) % _size_r), 1) _accretion // usage: float[] rates = array.from(3.2, 4.1, 7.8) console.queue_one(__C, str.format('Compound interest for the principal (${0}) with variable interest rates ({1}%) for a duration ({2} periods) = total ${3}', 10000.0, str.tostring(rates, '#.##'), 12, variable_compound(10000.0, rates, 12))) //{ remarks: //}}} // @function Computes variable compound interest for given duration. // @param principal float, the principal or starting value. // @param rates float array, the rates of interest. // @param duration int, the period of growth. // @returns float array. export simple_compound_array (float principal, float rate, int duration) => //{ float[] _accretion = array.new_float(duration + 1, principal) for _i = 1 to duration array.set(_accretion, _i, simple_compound(array.get(_accretion, _i - 1), rate, 1)) _accretion // usage: console.queue_one(__C, str.format('Compound interest for the principal (${0}) with interest rate ({1}%) for a duration ({2} periods)\n\t\t\t\t\t\t\t\t = total ${3}', 10000.0, 3.6, 12, str.tostring(simple_compound_array(10000.0, 3.6, 12), '#.##'))) //{ remarks: //}}} // @function Computes variable compound interest for given duration. // @param principal float, the principal or starting value. // @param rates float array, the rates of interest. // @param duration int, the period of growth. // @returns float array. export variable_compound_array (float principal, float[] rates, int duration) => //{ int _size_r = array.size(rates) float[] _accretion = array.new_float(duration + 1, principal) for _i = 1 to duration array.set(_accretion, _i, simple_compound(array.get(_accretion, _i - 1), array.get(rates, (_i - 1) % _size_r), 1)) _accretion // usage: console.queue_one(__C, str.format('Compound interest for the principal (${0}) with variable interest rates ({1}%) for a duration ({2} periods)\n\t\t\t\t\t\t\t\t = total ${3}', 10000.0, str.tostring(rates, '#.##'), 12, str.tostring(variable_compound_array(10000.0, rates, 12), '#.##'))) //{ remarks: //}}} // @function compound interest periods // @param principal float, value of investment. // @param final float, target final value. // @param rate float, interest rate. export compound_interest_periods (float principal, float final, float rate) => //{ math.log(final / principal) / math.log(1.0 + rate) // usage: console.queue_one(__C, str.format('Compound interest to achieve final (${1}) from principal (${0}) with interest rates ({2}%) will require a duration: \n\t\t\t\t\t\t\t\t = {3} periods', 10000.0, 20000, str.tostring(8.0, '#.##'), str.tostring(compound_interest_periods(10000.0, 20000.0, 0.08), '#.##'))) //{ remarks: //}}} // @function compound interest principal // @param final float, target final value. // @param rate float, interest rate. // @param period float, period of investment. export compound_interest_principal (float final, float rate, float period) => //{ final / math.pow(1 + rate, period) // usage: console.queue_one(__C, str.format('Principal with final (${0}) with interest rates ({1}%) and duration of {2} periods: \n\t\t\t\t\t\t\t\t = ${3}', 20000, str.tostring(8.0, '#.##'), 9, str.tostring(compound_interest_principal(20000.0, 0.08, 9.0), '#.##'))) //{ remarks: //}}} console.update(__T, __C)
FunctionElementsInArray
https://www.tradingview.com/script/lCwQarPb-FunctionElementsInArray/
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 Methods to count number of elements in arrays library("FunctionElementsInArray") import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(20) // @function Counts the number of elements equal to provided value in array. // @param sample float array, sample data to process. // @param value float value to check for equality. // @returns int. export count(float[] sample, float value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> count_float(): "sample" has no elements.') // float[] _copy = array.copy(sample) int _count = 0 for _i = 1 to _size_s int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) _count += 1 _count //{ usage: float[] count_a = array.from(0.1, 2, 0.3, 0.3, 77, 0.7, 0.3) console.queue_one(__C, str.format('there is {1} elements with value 0.3 in {0}', count_a, count(count_a, 0.3))) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array. // @param sample int array, sample data to process. // @param value int value to check for equality. // @returns int. export count (int[] sample, int value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> count_int(): "sample" has no elements.') // int[] _copy = array.copy(sample) int _count = 0 for _i = 1 to _size_s int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) _count += 1 _count //{ usage: int[] count_b = array.from(1, 2, 3, 3, 77, 7, 3) console.queue_one(__C, str.format('there is {1} elements with value 3 in {0}', count_b, count(count_b, 3))) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array. // @param sample string array, sample data to process. // @param value string value to check for equality. // @returns int. export count (string[] sample, string value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> count_string(): "sample" has no elements.') // string[] _copy = array.copy(sample) int _count = 0 for _i = 1 to _size_s int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) _count += 1 _count //{ usage: string[] count_c = array.from("1", "2", "3", "3", "77", "7", "3") console.queue_one(__C, str.format('there is {1} elements with value "3" in "{0}"', count_c, count(count_c, "3"))) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array. // @param sample bool array, sample data to process. // @param value bool value to check for equality. // @returns int. export count (bool[] sample, bool value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> count_bool(): "sample" has no elements.') // bool[] _copy = array.copy(sample) int _count = 0 for _i = 1 to _size_s int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) _count += 1 _count //{ usage: bool[] count_d = array.from(false, false, true, true, false, true, false) console.queue_one(__C, str.format('there is {1} elements with value "true" in {0}', count_d, count(count_d, true))) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array. // @param sample color array, sample data to process. // @param value color value to check for equality. // @returns int. export count (color[] sample, color value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> count_color(): "sample" has no elements.') // color[] _copy = array.copy(sample) int _count = 0 for _i = 1 to _size_s int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) _count += 1 _count //{ usage: color[] count_e = array.from(#000000, #ffff25, #ffffff, #ffffff, #ffffff00, #000000, #ffffff) console.queue_one(__C, str.format('there is {1} elements with value "#ffffff" in {0}', "------", count(count_e, #ffffff))) // cant stringify color //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array, and returns its indices. // @param sample float array, sample data to process. // @param value float value to check for equality. // @returns int. export extract_indices (float[] sample, float value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> extract_indices_float(): "sample" has no elements.') // float[] _copy = array.copy(sample) int[] _indices = array.new_int(0) int _count = 0 for _i = 0 to _size_s-1 int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) array.push(_indices, _idx + _i) // rectified for exclusion _count += 1 [_count, _indices] //{ usage: [eif_count, eif_indices] = extract_indices(count_a, 0.3) console.queue_one(__C, str.format('there is {1} elements at indices({2}) with value 0.3 in {0}', count_a, eif_count, eif_indices)) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array, and returns its indices. // @param sample int array, sample data to process. // @param value int value to check for equality. // @returns int. export extract_indices (int[] sample, int value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> extract_indices_int(): "sample" has no elements.') // int[] _copy = array.copy(sample) int[] _indices = array.new_int(0) int _count = 0 for _i = 0 to _size_s-1 int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) array.push(_indices, _idx + _i) // rectified for exclusion _count += 1 [_count, _indices] //{ usage: [eii_count, eii_indices] = extract_indices(count_b, 3) console.queue_one(__C, str.format('there is {1} elements at indices({2}) with value 3 in {0}', count_b, eii_count, eii_indices)) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array, and returns its indices. // @param sample string array, sample data to process. // @param value string value to check for equality. // @returns int. export extract_indices (string[] sample, string value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> extract_indices_string(): "sample" has no elements.') // string[] _copy = array.copy(sample) int[] _indices = array.new_int(0) int _count = 0 for _i = 0 to _size_s-1 int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) array.push(_indices, _idx + _i) // rectified for exclusion _count += 1 [_count, _indices] //{ usage: [eis_count, eis_indices] = extract_indices(count_c, "3") console.queue_one(__C, str.format('there is {1} elements at indices({2}) with value 3 in {0}', count_c, eis_count, eis_indices)) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array, and returns its indices. // @param sample bool array, sample data to process. // @param value bool value to check for equality. // @returns int. export extract_indices (bool[] sample, bool value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> extract_indices_bool(): "sample" has no elements.') // bool[] _copy = array.copy(sample) int[] _indices = array.new_int(0) int _count = 0 for _i = 0 to _size_s-1 int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) array.push(_indices, _idx + _i) // rectified for exclusion _count += 1 [_count, _indices] //{ usage: [eib_count, eib_indices] = extract_indices(count_d, true) console.queue_one(__C, str.format('there is {1} elements at indices({2}) with value true in {0}', count_c, eis_count, eis_indices)) //{ remarks: //}}} // @function Counts the number of elements equal to provided value in array, and returns its indices. // @param sample color array, sample data to process. // @param value color value to check for equality. // @returns int. export extract_indices (color[] sample, color value) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('FunctionElementsInArray -> extract_indices_color(): "sample" has no elements.') // color[] _copy = array.copy(sample) int[] _indices = array.new_int(0) int _count = 0 for _i = 0 to _size_s-1 int _idx = array.indexof(_copy, value) if _idx < 0 break 0 else array.remove(_copy, _idx) array.push(_indices, _idx + _i) // rectified for exclusion _count += 1 [_count, _indices] //{ usage: [eic_count, eic_indices] = extract_indices(count_e, #ffffff) console.queue_one(__C, str.format('there is {1} elements at indices({2}) with value #ffffff in {0}', '------', eic_count, eic_indices)) // cant stringify color //{ remarks: //}}} console.update(__T, __C)
LinearRegressionLibrary
https://www.tradingview.com/script/8dWXwYuT-LinearRegressionLibrary/
tbiktag
https://www.tradingview.com/u/tbiktag/
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/ // © tbiktag //@version=5 library("LinearRegressionLibrary") export RepeatedMedian(float y, int n, int lastBar) => // // Repeated median regression (robust regression) algorithm: // For each point, get slopes of lines connecting it with other data points, // and calculate the median. Then calculate the slope of regression line as // the median of the median slopes. // Finally, calculate the intercept of the regression line. // // Input: // y :: float, series, source time series, e.g. close // n :: integet, number of points in the lookback window // lastBar :: integer, index of the last bar in the selected interval // Output: // mSlope :: float, slope of the regression line // mInter :: float, intercept of the regression line // var float[] S = array.new_float(0) var float[] I = array.new_float(0) float m = 0.0 float mSlope = 0.0 float mInter = 0.0 bool isDone = false // if bar_index[1] <= lastBar and bar_index >= lastBar and n > 1 and not isDone isDone := true for i = 0 to n - 1 float[] S1 = array.new_float(0) for j = 0 to n - 1 if i != j array.push(S1, (y[i] - y[j]) / (j - i)) m := array.median(S1) array.push(S, m) // Control the array size if array.size(S) > n array.remove(S,0) // // Calculate intercept float mSlopeLocal = array.median(S) for i = 0 to n - 1 array.push(I, y[n - 1 - i] - mSlopeLocal * i) // Control the array size if array.size(I) > n array.remove(I,0) mSlope := array.median(S) mInter := array.median(I) // [mSlope, mInter] export TheilSen(float y, int n, int lastBar) => // // Theil-Sen estimator (robust regression) algorithm: // Get slopes of all lines connecting the data points in the sample. // Then calculate the slope of regression line as the median of the slopes. // Finally, calculate the intercept of the regression line. // // Input: // y :: float, series, source time series, e.g. close // n :: integet, number of points in the lookback window // lastBar :: integer, index of the last bar in the selected interval // Output: // mSlope :: float, slope of the regression line // mInter :: float, intercept of the regression line // var float[] S = array.new_float(0) var float[] I = array.new_float(0) float tsSlope = 0.0 float tsInter = 0.0 bool isDone = false // if bar_index[1] <= lastBar and bar_index >= lastBar and n > 1 and not isDone isDone := true for i = 0 to n - 2 for j = i + 1 to n - 1 array.push(S, (y[i] - y[j]) / (j - i)) // Control the array size if array.size(S) > n*(n-1)/2 array.remove(S,0) // // Calculate intercept float mSlopeLocal = array.median(S) for i = 0 to n - 1 array.push(I, y[n - 1 - i] - mSlopeLocal * i) // Control the array size if array.size(I) > n array.remove(I,0) tsSlope := array.median(S) tsInter := array.median(I) // [tsSlope, tsInter] export OrdinaryLeastSquares(float y, int n, int lastBar) => // // Ordinary least square regression (non-robust) algorithm. // // Input: // y :: float, series, source time series, e.g. close // n :: integet, number of points in the lookback window // lastBar :: integer, index of the last bar in the selected interval // Output: // olsSlope :: float, slope of the regression line // olsInter :: float, intercept of the regression line // var float olsSlope = 0.0 var float olsInter = 0.0 bool isDone = false // if bar_index[1] <= lastBar and bar_index >= lastBar and n > 1 and not isDone isDone := true float meanX = (n+1)/2 float meanY = 0.0 for i = 0 to n - 1 meanY += y[n - 1 - i]/n float sum1 = 0.0 float sum2 = 0.0 for i = 0 to n - 1 sum1 += (i - meanX)*(y[n - 1 - i] - meanY) sum2 += (i - meanX)*(i - meanX) olsSlope := sum1/sum2 olsInter := meanY - olsSlope*meanX // [olsSlope, olsInter] export metricRMSE(float y, int n, int lastBar, float slope, float intercept) => // // Model performance metric: root-mean-square error (RMSE) of the regression. // // Input: // y :: float,series, input time series, e.g. close // n :: integer, number of points in the interval // lastBar :: integer, index of the last bar in the interval // slope :: float, model slope // intercept :: float, model intercept // Output: // rmse :: float, root mean square error // float rmse = na if bar_index[1] <= lastBar and bar_index >= lastBar and n > 1 and na(rmse) rmse := 0.0 for i = 0 to n-1 rmse := rmse + math.pow(y[i] - intercept - slope*(n - i),2)/n math.sqrt(rmse) export metricMAE(float y, int n, int lastBar, float slope, float intercept) => // // Model performance metric: mean absolute error (MAE) of the regression. // // Input: // y :: float,series, input time series, e.g. close // n :: integer, number of points in the interval // lastBar :: integer, index of the last bar in the interval // slope :: float, model slope // intercept :: float, model intercept // Output: // mae :: float, mean absolute error // var float mae = na if bar_index[1] <= lastBar and bar_index >= lastBar and n > 1 and na(mae) mae := 0.0 for i = 0 to n-1 mae += math.abs(y[i] - intercept - slope*(n - i))/n mae export metricR2(float y, int n, int lastBar, float slope, float intercept) => // // Model performance metric: coefficient of determination (R-square) of the regression. // // Input: // y :: float,series, input time series, e.g. close // n :: integer, number of points in the interval // lastBar :: integer, index of the last bar in the interval // slope :: float, model slope // intercept :: float, model intercept // Output: // Rsq :: float, R-square score // var float Rsq = 0.0 bool isDone = false // if bar_index[1] <= lastBar and bar_index >= lastBar and n > 1 and not isDone isDone := true float meanY = 0.0 for i = 0 to n - 1 meanY += y[i]/n float u = 0.0 float v = 0.0 for i = 0 to n - 1 float hatY = intercept + slope*(n - i) u += (y[i] - hatY)*(y[i] - hatY) v += (y[i] - meanY)*(y[i] - meanY) Rsq := 1 - u/v // Rsq
ZenLibrary
https://www.tradingview.com/script/yUWPxUBt-ZenLibrary/
ZenAndTheArtOfTrading
https://www.tradingview.com/u/ZenAndTheArtOfTrading/
296
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/ // © ZenAndTheArtOfTrading // Last Updated: 9th March, 2022 // @version=5 // @description A collection of custom tools & utility functions commonly used with my scripts library("ZenLibrary") // --- 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
lib_Indicators_DT
https://www.tradingview.com/script/TXl700vK-lib-Indicators-DT/
dturkuler
https://www.tradingview.com/u/dturkuler/
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/ // © dturkuler // library includes indicators, snippets from tradingview library , user @RodrigoKazuma indicator //@version=5 // @description This library functions returns some Moving averages and indicators. Created it to feed my indicator/strategy "INDICATOR & CONDITIONS COMBINATOR FRAMEWORK v[x] [DTU]" library("lib_Indicators_DT", overlay = false) //-------------------------- //--------Constants--------- //-------------------------- fastlength = 5 slowlength = 34 mult = 2.0 PI = 3.14159265 AlmaOffset = 0.85 //Defaut is 0.5 or 0.85 AlmaSigma = 6 //Defaut is 1 or 6 LAPercLen = 5 //input(title="Lag Adapt: Perc length_", type=integer, defval=5, minval=1) FPerc = 50 //input(title="Percntl: Percentile", type=float, defval=50.0, minval=0.0, maxval=100.0) LOffset = 1 //input(title="Offset", type=integer, defval=0, minval=0) //-------------------------- len = 14 useSimpleLog = false plotSWMA = false plotingType = input.string('Original', options=['Original', 'Stochastic', 'PercentRank']) stochlen = 50 smaFunction = true //-------------------------- //--------Functions--------- //-------------------------- plotFunction(src_) => plotingType == 'Stochastic' ? ta.stoch(src_, src_, src_, stochlen) / 50 - 1 : plotingType == 'PercentRank' ? ta.percentrank(src_, stochlen) / 50 - 1 : src_ PlotFunction(float src_, simple string plotingType_="Original", simple int stochlen_=50) => plotingType_ == 'Stochastic' ? ta.stoch(src_, src_, src_, stochlen_) / 50 - 1 : plotingType_ == 'PercentRank' ? ta.percentrank(src_, stochlen_) / 50 - 1 : src_ simpleLog(src_) => useSimpleLog ? math.log(src_) : src_ plotting(src_) => srcP = plotFunction(src_) plotSWMA ? ta.swma(srcP) : srcP // @function Prepare Indicator Plot Type // @param src_ Source // @param src_ plotingType_ "Original, Stochastic, Percent" // @param src_ stochlen_ Stochasting plottingtype length // @param src_ plotSWMA_ Use SWMA for the output // @returns Return the prepared indicator export f_plotPrep(float src_, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false) => srcP = PlotFunction(src_, plotingType_, stochlen_) plotSWMA_ ? ta.swma(srcP) : srcP //bollinger %% bbr(src_, length_) => dev = mult * ta.stdev(src_, length_) (src_ - ta.sma(src_, length_) + dev) / (2 * dev) kcr(src_, length_) => range_1 = mult * ta.ema(ta.tr, length_) (src_ - ta.ema(src_, length_) - range_1) / (2 * range_1) count(src_, length_) => red_count = 0 red_src = 0.0 green_count = 0 green_src = 0.0 for i = 0 to length_ by 1 if close[i] < open[i] red_count := red_count + 1 red_src := red_src + src_[i] red_src if close[i] > open[i] green_count := green_count + 1 green_src := green_src + src_[i] green_src green_ave = green_src / green_count red_ave = red_src / red_count green_ave - red_ave dema(src_, length_) => ema1 = ta.ema(src_, length_) ema2 = ta.ema(ema1, length_) 2 * ema1 - ema2 tema(src_, length_) => ema1 = ta.ema(src_, length_) ema2 = ta.ema(ema1, length_) ema3 = ta.ema(ema2, length_) 3 * (ema1 - ema2) + ema3 cctbbo(src_, length_) => deviation = ta.stdev(src_, length_) smooth = ta.sma(src_, length_) (src_ + 2 * deviation - smooth) / (4 * deviation) - 0.4 //Ehler's super smoother, 2 pole super2(src_, length_) => y = float(na) a1 = math.exp(-math.sqrt(2) * PI / length_) b1 = 2 * a1 * math.cos(math.sqrt(2) * PI / length_) coef2 = b1 coef3 = -math.pow(a1, 2) coef1 = 1 - coef2 - coef3 y := coef1 * (src_ + nz(src_[1], src_)) / 2 + coef2 * nz(y[1]) + coef3 * nz(y[2]) y //Ehler's super smoother, 3 pole super3(src_, length_) => y = float(na) a1 = math.exp(-PI / length_) b1 = 2 * a1 * math.cos(1.738 * PI / length_) c1 = math.pow(a1, 2) coef2 = b1 + c1 coef3 = -c1 * (1 + b1) coef4 = c1 * c1 coef1 = 1 - coef2 - coef3 - coef4 y := coef1 * (src_ + nz(src_[1], src_)) / 2 + coef2 * nz(y[1]) + coef3 * nz(y[2]) + coef4 * nz(y[3]) y willprc(src_, length_) => masrcP = ta.highest(src_, length_) minP = ta.lowest(src_, length_) 100 * (src_ - masrcP) / (masrcP - minP) trix(src_, length_) => 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(src_), length_), length_), length_)) copcurve(src_, length_) => ta.wma(ta.roc(src_, slowlength) + ta.roc(src_, fastlength), length_) smiSignal(src_, length_) => erg = ta.tsi(src_, fastlength, slowlength) //indicaot sig = ta.ema(erg, length_) //Signal sig smiOscillator(src_, length_) => erg = ta.tsi(src_, fastlength, slowlength) //indicaot sig = ta.ema(erg, length_) //Signal osc = erg - sig //Oscillator osc //lowest exponential expanding moving line lexp(src_, length_) => y = float(na) y := na(y[1]) ? src_ : src_ <= y[1] ? src_ : y[1] + (src_ - y[1]) / length_ y //Ehler's Adaptive Laguerre filter lagAdapt(src_, length_) => y = float(na) alpha = float(na) error = math.abs(src_ - nz(y[1])) range_2 = ta.highest(error, length_) - ta.lowest(error, length_) perc = range_2 != 0 ? (error - ta.lowest(error, length_)) / 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 y //Ehler's Adaptive Laguerre filter variation lagAdaptV(src_, length_) => y = float(na) alpha = float(na) error = math.abs(src_ - nz(y[1])) range_3 = ta.highest(error, length_) - ta.lowest(error, length_) perc = range_3 != 0 ? (error - ta.lowest(error, length_)) / range_3 : nz(alpha[1]) alpha := ta.percentile_linear_interpolation(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 y //Ehler's Laguerre filter laguerre(src_, length_) => y = float(na) alpha = math.exp((1 - length_) / 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 y //lowest exponential esrcpanding moving line lesrcp(src_, length_) => y = float(na) y := na(y[1]) ? src_ : src_ <= y[1] ? src_ : y[1] + (src_ - y[1]) / length_ y //---Smoothed Moving Average (SMMA) calc_smma(src,l)=> smmaMA = 0.0 smmaMA := na(smmaMA[1]) ? ta.sma(src, l) : (smmaMA[1] * (l - 1) + src) / l smmaMA //---Sine-Weighted Moving Average (SW-MA) calc_swma(src,l) => PI = 2 * math.asin(1) sum = 0.0 weightSum = 0.0 for i = 0 to l - 1 weight = math.sin((i + 1) * PI / (l + 1)) sum := sum + nz(src[i]) * weight weightSum := weightSum + weight sineWeightMA = sum / weightSum sineWeightMA //---Triangular Moving Average (TMA) calc_tma(src,l) => triMA = ta.sma(ta.sma(src, math.ceil(l / 2)), math.floor(l / 2) + 1) triMA //Geometric Mean Moving Average (GMMA) calc_gmma(src,l) => lmean = math.log(src) smean = math.sum(lmean,l) geoMA = math.exp(smean/l) geoMA //---Variable Index Dynamic Average (VIDA) calc_vida(src,l) => mom = ta.change(src) upSum = math.sum(math.max(mom, 0), l) downSum = math.sum(-math.min(mom, 0), l) cmo = math.abs((upSum - downSum) / (upSum + downSum)) F = 2/(l+1) vida = 0.0 vida := src * F * cmo + nz(vida[1]) * (1 - F * cmo) vida //---Corrective Moving average (CMA) calc_cma(src,l) => sma = ta.sma(src, l) cma = sma v1 = ta.variance(src, l) 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 if err > tolerance k := v3 * kPrev * (2 - kPrev) err := kPrev - k kPrev := k cma := nz(cma[1], src) + k * (sma - nz(cma[1], src)) cma //---Ramnge EMA (REMA) calc_range_ema (src,l) => alpha = 2/(1 + l) 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]) ma = num/den ma f_func(string f, float src_, simple int length_) => float y = switch f 'Hide' => src_ 'alma' => ta.alma(src_, length_, AlmaOffset, AlmaSigma) 'bbr' => bbr(src_, length_) 'bbw' => ta.bbw(src_, length_, mult) 'cci' => ta.cci(src_, length_) 'cctbbo' => cctbbo(src_, length_) 'change' => ta.change(src_, length_) 'cmo' => ta.cmo(src_, length_) 'cog' => ta.cog(src_, length_) 'count' => count(src_, length_) 'dev' => ta.dev(src_, length_) 'stdev' => ta.stdev(src_, length_) 'sma' => ta.sma(src_, length_) 'ema' => ta.ema(src_, length_) 'dema' => dema(src_, length_) 'rma' => ta.rma(src_, length_) 'super2' => super2(src_, length_) 'super3' => super3(src_, length_) 'hull' => ta.wma(2 * ta.wma(src_, length_ / 2) - ta.wma(src_, length_), math.round(math.sqrt(length_))) 'kcr' => kcr(src_, length_) 'kcw' => ta.kcw(src_, length_, mult) 'linreg' => ta.linreg(src_, length_, LOffset) 'mfi' => ta.mfi(src_, length_) 'roc' => ta.roc(src_, length_) 'rsi' => ta.rsi(src_, length_) * 10 'variance' => ta.variance(src_, length_) 'vwma' => ta.vwma(src_, length_) 'wma' => ta.wma(src_, length_) 'willprc' => willprc(src_, length_) 'trix' => trix(src_, length_) 'copcurve' => copcurve(src_, length_) 'smi_sig' => smiSignal(src_, length_) 'smi_Osc' => smiOscillator(src_, length_) 'correl' => ta.correlation(src_, src_[1], length_) 'hl2ma' => (ta.highest(src_, length_) + ta.lowest(src_, length_)) / 2 'lagAdapt' => lagAdapt(src_, length_) 'lagAdaptV' => lagAdaptV(src_, length_) 'laguerre' => laguerre(src_, length_) 'lesrcp' => lesrcp(src_, length_) 'percntl' => ta.percentile_nearest_rank(src_, length_, FPerc) 'percntli' => ta.percentile_linear_interpolation(src_, length_, FPerc) 'tsi' => ta.tsi(src_, fastlength, slowlength) 'macd' => ta.sma(src_, length_) - ta.sma(src_, 2 * length_) 'lexp' => lexp(src_, length_) 'smma' => calc_smma(src_, length_) 'swma' => calc_swma(src_, length_) 'tma' => calc_tma(src_, length_) 'gmma' => calc_gmma(src_, length_) 'vida' => calc_vida(src_, length_) 'cma' => calc_cma(src_, length_) 'rema' => calc_range_ema(src_, length_) 'tema' => tema(src_, length_) y // @function f_funcPlot(string f, float src_, simple int length_, string plotingType_ = "Original", simple int stochlen_=50, bool plotSWMA=false) Return selected indicator value with different parameters // @param string f indicator-> options=['Hide' // '▼▼▼ MOV AVGs ▼▼▼', // 'alma', 'cma','dema', 'ema', 'gmma','hl2ma','hull','lagAdapt', 'lagAdaptV', 'laguerre', 'lesrcp','linreg', 'lexp', 'percntl', // 'percntli', 'rema','rma','sma','smma','super2', 'super3','swma','tema', 'tma','vida','vwma', 'wma', // '▼▼▼ INDICATORS ▼▼▼', // 'bbr', 'bbw', 'cci', 'cctbbo', 'change', 'cmo', 'cog', 'copcurve', 'correl', 'count', 'dev', 'kcr', 'kcw', // 'macd', 'mfi', 'roc', 'rsi', 'smi_Oscillator', 'smi_signal', 'stdev','trix' , 'tsi', 'variance', 'willprc'] // @param float src_ close,open..... // @param simple int length_ indicator length // @param string plotingType return param-> options=['Original', 'Stochastic', 'PercentRank') // @param simple int stochlen_ length for return Param // @param bool plotSWMA Use SWMA on Plot // @returns float [series] export f_funcPlot(string f, float src_, simple int length_, string plotingType_ = "Original", simple int stochlen_=50, bool plotSWMA=false) => fPlotSrc_=f_func(f, src_, length_) srcP = plotingType_ == 'Stochastic' ? ta.stoch(fPlotSrc_, fPlotSrc_, fPlotSrc_, stochlen_) / 50 - 1 : plotingType_ == 'PercentRank' ? ta.percentrank(fPlotSrc_, stochlen_) / 50 - 1 : fPlotSrc_ plotSWMA ? ta.swma(srcP) : srcP ////USAGE ////@version=5 //indicator("My Script") //import dturkuler/lib_Indicators_DT/1 as ind // library includes indicators, snippets from tradingview library , @03.freeman ("All MAs displayed") indicator... // //ind_src= input.string( defval='ema', title='IND:', options=['Hide', // '▼▼▼ MOV AVGs ▼▼▼', // 'alma', 'cma','dema', 'ema', 'gmma','hl2ma','hull','lagAdapt', 'lagAdaptV', 'laguerre', 'lesrcp','linreg', 'lexp', 'percntl', // 'percntli', 'rema','rma','sma','smma','super2', 'super3','swma','tema', 'tma','vida','vwma', 'wma', // '▼▼▼ OTHER INDICATORS ▼▼▼', // 'bbr', 'bbw', 'cci', 'cctbbo', 'change', 'cmo', 'cog', 'copcurve', 'correl', 'count', 'dev', 'kcr', 'kcw', // 'macd', 'mfi', 'roc', 'rsi', 'smi_Oscillator', 'smi_signal', 'stdev','trix' , 'tsi', 'variance', 'willprc'] // , group="════════════ INDICATORS ════════════", inline="ind") //ind_len = input.int( defval=48, title='', group="════════════ INDICATORS ════════════", inline="ind") //ind_pType = input.string( defval="Original", title="", group="════════════ INDICATORS ════════════", inline="ind", options=['Original', 'Stochastic', 'PercentRank']) //ind_color = input( defval=color.green, title="", group="════════════ INDICATORS ════════════", inline="ind") //ind_pSWMA= input.bool( defval=false, title="Smooth", group="════════════ INDICATORS ════════════", inline="ind") // //indicator=ind.f_funcPlot(ind_src, close, length_=ind_len, plotingType_=ind_pType, plotSWMA=ind_pSWMA) //plot(ind_src!="Hide" ? indicator:na, "INDICATOR",ind_color)
FunctionProbabilityDistributionSampling
https://www.tradingview.com/script/mIw3uhtT-FunctionProbabilityDistributionSampling/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Methods for probability distribution sampling selection. library(title="FunctionProbabilityDistributionSampling") import RicardoSantos/ArrayOperationsFloat/1 as aof import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(20) // @function Computes a random selected index from a probability distribution. // @param probabilities float array, probabilities of sample. // @returns int. export sample (float[] probabilities) => //{ int _size_p = array.size(probabilities) float _sum_p = array.sum(probabilities) // // errors switch (_size_p < 1) => runtime.error('FunctionProbabilityDistributionSampling -> sample(): "probabilities" has the wrong size.') (_sum_p <= 0) => runtime.error(str.format('FunctionProbabilityDistributionSampling -> sample(): "probabilities" must sum to a value greater than 0, actual: {0}.', _sum_p)) // float[] _normalized = aof.divide(probabilities, array.from(_sum_p)) float _sample = math.random() float _total = 0.0 int _idx = na for _i = 0 to _size_p - 1 _total += array.get(_normalized, _i) if _sample < _total _idx := _i break _idx //{ usage: if barstate.isfirst var int[] counts = array.new_int(10, 0) for _i = 0 to 10000 int _idx = sample(array.from(0.02, 0.03, 0.05, 0.1, 0.25, 0.35, 0.25, 0.05, 0.03, 0.02)) array.set(counts, _idx, array.get(counts, _idx) + 1) console.queue_one(__C, str.tostring(counts)) console.queue_one(__C, str.tostring(aof.multiply(aof.divide(counts, array.from(10000)), array.from(100)), format.percent)) //{ remarks: // https://gist.github.com/brannondorsey/dc4cfe00d6b124aebd3277159dcbdb14 //}}} console.update(__T, __C)
ArrayMultipleDimensionPrototype
https://www.tradingview.com/script/oZvVOvXI-ArrayMultipleDimensionPrototype/
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 A prototype library for Multiple Dimensional array methods library(title="ArrayMultipleDimensionPrototype") import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(20) export index_md_to_1d (float[] dimensions, float[] indices) => //{ int _size_d = array.size(dimensions) int _size_i = array.size(indices) // switch (_size_d < 2) => runtime.error('... -> index_md_to_1d(): "dimensions" must be have atleast 2 dimensions.') (_size_i < 2) => runtime.error('... -> index_md_to_1d(): "indices" must be have atleast 2 dimensions.') (_size_d != _size_i) => runtime.error('... -> index_md_to_1d(): "dimensions" and "indices" must be the same size.') // int _idx = int(array.get(indices, _size_d-1)) int _cum_d = int(array.get(dimensions, _size_d-1)) // if _idx >= _cum_d runtime.error(str.format('... -> index_md_to_1d(): "indices" out of bounds. expected indice under: {0}, found: {1}', _cum_d, _idx)) // for _i = _size_d - 2 to 0 int _current_i = int(array.get(indices, _i)) int _current_d = int(array.get(dimensions, _i)) // if _current_i >= _current_d runtime.error(str.format('... -> index_md_to_1d(): "indices" out of bounds. expected indice under: {0}, found: {1}', _current_d, _current_i)) // _idx += _current_i * _cum_d _cum_d *= _current_d _idx //{ usage: console.queue_one(__C, str.format('{0}', str.tostring(index_md_to_1d(array.from(2, 4), array.from(0, 3) )))) console.queue_one(__C, str.format('{0}', str.tostring(index_md_to_1d(array.from(2, 4), array.from(0, 1) )))) console.queue_one(__C, str.format('{0}', str.tostring(index_md_to_1d(array.from(2, 4), array.from(0, 2) )))) console.queue_one(__C, str.format('{0}', str.tostring(index_md_to_1d(array.from(2, 4), array.from(1, 0) )))) console.queue_one(__C, str.format('{0}', str.tostring(index_md_to_1d(array.from(2, 4), array.from(1, 1) )))) console.queue_one(__C, str.format('{0}', str.tostring(index_md_to_1d(array.from(2, 4), array.from(1, 2) )))) //}} // @function Creates a variable size multiple dimension array. // @param dimensions int array, dimensions of array. // @param initial_size float, default=na, initial value of the array. // @returns float array export new_float(int[] dimensions, float initial_value=na) => //{ int _size_s = array.size(dimensions) // switch (_size_s < 2) => runtime.error('ArrayMDim -> new_float(): "dimensions" must be have atleast 2 dimensions.') // int _size = 1 float[] _head = array.new_float(_size_s + 1, float(_size_s)) for _i = 0 to (_size_s - 1) _size *= array.get(dimensions, _i) array.set(_head, _i + 1, array.get(dimensions, _i)) array.concat(_head, array.new_float(_size, initial_value)) //{ usage: console.queue_one(__C, str.format('{0}', str.tostring(new_float(array.from(2, 3), 1)))) console.queue_one(__C, str.format('{0}', str.tostring(new_float(array.from(3, 3), 1)))) console.queue_one(__C, str.format('{0}', str.tostring(new_float(array.from(4, 3), 1)))) console.queue_one(__C, str.format('{0}', str.tostring(new_float(array.from(2, 2, 2), 1)))) //}} // @function set value of a element in a multiple dimensions array. // @param id float array, multiple dimensions array. // @param value float, new value. // @returns float. export dimensions (float[] id) => //{ int _size_h = int(array.get(id, 0)) + 1 // // TODO: errors // float[] _dims = array.slice(id, 1, _size_h) //{ usage var float[] test_222 = array.from( 3, 2, 2, 2, 0.00, 0.01, 0.10, 0.11, 1.00, 1.01, 1.10, 1.11 ) var float[] test_43 = array.from(2, 4, 3, 0.0, 0.1, 0.2, 1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2) console.queue_one(__C, str.format('test_222 has {0} dimensions', str.tostring(dimensions(test_222), '#0'))) //}} // @function get value of a multiple dimensions array. // @param id float array, multiple dimensions array. // @returns float. export get (float[] id, int[] indices) => //{ int _size_a = array.size(id) int _size_h = int(array.get(id, 0)) + 1 // // array.get(id, _size_h + index_md_to_1d(dimensions(id), indices)) //{ usage string temp_str = '[' for _i = 0 to 1 for _j = 0 to 1 for _k = 0 to 1 temp_str += str.tostring(get(test_222, array.from(_i, _j, _k)), '#0.00') if (_i == 1 and _j == 1 and _k == 1) temp_str += ']' else temp_str += ', ' console.queue_one(__C, str.format('get test_222 = {0}', str.tostring(temp_str))) //}} // @function set value of a element in a multiple dimensions array. // @param id float array, multiple dimensions array. // @returns float. export set (float[] id, int[] indices, float value) => //{ int _size_a = array.size(id) int _size_h = int(array.get(id, 0)) + 1 // // TODO: errors // float[] _dims = array.slice(id, 1, _size_h) array.set(id, _size_h + index_md_to_1d(_dims, indices), value) //{ usage test_set = new_float(array.from(4, 3), 1) console.queue_one(__C, str.format('{0}', str.tostring(test_set))) for _i = 0 to 3 for _j = 0 to 2 set(test_set, array.from(_i, _j), _i + _j * 0.1) console.queue_one(__C, str.format('{0}', str.tostring(test_set, '#0.0'))) //}} console.update(__T, __C)
DrawIndicatorOnTheChart
https://www.tradingview.com/script/1VedFQRo-DrawIndicatorOnTheChart/
LonesomeTheBlue
https://www.tradingview.com/u/LonesomeTheBlue/
283
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 to show an indicator (such RSI, CCI, MOM etc) on the main chart with indicator's horizontal lines in a window. Location of the window is calculated dynamically by last price movemements library("DrawIndicatorOnTheChart", overlay = true) // location function is used to find Y coordinates of the indicator window, // it checks the closing price movements and calculates if it needs to show the window at the top/bottom of the chart // returns top and bottom levels of the window findIndiLoc()=> var int indi_loc = 0 float h_ = ta.highest(292) float l_ = ta.lowest(292) float diff_ = (h_ - l_) / 10 float hl2_ = (h_ + l_) / 2 indi_loc := indi_loc == 0 ? (close >= hl2_ ? -1 : 1) : indi_loc == -1 and close < hl2_ - diff_ * 2 ? 1 : indi_loc == 1 and close > hl2_ + diff_ * 2 ? -1 : indi_loc float top = indi_loc == 1 ? h_ : l_ + (h_ - l_) / 5 float bottom = indi_loc == 1 ? h_ - (h_ - l_) / 5 : l_ [top, bottom, indi_loc] // finds relational location of any indicator value in the indicator window getIndiLevel(float indi, float indimax, float indimin, float top, float bottom)=> float relationalpos = bottom + (top - bottom) * ((indi - indimin) / (indimax - indimin)) // @function draws the realted indicator on the chart // @param enabled if it's enabled to show // @param indicatorName is the indicator name as string such "RSI", "CCI" etc // @param indicator1 is first indicator you want to show, such rsi(close, 14), mom(close, 10) etc // @param indicator2 is second indicator you want to show, such -DI of DMI // @param indicator3 is third indicator you want to show, such ADX of DMI // @param indicatorcolor is the color of indicator line // @param period is the length of the window to show // @param indimax_ is the maximum value of the indicator, for example for RSI it's 100.0, if the indicator (such CCI, MOM etc) doesn't have maximum value then use "na" // @param indimin_ is the minimum value of the indicator, for example for RSI it's 0.0, if the indicator (such CCI, MOM etc)doesn't have maximum value then use "na" // @param levels is the levels of the array for the horizontal lines. for example if you want horizontal lines at 30.0, and 70.0 then use array.from(30.0, 70.0). if no horizontal lines then use array.from(na) // @param precision is the precision/nuber of decimals that is used to show indicator values, for example for RSI set it 2 // @param xlocation is end location of the indicator window, for example if xlocation = 0 window is created on the index of the last bar/candle // @param lnwidth is the line width of the indicator lines // @returns none export drawIndicator(bool enabled, string indicatorName, float indicator1, float indicator2, float indicator3, color [] indicatorcolors, int period, float indimax_, float indimin_, float [] levels, int precision, int xlocation, int lnwidth)=> // Exception if the period is less than 20, stop running and show the error if period < 20 runtime.error('Period is too short! Please increase the Period') // if size of the array levels is 0 then add an null element if array.size(levels) == 0 array.push(levels, na) // calculate indimax and indimin that is used for the window, float ind_h_ = ta.highest(indicator1, period) float ind_l_ = ta.lowest(indicator1, period) // while calculatind max/min levels, also use horizontal levels, because last length values of the indicator may not fit to the windows suitable if not na(array.get(levels, 0)) ind_h_ := math.max(ind_h_, array.max(levels)) ind_l_ := math.min(ind_l_, array.min(levels)) float indimax = not na(indimax_) ? indimax_ : ind_h_ + (ind_h_ - ind_l_) * 0.10 float indimin = not na(indimin_) ? indimin_ : ind_l_ - (ind_h_ - ind_l_) * 0.10 // get top and bottom of the indicator window [top, bottom, indi_loc] = findIndiLoc() // find indicator location if enabled and barstate.islast // draw indicator window var line border_line_top = na line.delete(border_line_top) border_line_top := line.new(x1=bar_index - period - xlocation, y1=top, x2=bar_index + 1 - xlocation, y2=top, color=color.gray, width=4, style=line.style_solid) border_line_top var line border_line_bottom = na line.delete(border_line_bottom) border_line_bottom := line.new(x1=bar_index - period - xlocation, y1=bottom, x2=bar_index + 1 - xlocation, y2=bottom, color=color.gray, width=4, style=line.style_solid) border_line_bottom linefill.new(border_line_top, border_line_bottom, color.black) // delete old lines and draw new indicator & horizontal lines var indi_lines = array.new_line(0) // keeps all lines including horizontal lines var indinamelabels = array.new_label(0) for x = 0 to (array.size(indi_lines) > 0 ? array.size(indi_lines) - 1 : na) line.delete(array.pop(indi_lines)) for x = 0 to (array.size(indinamelabels) > 0 ? array.size(indinamelabels) - 1 : na) label.delete(array.pop(indinamelabels)) for x = 0 to (not na(array.get(levels, 0)) ? array.size(levels) - 1 : na) array.push(indi_lines, line.new( x1 = bar_index - xlocation, y1 = getIndiLevel(array.get(levels, x), indimax, indimin, top, bottom), x2 = bar_index - period - xlocation, y2 = getIndiLevel(array.get(levels, x), indimax, indimin, top, bottom), style = line.style_dashed)) array.push(indinamelabels, label.new(x = bar_index - xlocation - period + 5, y = getIndiLevel(array.get(levels, x), indimax, indimin, top, bottom), text = str.tostring( array.get(levels, x)), textcolor = color.blue, style = label.style_none)) // if multiple levels such DMI txt = "" indicname = str.split(indicatorName, " ") for y = 0 to (array.size(indicname) > 0 ? array.size(indicname) - 1 : na) txt := txt + (array.get(indicname, y) + " " + str.tostring(math.round((y == 0 ? indicator1 : y == 1 ? indicator2 : indicator3), precision))) + " " for x = 0 to period - 1 array.push(indi_lines, line.new( x1 = bar_index - x - xlocation, y1 = getIndiLevel((y == 0 ? indicator1[x] : y == 1 ? indicator2[x] : indicator3[x]), indimax, indimin, top, bottom), x2 = bar_index - x - 1 - xlocation, y2 = getIndiLevel((y == 0 ? indicator1[x + 1] : y == 1 ? indicator2[x + 1] : indicator3[x + 1]), indimax, indimin, top, bottom), color = array.get(indicatorcolors, y), width = lnwidth)) // show the indicator name and its last value at the top of the indicator window array.push(indinamelabels, label.new(x = bar_index - 15 - xlocation, y = indi_loc == 1 ? top : bottom, text = txt, textcolor = color.blue, style = label.style_none))
Bursa_Sector
https://www.tradingview.com/script/rtz7ADHN-Bursa-Sector/
Lanzhu0506
https://www.tradingview.com/u/Lanzhu0506/
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/ // © Lanzhu0506 //@version=5 // @description : List of stocks classified by sector in Bursa Malaysia (Keep updated) library("Bursa_Sector") // @function : Compile all stocks from Bursa Malaysia. Local use only // @param : Sector Id that been assigned // @returns : sectorList() will return tuple (sector name, sector list) sectorList(int sectorId) => energySector = array.new_string() // Assigned to id 1 constructionSector = array.new_string() // Assigned to id 2 consumerSector = array.new_string() // Assigned to id 3 industrySector = array.new_string() // Assigned to id 4 technologySector = array.new_string() // Assigned to id 5 financialSector = array.new_string() // Assigned to id 6 plantationSector = array.new_string() // Assigned to id 7 healthCareSector = array.new_string() // Assigned to id 8 telcoMediaSector = array.new_string() // Assigned to id 9 transportLogiSector = array.new_string() // Assigned to id 10 propertySector = array.new_string() // Assigned to id 11 utilitySector = array.new_string() // Assigned to id 12 reitSector = array.new_string() // Assigned to id 13 // Energy array.push(energySector,'YINSON') array.push(energySector,'ARMADA') array.push(energySector,'HIBISCS') array.push(energySector,'SAPNRG') array.push(energySector,'HENGYUAN') array.push(energySector,'SERBADK') array.push(energySector,'VELESTO') array.push(energySector,'PETRONM') array.push(energySector,'DAYANG') array.push(energySector,'KNM') array.push(energySector,'MHB') array.push(energySector,'WASEONG') array.push(energySector,'COASTAL') array.push(energySector,'PENERGY') array.push(energySector,'ICON') array.push(energySector,'PERDANA') array.push(energySector,'DELEUM') array.push(energySector,'T7GLOBAL') array.push(energySector,'UZMA') array.push(energySector,'THHEAVY') array.push(energySector,'RL') array.push(energySector,'CARIMIN') array.push(energySector,'TECHNAX') array.push(energySector,'OVH') array.push(energySector,'REACH') array.push(energySector,'BARAKAH') array.push(energySector,'ALAM') array.push(energySector,'HANDAL') array.push(energySector,'SCOMI') array.push(energySector,'DAYA') array.push(energySector,'SCOMIES') array.push(energySector,'SUMATEC') array.push(energySector,'PERISAI') array.push(energySector,'DIALOG') // Construction array.push(constructionSector,'GAMUDA') array.push(constructionSector,'IJM') array.push(constructionSector,'SUNCON') array.push(constructionSector,'KERJAYA') array.push(constructionSector,'WIDAD') array.push(constructionSector,'EKOVEST') array.push(constructionSector,'AME') array.push(constructionSector,'WCEHB') array.push(constructionSector,'WCT') array.push(constructionSector,'JAKS') array.push(constructionSector,'HSL') array.push(constructionSector,'ECONBHD') array.push(constructionSector,'PTARAS') array.push(constructionSector,'MGB') array.push(constructionSector,'MUHIBAH') array.push(constructionSector,'GDB') array.push(constructionSector,'GKENT') array.push(constructionSector,'GBGAQRS') array.push(constructionSector,'FAJAR') array.push(constructionSector,'KIMLUN') array.push(constructionSector,'GADANG') array.push(constructionSector,'BREM') array.push(constructionSector,'NESTCON') array.push(constructionSector,'NADIBHD') array.push(constructionSector,'MUDAJYA') array.push(constructionSector,'MITRA') array.push(constructionSector,'HOHUP') array.push(constructionSector,'PUNCAK') array.push(constructionSector,'PESONA') array.push(constructionSector,'TRC') array.push(constructionSector,'TCS') array.push(constructionSector,'SENDAI') array.push(constructionSector,'TJSETIA') array.push(constructionSector,'DKLS') array.push(constructionSector,'AZRB') array.push(constructionSector,'INTA') array.push(constructionSector,'IREKA') array.push(constructionSector,'ADVCON') array.push(constructionSector,'ANEKA') array.push(constructionSector,'VIZIONE') array.push(constructionSector,'LEBTECH') array.push(constructionSector,'BENALEC') array.push(constructionSector,'SCBUILD') array.push(constructionSector,'PRTASCO') array.push(constructionSector,'AGES') array.push(constructionSector,'PEB') array.push(constructionSector,'CRESBLD') array.push(constructionSector,'HAILY') array.push(constructionSector,'ZELAN') array.push(constructionSector,'SYCAL') array.push(constructionSector,'BPURI') array.push(constructionSector,'IHB') array.push(constructionSector,'OCR') array.push(constructionSector,'MELATI') array.push(constructionSector,'ZECON') array.push(constructionSector,'MTDACPI') array.push(constructionSector,'STELLA') array.push(constructionSector,'MERCURY') array.push(constructionSector,'TSRCAP') array.push(constructionSector,'TOPBLDS') array.push(constructionSector,'SIAB') array.push(constructionSector,'MNHLDG') // Consumer array.push(consumerSector,'NESTLE') array.push(consumerSector,'PPB') array.push(consumerSector,'MRDIY') array.push(consumerSector,'GENTING') array.push(consumerSector,'PETDAG') array.push(consumerSector,'GENM') array.push(consumerSector,'SIME') array.push(consumerSector,'QL') array.push(consumerSector,'F&N') array.push(consumerSector,'HEIM') array.push(consumerSector,'CARLSBG') array.push(consumerSector,'CAPITALA') array.push(consumerSector,'BAT') array.push(consumerSector,'UMW') array.push(consumerSector,'DRBHCOM') array.push(consumerSector,'ORIENT') array.push(consumerSector,'GCB') array.push(consumerSector,'HLIND') array.push(consumerSector,'MAGNUM') array.push(consumerSector,'SPTOTO') array.push(consumerSector,'LHI') array.push(consumerSector,'DLADY') array.push(consumerSector,'AEON') array.push(consumerSector,'PADINI') array.push(consumerSector,'SEM') array.push(consumerSector,'BAUTO') array.push(consumerSector,'PANAMY') array.push(consumerSector,'SHANG') array.push(consumerSector,'BJLAND') array.push(consumerSector,'MBMR') array.push(consumerSector,'MSM') array.push(consumerSector,'FPI') array.push(consumerSector,'AJI') array.push(consumerSector,'MAGNI') array.push(consumerSector,'AMWAY') array.push(consumerSector,'DKSH') array.push(consumerSector,'ZHULIAN') array.push(consumerSector,'SEG') array.push(consumerSector,'TCHONG') array.push(consumerSector,'BJFOOD') array.push(consumerSector,'MFLOUR') array.push(consumerSector,'HUPSENG') array.push(consumerSector,'MULPHA') array.push(consumerSector,'ATLAN') array.push(consumerSector,'KAWAN') array.push(consumerSector,'BAHVEST') array.push(consumerSector,'MYNEWS') array.push(consumerSector,'CIHLDG') array.push(consumerSector,'HAIO') array.push(consumerSector,'PWROOT') array.push(consumerSector,'LIIHEN') array.push(consumerSector,'NTPM') array.push(consumerSector,'ABLEGLOB') array.push(consumerSector,'3A') array.push(consumerSector,'INNATURE') array.push(consumerSector,'SERNKOU') array.push(consumerSector,'ASIAFLE') array.push(consumerSector,'EURO') array.push(consumerSector,'KAREX') array.push(consumerSector,'COCOLND') array.push(consumerSector,'ONEGLOVE') array.push(consumerSector,'PTRANS') array.push(consumerSector,'SPRITZER') array.push(consumerSector,'POHUAT') array.push(consumerSector,'RENEUCRENEUCO') array.push(consumerSector,'CCK') array.push(consumerSector,'KANGER') array.push(consumerSector,'AAX') array.push(consumerSector,'DPIH') array.push(consumerSector,'FIAMMA') array.push(consumerSector,'HARISON') array.push(consumerSector,'APOLLO') array.push(consumerSector,'POHKONG') array.push(consumerSector,'CAB') array.push(consumerSector,'RKI') array.push(consumerSector,'FOCUS') array.push(consumerSector,'TAFI') array.push(consumerSector,'SALUTE') array.push(consumerSector,'SIGN') array.push(consumerSector,'PELIKAN') array.push(consumerSector,'YENHER') array.push(consumerSector,'FCW') array.push(consumerSector,'LANDMRK') array.push(consumerSector,'PARKSON') array.push(consumerSector,'MUIIND') array.push(consumerSector,'BIOHLDG') array.push(consumerSector,'FOCUSP') array.push(consumerSector,'MAG') array.push(consumerSector,'HOMERIZ') array.push(consumerSector,'OWG') array.push(consumerSector,'MILUX') array.push(consumerSector,'PERTAMA') array.push(consumerSector,'LOTUS') array.push(consumerSector,'JAYCORP') array.push(consumerSector,'CCB') array.push(consumerSector,'OFI') array.push(consumerSector,'TEOSENG') array.push(consumerSector,'RGB') array.push(consumerSector,'SYF') array.push(consumerSector,'NHFATT') array.push(consumerSector,'HBGLOB') array.push(consumerSector,'ICONIC') array.push(consumerSector,'UPA') array.push(consumerSector,'LAYHONG') array.push(consumerSector,'BONIA') array.push(consumerSector,'MOBILIA') array.push(consumerSector,'CSCENIC') array.push(consumerSector,'G3') array.push(consumerSector,'YOCB') array.push(consumerSector,'KHIND') array.push(consumerSector,'TEKSENG') array.push(consumerSector,'LTKM') array.push(consumerSector,'WEGMANS') array.push(consumerSector,'MARCO') array.push(consumerSector,'LEESK') array.push(consumerSector,'SNC') array.push(consumerSector,'RHONEMA') array.push(consumerSector,'PARAGON') array.push(consumerSector,'SDS') array.push(consumerSector,'AVI') array.push(consumerSector,'WANGZNG') array.push(consumerSector,'IQGROUP') array.push(consumerSector,'CHEETAH') array.push(consumerSector,'ASB') array.push(consumerSector,'SUNZEN') array.push(consumerSector,'ASIABRN') array.push(consumerSector,'NICE') array.push(consumerSector,'TOMEI') array.push(consumerSector,'SOLID') array.push(consumerSector,'JADI') array.push(consumerSector,'REX') array.push(consumerSector,'BRAHIMS') array.push(consumerSector,'PRLEXUS') array.push(consumerSector,'IMPIANA') array.push(consumerSector,'OCNCASH') array.push(consumerSector,'MACPIE') array.push(consumerSector,'KHJB') array.push(consumerSector,'PARLO') array.push(consumerSector,'PWF') array.push(consumerSector,'OLYMPIA') array.push(consumerSector,'KTC') array.push(consumerSector,'SWSCAP') array.push(consumerSector,'PCCS') array.push(consumerSector,'MINDA') array.push(consumerSector,'SPRING') array.push(consumerSector,'CAELY') array.push(consumerSector,'EIG') array.push(consumerSector,'GREENYB') array.push(consumerSector,'PRG') array.push(consumerSector,'PENSONI') array.push(consumerSector,'PMCORP') array.push(consumerSector,'TGL') array.push(consumerSector,'WARISAN') array.push(consumerSector,'XDL') array.push(consumerSector,'GOCEAN') array.push(consumerSector,'PAOS') array.push(consumerSector,'OCB') array.push(consumerSector,'FIHB') array.push(consumerSector,'OVERSEA') array.push(consumerSector,'XL') array.push(consumerSector,'KTB') array.push(consumerSector,'ENGKAH') array.push(consumerSector,'NIHSIN') array.push(consumerSector,'CAMRES') array.push(consumerSector,'GCE') array.push(consumerSector,'PERMAJU') array.push(consumerSector,'PMHLDG') array.push(consumerSector,'SMCAP') array.push(consumerSector,'SINARAN') array.push(consumerSector,'PLABS') array.push(consumerSector,'HWATAI') array.push(consumerSector,'SHH') array.push(consumerSector,'TPC') array.push(consumerSector,'TECGUAN') array.push(consumerSector,'EUROSP') array.push(consumerSector,'CNH') array.push(consumerSector,'MESB') array.push(consumerSector,'SAUDEE') array.push(consumerSector,'KAMDAR') array.push(consumerSector,'CNOUHUA') array.push(consumerSector,'SCC') array.push(consumerSector,'CWG') array.push(consumerSector,'MBRIGHT') array.push(consumerSector,'EMICO') array.push(consumerSector,'AHB') array.push(consumerSector,'KHEESAN') array.push(consumerSector,'JERASIA') array.push(consumerSector,'EKA') array.push(consumerSector,'MSPORTS') array.push(consumerSector,'APFT') array.push(consumerSector,'CARING') array.push(consumerSector,'YEELEE') array.push(consumerSector,'MBG') array.push(consumerSector,'DEGEM') array.push(consumerSector,'LONBISC') array.push(consumerSector,'ECOMATE') array.push(consumerSector,'SENHENG') array.push(consumerSector,'FFB') array.push(consumerSector,'YXPM') array.push(consumerSector,'ORGABIO') // Industry array.push(industrySector,'PCHEM') array.push(industrySector,'PMETAL') array.push(industrySector,'HAPSENG') array.push(industrySector,'SUNWAY') array.push(industrySector,'SCIENTX') array.push(industrySector,'VS') array.push(industrySector,'LCTITAN') array.push(industrySector,'MCEMENT') array.push(industrySector,'PMBTECH') array.push(industrySector,'ATAIMS') array.push(industrySector,'SAM') array.push(industrySector,'OMH') array.push(industrySector,'SKPRES') array.push(industrySector,'DUFU') array.push(industrySector,'HEXTAR') array.push(industrySector,'KOBAY') array.push(industrySector,'ANNJOO') array.push(industrySector,'CMSB') array.push(industrySector,'EDGENTA') array.push(industrySector,'UCHITEC') array.push(industrySector,'BJCORP') array.push(industrySector,'PIE') array.push(industrySector,'KSENG') array.push(industrySector,'CHINHIN') array.push(industrySector,'BSTEAD') array.push(industrySector,'KGB') array.push(industrySector,'TGUAN') array.push(industrySector,'HIAPTEK') array.push(industrySector,'MSC') array.push(industrySector,'CANONE') array.push(industrySector,'SCIPACK') array.push(industrySector,'PESTECH') array.push(industrySector,'SLVEST') array.push(industrySector,'MUDA') array.push(industrySector,'LUXCHEM') array.push(industrySector,'COMFORT') array.push(industrySector,'NGGB') array.push(industrySector,'ANCOMNY') array.push(industrySector,'CBIP') array.push(industrySector,'KAB') array.push(industrySector,'PECCA') array.push(industrySector,'QES') array.push(industrySector,'KFIMA') array.push(industrySector,'PA') array.push(industrySector,'SAB') array.push(industrySector,'CYPARK') array.push(industrySector,'BOILERM') array.push(industrySector,'WELLCAL') array.push(industrySector,'HUMEIND') array.push(industrySector,'BPPLAS') array.push(industrySector,'FAVCO') array.push(industrySector,'CCM') array.push(industrySector,'SSTEEL') array.push(industrySector,'PERSTIM') array.push(industrySector,'SAMCHEM') array.push(industrySector,'CSCSTEL') array.push(industrySector,'PANTECH') array.push(industrySector,'FIMACOR') array.push(industrySector,'SCGM') array.push(industrySector,'PEKAT') array.push(industrySector,'MTAG') array.push(industrySector,'TONGHER') array.push(industrySector,'TAWIN') array.push(industrySector,'APM') array.push(industrySector,'DESTINI') array.push(industrySector,'FPGROUP') array.push(industrySector,'MIECO') array.push(industrySector,'LIONIND') array.push(industrySector,'KPS') array.push(industrySector,'SCOPE') array.push(industrySector,'HLT') array.push(industrySector,'SCICOM') array.push(industrySector,'SCGBHD') array.push(industrySector,'CHINWEL') array.push(industrySector,'KKB') array.push(industrySector,'LUSTER') array.push(industrySector,'EVERGRN') array.push(industrySector,'KUB') array.push(industrySector,'ASTINO') array.push(industrySector,'ULICORP') array.push(industrySector,'HIL') array.push(industrySector,'RGTBHD') array.push(industrySector,'LEONFB') array.push(industrySector,'SUBUR') array.push(industrySector,'MESTRON') array.push(industrySector,'SLP') array.push(industrySector,'PANSAR') array.push(industrySector,'AT') array.push(industrySector,'MASTEEL') array.push(industrySector,'ENGTEX') array.push(industrySector,'HSSEB') array.push(industrySector,'AYS') array.push(industrySector,'HEVEA') array.push(industrySector,'CHOOBEE') array.push(industrySector,'HIGHTEC') array.push(industrySector,'TOYOVEN') array.push(industrySector,'TECHBND') array.push(industrySector,'SAMAIDEN') array.push(industrySector,'LBALUM') array.push(industrySector,'BORNOIL') array.push(industrySector,'SUCCESS') array.push(industrySector,'WTK') array.push(industrySector,'NYLEX') array.push(industrySector,'TOMYPAK') array.push(industrySector,'PRESTAR') array.push(industrySector,'BSLCORP') array.push(industrySector,'GESHEN') array.push(industrySector,'OKA') array.push(industrySector,'HPMT') array.push(industrySector,'EITA') array.push(industrySector,'HEXZA') array.push(industrySector,'JAG') array.push(industrySector,'SCIB') array.push(industrySector,'MYTECH') array.push(industrySector,'UNIMECH') array.push(industrySector,'DANCO') array.push(industrySector,'TASHIN') array.push(industrySector,'HPPHB') array.push(industrySector,'EG') array.push(industrySector,'WONG') array.push(industrySector,'JCBNEXT') array.push(industrySector,'FITTERS') array.push(industrySector,'ESCERAM') array.push(industrySector,'IMASPRO') array.push(industrySector,'AJIYA') array.push(industrySector,'AWC') array.push(industrySector,'WTHORSE') array.push(industrySector,'METROD') array.push(industrySector,'GLOTEC') array.push(industrySector,'JADEM') array.push(industrySector,'CFM') array.push(industrySector,'TIENWAH') array.push(industrySector,'HEXIND') array.push(industrySector,'ROHAS') array.push(industrySector,'MYCRON') array.push(industrySector,'BOXPAK') array.push(industrySector,'CEKD') array.push(industrySector,'NWP') array.push(industrySector,'SCABLE') array.push(industrySector,'EFRAME') array.push(industrySector,'MELEWAR') array.push(industrySector,'PPHB') array.push(industrySector,'HWGB') array.push(industrySector,'JSB') array.push(industrySector,'KIMHIN') array.push(industrySector,'SUPERLN') array.push(industrySector,'ANALABS') array.push(industrySector,'GUH') array.push(industrySector,'DOMINAN') array.push(industrySector,'LIONPSIM') array.push(industrySector,'VERSATL') array.push(industrySector,'BINTAI') array.push(industrySector,'JOE') array.push(industrySector,'GFM') array.push(industrySector,'WAJA') array.push(industrySector,'ASIAPLY') array.push(industrySector,'EKSONS') array.push(industrySector,'KARYON') array.push(industrySector,'MINETEC') array.push(industrySector,'EFFICEN') array.push(industrySector,'EMETALL') array.push(industrySector,'PGF') array.push(industrySector,'DNONCE') array.push(industrySector,'ALCOM') array.push(industrySector,'SEB') array.push(industrySector,'PWRWELL') array.push(industrySector,'SEACERA') array.push(industrySector,'MINHO') array.push(industrySector,'FACBIND') array.push(industrySector,'TEXCYCL') array.push(industrySector,'YB') array.push(industrySector,'ARANK') array.push(industrySector,'MBL') array.push(industrySector,'LFECORP') array.push(industrySector,'SERSOL') array.push(industrySector,'CITAGLB') array.push(industrySector,'ORNA') array.push(industrySector,'ACO') array.push(industrySector,'CGB') array.push(industrySector,'UMSNGB') array.push(industrySector,'RESINTC') array.push(industrySector,'ATTA') array.push(industrySector,'FLBHD') array.push(industrySector,'CHUAN') array.push(industrySector,'KSSC') array.push(industrySector,'MASTER') array.push(industrySector,'FAST') array.push(industrySector,'UMS') array.push(industrySector,'YBS') array.push(industrySector,'LSTEEL') array.push(industrySector,'TEXCHEM') array.push(industrySector,'ARTRONIQ') array.push(industrySector,'TURBO') array.push(industrySector,'LYSAGHT') array.push(industrySector,'KPSCB') array.push(industrySector,'AEM') array.push(industrySector,'GIIB') array.push(industrySector,'KEINHIN') array.push(industrySector,'FLEXI') array.push(industrySector,'MCEHLDG') array.push(industrySector,'SCNWOLF') array.push(industrySector,'YKGI') array.push(industrySector,'JETSON') array.push(industrySector,'CSH') array.push(industrySector,'CNASIA') array.push(industrySector,'ANNUM') array.push(industrySector,'VOLCANO') array.push(industrySector,'DOLPHIN') array.push(industrySector,'AFUJIYA') array.push(industrySector,'BCMALL') array.push(industrySector,'APB') array.push(industrySector,'EPMB') array.push(industrySector,'PICORP') array.push(industrySector,'ESAFE') array.push(industrySector,'SKBSHUT') array.push(industrySector,'QUALITY') array.push(industrySector,'HHGROUP') array.push(industrySector,'CEPCO') array.push(industrySector,'MCLEAN') array.push(industrySector,'KNUSFOR') array.push(industrySector,'MEGASUN') array.push(industrySector,'BIG') array.push(industrySector,'MTRONIC') array.push(industrySector,'INGENIEU') array.push(industrySector,'KYM') array.push(industrySector,'PASUKGB') array.push(industrySector,'KOMARK') array.push(industrySector,'S&FCAP') array.push(industrySector,'AIM') array.push(industrySector,'TIMWELL') array.push(industrySector,'JASKITA') array.push(industrySector,'HHHCORP') array.push(industrySector,'COMPUGT') array.push(industrySector,'SAPIND') array.push(industrySector,'ADVPKG') array.push(industrySector,'WATTA') array.push(industrySector,'GPHAROS') array.push(industrySector,'BRIGHT') array.push(industrySector,'ANZO') array.push(industrySector,'MENTIGA') array.push(industrySector,'RALCO') array.push(industrySector,'SANICHI') array.push(industrySector,'CYL') array.push(industrySector,'FIBON') array.push(industrySector,'PNEPCB') array.push(industrySector,'CME') array.push(industrySector,'DFCITY') array.push(industrySector,'PWORTH') array.push(industrySector,'YLI') array.push(industrySector,'BTM') array.push(industrySector,'SMISCOR') array.push(industrySector,'WOODLAN') array.push(industrySector,'ABLEGRP') array.push(industrySector,'PJBUMI') array.push(industrySector,'KIALIM') array.push(industrySector,'DOLMITE') array.push(industrySector,'IQZAN') array.push(industrySector,'CAP') array.push(industrySector,'COMCORP') array.push(industrySector,'KINSTEL') array.push(industrySector,'TASEK') array.push(industrySector,'SIGGAS') array.push(industrySector,'ATECH') array.push(industrySector,'CORAZA') array.push(industrySector,'YEWLEE') array.push(industrySector,'SENFONG') array.push(industrySector,'EIB') array.push(industrySector,'UNIQUE') array.push(industrySector,'LEFORM') array.push(industrySector,'BETA') array.push(industrySector,'SUNVIEW') array.push(industrySector,'COSMOS') // Technology array.push(technologySector,'INARI') array.push(technologySector,'MPI') array.push(technologySector,'VITROX') array.push(technologySector,'GREATEC') array.push(technologySector,'HONGSENG') array.push(technologySector,'D&O') array.push(technologySector,'MYEG') array.push(technologySector,'UNISEM') array.push(technologySector,'UWC') array.push(technologySector,'FRONTKN') array.push(technologySector,'CTOS') array.push(technologySector,'PENTA') array.push(technologySector,'MI') array.push(technologySector,'DNEX') array.push(technologySector,'GHLSYS') array.push(technologySector,'GENETEC') array.push(technologySector,'DSONIC') array.push(technologySector,'JFTECH') array.push(technologySector,'GTRONIC') array.push(technologySector,'JHM') array.push(technologySector,'REVENUE') array.push(technologySector,'DATAPRP') array.push(technologySector,'IRIS') array.push(technologySector,'JCY') array.push(technologySector,'AEMULUS') array.push(technologySector,'MICROLN') array.push(technologySector,'ELSOFT') array.push(technologySector,'AWANTEC') array.push(technologySector,'KESM') array.push(technologySector,'VSTECS') array.push(technologySector,'N2N') array.push(technologySector,'KRONO') array.push(technologySector,'NCT') array.push(technologySector,'VINVEST') array.push(technologySector,'NOTION') array.push(technologySector,'EFORCE') array.push(technologySector,'VIS') array.push(technologySector,'SOLUTN') array.push(technologySector,'THETA') array.push(technologySector,'MMSV') array.push(technologySector,'OMESTI') array.push(technologySector,'WILLOW') array.push(technologySector,'IFCAMSC') array.push(technologySector,'CUSCAPI') array.push(technologySector,'CENSOF') array.push(technologySector,'RAMSSOL') array.push(technologySector,'MPAY') array.push(technologySector,'RGTECH') array.push(technologySector,'OPENSYS') array.push(technologySector,'REXIT') array.push(technologySector,'AIMFLEX') array.push(technologySector,'APPASIA') array.push(technologySector,'ARBB') array.push(technologySector,'K1') array.push(technologySector,'UCREST') array.push(technologySector,'MMAG') array.push(technologySector,'NOVAMSC') array.push(technologySector,'MIKROMB') array.push(technologySector,'HTPADU') array.push(technologySector,'NETX') array.push(technologySector,'TDEX') array.push(technologySector,'KEYASIC') array.push(technologySector,'EAH') array.push(technologySector,'MSNIAGA') array.push(technologySector,'LAMBO') array.push(technologySector,'SYSTECH') array.push(technologySector,'ITRONIC') array.push(technologySector,'DGB') array.push(technologySector,'SMETRIC') array.push(technologySector,'TRIVE') array.push(technologySector,'DFX') array.push(technologySector,'KGROUP') array.push(technologySector,'MQTECH') array.push(technologySector,'DIGISTA') array.push(technologySector,'SMRT') array.push(technologySector,'MLAB') array.push(technologySector,'TFP') array.push(technologySector,'TURIYA') array.push(technologySector,'ZENTECH') array.push(technologySector,'PINEAPP') array.push(technologySector,'EDARAN') array.push(technologySector,'YGL') array.push(technologySector,'CABNET') array.push(technologySector,'ASDION') array.push(technologySector,'VC') array.push(technologySector,'VSOLAR') array.push(technologySector,'EDUSPEC') array.push(technologySector,'SMTRACK') array.push(technologySector,'ALRICH') array.push(technologySector,'IDMENSN') array.push(technologySector,'WINTONI') array.push(technologySector,'FSBM') array.push(technologySector,'GNB') array.push(technologySector,'CNERGEN') array.push(technologySector,'LGMS') array.push(technologySector,'SFPTECH') array.push(technologySector,'INFOTEC') array.push(technologySector,'ECA') array.push(technologySector,'INFOM') array.push(technologySector,'AGMO') array.push(technologySector,'SNS') // Financial array.push(financialSector,'MAYBANK') array.push(financialSector,'PBBANK') array.push(financialSector,'CIMB') array.push(financialSector,'HLBANK') array.push(financialSector,'RHBBANK') array.push(financialSector,'HLFG') array.push(financialSector,'AMBANK') array.push(financialSector,'BIMB') array.push(financialSector,'BURSA') array.push(financialSector,'LPI') array.push(financialSector,'MBSB') array.push(financialSector,'ABMB') array.push(financialSector,'AFFIN') array.push(financialSector,'AEONCR') array.push(financialSector,'TAKAFUL') array.push(financialSector,'ALLIANZ') array.push(financialSector,'HLCAP') array.push(financialSector,'TA') array.push(financialSector,'RCECAP') array.push(financialSector,'MNRB') array.push(financialSector,'MPHBCAP') array.push(financialSector,'KENANGA') array.push(financialSector,'INSAS') array.push(financialSector,'MANULFE') array.push(financialSector,'ELKDESA') array.push(financialSector,'TUNEPRO') array.push(financialSector,'P&O') array.push(financialSector,'KUCHAI') array.push(financialSector,'APEX') array.push(financialSector,'MAA') array.push(financialSector,'JOHAN') array.push(financialSector,'OSKVI') array.push(financialSector,'ECM') array.push(financialSector,'FINTEC') array.push(financialSector,'PPJACK') // Property array.push(propertySector,'IOIPG') array.push(propertySector,'SPSETIA') array.push(propertySector,'SIMEPROP') array.push(propertySector,'UOADEV') array.push(propertySector,'ECOWLD') array.push(propertySector,'UEMS') array.push(propertySector,'OSK') array.push(propertySector,'MATRIX') array.push(propertySector,'MRCB') array.push(propertySector,'IGBB') array.push(propertySector,'MAHSING') array.push(propertySector,'YNHPROP') array.push(propertySector,'TROP') array.push(propertySector,'LAGENDA') array.push(propertySector,'AMPROP') array.push(propertySector,'EWINT') array.push(propertySector,'RAPID') array.push(propertySector,'E&O') array.push(propertySector,'HCK') array.push(propertySector,'MKH') array.push(propertySector,'LBS') array.push(propertySector,'KSL') array.push(propertySector,'BJASSET') array.push(propertySector,'TELADAN') array.push(propertySector,'GUOCO') array.push(propertySector,'SHL') array.push(propertySector,'PARAMON') array.push(propertySector,'IDEAL') array.push(propertySector,'ECOFIRS') array.push(propertySector,'AYER') array.push(propertySector,'PLENITU') array.push(propertySector,'TITIJYA') array.push(propertySector,'SUNSURIA') array.push(propertySector,'OIB') array.push(propertySector,'TANCO') array.push(propertySector,'SYMLIFE') array.push(propertySector,'CHHB') array.push(propertySector,'L&G') array.push(propertySector,'IWCITY') array.push(propertySector,'CRESNDO') array.push(propertySector,'TAMBUN') array.push(propertySector,'MAXIM') array.push(propertySector,'NAIM') array.push(propertySector,'KPPROP') array.push(propertySector,'Y&G') array.push(propertySector,'IBHD') array.push(propertySector,'MCT') array.push(propertySector,'MENANG') array.push(propertySector,'IBRACO') array.push(propertySector,'GLOMAC') array.push(propertySector,'MKLAND') array.push(propertySector,'MALTON') array.push(propertySector,'SDRED') array.push(propertySector,'JKGLAND') array.push(propertySector,'PGLOBE') array.push(propertySector,'YONGTAI') array.push(propertySector,'MAGNA') array.push(propertySector,'DBHD') array.push(propertySector,'BDB') array.push(propertySector,'MUIPROP') array.push(propertySector,'LIENHOE') array.push(propertySector,'ENCORP') array.push(propertySector,'ASIAPAC') array.push(propertySector,'GOB') array.push(propertySector,'PASDEC') array.push(propertySector,'MERIDIAN') array.push(propertySector,'PLB') array.push(propertySector,'GMUTUAL') array.push(propertySector,'KEN') array.push(propertySector,'ENRA') array.push(propertySector,'CVIEW') array.push(propertySector,'BCB') array.push(propertySector,'EUPE') array.push(propertySector,'PHB') array.push(propertySector,'TALAMT') array.push(propertySector,'MJPERAK') array.push(propertySector,'SNTORIA') array.push(propertySector,'TWL') array.push(propertySector,'SBCCORP') array.push(propertySector,'HUAYANG') array.push(propertySector,'EWEIN') array.push(propertySector,'SEAL') array.push(propertySector,'AXTERIA') array.push(propertySector,'THRIVEN') array.push(propertySector,'DPS') array.push(propertySector,'ACME') array.push(propertySector,'PTT') array.push(propertySector,'LBICAP') array.push(propertySector,'IVORY') array.push(propertySector,'SAPRES') array.push(propertySector,'JIANKUN') array.push(propertySector,'PARKWD') array.push(propertySector,'WMG') array.push(propertySector,'FARLIM') array.push(propertySector,'SMI') array.push(propertySector,'MUH') array.push(propertySector,'MPCORP') array.push(propertySector,'ARK') array.push(propertySector,'BERTAM') array.push(propertySector,'KBUNAI') array.push(propertySector,'TAGB') array.push(propertySector,'AMVERTON') array.push(propertySector,'MBWORLD') // Plantation array.push(plantationSector,'SIMEPLT') array.push(plantationSector,'IOICORP') array.push(plantationSector,'KLK') array.push(plantationSector,'BKAWAN') array.push(plantationSector,'GENP') array.push(plantationSector,'UTDPLT') array.push(plantationSector,'FGV') array.push(plantationSector,'IJMPLNT') array.push(plantationSector,'SOP') array.push(plantationSector,'FAREAST') array.push(plantationSector,'HSPLANT') array.push(plantationSector,'TSH') array.push(plantationSector,'KMLOONG') array.push(plantationSector,'BPLANT') array.push(plantationSector,'TAANN') array.push(plantationSector,'KRETAM') array.push(plantationSector,'UMCCA') array.push(plantationSector,'BLDPLNT') array.push(plantationSector,'JTIASA') array.push(plantationSector,'CHINTEK') array.push(plantationSector,'SWKPLNT') array.push(plantationSector,'THPLANT') array.push(plantationSector,'INNO') array.push(plantationSector,'KWANTAS') array.push(plantationSector,'RSAWIT') array.push(plantationSector,'TDM') array.push(plantationSector,'PLS') array.push(plantationSector,'DUTALND') array.push(plantationSector,'KLUANG') array.push(plantationSector,'SBAGAN') array.push(plantationSector,'NSOP') array.push(plantationSector,'CEPAT') array.push(plantationSector,'NPC') array.push(plantationSector,'INCKEN') array.push(plantationSector,'GOPENG') array.push(plantationSector,'MATANG') array.push(plantationSector,'RVIEW') array.push(plantationSector,'MHC') array.push(plantationSector,'HARNLEN') array.push(plantationSector,'SHCHAN') array.push(plantationSector,'GLBHD') array.push(plantationSector,'MALPAC') array.push(plantationSector,'AASIA') array.push(plantationSector,'PINEPAC') // Health Care array.push(healthCareSector,'IHH') array.push(healthCareSector,'TOPGLOV') array.push(healthCareSector,'HARTA') array.push(healthCareSector,'SUPERMX') array.push(healthCareSector,'KOSSAN') array.push(healthCareSector,'KPJ') array.push(healthCareSector,'DPHARMA') array.push(healthCareSector,'SCOMNET') array.push(healthCareSector,'AHEALTH') array.push(healthCareSector,'PHARMA') array.push(healthCareSector,'TMCLIFE') array.push(healthCareSector,'CAREPLS') array.push(healthCareSector,'KOTRA') array.push(healthCareSector,'OPTIMAX') array.push(healthCareSector,'MGRC') array.push(healthCareSector,'YSPSAH') array.push(healthCareSector,'NOVA') array.push(healthCareSector,'ADVENTA') array.push(healthCareSector,'LKL') array.push(healthCareSector,'LYC') array.push(healthCareSector,'CENGILD') array.push(healthCareSector,'UMC') array.push(healthCareSector,'HEXCARE') // Telco & Media array.push(telcoMediaSector,'MAXIS') array.push(telcoMediaSector,'AXIATA') array.push(telcoMediaSector,'DIGI') array.push(telcoMediaSector,'TM') array.push(telcoMediaSector,'TIMECOM') array.push(telcoMediaSector,'ASTRO') array.push(telcoMediaSector,'MEDIA') array.push(telcoMediaSector,'OCK') array.push(telcoMediaSector,'REDTONE') array.push(telcoMediaSector,'OPCOM') array.push(telcoMediaSector,'MEDIAC') array.push(telcoMediaSector,'STAR') array.push(telcoMediaSector,'SEDANIA') array.push(telcoMediaSector,'GPACKET') array.push(telcoMediaSector,'XOX') array.push(telcoMediaSector,'PUC') array.push(telcoMediaSector,'SJC') array.push(telcoMediaSector,'BINACOM') array.push(telcoMediaSector,'PRIVA') array.push(telcoMediaSector,'MTOUCHE') array.push(telcoMediaSector,'NEXGRAM') array.push(telcoMediaSector,'INNITY') array.push(telcoMediaSector,'AMTEL') array.push(telcoMediaSector,'SASBADI') array.push(telcoMediaSector,'ECOHLDS') array.push(telcoMediaSector,'XOXTECH') array.push(telcoMediaSector,'MNC') array.push(telcoMediaSector,'SRIDGE') array.push(telcoMediaSector,'PPG') array.push(telcoMediaSector,'AMEDIA') array.push(telcoMediaSector,'CATCHA') array.push(telcoMediaSector,'BJMEDIA') // Transport & Logi array.push(transportLogiSector,'MISC') array.push(transportLogiSector,'WPRTS') array.push(transportLogiSector,'AIRPORT') array.push(transportLogiSector,'MMCCORP') array.push(transportLogiSector,'BIPORT') array.push(transportLogiSector,'LITRAK') array.push(transportLogiSector,'GDEX') array.push(transportLogiSector,'TASCO') array.push(transportLogiSector,'MAYBULK') array.push(transportLogiSector,'HARBOUR') array.push(transportLogiSector,'FM') array.push(transportLogiSector,'POS') array.push(transportLogiSector,'TNLOGIS') array.push(transportLogiSector,'SYSCORP') array.push(transportLogiSector,'SURIA') array.push(transportLogiSector,'CHGP') array.push(transportLogiSector,'CJCEN') array.push(transportLogiSector,'HEXTECH') array.push(transportLogiSector,'TOCEAN') array.push(transportLogiSector,'GCAP') array.push(transportLogiSector,'PDZ') array.push(transportLogiSector,'HUBLINE') array.push(transportLogiSector,'ANCOMLB') array.push(transportLogiSector,'STRAITS') array.push(transportLogiSector,'BHIC') array.push(transportLogiSector,'TRIMODE') array.push(transportLogiSector,'XINHWA') array.push(transportLogiSector,'ILB') array.push(transportLogiSector,'SEEHUP') array.push(transportLogiSector,'SEALINK') array.push(transportLogiSector,'EATECH') array.push(transportLogiSector,'TAS') array.push(transportLogiSector,'M&G') array.push(transportLogiSector,'PRKCORP') array.push(transportLogiSector,'NATWIDE') array.push(transportLogiSector,'SWIFT') // Utility array.push(utilitySector,'TENAGA') array.push(utilitySector,'PETGAS') array.push(utilitySector,'YTL') array.push(utilitySector,'YTLPOWR') array.push(utilitySector,'MALAKOF') array.push(utilitySector,'MFCB') array.push(utilitySector,'GASMSIA') array.push(utilitySector,'TALIWRK') array.push(utilitySector,'RANHILL') array.push(utilitySector,'PBA') array.push(utilitySector,'SALCON') array.push(utilitySector,'BTECH') array.push(utilitySector,'EDEN') // Reit array.push(reitSector,'KLCC') array.push(reitSector,'IGBREIT') array.push(reitSector,'SUNREIT') array.push(reitSector,'PAVREIT') array.push(reitSector,'AXREIT') array.push(reitSector,'YTLREIT') array.push(reitSector,'IGBCR') array.push(reitSector,'CLMT') array.push(reitSector,'SENTRAL') array.push(reitSector,'ALAQAR') array.push(reitSector,'UOAREIT') array.push(reitSector,'KIPREIT') array.push(reitSector,'ARREIT') array.push(reitSector,'ATRIUM') array.push(reitSector,'ALSREIT') array.push(reitSector,'AMFIRST') array.push(reitSector,'HEKTAR') array.push(reitSector,'AHP') array.push(reitSector,'TWRREIT') if sectorId == 0 if array.includes(energySector, syminfo.ticker) ['MYX:ENERGY', energySector] else if array.includes(constructionSector, syminfo.ticker) ['MYX:CONSTRUCTN', constructionSector] else if array.includes(consumerSector, syminfo.ticker) ['MYX:CONSUMER', consumerSector] else if array.includes(industrySector, syminfo.ticker) ['MYX:IND-PROD', industrySector] else if array.includes(technologySector, syminfo.ticker) ['MYX:TECHNOLOGY', technologySector] else if array.includes(financialSector, syminfo.ticker) ['MYX:FINANCE', financialSector] else if array.includes(plantationSector, syminfo.ticker) ['MYX:PLANTATION', plantationSector] else if array.includes(healthCareSector, syminfo.ticker) ['MYX:HEALTH', healthCareSector] else if array.includes(telcoMediaSector, syminfo.ticker) ['MYX:TELECOMMUNICATIONS', telcoMediaSector] else if array.includes(transportLogiSector, syminfo.ticker) ['MYX:TRANSPORTATION', transportLogiSector] else if array.includes(propertySector, syminfo.ticker) ['MYX:PROPERTIES', propertySector] else if array.includes(utilitySector, syminfo.ticker) ['MYX:UTILITIES', utilitySector] else if array.includes(reitSector, syminfo.ticker) ['MYX:REIT', reitSector] else if sectorId == 1 ['MYX:ENERGY', energySector] else if sectorId == 2 ['MYX:CONSTRUCTN', constructionSector] else if sectorId == 3 ['MYX:CONSUMER', consumerSector] else if sectorId == 4 ['MYX:IND-PROD', industrySector] else if sectorId == 5 ['MYX:TECHNOLOGY', technologySector] else if sectorId == 6 ['MYX:FINANCE', financialSector] else if sectorId == 7 ['MYX:PLANTATION', plantationSector] else if sectorId == 8 ['MYX:HEALTH', healthCareSector] else if sectorId == 9 ['MYX:TELECOMMUNICATIONS', telcoMediaSector] else if sectorId == 10 ['MYX:TRANSPORTATION', transportLogiSector] else if sectorId == 11 ['MYX:PROPERTIES', propertySector] else if sectorId == 12 ['MYX:UTILITIES', utilitySector] else if sectorId == 13 ['MYX:REIT', reitSector] // @function : Get sector belongs to current ticker // @param : No parameter is required // @returns : getSector() will return sector name export getSectorName() => [a, b] = sectorList(0) a // @function : Get energy sector // @param : No parameter is required // @returns : getEnergySectorList() will return list of tickers export getEnergySectorList() => [a, b] = sectorList(1) b // @function : Get construction sector // @param : No parameter is required // @returns : getConstructionSectorList() will return list of tickers export getConstructionSectorList() => [a, b] = sectorList(2) b // @function : Get consumer sector // @param : No parameter is required // @returns : getConsumerSectorList() will return list of tickers export getConsumerSectorList() => [a, b] = sectorList(3) b // @function : Get industry sector // @param : No parameter is required // @returns : getIndustrySectorList() will return list of tickers export getIndustrySectorList() => [a, b] = sectorList(4) b // @function : Get technology sector // @param : No parameter is required // @returns : getTechnologySectorList() will return list of tickers export getTechnologySectorList() => [a, b] = sectorList(5) b // @function : Get financial sector // @param : No parameter is required // @returns : getFinancialSectorList() will return list of tickers export getFinancialSectorList() => [a, b] = sectorList(6) b // @function : Get plantation sector // @param : No parameter is required // @returns : getPlantationSectorList() will return list of tickers export getPlantationSectorList() => [a, b] = sectorList(7) b // @function : Get health sector // @param : No parameter is required // @returns : getHealthSectorList() will return list of tickers export getHealthSectorList() => [a, b] = sectorList(8) b // @function : Get telco&media sector // @param : No parameter is required // @returns : getTelcoMediaSectorList() will return list of tickers export getTelcoMediaSectorList() => [a, b] = sectorList(9) b // @function : Get transportation sector // @param : No parameter is required // @returns : getTransportationSectorList() will return list of tickers export getTransportationSectorList() => [a, b] = sectorList(10) b // @function : Get property sector // @param : No parameter is required // @returns : getPropertySectorList() will return list of tickers export getPropertySectorList() => [a, b] = sectorList(11) b // @function : Get utility sector // @param : No parameter is required // @returns : getUtilitySectorList() will return list of tickers export getUtilitySectorList() => [a, b] = sectorList(12) b // @function : Get reit sector // @param : No parameter is required // @returns : getReitSectorList() will return list of tickers export getReitSectorList() => [a, b] = sectorList(13) b var table t = table.new(position.bottom_right, 2, 2, border_width=1) table.cell(t, 0, 0, text=getSectorName(), width=15, bgcolor=color.new(color.blue, 50), text_color=color.black, text_size=size.small) table.cell(t, 1, 0, text=syminfo.ticker, width=15, bgcolor=color.new(color.yellow,50), text_color=color.black, text_size=size.small)
FFTLibrary
https://www.tradingview.com/script/LNYtGWz3-FFTLibrary/
tbiktag
https://www.tradingview.com/u/tbiktag/
65
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/ // © tbiktag //@version=5 // @description: The library contains a function for performing Fast Fourier Transform (FFT) of a time series // along with helper functions. In general, FFT is defined for complex inputs and outputs. // The real and imaginary parts of formally complex data are handled as separate arrays (denoted // as x and y). In case of real-valued data, the array of the imaginary parts should be filled with zeros. library("FFTLibrary") // @function: Computes the discrete Fourier transform using an FFT algorithm. // @param x: float[] array, real part of the data, array size must be a power of 2 // @param y: float[] array, imaginary part of the data, array size must be the same as x; for real-valued input, y must be an array of zeros // @param dir: string, options = ["Forward", "Inverse"], defines the direction of the transform: forward" (time-to-frequency) or inverse (frequency-to-time) // @returns [x, y]: tuple [float[], float[]], real and imaginary parts of the transformed data (original x and y are changed on output) export fft(float[] x, float[] y, string dir) => // if dir != "Forward" and dir != "Inverse" runtime.error("Specify the direction of the transform (dir = Forward or dir = Inverse).") // // --- Take care of the input array size --- int initN = array.size(x) if initN != array.size(y) runtime.error("The size of the real (array x) and imaginary (array y) parts of the input does not match.") // // Make sure that the array size is a power of 2 float initm = math.log(initN)/math.log(2) //approximation of log2 if initm/math.floor(initm) != 1.0 runtime.error("The size of the input arrays must be a power of 2 (e.g., 64, 128, 256, 512, etc.)") int m = math.floor(initm) int N = int(math.pow(2,m)) // // In-place complex-to-complex FFT algorithm is adapted from http://paulbourke.net/miscellaneous/dft/ // --- Do the bit reversal --- int ii = 0 int k = 0 float tmpx = 0.0 float tmpy = 0.0 for i = 0 to N - 2 if i < ii tmpx := array.get(x,i) tmpy := array.get(y,i) array.set(x,i,array.get(x,ii)) array.set(y,i,array.get(y,ii)) array.set(x,ii,tmpx) array.set(y,ii,tmpy) k := int(N/2) for tmp = 0 to m if k > ii break ii -= k k := int(k/2) ii += k // // --- Compute the FFT --- int i1 = 0 float u1 = 0.0 float u2 = 0.0 float t1 = 0.0 float t2 = 0.0 float z = 0.0 //Initial cosine & sine float c1 = -1.0 float c2 = 0.0 // Loop for each stage int l1 = 0 int l2 = 1 for l = 0 to m-1 l1 := l2 l2 := int(l2*2) // int(l2*2) is equivalent to bitwise l2 <<= 1 in C // // Initial vertex u1 := 1.0 u2 := 0.0 // Loop for each sub DFT for j = 0 to l1 - 1 for i = j to N - 1 by l2 i1 := i + l1 t1 := u1*array.get(x,i1) - u2*array.get(y,i1) t2 := u1*array.get(y,i1) + u2*array.get(x,i1) array.set(x,i1,array.get(x,i)-t1) array.set(y,i1,array.get(y,i)-t2) array.set(x, i,array.get(x,i)+t1) array.set(y, i,array.get(y,i)+t2) // Next polygon vertex z := u1 * c1 - u2 * c2 u2 := u1 * c2 + u2 * c1 u1 := z //Half-angle sine c2 := math.sqrt((1.0 - c1)/2.0) if dir == "Forward" c2 := -c2 //Half-angle cosine c1 := math.sqrt((1.0 + c1)/2.0) //Scaling for forward transform if dir == "Forward" for i = 0 to N-1 array.set(x,i,array.get(x,i)/N) array.set(y,i,array.get(y,i)/N) [x, y] // @function: Helper function that computes the power of each frequency component // (in other words, Fourier amplitudes squared). // @param x : float[] array, real part of the Fourier amplitudes // @param y : float[] array, imaginary part of the Fourier amplitudes // @returns power : float[] array of the same length as x and y, Fourier amplitudes squared export fftPower(float[] x, float[] y) => int N = array.size(x) float[] power = array.new_float(na) for i = 0 to N-1 array.push(power,math.pow(array.get(x,i),2) + math.pow(array.get(y,i),2)) power // @function: Helper function that returns the discrete Fourier transform sample frequencies // defined in cycles per timeframe unit. For example, if the timeframe is 5m, // the frequencies are in cycles/(5 minutes). // @param N : int, window length (number of points in the transformed dataset) // @returns freq : float[] array of N, contains the sample frequencies (with zero at the start). export fftFreq(int N) => float[] freq = array.new_float(N) int i = 0 for f = 0 to N/2 - 1 array.set(freq, i, f/N) i += 1 for f = -N/2 to -1 by 1 array.set(freq, i, f/N) i += 1 freq // -- sample output -- int N = 32 float[] X = array.new_float(N) float[] Y = array.new_float(N) for i = 0 to N-1 float x_i = math.cos(2*math.pi/16*i) + math.cos(2*math.pi/4*i) + math.random(-1,1,124234) array.set(X,i,x_i) array.set(Y,i,0.0) if barstate.islast for i = 0 to N-2 float y1 = array.get(X,i) float y2 = array.get(X,i+1) int x0 = N/2+2 line.new(bar_index[i+x0], y1, bar_index[i+1+x0],y2,color=color.blue) // apply FFT and calculate powers [Xt, Yt] = fft(X, Y, "Forward") float[] P = fftPower(Xt,Yt) // plot if barstate.islast for i = 0 to N/2-2 float y1 = array.get(P,i)*10 float y2 = array.get(P,i+1)*10 line.new(bar_index[i], y1, bar_index[i+1],y2,color=color.red) line.new(bar_index, 0.0, bar_index[N/2], 0.0, style = line.style_arrow_right, color=color.silver) label.new(bar_index[N/2], 0.0, text="freq", style=label.style_none, textcolor = color.silver)
Algomojo V1.0
https://www.tradingview.com/script/teru8FCX-Algomojo-V1-0/
algomojo
https://www.tradingview.com/u/algomojo/
14
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/ // © algomojo //@version=5 library(title="Algomojo", overlay=true) export algomodule(string br_code="ab",string api_key="",string api_secret="",string strg_name="Tradingview",string Tsym="RELIANCE",string exch="NSE",int qty=1,string prctyp = "MKT", string Pcode = "MIS") => s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML" discqty = "0" MktPro ="NA" Price = "0" TrigPrice = "0" AMO = "NO" Ret = "DAY" //Block 2 : Autotrading API data configuration if(br_code=="ab" or br_code=="tj" or br_code=="zb") //BE - Buy Entry (1x qty), SX - Short Exit (1x qty), BSR - Buy Stop and Reverse (2x qty) BE = "{ \"api_key\":\""+api_key+"\", \"api_secret\":\""+api_secret+"\", \"data\": { \"strg_name\":\""+strg_name+"\", \"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\", \"Tsym\":\""+Tsym+"\", \"exch\":\""+exch+"\", \"Ttranstype\":\"B\", \"Ret\":\"DAY\", \"prctyp\":\""+prctyp+"\", \"qty\":\""+str.tostring(qty)+"\", \"discqty\":\"0\", \"MktPro\":\"NA\", \"Price\":\"0\", \"TrigPrice\":\"0\", \"Pcode\":\""+Pcode+"\", \"AMO\":\"NO\" } }" SX = "{ \"api_key\":\""+api_key+"\", \"api_secret\":\""+api_secret+"\", \"data\": { \"strg_name\":\""+strg_name+"\", \"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\", \"Tsym\":\""+Tsym+"\", \"exch\":\""+exch+"\", \"Ttranstype\":\"B\", \"Ret\":\"DAY\", \"prctyp\":\""+prctyp+"\", \"qty\":\""+str.tostring(qty)+"\", \"discqty\":\"0\", \"MktPro\":\"NA\", \"Price\":\"0\", \"TrigPrice\":\"0\", \"Pcode\":\""+Pcode+"\", \"AMO\":\"NO\" } }" BSR = "{ \"api_key\":\""+api_key+"\", \"api_secret\":\""+api_secret+"\", \"data\": { \"strg_name\":\""+strg_name+"\", \"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\", \"Tsym\":\""+Tsym+"\", \"exch\":\""+exch+"\", \"Ttranstype\":\"B\", \"Ret\":\"DAY\", \"prctyp\":\""+prctyp+"\", \"qty\":\""+str.tostring(qty*2)+"\", \"discqty\":\"0\", \"MktPro\":\"NA\", \"Price\":\"0\", \"TrigPrice\":\"0\", \"Pcode\":\""+Pcode+"\", \"AMO\":\"NO\" } }" //SE - Short Entry (1x qty), Buy Exit - Short Exit (1x qty), SXR - Short Stop and Reveverse (2x qty) SE = "{ \"api_key\":\""+api_key+"\", \"api_secret\":\""+api_secret+"\", \"data\": { \"strg_name\":\""+strg_name+"\", \"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\", \"Tsym\":\""+Tsym+"\", \"exch\":\""+exch+"\", \"Ttranstype\":\"S\", \"Ret\":\"DAY\", \"prctyp\":\""+prctyp+"\", \"qty\":\""+str.tostring(qty)+"\", \"discqty\":\"0\", \"MktPro\":\"NA\", \"Price\":\"0\", \"TrigPrice\":\"0\", \"Pcode\":\""+Pcode+"\", \"AMO\":\"NO\" } }" BX = "{ \"api_key\":\""+api_key+"\", \"api_secret\":\""+api_secret+"\", \"data\": { \"strg_name\":\""+strg_name+"\", \"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\", \"Tsym\":\""+Tsym+"\", \"exch\":\""+exch+"\", \"Ttranstype\":\"S\", \"Ret\":\"DAY\", \"prctyp\":\""+prctyp+"\", \"qty\":\""+str.tostring(qty)+"\", \"discqty\":\"0\", \"MktPro\":\"NA\", \"Price\":\"0\", \"TrigPrice\":\"0\", \"Pcode\":\""+Pcode+"\", \"AMO\":\"NO\" } }" SSR = "{ \"api_key\":\""+api_key+"\", \"api_secret\":\""+api_secret+"\", \"data\": { \"strg_name\":\""+strg_name+"\", \"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\", \"Tsym\":\""+Tsym+"\", \"exch\":\""+exch+"\", \"Ttranstype\":\"S\", \"Ret\":\"DAY\", \"prctyp\":\""+prctyp+"\", \"qty\":\""+str.tostring(qty*2)+"\", \"discqty\":\"0\", \"MktPro\":\"NA\", \"Price\":\"0\", \"TrigPrice\":\"0\", \"Pcode\":\""+Pcode+"\", \"AMO\":\"NO\" } }" [BE,SX,BSR,SE,BX,SSR]
MathSpecialFunctionsDiscreteFourierTransform
https://www.tradingview.com/script/1UZM90fW-MathSpecialFunctionsDiscreteFourierTransform/
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 Method for Complex Discrete Fourier Transform (DFT). library(title='MathSpecialFunctionsDiscreteFourierTransform') import RicardoSantos/MathComplexCore/1 as complex import RicardoSantos/MathComplexOperator/1 as complex_op import RicardoSantos/MathComplexArray/1 as complex_array // @function Complex Discrete Fourier Transform (DFT). // @param inputs float array, pseudo complex array of paired values [(a0+b0i), ...]. // @param inverse bool, invert the transformation. // @returns float array, pseudo complex array of paired values [(a0+b0i), ...]. export dft (float[] _inputs, bool _inverse) => //{ int _size = int(math.floor(array.size(id=_inputs) / 2)) float _pi = 3.14159265359 float _pi2 = _inverse ? 2.0 * _pi : -2.0 * _pi float _invs = 1.0 / _size //| @return: //| _output: Complex array float[] _output = complex_array.new(_size, complex.new(0.0, 0.0)) for _y = 0 to _size - 1 by 1 for _x = 0 to _size - 1 by 1 _a = _pi2 * _y * _x * _invs _ca = math.cos(_a) _sa = -math.sin(_a) float[] _complex_input = complex_array.get(_inputs, _x) float[] _complex_output = complex_array.get(_output, _y) float _input_real = complex.get_real(_complex_input) float _input_imaginary = complex.get_imaginary(_complex_input) float _output_real = complex.get_real(_complex_output) float _output_imaginary = complex.get_imaginary(_complex_output) float _add_real = _output_real + _input_real * _ca - _input_imaginary * _sa float _add_imaginary = _output_imaginary + _input_real * _sa + _input_imaginary * _ca complex_array.set(_output, _y, complex.new(_add_real, _add_imaginary)) if not _inverse float[] _mult = complex_op.multiply(complex_array.get(_output, _y), complex.new(_invs, _invs)) complex_array.set(_output, _y, _mult) _output //{ usage: var float[] inputs = complex_array.new(8, complex.new(0.0, 0.0)) if barstate.islast for _i = 0 to 8 by 1 complex_array.set(inputs, _i, complex.new(close[_i], _i)) // plot(series=f_Sre(0), color=acol, linewidth=aline, style=plot.style_histogram, transp=20, histbase=0, offset=-0, show_last=1) // plot(series=f_Sim(0), color=bcol, linewidth=bline, style=plot.style_histogram, transp=20, histbase=0, offset=-0, show_last=1) float[] S = dft(inputs, false) float[] A = dft(S, true) var table T = table.new(position.bottom_right, 3, 9, border_width=1) table.cell(T, 0, 0, 'Original', text_color=color.silver, text_size=size.small, bgcolor=color.gray) table.cell(T, 1, 0, 'DFT', text_color=color.silver, text_size=size.small, bgcolor=color.gray) table.cell(T, 2, 0, 'Inverse', text_color=color.silver, text_size=size.small, bgcolor=color.gray) if barstate.islast for _l = 0 to math.floor(array.size(inputs) / 2) - 1 by 1 table.cell(T, 0, _l+1, str.tostring(complex_array.get(inputs, _l)), text_size=size.small, bgcolor=color.silver) table.cell(T, 1, _l+1, str.tostring(complex_array.get(S, _l)), text_size=size.small, bgcolor=color.silver) table.cell(T, 2, _l+1, str.tostring(complex_array.get(A, _l)), text_size=size.small, bgcolor=color.silver) // interface to validate if there is values: f_Sre(_i) => array.size(S) > 0 ? complex.get_real(complex_array.get(S, _i)) : na f_Sim(_i) => array.size(S) > 0 ? complex.get_imaginary(complex_array.get(S, _i)) : na color acol = input(#0000ff50) color bcol = input(#8080a050) int aline = 8 int bline = 3 plot(series=f_Sre(1), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-1, show_last=1) plot(series=f_Sim(1), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-1, show_last=1) plot(series=f_Sre(2), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-2, show_last=1) plot(series=f_Sim(2), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-2, show_last=1) plot(series=f_Sre(3), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-3, show_last=1) plot(series=f_Sim(3), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-3, show_last=1) plot(series=f_Sre(4), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-4, show_last=1) plot(series=f_Sim(4), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-4, show_last=1) plot(series=f_Sre(5), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-5, show_last=1) plot(series=f_Sim(5), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-5, show_last=1) plot(series=f_Sre(6), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-6, show_last=1) plot(series=f_Sim(6), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-6, show_last=1) plot(series=f_Sre(7), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-7, show_last=1) plot(series=f_Sim(7), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-7, show_last=1) plot(series=f_Sre(8), color=acol, linewidth=aline, style=plot.style_histogram, histbase=0, offset=-8, show_last=1) plot(series=f_Sim(8), color=bcol, linewidth=bline, style=plot.style_histogram, histbase=0, offset=-8, show_last=1) //{ remarks: // https://en.wikipedia.org/wiki/Discrete_Fourier_transform // https://www.tradingview.com/script/XXBfMnVE-Function-Discrete-Fourier-Transform/ // https://www.gaussianwaves.com/2015/11/interpreting-fft-results-complex-dft-frequency-bins-and-fftshift/ //}}}
Labels
https://www.tradingview.com/script/NkA1xe0i-Labels/
SimpleCryptoLife
https://www.tradingview.com/u/SimpleCryptoLife/
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/ // © SimpleCryptoLife //@version=5 // @description Functions to create labels, from simple to complex. library("Labels", overlay=true) string inputShowLabel = input.string(title="Show Label:", options=["labelSimple","labelLast","labelTextAndFloat","labelTextAndFloatSigFig","labelTextAndFloatDecimals"], defval="labelSimple") int inputOffset = input.int(title="Label Offset", minval=0, maxval=20, defval=0) int inputSigNumFig = input.int(defval=3, minval=1, title="Number of significant figures for the labelTextAndFloatSigFig function") int inputDecimals = input.int(defval=3, minval=0, title="Number of decimal places for the labelTextAndFloatDecimals function") // ===========================================// // SIMPLE LABEL // // ===========================================// // @function Creates a label each time a condition is true. All label parameters can be customised. // @param _condition The condition which must evaluate true for the label to be printed. // @param _x The x location. // @param _y The y location. // @param _text The text to print on the label. // @param _color The colour of the label. // @param _textColor The colour of the text. // @param _style The style of the label. // @param _yloc The y location type. // @returns An unnamed label object with the supplied characteristics. To give it a name, assign the output of the function to a label variable, as in the examples below. export labelSimple(bool _condition=true, int _x=bar_index, float _y=high, string _text="Your text here", color _color=color.white, color _textColor=color.black, string _style=label.style_label_down, string _yloc=yloc.price) => if _condition label.new(x = _x, y = _y, text = _text, color=_color, textcolor=_textColor, style=_style, yloc=_yloc) else na // mySimpleLabel1 is an example of supplying only a few of the parameters. The parameters that are not supplied will revert to the defaults. var label mySimpleLabel1 = na mySimpleLabel1 := labelSimple(_condition=inputShowLabel=="labelSimple", _text="Bender cracked\ncorn") // mySimpleLabel2 is an example of supplying all parameters. Some parameters duplicate the defaults and some replace them. var label mySimpleLabel2 = na mySimpleLabel2 := labelSimple(_condition=barstate.islast and inputShowLabel=="labelSimple",_x=bar_index, _y=low, _text="and I don't care", _color=color.yellow, _textColor=color.gray, _style=label.style_label_up, _yloc=yloc.price) // ===========================================// // + KEEP LAST // // + OFFSET // // ===========================================// // @function Creates a label each time a condition is true. All label parameters can be customised. + Option to keep only the most recent label. + Option to display the label a configurable number of bars ahead; otherwise the x location is fixed at the bar time. // @param _offset How many bars ahead to draw the label. // @param _keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit. // @param _condition The condition which must evaluate true for the label to be printed. // @param _y The y location. // @param _text The text to print on the label. // @param _color The colour of the label. // @param _textColor The colour of the text. // @param _textAlign The alignment of the text. // @param _style The style of the label. // @param _yloc The y location type. // @returns A named label object with the supplied characteristics. You can rename it, as in the second example below. export labelLast(int _offset = 0, bool _keepLast = true, bool _condition=true, float _y=open, string _text="Your text here", color _color=color.white, color _textColor=color.black, string _textAlign=text.align_center, string _style=label.style_label_left, string _yloc=yloc.price) => var label SCL_myLabelLast = na _timeblock1 = (time - time[1]) _futureTime = time + (_timeblock1 * _offset) _x = _futureTime if _condition SCL_myLabelLast := label.new(x = _x, y = _y, text = _text, color=_color, textcolor=_textColor, textalign=_textAlign, style=_style, yloc=_yloc, xloc=xloc.bar_time) else na if _keepLast label.delete(SCL_myLabelLast[1]) SCL_myLabelLast // 1. Use this method of calling the function if you don't care what the name is. labelLast(_condition=inputShowLabel=="labelLast",_text="labelLast", _offset=inputOffset) // 2. Use this method if you want to rename the label. // var label myLabelLast = na, myLabelLast := labelLast(_condition=inputShowLabel=="labelLast",_text="labelLast", _offset=inputOffset) // ===========================================// // + FLOAT // // ===========================================// // @function Creates a label each time a condition is true. All label parameters can be customised. Option to keep only the most recent label. Option to display the label a configurable number of bars ahead; otherwise the x location is fixed at the bar time. + Prints (optional) text and a floating-point number on the next line. // @param _offset How many bars ahead to draw the label. // @param _float The floating-point number that you want to display on the label. // @param _keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit. // @param _condition The condition which must evaluate true for the label to be printed. // @param _y The y location. // @param _text The text to print on the label. // @param _color The colour of the label. // @param _textColor The colour of the text. // @param _textAlign The alignment of the text. // @param _style The style of the label. // @param _yloc The y location type. // @returns A named label object with the supplied characteristics. export labelTextAndFloat(int _offset = 0, float _float=123.456, bool _keepLast = true, bool _condition=true, float _y=open, string _text="My lovely float:", color _color=color.white, color _textColor=color.black, string _textAlign=text.align_center, string _style=label.style_label_left, string _yloc=yloc.price) => string _floatText = not na (_float) ? str.tostring(_float) : na string _newline = not na(_text) ? '\n' : na var label SCL_myLabelTextAndFloat = na _timeblock1 = (time - time[1]) _futureTime = time + (_timeblock1 * _offset) if _condition SCL_myLabelTextAndFloat := label.new(x = _futureTime, y = _y, text = _text+_newline+_floatText, color=_color, textcolor=_textColor, textalign=_textAlign, style=_style, yloc=_yloc, xloc=xloc.bar_time) else na if _keepLast label.delete(SCL_myLabelTextAndFloat[1]) SCL_myLabelTextAndFloat labelTextAndFloat(_condition=inputShowLabel=="labelTextAndFloat", _float=close[1], _offset=inputOffset) // ===========================================// // + FLOAT TO SIGNIFICANT FIGURES // // ===========================================// // @function Creates a label each time a condition is true. All label parameters can be customised. Option to keep only the most recent label. Option to display the label a configurable number of bars ahead; otherwise the x location is fixed at the bar time. Prints (optional) text and a floating-point number on the next line + to a given number of significant figures. // @param _offset How many bars ahead to draw the label. // @param _sigNumFig The number of significant figures to display the floating-point number to. // @param _float The floating-point number that you want to display on the label. // @param _keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit. // @param _condition The condition which must evaluate true for the label to be printed. // @param _y The y location. // @param _text The text to print on the label. // @param _color The colour of the label. // @param _textColor The colour of the text. // @param _textAlign The alignment of the text. // @param _style The style of the label. // @param _yloc The y location type. // @returns A named label object with the supplied characteristics. import SimpleCryptoLife/SignificantFigures/1 as SCLSigFig export labelTextAndFloatSigFig(int _offset=0, int _sigNumFig=5, float _float=123456.7891234, bool _keepLast=true, bool _condition=true, float _y=open, string _text="My lovely float:", color _color=color.white, color _textColor=color.black, string _textAlign=text.align_center, string _style=label.style_label_left, string _yloc=yloc.price) => var string _floatText = na if not na(_float) _sigFloat = SCLSigFig.sigFig(_float, _sigNumFig) _floatText := str.tostring(_sigFloat) _timeblock1 = (time - time[1]) _futureTime = time + (_timeblock1 * _offset) _x = _futureTime string _newline = not na(_text) ? '\n' : na var label SCL_myLabelTextAndFloatSigFig = na if _condition SCL_myLabelTextAndFloatSigFig := label.new(x = _futureTime, y = _y, text = _text+_newline+_floatText, color=_color, textcolor=_textColor, textalign=_textAlign, style=_style, yloc=_yloc, xloc=xloc.bar_time) else na if _keepLast label.delete(SCL_myLabelTextAndFloatSigFig[1]) SCL_myLabelTextAndFloatSigFig exampleFloat = 98765.4321987 labelTextAndFloatSigFig(_condition=inputShowLabel=="labelTextAndFloatSigFig", _offset=inputOffset, _textColor = color.white, _float=exampleFloat, _text="Float: " + str.tostring(exampleFloat) + "\n to " + str.tostring(inputSigNumFig) + "\nsignificant figures:", _sigNumFig = inputSigNumFig, _color=color.teal) // ===========================================// // + FLOAT TO DECIMAL PLACES // // ===========================================// // @function Creates a label each time a condition is true. All label parameters can be customised. Option to keep only the most recent label. Option to display the label a configurable number of bars ahead. Prints (optional) text and a floating-point number on the next line + to a given number of decimal places. // @param _offset How many bars ahead to draw the label. // @param _decimals The number of decimal places to display the floating-point number to. // @param _float The floating-point number that you want to display on the label. // @param _keepLast If true (the default), keeps only the most recent label. If false, prints labels up to the TradingView limit. // @param _condition The condition which must evaluate true for the label to be printed. // @param _y The y location. // @param _text The text to print on the label. // @param _color The colour of the label. // @param _textColor The colour of the text. // @param _textAlign The alignment of the text. // @param _style The style of the label. // @param _yloc The y location type. // @returns A named label object with the supplied characteristics. export labelTextAndFloatDecimals(int _offset=0, int _decimals=5, float _float=9876.5432198, bool _keepLast = true, bool _condition=true, float _y=open, string _text="My lovely float:", color _color=color.white, color _textColor=color.black, string _textAlign=text.align_center, string _style=label.style_label_left, string _yloc=yloc.price) => var string _floatText = na if not na(_float) _floatDecimals = math.round(_float,_decimals) _floatText := str.tostring(_floatDecimals) _timeblock1 = (time - time[1]) _futureTime = time + (_timeblock1 * _offset) _x = _futureTime string _newline = not na(_text) ? '\n' : na var label SCL_myLabelTextAndFloatDecimals = na if _condition SCL_myLabelTextAndFloatDecimals := label.new(x = _futureTime, y = _y, text = _text+_newline+_floatText, color=_color, textcolor=_textColor, textalign=_textAlign, style=_style, yloc=_yloc, xloc=xloc.bar_time) else na if _keepLast label.delete(SCL_myLabelTextAndFloatDecimals[1]) SCL_myLabelTextAndFloatDecimals exampleFloat2 = 98765.4321987 labelTextAndFloatDecimals(_condition=inputShowLabel=="labelTextAndFloatDecimals", _offset=inputOffset, _float=exampleFloat2, _text="Float: " + str.tostring(exampleFloat2) + "\n to " + str.tostring(inputDecimals) + "\ndecimal places:", _decimals = inputDecimals, _color=color.orange)
TimeframeToMinutes
https://www.tradingview.com/script/dAJ9rCXS-TimeframeToMinutes/
SimpleCryptoLife
https://www.tradingview.com/u/SimpleCryptoLife/
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/ // © SimpleCryptoLife //@version=5 // @description Functions for working with timeframes. The timeframeToMinutes() function returns the number of minutes in an arbitrary timeframe string. library("TimeframeToMinutes", overlay=true) string inputTF = input.string(defval="D", title="Example Timeframe") // @function timeframeToMinutes() returns the number of minutes in the supplied timeframe string, which is arbitrary, i.e. it doesn't have to be the timeframe of the current chart but can be taken from an input. // The sole advantage over the short and neat Pinecoders f_resInMinutes function from their excellent MTF Selection Framework (at https://www.tradingview.com/script/90mqACUV-MTF-Selection-Framework-PineCoders-FAQ/) is that it doesn't use up a security() call. // To convert the other way, from minutes to timeframe.period format, I would use the f_resFromMinutes function from the Pinecoders' MTF Selection Framework, which does not use security(). // Error-checking:: It has light error-checking to make sure the string is in the format timeframe.period, e.g. 15S, 1 (minute), 60 (1H), 1D, 1W, 1M. // It will throw an error for some non-standard timeframes such as 30 hours (1800 minutes). Above 1440 minutes, only whole numbers of days are allowed. This is to be consistent with the security() function. // But it will allow some non-standard timeframes such as 7 hours (420 minutes). Such timeframes must still be supplied in the standard timeframe.period format. // @param _tf The timeframe to convert to minutes. Must be in timeframe.period format. // @returns A float representing the number of minutes that the timeframe period is equivalent to. var string errorTextLibraryName = "SimpleCryptoLife/TimeframeToMinutes" export timeframeToMinutes(string _tf) => var string _errorTextFunctionName = "timeframeToMinutes()" if _tf == "" runtime.error("Timeframe cannot be empty. Using input.timeframe() gives an empty string if it is set to Chart. You need to convert an empty timeframe to the current chart timeframe before passing it to this library. An example is given in the library of how to do this. [Error001" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") _arrayTFString = str.split(_tf, "") // Split string into an array bool _tfContainsS = array.includes(_arrayTFString, "S")// Check if it contains S because the error-checking is different for seconds int _lastIndexTFString = array.size(_arrayTFString) - 1 // Get the index of the last element in the array (indexes are numberd 0,1,2 etc) // Pop each array element (remove from the end of the array) and check if it's an integer. _arrayTFInt = array.new_int(0) // Create a new array to hold the integers _minuteMultiplier = 1 // Initialise the minute multiplier to one in case there's no D, W, or M letter. for i = 0 to _lastIndexTFString _elementTFString = array.pop(_arrayTFString) // If it is an integer, convert to an integer and push it (add it to the end) into another array of type int. This should reverse the number. bool _isInt = not na(str.tonumber(_elementTFString)) if _isInt _float = str.tonumber(_elementTFString) _int = int(_float) array.push(_arrayTFInt,_int) // If it is not an integer and is one of "D", "W", "M", convert it to an integer: D = 1440m, W = 10080, M = 43800. This minute multiplier is initialised as 1. _minuteMultiplier := switch _elementTFString "S" => 10 // Just to get past error-checking "D" => 1440 "W" => 10080 "M" => 43800 => _minuteMultiplier if _minuteMultiplier == 1 and not _isInt and not na(_elementTFString) and not _tfContainsS runtime.error("Timeframe is badly formed. [Error002" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")// If it is not null, but not any of the above, throw an error because the timeframe is badly formed. // If the integer array has more than 5 elements, throw an error because that's higher than 1 day and so the timeframe is badly formed. if array.size(_arrayTFInt) > 4 runtime.error("Timeframe is badly formed. [Error003" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") // If the integer array is empty and the minute multiplier is 1, throw an error because the timeframe is badly formed. bool _intArrayIsEmpty = array.sum(_arrayTFInt) == 0 or na(array.sum(_arrayTFInt)) if _minuteMultiplier == 1 and _intArrayIsEmpty and not _tfContainsS runtime.error("Timeframe is badly formed. [Error004" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") // If the integer array is empty and the minute multiplier is > 1, populate the integer array with 1. if _intArrayIsEmpty and _minuteMultiplier > 1 array.push(_arrayTFInt,1) // Pop each element of the integer array, multiply it by 10 to the power of the element index, and push it to another array. int _lastIndexTFInt = array.size(_arrayTFInt) - 1 // Get the index of the last element in the integer array _arrayTFToSum = array.new_int(0) // Create a new array to hold the integers for i = 0 to _lastIndexTFInt int _elementTFInt = array.shift(_arrayTFInt) _elementTFIntPow = _elementTFInt * math.pow(10,i) int _elementTFIntPowInt = int(_elementTFIntPow) // Have to cast it to int because the previous operation makes it a float array.push(_arrayTFToSum,_elementTFIntPowInt) int _sumIntTF = array.sum(_arrayTFToSum) // Sum the array. // If the sum of minutes is greater than 1440, throw an error because that is greater than one day. if _sumIntTF > 1440 runtime.error("Timeframe is greater than 1D and must be specified in a whole number of days [Error005" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") // Multiply the sum by the minute multiplier to get the final number of minutes. float _finalMinutes = _sumIntTF * _minuteMultiplier // Hack override if it's one of the four seconds intervals supported by TradingView _finalMinutes := switch _tf "S" => 0.0166666667 "5S" => 0.0833333333 "15S" => 0.25 "30S" => 0.5 => _finalMinutes if _tfContainsS and (_tf != "S" and _tf != "5S" and _tf != "15S" and _tf != "30S") runtime.error("Timeframe is a disallowed number of seconds. [Error006" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") _finalMinutes // DEMONSTRATION // string inputTFFixed = inputTF == "" ? timeframe.period : inputTimeframe // Uncomment to fix empty timeframes before sending to the function var numberOfMinutes = timeframeToMinutes(inputTF) // You only need to call this function once, to avoid unnecessary calculations, hence assigning the results using var. import SimpleCryptoLife/Labels/1 as SCL_Label string debugText = "Chart timeframe: " + str.tostring(timeframe.period) + "\nInput timeframe: " + str.tostring(inputTF) + "\nNo. of minutes: " + str.tostring(numberOfMinutes) SCL_Label.labelLast(_text=debugText, _offset=3)
FunctionLinearRegression
https://www.tradingview.com/script/QSgzfekm-FunctionLinearRegression/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
183
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 for Linear Regression using array sample points. library(title='FunctionLinearRegression', overlay=true) // @function Performs Linear Regression over the provided sample points. // @param sample_x float array, sample points X value. // @param sample_y float array, sample points Y value. // @returns tuple with: // _predictions: Array with adjusted Y values. // _max_dev: Max deviation from the mean. // _min_dev: Min deviation from the mean. // _stdev/_sizeX: Average deviation from the mean. export linreg (float[] sample_x, float[] sample_y) => //{ //| Returns a linear regression channel using (X,Y) vector points. int _sizeX = array.size(id=sample_x) int _sizeY = array.size(id=sample_y) // switch (_sizeX < 1) => runtime.error('FunctionLinearRegression -> linreg(): "sample_x" has the wrong size.') (_sizeX != _sizeY) => runtime.error('FunctionLinearRegression -> linreg(): "sample_x" and "sample_y" size must match.') // float _sumX = array.sum(id=sample_x) float _sumY = array.sum(id=sample_y) float _sumXY = 0.0 float _sumX2 = 0.0 float _sumY2 = 0.0 // for _i = 0 to _sizeY - 1 by 1 float _Xi = nz(array.get(id=sample_x, index=_i)) float _Yi = nz(array.get(id=sample_y, index=_i)) _sumXY := _sumXY + _Xi * _Yi _sumX2 := _sumX2 + math.pow(_Xi, 2) _sumY2 := _sumY2 + math.pow(_Yi, 2) _sumY2 // float _a = (_sumY * _sumX2 - _sumX * _sumXY) / (_sizeX * _sumX2 - math.pow(_sumX, 2)) float _b = (_sizeX * _sumXY - _sumX * _sumY) / (_sizeX * _sumX2 - math.pow(_sumX, 2)) float[] _predictions = array.new_float(size=0, initial_value=0.0) float _max_dev = 0.0 float _min_dev = 0.0 float _stdev = 0.0 // for _i = 0 to _sizeX - 1 by 1 float _vector = _a + _b * array.get(id=sample_x, index=_i) array.push(id=_predictions, value=_vector) // float _Yi = array.get(id=sample_y, index=_i) float _diff = _Yi - _vector if _diff > _max_dev _max_dev := _diff _max_dev if _diff < _min_dev _min_dev := _diff _min_dev _stdev := _stdev + math.abs(_diff) _stdev // [_predictions, _max_dev, _min_dev, _stdev / _sizeX] //{ usage: //{ remarks: // https://www.statisticshowto.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/#FindaLinear //}}} // @function Method for drawing the Linear Regression into chart. // @param sample_x float array, sample point X value. // @param sample_y float array, sample point Y value. // @param extend string, default=extend.none, extend lines. // @param mid_color color, default=color.blue, middle line color. // @param mid_style string, default=line.style_solid, middle line style. // @param mid_width int, default=2, middle line width. // @param std_color color, default=color.aqua, standard deviation line color. // @param std_style string, default=line.style_dashed, standard deviation line style. // @param std_width int, default=1, standard deviation line width. // @param max_color color, default=color.purple, max range line color. // @param max_style string, default=line.style_dotted, max line style. // @param max_width int, default=1, max line width. // @returns line array. export draw ( float[] sample_x, float[] sample_y, string extend=extend.none, color mid_color=color.blue, string mid_style=line.style_solid, int mid_width=2, color std_color=color.aqua, string std_style=line.style_dashed, int std_width=1, color max_color=color.purple, string max_style=line.style_dotted, int max_width=1 ) => //{ [D, Dmax, Dmin, Dstdev] = linreg(sample_x, sample_y) string _xloc = xloc.bar_index var line ln_mid = line.new(bar_index, open, bar_index, open, _xloc, extend, mid_color, mid_style, mid_width) var line ln_max = line.new(bar_index, open, bar_index, open, _xloc, extend, max_color, max_style, max_width) var line ln_min = line.new(bar_index, open, bar_index, open, _xloc, extend, max_color, max_style, max_width) var line ln_upper = line.new(bar_index, open, bar_index, open, _xloc, extend, std_color, std_style, std_width) var line ln_lower = line.new(bar_index, open, bar_index, open, _xloc, extend, std_color, std_style, std_width) int first = 0 int last = array.size(id=sample_x) - 1 ln_y1 = array.get(id=D, index=first) ln_y2 = array.get(id=D, index=last) line.set_xy1(id=ln_mid, x=int(array.get(id=sample_x, index=first)), y=ln_y1) line.set_xy2(id=ln_mid, x=int(array.get(id=sample_x, index=last)), y=ln_y2) line.set_xy1(id=ln_max, x=int(array.get(id=sample_x, index=first)), y=ln_y1 + Dmax) line.set_xy2(id=ln_max, x=int(array.get(id=sample_x, index=last)), y=ln_y2 + Dmax) line.set_xy1(id=ln_min, x=int(array.get(id=sample_x, index=first)), y=ln_y1 + Dmin) line.set_xy2(id=ln_min, x=int(array.get(id=sample_x, index=last)), y=ln_y2 + Dmin) line.set_xy1(id=ln_upper, x=int(array.get(id=sample_x, index=first)), y=ln_y1 + Dstdev) line.set_xy2(id=ln_upper, x=int(array.get(id=sample_x, index=last)), y=ln_y2 + Dstdev) line.set_xy1(id=ln_lower, x=int(array.get(id=sample_x, index=first)), y=ln_y1 - Dstdev) line.set_xy2(id=ln_lower, x=int(array.get(id=sample_x, index=last)), y=ln_y2 - Dstdev) var line[] _lines = array.from(ln_mid, ln_max, ln_min, ln_upper, ln_lower) //} int length = input(10) var float[] prices = array.new_float(size=length, initial_value=open) var int[] indices = array.new_int(size=length, initial_value=0) if ta.pivothigh(2, 2) e = array.pop(id=prices) i = array.pop(id=indices) array.unshift(id=prices, value=high[2]) array.unshift(id=indices, value=bar_index[2]) if ta.pivotlow(2, 2) e = array.pop(id=prices) i = array.pop(id=indices) array.unshift(id=prices, value=low[2]) array.unshift(id=indices, value=bar_index[2]) lines = draw(indices, prices)
supertrend
https://www.tradingview.com/script/guHY9dmv-supertrend/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
235
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 supertrend : Library dedicated to different variations of supertrend library("supertrend", overlay=true) import HeWhoMustNotBeNamed/enhanced_ta/10 as eta import HeWhoMustNotBeNamed/zigzag/5 as zg f_getCurrentState(source, states) => 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 supertrend_atr: Simple supertrend based on atr but also takes into consideration of custom MA Type, sources // @param length : ATR Length // @param multiplier : ATR Multiplier // @param atrMaType : Moving Average type for ATR calculation. This can be sma, ema, hma, rma, wma, vwma, swma // @param source : Default is close. Can Chose custom source // @param highSource : Default is high. Can also use close price for both high and low source // @param lowSource : Default is low. Can also use close price for both high and low source // @param waitForClose : Considers source for direction change crossover if checked. Else, uses highSource and lowSource. // @param delayed : if set to true lags supertrend atr stop based on target levels. // @returns dir : Supertrend direction // supertrend : BuyStop if direction is 1 else SellStop export supertrend_atr(simple int length, simple float multiplier, simple string atrMaType="sma", float source = close, float highSource = high, float lowSource = low, simple bool waitForClose = false, simple bool delayed = false) => atrDiff = nz(eta.atr(atrMaType, length), ta.tr)*multiplier var buyStop = lowSource - atrDiff var sellStop = highSource + atrDiff var dir = 1 buyStopCurrent = lowSource - atrDiff sellStopCurrent = highSource + atrDiff buyStopInverse = lowSource - atrDiff/2 sellStopInverse = highSource + atrDiff/2 highConfirmation = waitForClose ? source : highSource lowConfirmation = waitForClose? source : lowSource dir := dir == 1 and lowConfirmation[1] < buyStop[1]? -1 : dir == -1 and highConfirmation[1] > sellStop[1]? 1 : dir targetReached = (dir == 1 and nz(highConfirmation[1]) >= nz(sellStop[1])) or (dir == -1 and nz(lowConfirmation[1]) <= nz(buyStop[1])) or not delayed buyStop := dir == 1? (targetReached? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent): buyStop): targetReached ? buyStopCurrent : math.max(nz(buyStop, buyStopInverse), buyStopInverse) sellStop := dir == -1? (targetReached? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent): sellStop): targetReached? sellStopCurrent : math.min(nz(sellStop, sellStopInverse), sellStopInverse) [dir, dir > 0? buyStop : sellStop] // @function supertrend_bands: Simple supertrend based on atr but also takes into consideration of custom MA Type, sources // @param bandType : Type of band used - can be bb, kc or dc // @param maType : Moving Average type for Bands. This can be sma, ema, hma, rma, wma, vwma, swma // @param length : Band Length // @param multiplier : Std deviation or ATR multiplier for Bollinger Bands and Keltner Channel // @param source : Default is close. Can Chose custom source // @param highSource : Default is high. Can also use close price for both high and low source // @param lowSource : Default is low. Can also use close price for both high and low source // @param waitForClose : Considers source for direction change crossover if checked. Else, uses highSource and lowSource. // @param useTrueRange : Used for Keltner channel. If set to false, then high-low is used as range instead of true range // @param useAlternateSource - Custom source is used for Donchian Chanbel only if useAlternateSource is set to true // @param alternateSource - Custom source for Donchian channel // @param sticky : if set to true borders change only when price is beyond borders. // @returns dir : Supertrend direction // supertrend : BuyStop if direction is 1 else SellStop export supertrend_bands(simple string bandType = "bb", simple string maType="sma", simple int length=20, float multiplier=2.0, float source=close,float highSource = high, float lowSource = low, simple bool waitForClose = false, simple bool useTrueRange=true, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false)=> [bbmiddle, bbupper, bblower] = eta.bb(source, maType, length, multiplier, sticky) [kcmiddle, kcupper, kclower] = eta.kc(source, maType, length, multiplier, useTrueRange, sticky) [dcmiddle, dcupper, dclower] = eta.dc(length, useAlternateSource, alternateSource, sticky) lower = switch bandType "bb" => bblower "kc" => kclower => dclower upper = switch bandType "bb"=> bbupper "kc"=> kcupper => dcupper var buyStop = lower var sellStop = upper var dir = 1 buyStopCurrent = lower sellStopCurrent = upper highConfirmation = waitForClose ? source : highSource lowConfirmation = waitForClose? source : lowSource dir := dir == 1 and lowConfirmation[1] < buyStop[1]? -1 : dir == -1 and highConfirmation[1] > sellStop[1]? 1 : dir buyStop := dir == 1? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent): buyStopCurrent sellStop := dir == -1? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent): sellStopCurrent [dir, dir > 0? buyStop : sellStop] // @function supertrend_zigzag: Zigzag pivot based supertrend // @param length : Zigzag Length // @param history : number of historical pivots to consider // @param useAlternateSource - Custom source is used for Zigzag only if useAlternateSource is set to true // @param alternateSource - Custom source for Zigzag // @param source : Default is close. Can Chose custom source // @param highSource : Default is high. Can also use close price for both high and low source // @param lowSource : Default is low. Can also use close price for both high and low source // @param waitForClose : Considers source for direction change crossover if checked. Else, uses highSource and lowSource. // @param atrlength : ATR Length // @param multiplier : ATR Multiplier // @param atrMaType : Moving Average type for ATR calculation. This can be sma, ema, hma, rma, wma, vwma, swma // @returns dir : Supertrend direction // supertrend : BuyStop if direction is 1 else SellStop export supertrend_zigzag(simple int length, simple int history = 1, simple bool useAlternativeSource = false, float alternativeSource=close, float source = close, float highSource = high, float lowSource = low, simple bool waitForClose = false, simple int atrlength=22, simple float multiplier=1.0, simple string atrMaType="sma")=> zigzagHistory = history*2 + 1 [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] = zg.zigzag(length, zigzagHistory, useAlternativeSource, alternativeSource) atrDiff = nz(eta.atr(atrMaType, atrlength), ta.tr)*multiplier var buyStop = array.min(zigzagpivots) - atrDiff var sellStop =array.max(zigzagpivots) + atrDiff var dir = 1 buyStopCurrent = array.min(zigzagpivots) - atrDiff sellStopCurrent = array.max(zigzagpivots) + atrDiff highConfirmation = waitForClose ? source : highSource lowConfirmation = waitForClose? source : lowSource dir := dir == 1 and lowConfirmation[1] < buyStop[1]? -1 : dir == -1 and highConfirmation[1] > sellStop[1]? 1 : dir buyStop := dir == 1? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent): buyStopCurrent sellStop := dir == -1? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent): sellStopCurrent [dir, dir > 0? buyStop : sellStop] // @function zupertrend: Zigzag pivot based supertrend // @param length : Zigzag Length // @param history : number of historical pivots to consider // @param useAlternateSource - Custom source is used for Zigzag only if useAlternateSource is set to true // @param alternateSource - Custom source for Zigzag // @param source : Default is close. Can Chose custom source // @param highSource : Default is high. Can also use close price for both high and low source // @param lowSource : Default is low. Can also use close price for both high and low source // @param waitForClose : Considers source for direction change crossover if checked. Else, uses highSource and lowSource. // @param atrlength : ATR Length // @param multiplier : ATR Multiplier // @param atrMaType : Moving Average type for ATR calculation. This can be sma, ema, hma, rma, wma, vwma, swma // @returns dir : Supertrend direction // supertrend : BuyStop if direction is 1 else SellStop export zupertrend(simple int length, simple int history = 1, simple bool useAlternativeSource = false, float alternativeSource=close, float source = close, float highSource = high, float lowSource = low, simple bool waitForClose = false, simple int atrlength=22, simple float multiplier=1.0, simple string atrMaType="sma")=> zigzagHistory = history*2 + 1 [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] = zg.czigzag(length, zigzagHistory, useAlternativeSource?alternativeSource:highSource, useAlternativeSource?alternativeSource:lowSource) atrDiff = nz(eta.atr(atrMaType, atrlength), ta.tr)*multiplier var buyStop = array.min(zigzagpivots) - atrDiff var sellStop =array.max(zigzagpivots) + atrDiff var dir = 1 buyStopCurrent = array.min(zigzagpivots) - atrDiff sellStopCurrent = array.max(zigzagpivots) + atrDiff highConfirmation = waitForClose ? source : highSource lowConfirmation = waitForClose? source : lowSource dir := dir == 1 and lowConfirmation[1] < buyStop[1]? -1 : dir == -1 and highConfirmation[1] > sellStop[1]? 1 : dir buyStop := dir == 1? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent): buyStopCurrent sellStop := dir == -1? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent): sellStopCurrent [dir, dir > 0? buyStop : sellStop] // @function zsupertrend: Same as zigzag supertrend. But, works on already calculated array rather than Calculating fresh zigzag // @param zigzagpivots : Precalculated zigzag pivots // @param history : number of historical pivots to consider // @param source : Default is close. Can Chose custom source // @param highSource : Default is high. Can also use close price for both high and low source // @param lowSource : Default is low. Can also use close price for both high and low source // @param waitForClose : Considers source for direction change crossover if checked. Else, uses highSource and lowSource. // @param atrlength : ATR Length // @param multiplier : ATR Multiplier // @param atrMaType : Moving Average type for ATR calculation. This can be sma, ema, hma, rma, wma, vwma, swma // @returns dir : Supertrend direction // supertrend : BuyStop if direction is 1 else SellStop export zsupertrend(float[] zigzagpivots, simple int history = 1, float source = close, float highSource = high, float lowSource = low, simple bool waitForClose = false, simple string atrMaType = "sma", simple int atrlength = 22, simple float multiplier = 1)=> zigzagHistory = history*2 + 1 shortArray = array.size(zigzagpivots) > zigzagHistory ? array.slice(zigzagpivots, 0, zigzagHistory) : zigzagpivots atrDiff = nz(eta.atr(atrMaType, atrlength), ta.tr)*multiplier var buyStop = array.min(shortArray) - atrDiff var sellStop =array.max(shortArray) + atrDiff var dir = 1 buyStopCurrent = array.min(shortArray) - atrDiff sellStopCurrent = array.max(shortArray) + atrDiff highConfirmation = waitForClose ? source : highSource lowConfirmation = waitForClose? source : lowSource dir := dir == 1 and lowConfirmation[1] < buyStop[1]? -1 : dir == -1 and highConfirmation[1] > sellStop[1]? 1 : dir buyStop := dir == 1? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent): buyStopCurrent sellStop := dir == -1? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent): sellStopCurrent [dir, dir > 0? buyStop : sellStop] // @function msupertrend : Dynamic trailing supertrend based on multiple bands - either bollinger bands or keltener channel // @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 highSource : Default is high. Can also use close price for both high and low source // @param lowSource : Default is low. Can also use close price for both high and low source // @param waitForClose : Considers source for direction change crossover if checked. Else, uses highSource and lowSource. // @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 // @param trailingDistance : Number of band states to trail for trailing stop. // @param trailStates : If selected trails the band states along with trailing price. If unselected only price is trailed. // @returns dir : Supertrend direction // supertrend : BuyStop if direction is 1 else SellStop export msupertrend(simple string bandType="bb", float source=close, simple string maType = "sma", simple int length = 60, simple bool useTrueRange=false, float highSource = high, float lowSource = low, simple bool waitForClose = false, simple int numberOfBands=20, simple float multiplierStart = 0.5, simple float multiplierStep = 0.5, simple int trailingDistance=10, simple bool trailStates = false)=> bands = eta.multibands(bandType, source, maType, length, useTrueRange, false, numberOfBands, multiplierStart, multiplierStep) currentState = f_getCurrentState(source, bands) var dir = 1 var buyStopState = math.max(currentState - trailingDistance, 0) var sellStopState = math.min(currentState + trailingDistance, numberOfBands*2) var buyStop = array.get(bands, buyStopState) var sellStop = array.get(bands, sellStopState) currentBuyStopState = math.max(currentState - trailingDistance, 0) currentSellStopState = math.min(currentState + trailingDistance, numberOfBands*2) highConfirmation = waitForClose ? source : highSource lowConfirmation = waitForClose? source : lowSource dir := dir == 1 and lowConfirmation[1] < buyStop[1]? -1 : dir == -1 and highConfirmation[1] > sellStop[1]? 1 : dir buyStopState := trailStates and dir == 1? math.max(nz(buyStopState, currentBuyStopState), currentBuyStopState): currentBuyStopState sellStopState := trailStates and dir == -1? math.min(nz(sellStopState, currentSellStopState), currentSellStopState): currentSellStopState buyStopCurrent = array.get(bands, currentBuyStopState) sellStopCurrent = array.get(bands, currentSellStopState) buyStop := dir == 1? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent): buyStopCurrent sellStop := dir == -1? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent): sellStopCurrent [dir, dir > 0? buyStop : sellStop] // ************************************************************* Examples ******************************************************************** type = input.string("zupertrend", "Type", options=["atr", "bands", "zigzag", "zsupertrend", "msupertrend","zupertrend"], group="Supertrend") source = input.source(close, "Source", group="Supertrend") highSource = input.source(high, "High", group="Supertrend") lowSource = input.source(low, "Low", group="Supertrend") waitForClose = input.bool(false, "Wait For Close", group="Supertrend") stepped = input.bool(false, "Delayed/Sticky", group="Supertrend") atrMaType = input.string("sma", "MA Type", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "highlow", "linreg", "median"], group="ATR") atrLength = input.int(22, "MA Length", group="ATR") atrMultiplier = input.int(4, "Multiplier", group="ATR") bandType = input.string("bb", "Band Type", options=["bb", "kc", "dc"], group="Bands") bandMaType = input.string("sma", "MA Type", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "highlow", "linreg", "median"], group="Bands") bandLength = input.int(20, "MA Length", group="Bands") bandMultiplier = input.int(2, "Multiplier", group="Bands") useTrueRange = input.bool(true, title="Use True Range (KC)", group="Bands") useAlternateSource = input.bool(false, title="Use Alternate Source (DC)", group="Bands") alternateSource = input.source(close, "Alternate Source", group="Bands") useSupertrendParamsForBands = input.bool(false, "Use Supertrend and ATR Settings", group="Bands") numberOfBands = input.int(20, "Number of Bands", group="Multibands") multiplierStart = input.float(0.5, "Start", group="Multibands") multiplierStep = input.float(0.5, "Step", group="Multibands") trailingDistance = input.int(10, "Trailing Distance", group="Multibands") trailStates = input.bool(false, "Trail States", group = "Multibands") zigzagLength = input.int(5, "Length", group="Zigzag") history = input.int(1, "Pivot History", group="Zigzag") useAlternateSourceZigzag = input.bool(false, title="Use Alternate Source", group="Zigzag") alternateSourceZigzag = input.source(close, "Alternate Source", group="Zigzag") useSupertrendAndAtrParamsForZigzag = input.bool(false, "Use Supertrend and ATR Settings", group="Zigzag") dir = 1 supertrend = close if(type == "atr") [dir_atr, supertrenda] = supertrend_atr(length=atrLength, multiplier=atrMultiplier, atrMaType=atrMaType, source=source, highSource=highSource, lowSource=lowSource, waitForClose=waitForClose, delayed=stepped) dir := dir_atr supertrend := supertrenda else if(type == "bands") if(useSupertrendParamsForBands) [dir_bands, supertrendb] = supertrend_bands(bandType = bandType, maType=bandMaType, length=bandLength, multiplier=bandMultiplier, source=source, highSource=highSource, lowSource=lowSource, waitForClose=waitForClose, useTrueRange=useTrueRange, useAlternateSource = useAlternateSource, alternateSource = alternateSource, sticky=stepped) dir := dir_bands supertrend := supertrendb else [dir_bands, supertrendb] = supertrend_bands(bandType = bandType, maType=bandMaType, length=bandLength, multiplier=bandMultiplier, useTrueRange=useTrueRange, useAlternateSource = useAlternateSource, alternateSource = alternateSource, sticky=stepped) dir := dir_bands supertrend := supertrendb else if(type == "zigzag") if(useSupertrendAndAtrParamsForZigzag) [dir_zigzag, supertrendz] = supertrend_zigzag(length=zigzagLength, history = history, useAlternativeSource = useAlternateSourceZigzag, alternativeSource=alternateSourceZigzag, source=source, highSource=highSource, lowSource=lowSource, waitForClose=waitForClose, atrlength=atrLength, multiplier=atrMultiplier, atrMaType=atrMaType) dir := dir_zigzag supertrend := supertrendz else [dir_zigzag, supertrendz] = supertrend_zigzag(length=zigzagLength, history = history, useAlternativeSource = useAlternateSourceZigzag, alternativeSource=alternateSourceZigzag) dir := dir_zigzag supertrend := supertrendz else if(type=="zsupertrend") [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] = zg.zigzag(zigzagLength) [dir_zigzag, supertrendz] = zsupertrend(zigzagpivots, history) dir := dir_zigzag supertrend := supertrendz else if(type=="zupertrend") [dir_zigzag, supertrendz] = zupertrend(length=zigzagLength, history = history, useAlternativeSource = useAlternateSourceZigzag, alternativeSource=alternateSourceZigzag, source=source, highSource=highSource, lowSource=lowSource, waitForClose=waitForClose, atrlength=atrLength, multiplier=atrMultiplier, atrMaType=atrMaType) dir := dir_zigzag supertrend := supertrendz else [dir_m, supertrend_m] = msupertrend(bandType, source, bandMaType, bandLength, useTrueRange, highSource, lowSource, waitForClose, numberOfBands, multiplierStart, multiplierStep, trailingDistance) dir := dir_m supertrend := supertrend_m plot(supertrend, color = dir >0 ? color.green : color.red, title="supertrend")
FunctionPolynomialRegression
https://www.tradingview.com/script/As6AbGd5-FunctionPolynomialRegression/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
135
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: library(title='FunctionPolynomialRegression', overlay=true) // @function Method to return a polynomial regression channel using (X,Y) sample points. // @param sample_x float array, sample data X points. // @param sample_y float array, sample data Y points. // @returns tuple with: // _predictions: Array with adjusted Y values. // _max_dev: Max deviation from the mean. // _min_dev: Min deviation from the mean. // _stdev/_sizeX: Average deviation from the mean. export polyreg(float[] sample_x, float[] sample_y) => //{ int _sizeY = array.size(id=sample_y) int _sizeX = array.size(id=sample_x) // switch (_sizeX < 1) => runtime.error('FunctionPolynomialRegression -> polyreg(): "sample_x" has the wrong size.') (_sizeX != _sizeY) => runtime.error('FunctionPolynomialRegression -> polyreg(): "sample_x" and "sample_y" size does not match.') // float _meanX = array.sum(id=sample_x) / _sizeX float _meanY = array.sum(id=sample_y) / _sizeX float _meanXY = 0.0 float _meanY2 = 0.0 float _meanX2 = 0.0 float _meanX3 = 0.0 float _meanX4 = 0.0 float _meanX2Y = 0.0 // for _i = 0 to _sizeY - 1 by 1 float _Xi = array.get(id=sample_x, index=_i) float _Yi = array.get(id=sample_y, index=_i) _meanXY := _meanXY + _Xi * _Yi _meanY2 := _meanY2 + math.pow(_Yi, 2) _meanX2 := _meanX2 + math.pow(_Xi, 2) _meanX3 := _meanX3 + math.pow(_Xi, 3) _meanX4 := _meanX4 + math.pow(_Xi, 4) _meanX2Y := _meanX2Y + math.pow(_Xi, 2) * _Yi _meanX2Y _meanXY := _meanXY / _sizeX _meanY2 := _meanY2 / _sizeX _meanX2 := _meanX2 / _sizeX _meanX3 := _meanX3 / _sizeX _meanX4 := _meanX4 / _sizeX _meanX2Y := _meanX2Y / _sizeX _meanX2Y //-----------|covs float _sXX = _meanX2 - _meanX * _meanX float _sXY = _meanXY - _meanX * _meanY float _sXX2 = _meanX3 - _meanX * _meanX2 float _sX2X2 = _meanX4 - _meanX2 * _meanX2 float _sX2Y = _meanX2Y - _meanX2 * _meanY //-----------| float _b = (_sXY * _sX2X2 - _sX2Y * _sXX2) / (_sXX * _sX2X2 - _sXX2 * _sXX2) float _c = (_sX2Y * _sXX - _sXY * _sXX2) / (_sXX * _sX2X2 - _sXX2 * _sXX2) float _a = _meanY - _b * _meanX - _c * _meanX2 //-----------| float[] _predictions = array.new_float(size=0, initial_value=0.0) float _max_dev = 0.0 float _min_dev = 0.0 float _stdev = 0.0 for _i = 0 to _sizeX - 1 by 1 float _Xi = array.get(id=sample_x, index=_i) float _vector = _a + _b * _Xi + _c * _Xi * _Xi array.push(id=_predictions, value=_vector) // float _Yi = array.get(id=sample_y, index=_i) float _diff = _Yi - _vector if _diff > _max_dev _max_dev := _diff _max_dev if _diff < _min_dev _min_dev := _diff _min_dev _stdev := _stdev + math.abs(_diff) _stdev [_predictions, _max_dev, _min_dev, _stdev / _sizeX] //{ usage: //{ remarks: // language D: https://rosettacode.org/wiki/Polynomial_regression //}}} // @function Method for drawing the Polynomial Regression into chart. // @param sample_x float array, sample point X value. // @param sample_y float array, sample point Y value. // @param extend string, default=extend.none, extend lines. // @param mid_color color, default=color.blue, middle line color. // @param mid_style string, default=line.style_solid, middle line style. // @param mid_width int, default=2, middle line width. // @param std_color color, default=color.aqua, standard deviation line color. // @param std_style string, default=line.style_dashed, standard deviation line style. // @param std_width int, default=1, standard deviation line width. // @param max_color color, default=color.purple, max range line color. // @param max_style string, default=line.style_dotted, max line style. // @param max_width int, default=1, max line width. // @returns line array. export draw ( float[] sample_x, float[] sample_y, int n_segments=10, string extend=extend.none, color mid_color=color.blue, string mid_style=line.style_solid, int mid_width=2, color std_color=color.aqua, string std_style=line.style_dashed, int std_width=1, color max_color=color.purple, string max_style=line.style_dotted, int max_width=1 ) => //{ // [P, Pmax, Pmin, Pstdev] = polyreg(sample_x, sample_y) string _xloc = xloc.bar_index // var line[] _lines_mid = array.new_line(n_segments) var line[] _lines_max = array.new_line(n_segments) var line[] _lines_min = array.new_line(n_segments) var line[] _lines_upper = array.new_line(n_segments) var line[] _lines_lower = array.new_line(n_segments) // for _i=0 to (n_segments - 1) string _extend = extend.none if _i == 0 switch (extend) (extend.left) => _extend := extend.left (extend.both) => _extend := extend.left => _extend := extend.none if _i == (n_segments - 1) switch (extend) (extend.right) => _extend := extend.right (extend.both) => _extend := extend.right => _extend := extend.none // array.set(_lines_mid , _i, line.new(bar_index, open, bar_index, open, _xloc, _extend, mid_color, mid_style, mid_width)) array.set(_lines_max , _i, line.new(bar_index, open, bar_index, open, _xloc, _extend, max_color, max_style, max_width)) array.set(_lines_min , _i, line.new(bar_index, open, bar_index, open, _xloc, _extend, max_color, max_style, max_width)) array.set(_lines_upper , _i, line.new(bar_index, open, bar_index, open, _xloc, _extend, std_color, std_style, std_width)) array.set(_lines_lower , _i, line.new(bar_index, open, bar_index, open, _xloc, _extend, std_color, std_style, std_width)) // int pr_size = array.size(id=P) int pr_step = math.max(pr_size / n_segments, 1) for _i = 0 to pr_size - pr_step - 1 by pr_step int _next_step_index = _i + pr_step int _line = _i / pr_step // line.set_xy1(id=array.get(_lines_mid , _line), x=int(array.get(id=sample_x, index=_i)), y=array.get(id=P, index=_i)) line.set_xy2(id=array.get(_lines_mid , _line), x=int(array.get(id=sample_x, index=_i + pr_step)), y=array.get(id=P, index=_i + pr_step)) line.set_xy1(id=array.get(_lines_max , _line), x=int(array.get(id=sample_x, index=_i)), y=array.get(id=P, index=_i) + Pmax) line.set_xy2(id=array.get(_lines_max , _line), x=int(array.get(id=sample_x, index=_i + pr_step)), y=array.get(id=P, index=_i + pr_step) + Pmax) line.set_xy1(id=array.get(_lines_min , _line), x=int(array.get(id=sample_x, index=_i)), y=array.get(id=P, index=_i) + Pmin) line.set_xy2(id=array.get(_lines_min , _line), x=int(array.get(id=sample_x, index=_i + pr_step)), y=array.get(id=P, index=_i + pr_step) + Pmin) line.set_xy1(id=array.get(_lines_upper, _line), x=int(array.get(id=sample_x, index=_i)), y=array.get(id=P, index=_i) + Pstdev) line.set_xy2(id=array.get(_lines_upper, _line), x=int(array.get(id=sample_x, index=_i + pr_step)), y=array.get(id=P, index=_i + pr_step) + Pstdev) line.set_xy1(id=array.get(_lines_lower, _line), x=int(array.get(id=sample_x, index=_i)), y=array.get(id=P, index=_i) - Pstdev) line.set_xy2(id=array.get(_lines_lower, _line), x=int(array.get(id=sample_x, index=_i + pr_step)), y=array.get(id=P, index=_i + pr_step) - Pstdev) // [_lines_mid, _lines_max, _lines_min, _lines_upper, _lines_lower] //{ usage: //{ remarks: //}}} int length = input(10) var float[] prices = array.new_float(size=length, initial_value=open) var int[] indices = array.new_int(size=length, initial_value=0) int fractal_size = input(2) if ta.pivothigh(fractal_size, fractal_size) e = array.pop(id=prices) i = array.pop(id=indices) array.insert(id=prices, index=0, value=high[fractal_size]) array.insert(id=indices, index=0, value=bar_index[fractal_size]) if ta.pivotlow(fractal_size, fractal_size) e = array.pop(id=prices) i = array.pop(id=indices) array.insert(id=prices, index=0, value=low[fractal_size]) array.insert(id=indices, index=0, value=bar_index[fractal_size]) draw(indices, prices)
FunctionBoxCoxTransform
https://www.tradingview.com/script/eC0u3cNf-FunctionBoxCoxTransform/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Methods to compute the Box-Cox Transformer. library(title='FunctionBoxCoxTransform') // reference: // https://www.statology.org/box-cox-transformation-excel/ // https://www.geeksforgeeks.org/box-cox-transformation-using-python/ // https://github.com/business-science/timetk/blob/master/R/vec-box_cox.R // https://frost-lee.github.io/box-cox-linear-model/ // https://otexts.com/fpp2/transformations.html // // @function Regular transform. // @param sample float array, sample data values. // @param lambda float, scaling factor. // @returns float array. export regular(float[] sample, float lambda) => //{ int _size = array.size(id=sample) // switch (_size < 1) => runtime.error('FunctionBoxCoxTransformer -> regular(): "sample" has the wrong size.') // float[] _X = array.copy(id=sample) for _i = 0 to _size - 1 _xi = array.get(id=_X, index=_i) if lambda == 0 array.set(id=_X, index=_i, value=math.log(_xi)) else array.set(id=_X, index=_i, value=math.sign(_xi) * (math.pow(math.abs(_xi), lambda) - 1) / lambda) _X //{ usage: //{ remarks: // lambda: 1:no rescale, >1:scale up and keep structure, <1:scale down and aproximate to log curve //}}} // @function Regular transform. // @param sample float array, sample data values. // @param lambda float, scaling factor. // @returns float array. export inverse (float[] sample, float lambda) => //{ int _size = array.size(id=sample) // switch (_size < 1) => runtime.error('FunctionBoxCoxTransformer -> inverse(): "sample" has the wrong size.') // float[] _X = array.copy(id=sample) for _i = 0 to _size - 1 by 1 _xi = array.get(id=_X, index=_i) if lambda == 0 array.set(id=_X, index=_i, value=math.exp(_xi)) else _xe = lambda * _xi + 1.0 array.set(id=_X, index=_i, value=math.sign(_xe) * math.pow(math.abs(_xe), 1.0 / lambda)) _X //{ usage: //{ remarks: //}}} lambda = input(0.5225) var sample_data = array.from(4.0, 5.0, 2.0, 5.0, 7.0, 2.0, 2.0, 4.0, 6.0, 3.0, 4.0, 3.0, 8.0, 6.0, 1, 2, 4, 7, 8, 3, 5, 9) Y = regular(sample_data, lambda) iY = inverse(Y, lambda) var label la = label.new(bar_index, 0.0, '') label.set_xy(la, bar_index, 0.0) label.set_text(la, 'sample: ' + str.tostring(sample_data) + '\ninverse: ' + str.tostring(iY) + '\nregular: ' + str.tostring(Y)) plot(array.get(Y, bar_index % array.size(Y))) plot(array.get(iY, bar_index % array.size(Y)))
raf_BollingerBandsSqueezy
https://www.tradingview.com/script/x0ZuAru7-raf-BollingerBandsSqueezy/
rafaraf
https://www.tradingview.com/u/rafaraf/
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/ // © rafaraf //@version=5 // @description B Bands with some squeese indicating additions library('raf_BollingerBandsSqueezy', overlay=true) // inputs color bbbgcolor = input(color.new(#673ab7, 95), title='BB Background') color cFillUpperExits = input(color.new(#00ff00, 50), title='Fill this color when prise above UPPER') color cFillLowerExits = input(color.new(#ff0000, 50), title='Fill this color when prise below LOWER') // these need to stay constant or be changed only from code, since strategies depend on these // the commended out "input" is for finding the parameters more easily, then they should be frozen again float __src__ = close // input(close, title='Price input') int length = 15 // input.int(15, minval=1) float mult = 1.3 // input.float(1.3, minval=0.001, maxval=50, step=0.05, title='StdDev') bool is_exponential = true // input(true, title='Exponential MA?') int len_sqz_sma = 100 // input.int(100, 'BB Relative Squeeze Length', minval=5) float sqz_threshold = 0.5 // input.float(0.5, 'BB Squeeze Threshold', maxval=1, step=0.05) int len_fast_ma = 3 // input.int(3, 'Fast MA Length', minval=1, step=1) // @function Calcs BB // @returns the tree lines, upper, basis and lower export bbands_lines() => ema_line = ta.ema(__src__, length) sma_line = ta.sma(__src__, length) bb_basis = is_exponential ? ema_line : sma_line bb_dev = mult * ta.stdev(__src__, length) bb_upper = bb_basis + bb_dev bb_lower = bb_basis - bb_dev // Calculate BB spread and average spread spread = bb_upper - bb_lower avgspread = ta.sma(spread, len_sqz_sma) // squeeze upper and lower bb_sqz_upper = bb_basis + avgspread * sqz_threshold bb_sqz_lower = bb_basis - avgspread * sqz_threshold [bb_upper, bb_basis, bb_lower, bb_sqz_upper, bb_sqz_lower] // @function calcs the fast moving average, to be used to compare how prise is positioned against BB // @returns the fast EMA line, and the difference between it and the BB basis line export bbands_fast_ma() => ta.ema(__src__, len_fast_ma) // render [bb_upper, bb_basis, bb_lower, bb_sqz_upper, bb_sqz_lower] = bbands_lines() plot(bb_basis, 'Basis', color=color.new(#4a148c, 70), linewidth=3) p1 = plot(bb_upper, 'Upper', color=color.new(#ce93d8, 50), linewidth=2) p2 = plot(bb_lower, 'Lower', color=color.new(#ce93d8, 50), linewidth=2) fill(p1, p2, title='Background', color=bbbgcolor) psqz_u = plot(bb_sqz_upper, 'Squeeze Upper', color=color.new(color.orange, 50), linewidth=2) psqz_l = plot(bb_sqz_lower, 'Squeeze Lower', color=color.new(color.orange, 50), linewidth=2) fill(psqz_u, psqz_l, color=color.new(color.orange, 85)) psrc = plot(close, title='Price bar close', display=display.none) fill(psrc, p1, color=close > bb_upper ? cFillUpperExits : na) fill(psrc, p2, color=close < bb_lower ? cFillLowerExits : na) fast_ma_line = bbands_fast_ma() plot(fast_ma_line, 'Fast MA line', color=color.new(color.blue, 0), linewidth=2) // important events happening in this indicator // export indicator_signals() => // // enter // hasEnteredFromAbove = src < upper and src[1] >= upper // hasEnteredFromBelow = src >= lower and src[1] < lower // hasEnteredFromAboveToAboveMid = hasEnteredFromAbove and src > basis // hasEnteredFromAboveToBelowMid = hasEnteredFromAbove and src <= basis // hasEnteredFromBelowToAboveMid = hasEnteredFromBelow and src > basis // hasEnteredFromBelowToBelowMid = hasEnteredFromBelow and src <= basis // // exit // hasExitedFromAbove = src > upper and src[1] <= upper // hasExitedFromBelow = src < lower and src[1] >= lower // // go through like no care // hasGoneThroughFromBelow = src > upper and src[1] < lower // hasGoneThroughFromAbove = src < lower and src[1] > upper // //////////////////////// // for strategies: // export strategic_signals_please() => // // helpful vars // candle_head = math.max(open, close) // candle_ass = math.min(open, close) // bool ssig_candle_body_inside = candle_head <= upper and candle_ass >= lower // bool ssig_candle_pokes_above = ssig_candle_body_inside and high > upper // bool ssig_candle_pokes_below = ssig_candle_body_inside and lower > low // bool ssig_candle_sticks_head_out = candle_head > upper and upper >= candle_ass // bool cssig_andle_sticks_ass_out = candle_head >= lower and lower > candle_ass // bool ssig_candle_body_above = candle_ass > upper // bool ssig_candle_body_below = lower > candle_head // bool ssig_candle_gone_fly = ssig_candle_body_above and low > upper // bool ssig_candle_gone_dive = ssig_candle_body_below and lower > high // bool ssig_bb_shrinks = upper - lower < upper[1] - lower[1] // basis_slope_line = basis - basis[1] // bool ssig_continuing_positive_bb_basis_line_uptrend = // basis_slope_line > 0 and basis_slope_line >= basis_slope_line[1] // and basis_slope_line[1] > 0 and basis_slope_line[1] >= basis_slope_line[2] // and basis_slope_line[2] > 0 and basis_slope_line[2] >= basis_slope_line[3] // and basis_slope_line[3] > 0 and basis_slope_line[3] >= basis_slope_line[4] // // and basis_slope_line[4] > 0 and basis_slope_line[4] >= basis_slope_line[5] // // and basis_slope_line[5] > 0 and basis_slope_line[5] >= basis_slope_line[6] // // and basis_slope_line[6] > 0 and basis_slope_line[6] >= basis_slope_line[7] // // and basis_slope_line[7] > 0 and basis_slope_line[7] >= basis_slope_line[8]
FunctionForecastLinear
https://www.tradingview.com/script/yrWNuLRa-FunctionForecastLinear/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
19
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 for linear Forecast, same as found in excel and other sheet packages. library(title='FunctionForecastLinear') import RicardoSantos/ArrayGenerate/1 as ag // @function linear forecast method. // @param sample_x float array, sample data X value. // @param sample_y float array, sample data Y value. // @param target_x float, target X to get Y forecast value. // @returns float export forecast (float[] sample_x, float[] sample_y, float target_x) => //{ // @function: Linear forecast, same as excel and other sheet packages. calculates the future value given known data. // @parameters: // sample_x: float[] or int[], data sample for X. // sample_y: float[] or int[], data sample for Y. // target_x: float or int, 0>x, value of X to predict Y. // @reference: // https://support.microsoft.com/en-us/office/forecast-and-forecast-linear-functions-50ca49c9-7b40-4892-94e4-7ad38bbeda99?ui=en-us&rs=en-us&ad=us // https://stackoverflow.com/questions/39373328/forecast-formula-from-excel-in-javascript int _size_x = array.size(sample_x) int _size_y = array.size(sample_y) // switch (_size_x < 1) => runtime.error('FunctionForecastLinear -> forecast(): "sample_x" has the wrong size.') (_size_x != _size_y) => runtime.error('FunctionForecastLinear -> forecast(): "sample_x" and "sample_y" size does not match.') // float _nr = 0. float _dr = 0. float _ax = array.avg(sample_x) float _ay = array.avg(sample_y) for _i = 0 to _size_x - 1 by 1 _xi = array.get(sample_x, _i) _yi = array.get(sample_y, _i) _nr := _nr + (_xi - _ax) * (_yi - _ay) _dr := _dr + (_xi - _ax) * (_xi - _ax) // float _b = _nr / _dr float _a = _ay - _b * _ax _a + _b * target_x //{ usage: //{ remarks: //}}} //test samples from: https://corporatefinanceinstitute.com/resources/excel/functions/forecast-linear-function/ test_earnings = array.from(879., 1259., 1230., 1471., 1562., 1526., 1437., 1637., 1689., 1720., 1456., 1653.) test_expenses = array.from(263.7, 377.7, 369., 441.3, 468.6, 457.8, 431.1, 491.1, 506.7, 516., 436.8, 495.9) f0 = forecast(array.from(1, 2, 3, 4, 5), array.from(6., 7., 8., 9., 10.), 6) f1 = forecast(test_earnings, test_expenses, 1705.25) // f0 = forecast(array.from(20, 28, 31, 38, 40), array.from(6, 7, 9, 15, 21), 30) f2 = bar_index <= 100 ? 0.0 : forecast(ag.sequence_from_series(bar_index, 100, 0, true), ag.sequence_from_series(close, 100, 0, true), bar_index + 30) t = str.format('forecast linear sample: {0}\nforecast from data sample: {1}\nforecast from series: {2}', f0, f1, f2) if barstate.islast label.new(bar_index, 0.0, t)
[MX]Moving Average - Library
https://www.tradingview.com/script/rIjrXh97/
Marqx
https://www.tradingview.com/u/Marqx/
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/ // © Marqx //@version=5 library("MovingAverage_library", overlay = true) Source = input(close,"Source") Length = input(12,"Length") //@function Calculates different types of moving average //@param dema Double Exponential Moving Average //@param tema Triple Exponential Moving Average //@param wwma Welles Wilder Moving Average //@param gma Geometric Moving Average //@returns Different Moving Average types. export tema(float price, simple int length) => tema_source1 = ta.ema(price,length) tema_source2 = ta.ema(tema_source1,length) tema_source3 = ta.ema(tema_source2,length) 3 * (tema_source1 - tema_source2) + tema_source3 export dema(float price, simple int length) => dema_source1 = ta.ema(price,length) dema_source2 = ta.ema(dema_source1,length) 2 * dema_source1 - dema_source2 export wwma(float price, simple int length) => WWMA = 0.0 WWMA := (nz(WWMA[1]) * (length - 1) + price) / length export gma(float price, simple int length) => sum = price for i = 1 to length-1 sum := sum * price[i] math.pow(sum,(1/length)) DEMA = dema(Source,Length) TEMA = tema(Source,Length) WWMA = wwma(Source,Length) GMA = gma(Source,Length) plot(DEMA,"Dema Moving Average",color.white,4) plot(TEMA,"Tema Moving Average",color.white,4) plot(WWMA,"Welles Wilder Moving Average",color.white,4) plot(GMA,"Geometric Moving Average",color.white,4)
FunctionDaysInMonth
https://www.tradingview.com/script/Wz2OSQgL-FunctionDaysInMonth/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Method to find the number of days in a given month of year. library(title='FunctionDaysInMonth') // @function Method to find the number of days in a given month of year. // @param year int, year of month, so we know if year is a leap year or not. // @param month int, month number. // @returns int export days_in_month (int year_value, int month_value) => //{ switch (month_value < 1) => runtime.error('FunctionDaysInMonth -> days_in_month(): "month" must be a integer over or equal to 1') (month_value > 12) => runtime.error('FunctionDaysInMonth -> days_in_month(): "month" must be a integer under or equal to 12') // int _is_leap_year_february = (year_value % 4 == 0) and (month_value == 2) ? 1 : 0 28 + _is_leap_year_february + (month_value + math.floor(month_value / 8)) % 2 + 2 % month_value + 2 * math.floor(1 / month_value) //{ usage: var string[] months = array.from("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") int i_year = input.int(2019) int i_month = input.int(1) int days = days_in_month(i_year, i_month) var label la = label.new(bar_index, 0.0, str.format('{0} in Year {1} has {2} days.', array.get(months, i_month-1), i_year, days)) //{ Remarks: // https://cmcenroe.me/2014/12/05/days-in-month-formula.html //}}}
SignificantFigures
https://www.tradingview.com/script/mf3vCZsx-SignificantFigures/
SimpleCryptoLife
https://www.tradingview.com/u/SimpleCryptoLife/
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/ // © SimpleCryptoLife //@version=5 // @description Takes a floating-point number - one that can, but doesn't have to, include a decimal point - and converts it to a floating-point number with only a certain number of digits left. // For example, say you want to display a variable from your script to the user and it comes out to something like 45.366666666666666666666667 or whatever. // That looks awful when you, for example, print it in a label. Now you could round it up to the nearest integer easily using a built-in function, or even to a certain number of decimal places // using a reasonably simple custom function. But that's a bit arbitrary. Suppose you don't know what asset the script will be used on, and so you can't predict what the price is, // and what the value will turn out to be. It could be 0.00045366666666666666666666667 instead. Now if you round it up to 3 decimal places it comes out as 0.000, which is useless. // My function will round that number to 0.0004536 instead, if told to do it to 4 significant digits. I think this is more friendly. // Note that this function only truncates the number, it does not do any rounding. So in the example above, it will show 0.0004536 and not 0.0004537. Feel free to extend it to do this if you have the time. library("SignificantFigures", overlay=true) // @function sigFig Converts float with arbitrary number of digits to one with a specified number of significant figures. // @param float _float is the floating-point number to manipulate. // @param int _figures is the number of significant figures you want. // @returns Returns a float with the specified number of significant figures. inputFloat = input.float(defval=12345.678912345, title="Float", tooltip="The number that you want to round.") // Values used for testing: 123456789 123456789.123 12.3456789 0.123456789 0.0000123456 inputSigFigs = input.int(defval=4, minval=1, maxval=99, title="Significant Figures", tooltip="The number of significant figures that you want the number rounded to.") inputShowLabel = input.bool(defval=true, title="Show label with numbers") export sigFig(float _float = 12345.6789, int _figures = 7) => float _numberOfTens = math.log10(math.abs(_float)) // How many tens are in the number (or whatever; I don't really maths) int _remainingTens = int(_numberOfTens) - _figures // How many more than the significant figures is that var float _roundedFloat = na if _figures > _numberOfTens // Detect if the decimal place is included in the number of significant digits specified, or not _roundedFloat := math.round(_float, _figures-int(math.floor(math.log10(math.abs(_float))))-1) // Method to round if it is, courtesy of @tepmoc else _roundedFloat := (math.round(_float / math.pow(10, _remainingTens+1))) * math.pow(10,_remainingTens+1) // Method to round if it is not, what I made up _roundedFloat // === EXAMPLE USAGE === var floatSigFigged = sigFig(inputFloat,inputSigFigs) string labelText = "Original float: " + str.tostring(inputFloat) + "\nTruncated to " + str.tostring(inputSigFigs) + " significant figures: " + str.tostring(floatSigFigged) var label labelExample = na int timeblock = (time - time[1]) // So you can plot labels or lines in the future if inputShowLabel labelExample := label.new(time + (timeblock*3), close[1], labelText, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_left, size=size.normal, color=color.gray, textcolor=color.white) label.delete(labelExample[1]) // Only keep the most recent one
StringEvaluation
https://www.tradingview.com/script/PM7KRF8I-StringEvaluation/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Methods to handle evaluation of strings. library(title='StringEvaluation') // imports: import RicardoSantos/MathOperator/1 as op import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(20) // Helper Functions: // @function Check if char is a comma ".". // @param char string, 1 character string. // @returns bool. export is_comma (string char) => //{ char == '.' ? true : false //} // @function Check if char is a operator component. // @param char string, 1 character string. // @returns bool. export is_op_component (string char) => //{ switch char '=' => true '!' => true '>' => true '<' => true => false //} // @function Check if char is a boolean operator. // @param char string, 1 character string. // @returns bool. export is_boolean_op (string char) => //{ switch char '==' => true '!=' => true '>=' => true '<=' => true '>' => true '<' => true 'and' => true 'or' => true => false //} // @function Check if char is a operator. // @param char string, 1 character string. // @returns bool. export is_op (string char) => //{ switch char '+' => true '-' => true '*' => true '/' => true '^' => true '%' => true // booleans '==' => true '!=' => true '>=' => true '<=' => true '>' => true '<' => true 'and' => true 'or' => true => false //} // @function Check if char is alphabet. // @param char string, 1 character string. // @returns bool. export is_alpha (string char) => //{ switch char 'a' => true 'b' => true 'c' => true 'd' => true 'e' => true 'f' => true 'g' => true 'h' => true 'i' => true 'j' => true 'k' => true 'l' => true 'm' => true 'n' => true 'o' => true 'p' => true 'q' => true 'r' => true 's' => true 't' => true 'u' => true 'v' => true 'w' => true 'x' => true 'y' => true 'z' => true => false //} // @function convert a single char string into valid number. // @param char string, 1 character string. // @returns float. export number (string char) => //{ switch char '0' => 0 '1' => 1 '2' => 2 '3' => 3 '4' => 4 '5' => 5 '6' => 6 '7' => 7 '8' => 8 '9' => 9 => na //} // @function boolean 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. export boolean_operator (string op, float left, float right) => //{ switch op '==' => op.equal(left, right) '!=' => op.not_equal(left, right) '>=' => op.over_equal(left, right) '<=' => op.under_equal(left, right) '>' => op.over(left, right) '<' => op.under(left, right) 'and' => op.and_(left, right) 'or' => op.or_(left, right) => na //} // @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. export operator (string op, float left, float right) => //{ switch op '+' => op.add(left, right) '-' => op.subtract(left, right) '*' => op.multiply(left, right) '/' => op.divide(left, right) '^' => math.pow(left, right) '%' => op.remainder(left, right) // booleans '==' => op.equal(left, right) ? 1 : 0 '!=' => op.not_equal(left, right) ? 1 : 0 '>=' => op.over_equal(left, right) ? 1 : 0 '<=' => op.under_equal(left, right) ? 1 : 0 '>' => op.over(left, right) ? 1 : 0 '<' => op.under(left, right) ? 1 : 0 'and' => op.and_(left, right) ? 1 : 0 'or' => op.or_(left, right) ? 1 : 0 => na //} // @function level of precedence of operator. // @param op string, operator 1 char string. // @returns int. export operator_precedence (string op) => //{ switch op '+' => 3 '-' => 3 '*' => 4 '/' => 4 '^' => 5 '%' => 4 // booleans '==' => 2 '!=' => 2 '>=' => 2 '<=' => 2 '>' => 2 '<' => 2 'and' => 1 'or' => 1 => 0 //} // @function level of precedence of operator. // @param op string, operator 1 char string. // @returns int. export boolean_operator_precedence (string op) => //{ switch op '==' => 2 '!=' => 2 '>=' => 2 '<=' => 2 '>' => 2 '<' => 2 'and' => 1 'or' => 1 => 0 //} // @function Aggregates words, numbers and operators into one. // @param tokens string array, array with split string into character tokens. // @returns string array. export aggregate_words (string[] tokens) => //{ int _size_t = array.size(id=tokens) // switch (_size_t < 1) => runtime.error('StringEvaluation -> aggregate_words(): "tokens" is empty.') // string[] _tokens = array.copy(tokens) for _i = _size_t - 1 to 1 string _current = array.get(_tokens, _i) string _previous = array.get(_tokens, _i-1) //add to number if (str.tonumber(_current) or is_comma(_current)) and (str.tonumber(_previous) or is_comma(_previous)) array.set(_tokens, _i-1, _previous+_current) array.remove(_tokens, _i) // console.queue(__C, str.tostring(_tokens)) if (is_alpha(array.get(str.split(_current, ''), 0)) or is_comma(_current)) and (is_alpha(_previous) or is_comma(_previous)) array.set(_tokens, _i-1, _previous+_current) array.remove(_tokens, _i) // console.queue(__C, str.tostring(_tokens)) if (is_op_component(array.get(str.split(_current, ''), 0))) and (is_op_component(_previous)) array.set(_tokens, _i-1, _previous+_current) array.remove(_tokens, _i) // console.queue(__C, str.tostring(_tokens)) _tokens // aggregate_words(str.split('123 a 321 bb cc 123. a .123 + 1.23 - 12.3 | .a | b. | a.b', '')) //} // @function Evaluate a string to clean up and retrieve only used chars // @param _str string, arithmetic operations in a string. // @returns string array, evaluated array. export cleanup (string _str) => //{ // remove spaces: _unspaced = str.replace_all(source=_str, target=' ', replacement='') // aggregate numbers and words: _T0 = aggregate_words(str.split(_unspaced, '')) // // adds ( ) + - / * characters: // join digit sequences into 1 whole number: _T1 = array.new_string(0) string _saved_expression = '' for _i = 0 to array.size(id=_T0)-1 _state = 0 _current = array.get(id=_T0, index=_i) if _current == '(' or _current == ')' if _saved_expression != '' array.push(id=_T1, value=_saved_expression) array.push(id=_T1, value=_current) _saved_expression := '' _state := 0 if (not na(operator(_current, 1, 1))) if _saved_expression != '' array.push(id=_T1, value=_saved_expression) array.push(id=_T1, value=_current) _saved_expression := '' _state := 0 // save words: if _state <= 0 and na(str.tonumber(_saved_expression)) and is_alpha(_current) _saved_expression += _current _state := -1 // save numbers: if _state >= 0 and (not na(number(_current)) or is_comma(_current)) _saved_expression += _current _state := 1 array.push(id=_T1, value=_saved_expression) _T1 //{ usage: // cleanup_a = '1+ 66* 7/2^2 %5 ' // cleanup_b = '0 > 1 and 1> 0 >= 2 <= 1 or 1 == 0 != 1' // console.queue_one(__C, str.format('cleanup "{0}": "{1}"', cleanup_a, str.tostring(cleanup(cleanup_a)))) // console.queue_one(__C, str.format('cleanup "{0}": "{1}"', cleanup_b, str.tostring(cleanup(cleanup_b)))) //} // @function uses Shunting-Yard algorithm to generate a RPN (Reverse Polish notation) // array of strings from a array of strings containing arithmetic notation. // ex:.. '[3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3]' --> '[3 4 2 * 1 5 - 2 3 ^ ^ / +]' // @param tokens string array, array with arithmetic notation. // @returns export generate_rpn (string[] tokens)=> //{ int _size = array.size(id=tokens) if _size < 1 runtime.error('StringEvaluation -> generate_rpn(): "tokens" is empty.') string[] _S = array.new_string(na) else _opstack = array.new_string(size=0) _output = array.new_string(size=0) for _i = 0 to _size-1 string _current_token = array.get(id=tokens, index=_i) _current_arrified = str.split(_current_token, '') int _current_size = array.size(id=_current_arrified) if not na(number(array.get(id=_current_arrified, index=0))) array.push(id=_output, value=_current_token) else if _current_token == '(' array.push(id=_opstack, value=_current_token) else if _current_token == ')' int _size_stack = array.size(id=_opstack) if _size_stack > 0 for _j = _size_stack-1 to 0 string _op = array.pop(id=_opstack) if _op == '(' break else array.push(id=_output, value=_op) else if is_op(_current_token) int _size_stack = array.size(id=_opstack) if _size_stack > 0 for _j = _size_stack-1 to 0 string _op = array.pop(id=_opstack) int _op_precedence = operator_precedence(_op) int _token_precedence = operator_precedence(_current_token) if _op_precedence > _token_precedence or (_op_precedence == _token_precedence and _op != '^') array.push(id=_output, value=_op) else array.push(id=_opstack, value=_op) break array.push(id=_opstack, value=_current_token) int _size_stack = array.size(id=_opstack) if _size_stack > 0 for _i = _size_stack-1 to 0 string _op = array.pop(id=_opstack) if _op == '(' runtime.error('StringEvaluation -> generate_rpn(): mismatched parentesis!.') else array.push(id=_output, value=_op) _output //{ usage: // if barstate.islastconfirmedhistory // // label.new(bar_index, 0.0, str.tostring(generate_rpn(cleanup('1+ 66* 7/2^2 %5 ')))) // label.new(bar_index, 0.0, str.tostring(generate_rpn(cleanup('1 == 1')))) //{ reference: // https://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm // https://en.wikipedia.org/wiki/Shunting-yard_algorithm // https://brilliant.org/wiki/shunting-yard-algorithm/ //}}} // @function evaluate a RPN (Reverse Polish notation) array of strings. // ex:.. 3 4 2 * 1 5 - 2 3 ^ ^ / + //| @param tokens string array, RPN ordered tokens, ex(['3', '4', '2', '1', '5', '2', '3', '*', '-', '^', '^', '/', '+']). //| @returns float, solution. export parse_rpn (string[] tokens) => //{ int _size = array.size(id=tokens) if _size < 1 runtime.error('StringEvaluation -> generate_rpn(): "tokens" is empty.') float(na) else float _solution = na _stack = array.new_float() for _i = 0 to _size-1 string _token = array.get(id=tokens, index=_i) float _number = str.tonumber(_token) if not na(_number)// array.push(id=_stack, value=_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) float _op = operator(_token, o1, o2) array.push(id=_stack, value=_op) else runtime.error('StringEvaluation -> generate_rpn(): unrecognized operator: (' + _token + ' ).') _solution := array.pop(id=_stack) _solution //{ usage: // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, str.tostring(parse_rpn(generate_rpn(cleanup('((10+ 10 *30/20-50)%10)^2'))))) //{ reference: // https://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm //}}} // @function evaluate a string with references to a array of arguments. //| @param tokens 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 float, solution. export eval (string tokens, float[] arguments) => //{ int _size_a = array.size(id=arguments) if _size_a < 1 runtime.error('StringEvaluation -> generate_rpn(): "arguments" is empty.') float(na) else string[] _tokens = generate_rpn(cleanup(tokens)) int _size_t = array.size(id=_tokens) if _size_t < 1 runtime.error('StringEvaluation -> generate_rpn(): "tokens" is empty.') float(na) else // calculate solution: float _solution = na _stack = array.new_float() 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=array.get(id=arguments, index=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) float _op = operator(_token, o1, o2) array.push(id=_stack, value=_op) else runtime.error('StringEvaluation -> generate_rpn(): unrecognized operator: (' + _token + ' ).') _solution := array.pop(id=_stack) _solution //{ usage: console.queue_one(__C, str.format('(((10+ 10 *30/20-50)%10)^2) = {0}', str.tostring(eval('(((0+ 0 *2/1-3)%0)^4)', array.from(10.0, 20, 30, 50, 2))))) console.queue_one(__C, str.format('20 > 10 = {0}', str.tostring(eval('1 > 0', array.from(10.0, 20, 30, 50, 2))))) console.queue_one(__C, str.format('20 >= 20 = {0}', str.tostring(eval('1 >= 1', array.from(10.0, 20, 30, 50, 2))))) console.queue_one(__C, str.format('20 and 10 = {0}', str.tostring(eval('1 and 0', array.from(10.0, 20, 30, 50, 2))))) console.queue_one(__C, str.format('20 or 10 = {0}', str.tostring(eval('1 or 0', array.from(10.0, 20, 30, 50, 2))))) console.queue_one(__C, str.format('((20 <= 10 or 20 > 10) + (20 > 10)) * 25.33 = {0}', str.tostring(eval('((1 <= 0 or 1 > 0) + (1 > 0)) * 3', array.from(10.0, 20, 30, 25.33, 2))))) //{ reference: // https://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm //}}} console.update(__T, __C)
ArrayOperationsFloat
https://www.tradingview.com/script/jOemC9t7-ArrayOperationsFloat/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Array Basic Operations for Integers library(title='ArrayOperationsFloat') import RicardoSantos/MathExtension/1 as me // @function Adds sample_b to sample_a and returns a new array. // @param sample_a values to be added to. // @param sample_b values to add. // @returns float array with added results. export add(float[] sample_a, float[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 float[] _output = array.new_float(size=_size_a) for _i = 0 to _size_a - 1 float _ai = array.get(id=sample_a, index=_i) float _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_bi + _ai) _output //{ usage: // if barstate.islastconfirmedhistory // float[] a = array.from(1.1, 2.2, 3.3), float[] b = array.from(5.5, 6.6, 1.1) // float[] c = add(sample_a=a, sample_b=b) // [6.6, 8.8, 4.4] // label.new(bar_index, 0.0, str.format('{0}\n+\n{1}\n=\n{2}', str.tostring(a, '#.###'), str.tostring(b, '#.###'), str.tostring(c, '#.###'))) //}} // @function subtracts sample_b from sample_a and returns a new array. // @param sample_a values to be subtracted from. // @param sample_b values to subtract. // @returns float array with subtracted results. export subtract(float[] sample_a, float[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 float[] _output = array.new_float(size=_size_a) for _i = 0 to _size_a - 1 float _ai = array.get(id=sample_a, index=_i) float _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai - _bi) _output //{ usage: // if barstate.islastconfirmedhistory // float[] a = array.from(1.1, 2.2, 3.3), float[] b = array.from(5.5, 6.6, 1.1) // float[] c = subtract(sample_a=a, sample_b=b) // [-4.4, -4.4, 2.2] // label.new(bar_index, 0.0, str.format('{0}\n-\n{1}\n=\n{2}', str.tostring(a, '#.###'), str.tostring(b, '#.###'), str.tostring(c, '#.###'))) //}} // @function multiply sample_a with sample_b and returns a new array. // @param sample_a values to multiply. // @param sample_b values to multiply with. // @returns float array with multiplied results. export multiply(float[] sample_a, float[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 float[] _output = array.new_float(size=_size_a) for _i = 0 to _size_a - 1 float _ai = array.get(id=sample_a, index=_i) float _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai * _bi) _output //{ usage: // if barstate.islastconfirmedhistory // float[] a = array.from(1.1, 2.2, 3.3), float[] b = array.from(5.5) // float[] c = multiply(sample_a=a, sample_b=b) // [6.05, 12.1, 18.15] // label.new(bar_index, 0.0, str.format('{0}\n*\n{1}\n=\n{2}', str.tostring(a, '#.###'), str.tostring(b, '#.###'), str.tostring(c, '#.###'))) //}} // @function divide sample_a with sample_b and returns a new array. // @param sample_a values to divide. // @param sample_b values to divide with. // @returns float array with divided results. export divide(float[] sample_a, float[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 float[] _output = array.new_float(size=_size_a) for _i = 0 to _size_a - 1 float _ai = array.get(id=sample_a, index=_i) float _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai / _bi) _output //{ usage: // if barstate.islastconfirmedhistory // float[] a = array.from(9.6, 3.5, 15.25), float[] b = array.from(5.6, 2.12) // float[] c = divide(sample_a=a, sample_b=b) // [1.714, 1.651, 2.723] // label.new(bar_index, 0.0, str.format('{0}\n/\n{1}\n=\n{2}', str.tostring(a, '#.###'), str.tostring(b, '#.###'), str.tostring(c, '#.###'))) //}} // @function rise sample_a to the power of sample_b and returns a new array. // @param sample_a base values to raise. // @param sample_b values of exponents. // @returns float array with raised results. export power(float[] sample_a, float[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 float[] _output = array.new_float(size=_size_a) for _i = 0 to _size_a - 1 float _ai = array.get(id=sample_a, index=_i) float _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=math.pow(_ai, _bi)) _output //{ usage: // if barstate.islastconfirmedhistory // float[] a = array.from(2.2, 3.5, 1.1), float[] b = array.from(5.1, 2.3) // float[] c = power(sample_a=a, sample_b=b) // [55.764, 17.838, 1.626] // label.new(bar_index, 0.0, str.format('{0}\n^\n{1}\n=\n{2}', str.tostring(a, '#.###'), str.tostring(b, '#.###'), str.tostring(c, '#.###'))) //}} // @function float remainder of sample_a under the dividend sample_b and returns a new array. // @param sample_a values of quotients. // @param sample_b values of dividends. // @returns float array with remainder results. export remainder(float[] sample_a, float[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 float[] _output = array.new_float(size=_size_a) for _i = 0 to _size_a - 1 float _ai = array.get(id=sample_a, index=_i) float _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=me.fmod(numerator=_ai, denominator=_bi)) _output //{ usage: // if barstate.islastconfirmedhistory // float[] a = array.from(0.9,0.5,15.4), float[] b = array.from(0.5,0.2) // float[] c = remainder(sample_a=a, sample_b=b) // [0.4, 0.1, 0.4] // label.new(bar_index, 0.0, str.format('{0}\n^\n{1}\n=\n{2}', str.tostring(a, '#.###'), str.tostring(b, '#.###'), str.tostring(c, '#.###'))) //}}
BinaryDecimalConversion
https://www.tradingview.com/script/4xSPNl0X-BinaryDecimalConversion/
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 Converts decimal to and from binary. library(title='BinaryDecimalConversion') // to_binary () { // @function convert integer to binary string // @param number int, value to convert. // @returns string export to_binary(int number) => string _str = '' int _num = number while _num >= 1 int _rem = _num % 2 _str := (_rem == 0 ? '0' : '1') + _str _num := (_num - _rem) / 2 _str // usage: // st = to_binary(3232) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, st) // 110010100000 // } // to_decimal () { // @function Converts a binary in a string to decimal. // @param binary string, binary number in a string. // @returns int export to_decimal (string binary) => //{ int _val = 0 int _b = int(str.tonumber(binary)) int i = 0 while _b > 0 int _rem = _b % 10 _val += int(_rem * math.pow(2, i)) _b := (_b - _rem) / 10 i += 1 _val // usage: // plot(to_decimal('110010100000')) // 3232 // } // leftshift_logical () { // reference: // https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python // @function Shift the bits of an integer to the left. // @param x int . Value to shift. // @param n int . Number of zeros to append to x. // @returns int. export leftshift_logical(int x, int n=1) => int _n = math.max(1, n) array<string> _bin = str.split(to_binary(x), '') for _i = 1 to _n array.shift(_bin) array.push(_bin, '0') to_decimal(_bin.join('')) // lls = leftshift_logical(10,2) // plot(lls) // 8 // } // rightshift_logical () { // reference: // https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python // @function Shift the bits of an integer to the right. // @param x int . Value to shift. // @param n int . Number of bits to remove at the right of x. // @returns int. export rightshift_logical (int x, int n=1) => int _n = math.max(1, n) array<string> _bin = str.split(to_binary(x), '') for _i = 1 to _n _bin.pop() _bin.unshift('0') to_decimal(_bin.join('')) // rls = rightshift_logical(10,2) // plot(rls) // 2 // } // leftshift_arithmetic () { // reference: // https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python // @function Shift the bits of an integer to the left. // @param x int . Value to shift. // @param n int . Number of zeros to append to x. // @returns int. export leftshift_arithmetic (int x, int n=1) => leftshift_logical(x, n) // las = leftshift_arithmetic(10,2) // plot(las) // 8 // } // rightshift_arithmetic () { // reference: // https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python // @function Shift the bits of an integer to the right. // @param x int . Value to shift. // @param n int . Number of bits to remove at the right of x. // @returns int. export rightshift_arithmetic (int x, int n=1) => int _n = math.max(1, n) array<string> _bin = str.split(to_binary(x), '') for _i = 1 to _n string _tmp = _bin.get(0) _bin.pop() _bin.unshift(_tmp) to_decimal(_bin.join('')) // ras = rightshift_arithmetic(10,2) // plot(ras) // 14 // }
ArrayOperationsInt
https://www.tradingview.com/script/MQkPveIL-ArrayOperationsInt/
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 Array Basic Operations for Integers library(title='ArrayOperationsInt') // @function Adds sample_b to sample_a and returns a new array. // @param sample_a values to be added to. // @param sample_b values to add. // @returns int array with added results. export add(int[] sample_a, int[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 int[] _output = array.new_int(size=_size_a) for _i = 0 to _size_a - 1 int _ai = array.get(id=sample_a, index=_i) int _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_bi + _ai) _output //{ usage: // if barstate.islastconfirmedhistory // int[] a = array.from(1,2,3), int[] b = array.from(5,6,1) // int[] c = add(sample_a=a, sample_b=b) // [6, 8, 4] // label.new(bar_index, 0.0, str.format('{0}\n+\n{1}\n=\n{2}', str.tostring(a, '#'), str.tostring(b, '#'), str.tostring(c, '#'))) //}} // @function subtracts sample_b from sample_a and returns a new array. // @param sample_a values to be subtracted from. // @param sample_b values to subtract. // @returns int array with subtracted results. export subtract(int[] sample_a, int[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 int[] _output = array.new_int(size=_size_a) for _i = 0 to _size_a - 1 int _ai = array.get(id=sample_a, index=_i) int _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=_ai - _bi) _output //{ usage: // if barstate.islastconfirmedhistory // int[] a = array.from(1,2,3), int[] b = array.from(5,6,1) // int[] c = subtract(sample_a=a, sample_b=b) // [-4, -4, 2] // label.new(bar_index, 0.0, str.format('{0}\n-\n{1}\n=\n{2}', str.tostring(a, '#'), str.tostring(b, '#'), str.tostring(c, '#'))) //}} // @function multiply sample_a with sample_b and returns a new array. // @param sample_a values to multiply. // @param sample_b values to multiply with. // @returns int array with multiplied results. export multiply(int[] sample_a, int[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 int[] _output = array.new_int(size=_size_a) for _i = 0 to _size_a - 1 int _ai = array.get(id=sample_a, index=_i) int _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=int(_ai * _bi)) _output //{ usage: // if barstate.islastconfirmedhistory // int[] a = array.from(1,2,3), int[] b = array.from(5) // int[] c = multiply(sample_a=a, sample_b=b) // [5, 10, 15] // label.new(bar_index, 0.0, str.format('{0}\n*\n{1}\n=\n{2}', str.tostring(a, '#'), str.tostring(b, '#'), str.tostring(c, '#'))) //}} // @function divide sample_a with sample_b and returns a new array. // @param sample_a values to divide. // @param sample_b values to divide with. // @returns int array with divided results. export divide(int[] sample_a, int[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 int[] _output = array.new_int(size=_size_a) for _i = 0 to _size_a - 1 int _ai = array.get(id=sample_a, index=_i) int _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=int(_ai / _bi)) _output //{ usage: // if barstate.islastconfirmedhistory // int[] a = array.from(9,5,15), int[] b = array.from(5,2) // int[] c = divide(sample_a=a, sample_b=b) // [1, 2, 3] // label.new(bar_index, 0.0, str.format('{0}\n/\n{1}\n=\n{2}', str.tostring(a, '#'), str.tostring(b, '#'), str.tostring(c, '#'))) //}} // @function rise sample_a to the power of sample_b and returns a new array. // @param sample_a base values to raise. // @param sample_b values of exponents. // @returns int array with raised results. export power(int[] sample_a, int[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 int[] _output = array.new_int(size=_size_a) for _i = 0 to _size_a - 1 int _ai = array.get(id=sample_a, index=_i) int _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=int(math.pow(_ai, _bi))) _output //{ usage: // if barstate.islastconfirmedhistory // int[] a = array.from(9,5,15), int[] b = array.from(5,2) // int[] c = power(sample_a=a, sample_b=b) // [59049, 25, 759375] // label.new(bar_index, 0.0, str.format('{0}\n^\n{1}\n=\n{2}', str.tostring(a, '#'), str.tostring(b, '#'), str.tostring(c, '#'))) //}} // @function integer remainder of sample_a under the dividend sample_b and returns a new array. // @param sample_a values of quotients. // @param sample_b values of dividends. // @returns int array with remainder results. export remainder(int[] sample_a, int[] sample_b) => //{ int _size_a = array.size(id=sample_a) if _size_a > 0 int _size_b = array.size(id=sample_b) if _size_b > 0 int[] _output = array.new_int(size=_size_a) for _i = 0 to _size_a - 1 int _ai = array.get(id=sample_a, index=_i) int _bi = array.get(id=sample_b, index=_i % _size_b) array.set(id=_output, index=_i, value=int(_ai % _bi)) _output //{ usage: // if barstate.islastconfirmedhistory // int[] a = array.from(9,5,15), int[] b = array.from(5,2) // int[] c = power(sample_a=a, sample_b=b) // [59049, 25, 759375] // label.new(bar_index, 0.0, str.format('{0}\n^\n{1}\n=\n{2}', str.tostring(a, '#'), str.tostring(b, '#'), str.tostring(c, '#'))) //}}
FunctionBestFitFrequency
https://www.tradingview.com/script/HRNWDI6a-FunctionBestFitFrequency/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description TODO: add library description here library(title='FunctionBestFitFrequency') import RicardoSantos/ArrayGenerate/1 as ag // @function Moving Average values for selected data. // @param sample float array, sample data values. // @param length int, length to smooth the data. // @param ommit_initial bool, default=true, ommit values at the start of the data under the length. // @param fillna string, default='na', options='na', '0', 'avg' // @returns float array // errors: // length > sample size "Canot call array methods when id of array is na." export array_moving_average (float[] sample, int length, bool ommit_initial=true, string fillna='na') => //{ int _size = array.size(id=sample) if _size > 1 and _size > length float[] _ma = array.copy(id=sample) float _nav = float(na) if fillna == '0' _nav := 0 if fillna == 'avg' _nav := array.avg(id=sample) float[] _ma_total = array.new_float(0) for _i = 0 to _size-1 array.push(id=_ma_total, value=array.get(id=sample, index=_i)) if array.size(id=_ma_total) > length array.shift(id=_ma_total) if ommit_initial and _i < length array.set(id=_ma, index=_i, value=_nav) else float _avg = array.avg(id=_ma_total) array.set(id=_ma, index=_i, value=_avg) _ma //{ // usage: // int length = input.int(defval=6) // bool ommit_init = input.bool(true) // string fill_na = input.string(defval='na', options=['na', '0', 'avg']) // rngs0 = array.from(79, 47, 5, 82, 31, 77, 58, 45, 15, 76, 76, 33, 47, 8, 1, 14, 65, 16, 16, 10, 60) // string tex = str.format('S: {0}', rngs0) // for _i = 2 to length // tex += str.format('\n{0}: {1}', _i, str.tostring(array_moving_average(rngs0, _i, ommit_init, fill_na), '#.##')) // if barstate.islast // label.new(bar_index, 0.0, tex) //}} // @function Search a frequency range for the fairest moving average frequency. // @param sample float array, sample data to based the moving averages. // @param start int lowest frequency. // @param end int highest frequency. // @returns tuple with (int frequency, float percentage) export best_fit_frequency (float[] sample, int start, int end) => //{ int _size = array.size(id=sample) if _size > 0 and end < _size and start > 0 and start <= end int _best = 0 float _percent = -999 for _freq = start to end float[] _avg = array_moving_average(sample=sample, length=_freq, ommit_initial=false, fillna='avg') float _esum = 0.0 for _i = 0 to _size-1 float _erri = array.get(id=sample, index=_i) - array.get(id=_avg, index=_i) if _erri >= 0 _esum += 1 float _tentative = -0.5 + (_esum / (_size-1)) if math.abs(_tentative) < math.abs(_percent) _best := _freq _percent := _tentative [_best, _percent] //{ usage: float[] sample = ag.sequence_from_series(src=close, length=input(100), shift=0, direction_forward=true) [best, percent] = best_fit_frequency(sample, input(2), input(20)) plot(best) plot(percent) //}}
ta
https://www.tradingview.com/script/BICzyhq0-ta/
TradingView
https://www.tradingview.com/u/TradingView/
184
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/ // © TradingView //@version=5 library("ta") // ta Library // v7, 2023.11.02 // 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 TradingView/RelativeValue/2 as TVrv // This library exports the following functions: // • ao: Awesome Oscillator // • aroon: Aroon Oscillator // • atr2: Average True Range (Alternate Version) // • cagr: Compound Annual Growth Rate // • changePercent: Calculate percentage change // • coppock: Coppock Curve // • dema: Double Exponential Moving Average // • dema2: Double Exponential Moving Average (Alternate Version) // • dm: Demarker Indicator // • donchian: Donchian Channel // • ema2: Exponential Moving Average (Alternate Version) // • eom: Ease of Movement // • frama: Fractal Adaptive Moving Average // • ft: Fisher Transform // • highestSince: Highest value since condition // • ht: Hilbert Transform function // • ichimoku: Ichimoku Cloud // • ift: Inverse Fisher Transform // • kvo: Klinger Volume Oscillator // • lowestSince: Lowest value since condition // • relativeVolume: Compare volume to its historical average // • rma2: Rolling Moving Average (Alternate Version) // • rms: Root Mean Square // • rwi: Random Walk Index // • stc: Schaff Trend Cycle // • stochFull: Full Stochastic Oscillator // • stochRsi: Stochastic RSI // • supertrend: SuperTrend Indicator // • supertrend2: SuperTrend Indicator (Alternate Version) // • szo: Sentiment Zone Oscillator // • t3: Tilson Moving Average (T3) // • t3Alt: Tilson Moving Average (T3 Alternate Version) // • tema: Triple Exponential Moving Average // • tema2: Triple Exponential Moving Average (Alternate Version) // • trima: Triangular Moving Average // • trix: TRIX indicator // • uo: Ultimate Oscillator // • vhf: Vertical Horizontal Filter // • vi: Vortex Indicator // • vStop: Volatility Stop // • vStop2: Volatility Stop (Alternate Version) // • vzo: Volume Zone Oscillator // • williamsFractal: Williams' Fractal // • wpo: Wave Period Oscillator // @function Calculates the dynamic Exponentially Weighted Moving Average used in // `atr2()`, `ema2()`, `frama()`, and `rma2()`. // @param source (series int/float) Series of values to process. // @param alpha (series int/float) The smoothing parameter of the filter. // @returns The dynamic exponentially weighted moving average value. ewma(series float source, series float alpha) => float result = na result := alpha * source + (1.0 - alpha) * nz(result[1], source) // @function Calculates the value of the Awesome Oscillator. // @param source (series int/float) Series of values to process. // @param shortLength (simple int) Number of bars for the fast moving average (length). // @param longLength (simple int) Number of bars for the slow moving average (length). // @returns (float) The oscillator value. export ao(series float source = hl2, simple int shortLength = 5, simple int longLength = 34) => float result = ta.sma(source, shortLength) - ta.sma(source, longLength) // @function Calculates the values of the Aroon indicator. // @param length (simple int) Number of bars (length). // @returns ([float, float]) A tuple of the Aroon-Up and Aroon-Down values. export aroon(simple int length) => float aroonDown = 100 * (ta.lowestbars(low, length) + length) / length float aroonUp = 100 * (ta.highestbars(high, length) + length) / length [aroonUp, aroonDown] // @function An alternate ATR function to the `ta.atr()` built-in, which allows a "series float" // `length` argument. // @param length (series int/float) Length for the smoothing parameter calculation. // @returns (float) The ATR value. export atr2(series float length) => float alpha = 1.0 / math.max(1.0, length) float result = ewma(ta.tr(true), alpha) // @function Calculates the "Compound Annual Growth Rate" between two points in time. // @param entryTime (series int) The starting timestamp. // @param entryPrice (series int/float) The starting point's price. // @param exitTime (series int) The ending timestamp. // @param exitPrice (series int/float) The ending point's price. // @returns (float) CAGR in % (50 is 50%). Returns `na` if there is not >=1D between `entryTime` and // `exitTime`, or until the two time points have not been reached by the script. export cagr(series int entryTime, series float entryPrice, series int exitTime, series float exitPrice) => int MS_IN_ONE_DAY = 24 * 60 * 60 * 1000 float daysBetween = (exitTime - entryTime) / MS_IN_ONE_DAY float result = if daysBetween >= 1 and not (na(entryPrice) or na(exitPrice)) float years = daysBetween / 365. float rate = exitPrice / entryPrice 100 * (math.pow(rate, 1 / years) - 1) else na // @function Calculates the percentage difference between two distinct values. // @param newValue (series int/float) The current value. // @param oldValue (series int/float) The previous value. // @returns (float) The percentage change from the `oldValue` to the `newValue`. export changePercent(series float newValue, series float oldValue) => float result = 100 * (newValue - oldValue) / oldValue // @function Calculates the value of the Coppock Curve indicator. // @param source (series int/float) Series of values to process. // @param longLength (simple int) Number of bars for the fast ROC value (length). // @param shortLength (simple int) Number of bars for the slow ROC value (length). // @param smoothLength (simple int) Number of bars for the weigted moving average value (length). // @returns (float) The oscillator value. export coppock(series float source, simple int longLength, simple int shortLength, simple int smoothLength) => float result = ta.wma(ta.roc(source, longLength) + ta.roc(source, shortLength), smoothLength) // @function Calculates the value of the Double Exponential Moving Average (DEMA). // @param source (series int/float) Series of values to process. // @param length (simple int) Length for the smoothing parameter calculation. // @returns (float) The double exponentially weighted moving average of the `source`. export dema(series float source, simple int length) => float ema1 = ta.ema(source, length) float ema2 = ta.ema(ema1, length) float result = 2 * ema1 - ema2 // @function An alternate EMA function to the `ta.ema()` built-in, which allows a "series float" // `length` argument. // @param source (series int/float) Series of values to process. // @param length (series int/float) Length for the smoothing parameter calculation. // @returns (float) The exponentially weighted moving average of the `source`. export ema2(series float source, series float length) => float alpha = 2.0 / (math.max(1.0, length) + 1.0) float result = ewma(source, alpha) // @function An alternate Double Exponential Moving Average (DEMA) function to `dema()`, which allows a // "series float" `length` argument. // @param source (series int/float) Series of values to process. // @param length (series int/float) Length for the smoothing parameter calculation. // @returns (float) The double exponentially weighted moving average of the `source`. export dema2(series float source, series float length) => float ema1 = ema2(source, length) float ema2 = ema2(ema1, length) float result = 2 * ema1 - ema2 // @function Calculates the value of the "Demarker" indicator. // "DeMark®" is a registered trademark of DeMark Analytics, LLC. This code is neither // endorsed, nor sponsored, nor affiliated with them. // @param length (simple int) Number of bars (length). // @returns (float) The oscillator value. export dm(simple int length) => float demax = math.max(ta.change(high), 0) float demin = -math.min(ta.change(low), 0) float result = ta.sma(demax, length) / (ta.sma(demax, length) + ta.sma(demin, length)) // @function Calculates the values of a Donchian Channel using `high` and `low` over a given `length`. // @param length (series int) Number of bars (length). // @returns ([float, float, float]) A tuple containing the channel high, low, and median, respectively. export donchian(series int length) => float highest = ta.highest(length) float lowest = ta.lowest(length) [highest, lowest, math.avg(highest, lowest)] // @function Calculates the value of the Ease of Movement indicator. // @param length (simple int) Number of bars (length). // @param div (simple int) Divisor used for normalzing values. Optional. The default is 10000. // @returns (float) The oscillator value. export eom(simple int length, simple int div = 10000) => float result = ta.sma(div * ta.change(hl2) * (high - low) / volume, length) // @function The Fractal Adaptive Moving Average (FRAMA), developed by John Ehlers, is an adaptive // moving average that dynamically adjusts its lookback period based on fractal geometry. // @param source (series int/float) Series of values to process. // @param length (series int) Number of bars (length). // @returns (float) The fractal adaptive moving average of the `source`. export frama(series float source, series int length) => int len = math.round(length / 2) float hh = ta.highest(len) float ll = ta.lowest(len) float n1 = (hh - ll) / len float n2 = (hh[len] - ll[len]) / len float n3 = (ta.highest(length) - ta.lowest(length)) / length float D = math.log((n1 + n2) / n3) / math.log(2) float alpha = math.exp(-4.6 * (D - 1)) float result = ewma(source, alpha) // @function Calculates the value of the Fisher Transform indicator. // @param source (series int/float) Series of values to process. // @param length (simple int) Number of bars (length). // @returns (float) The oscillator value. export ft(series float source, simple int length) => float value1 = 0.0 float fish = 0.0 float hh = ta.highest(source, length) float ll = ta.lowest(source, length) value1 := 0.66 * ((source - ll) / (hh - ll) - 0.5) + 0.67 * nz(value1[1]) float value2 = value1 > 0.99 ? 0.999 : value1 < -0.99 ? -0.999 : value1 fish := 0.5 * math.log((1 + value2) / (1 - value2)) + 0.5 * nz(fish[1]) float result = fish // @function Tracks the highest value of a series since the last occurrence of a condition. // @param cond (series bool) A condition which, when `true`, resets the tracking of the highest `source`. // @param source (series int/float) Series of values to process. Optional. The default is `high`. // @returns (float) The highest `source` value since the last time the `cond` was `true`. export highestSince(series bool cond, series float source = high) => var float result = na if cond result := source result := math.max(nz(source, result), nz(result, source)) // @function Calculates the value of the Hilbert Transform indicator. // @param source (series int/float) Series of values to process. // @returns (float) The oscillator value. export ht(series float source) => float result = 0.0962 * source + 0.5769 * nz(source[2]) - 0.5769 * nz(source[4]) - 0.0962 * nz(source[6]) // @function Calculates the midpoint between the highest `high` and lowest `low` over `length` bars. // @param length (series int) Number of bars (length). // @returns The midpoint of the data. midpoint(series int length) => float result = math.avg(ta.highest(length), ta.lowest(length)) // @function Calculates values of the Ichimoku Cloud indicator, including tenkan, kijun, senkouSpan1, // senkouSpan2, and chikou. // NOTE: offsets forward or backward can be done using the `offset` argument in `plot()`. // @param conLength (series int) Length for the Conversion Line (Tenkan). The default is 9 periods, which // returns the mid-point of the 9 period Donchian Channel. // @param baseLength (series int) Length for the Base Line (Kijun-sen). The default is 26 periods, which returns // the mid-point of the 26 period Donchian Channel. // @param senkouLength (series int) Length for the Senkou Span 2 (Leading Span B). The default is 52 periods, // which returns the mid-point of the 52 period Donchian Channel. // @returns ([float, float, float, float, float]) A tuple of the Tenkan, Kijun, Senkou Span 1, // Senkou Span 2, and Chikou Span values. NOTE: by default, the senkouSpan1 and senkouSpan2 // should be plotted 26 periods in the future, and the Chikou Span plotted 26 days in the past. export ichimoku(series int conLength = 9, series int baseLength = 26, series int senkouLength = 52) => float tenkan = midpoint(conLength) float kijun = midpoint(baseLength) float senkouSpan1 = math.avg(tenkan, kijun) float senkouSpan2 = midpoint(senkouLength) float chikou = close [tenkan, kijun, senkouSpan1, senkouSpan2, chikou] // @function Calculates the value of the Inverse Fisher Transform indicator. // @param source (series int/float) Series of values to process. // @returns (float) The oscillator value. export ift(series float source) => float exp = math.exp(2.0 * source) float result = (exp - 1.0) / (1.0 + exp) // @function Calculates the values of the Klinger Volume Oscillator. // @param fastLen (simple int) Length for the fast moving average smoothing parameter calculation. // @param slowLen (simple int) Length for the slow moving average smoothing parameter calculation. // @param trigLen (simple int) Length for the trigger moving average smoothing parameter calculation. // @returns ([float, float]) A tuple of the KVO value, and the trigger value. export kvo(simple int fastLen, simple int slowLen, simple int trigLen) => float trend = math.sign(ta.change(hlc3)) * volume * 100 float fast = ta.ema(trend, fastLen) float slow = ta.ema(trend, slowLen) float kvo = fast - slow float trigger = ta.ema(kvo, trigLen) [kvo, trigger] // @function Tracks the lowest value of a series since the last occurrence of a condition. // @param cond (series bool) A condition which, when `true`, resets the tracking of the lowest `source`. // @param source (series int/float) Series of values to process. Optional. The default is `low`. // @returns (float) The lowest `source` value since the last time the `cond` was `true`. export lowestSince(series bool cond, series float source = low) => var float result = na if cond result := source result := math.min(nz(source, result), nz(result, source)) // @function The "zone" calculation used in `pzo()` and `vzo()` functions. // @param source (series float) Series of values to process. // @param length (simple int) Length for the smoothing parameter calculation. // @returns (float) The oscillator value. zone(series float source, simple int length) => float result = 100 * nz(ta.ema(math.sign(ta.change(close)) * source, length) / ta.ema(source, length)) // @function Calculates the value of the Price Zone Oscillator. // @param length (simple int) Length for the smoothing parameter calculation. // @returns (float) The oscillator value. export pzo(simple int length) => float result = zone(close, length) // @function Calculates the volume since the last change in the time value from the // `anchorTimeframe`, the historical average volume using bars from past periods // that have the same relative time offset as the current bar from the start of its // period, and the ratio of these volumes. The volume values are cumulative by default, // but can be adjusted to non-accumulated with the `isCumulative` parameter. // @param length (simple int) The number of periods to use for the historical average calculation. // @param anchorTimeframe (simple string) The anchor timeframe used in the calculation. Optional. Default is "D". // @param isCumulative (simple bool) If `true`, the volume values will be accumulated since the start of the last // `anchorTimeframe`. If `false`, values will be used without accumulation. Optional. The // default is `true`. // @param adjustRealtime (simple bool) If `true`, estimates the cumulative value on unclosed bars based on the // data since the last `anchor` condition. Optional. The default is `false`. // @returns ([float, float, float]) A tuple of three float values. The first element is the current // volume. The second is the average of volumes at equivalent time offsets from past // anchors over the specified number of periods. The third is the ratio of the current volume // to the historical average volume. export relativeVolume( simple int length, simple string anchorTimeframe = "D", simple bool isCumulative = true, simple bool adjustRealtime = true ) => bool anchor = timeframe.change(anchorTimeframe) float currVol = isCumulative ? TVrv.calcCumulativeSeries(volume, anchor, adjustRealtime) : volume float pastVol = TVrv.averageAtTime(volume, length, anchorTimeframe, isCumulative) float volRatio = currVol / pastVol [currVol, pastVol, volRatio] // @function An alternate RMA function to the `ta.rma()` built-in, which allows a "series float" // `length` argument. // @param source (series int/float) Series of values to process. // @param length (series int/float) Length for the smoothing parameter calculation. // @returns (float) The rolling moving average of the `source`. export rma2(series float source, series float length) => float alpha = 1.0 / math.max(1.0, length) float result = ewma(source, alpha) // @function Calculates the Root Mean Square of the `source` over the `length`. // @param source (series int/float) Series of values to process. // @param length (series int) Number of bars (length). // @returns (float) The RMS value. export rms(series float source, series int length) => float result = math.sqrt(math.sum(math.pow(source, 2), length) / length) // @function Calculates the values of the Random Walk Index. // @param length (simple int) Lookback and ATR smoothing parameter length. // @returns ([float, float]) A tuple of the `rwiHigh` and `rwiLow` values. export rwi(simple int length) => float divisor = ta.atr(length) * math.sqrt(length) float rwiHigh = (high - nz(low[length])) / divisor float rwiLow = (nz(high[length]) - low) / divisor [rwiHigh, rwiLow] // @function Calculates the value of the Schaff Trend Cycle indicator. // @param source (series int/float) Series of values to process. // @param fast (simple int) Length for the MACD fast smoothing parameter calculation. // @param slow (simple int) Length for the MACD slow smoothing parameter calculation. // @param cycle (simple int) Number of bars for the Stochastic values (length). // @param d1 (simple int) Length for the initial %D smoothing parameter calculation. // @param d2 (simple int) Length for the final %D smoothing parameter calculation. // @returns (float) The oscillator value. export stc(series float source, simple int fast, simple int slow, simple int cycle, simple int d1, simple int d2) => float macd = ta.ema(source, fast) - ta.ema(source, slow) float k = nz(fixnan(ta.stoch(macd, macd, macd, cycle))) float d = ta.ema(k, d1) float kd = nz(fixnan(ta.stoch(d, d, d, cycle))) float stc = ta.ema(kd, d2) float result = math.max(math.min(stc, 100), 0) // @function Calculates the %K and %D values of the Full Stochastic indicator. // @param periodK (simple int) Number of bars for Stochastic calculation. (length). // @param smoothK (simple int) Number of bars for smoothing of the %K value (length). // @param periodD (simple int) Number of bars for smoothing of the %D value (length). // @returns ([float, float]) A tuple of the slow %K and the %D moving average values. export stochFull(simple int periodK, simple int smoothK, simple int periodD) => float k = ta.sma(ta.stoch(close, high, low, periodK), smoothK) float d = ta.sma(k, periodD) [k, d] // @function Calculates the %K and %D values of the Stochastic RSI indicator. // @param lengthRsi (simple int) Length for the RSI smoothing parameter calculation. // @param periodK (simple int) Number of bars for Stochastic calculation. (length). // @param smoothK (simple int) Number of bars for smoothing of the %K value (length). // @param periodD (simple int) Number of bars for smoothing of the %D value (length). // @param source (series int/float) Series of values to process. Optional. The default is `close`. // @returns ([float, float]) A tuple of the slow %K and the %D moving average values. export stochRsi( simple int lengthRsi, simple int periodK, simple int smoothK, simple int periodD, series float source = close ) => float rsi = ta.rsi(source, lengthRsi) float k = ta.sma(ta.stoch(rsi, rsi, rsi, periodK), smoothK) float d = ta.sma(k, periodD) [k, d] // @function Calculates the values of the SuperTrend indicator with the ability to take candle wicks // into account, rather than only the closing price. // @param factor (series int/float) Multiplier for the ATR value. // @param atrLength (simple int) Length for the ATR smoothing parameter calculation. // @param wicks (simple bool) Condition to determine whether to take candle wicks into account when // reversing trend, or to use the close price. Optional. Default is false. // @returns ([float, int]) A tuple of the superTrend value and trend direction. export supertrend(series float factor, simple int atrLength, simple bool wicks = false) => float source = hl2 int direction = na float superTrend = na float atr = ta.atr(atrLength) * factor float upperBand = source + atr float lowerBand = source - atr float highPrice = wicks ? high : close float lowPrice = wicks ? low : close float prevLowerBand = nz(lowerBand[1]) float prevUpperBand = nz(upperBand[1]) lowerBand := lowerBand > prevLowerBand or lowPrice[1] < prevLowerBand ? lowerBand : prevLowerBand upperBand := upperBand < prevUpperBand or highPrice[1] > prevUpperBand ? upperBand : prevUpperBand float prevSuperTrend = superTrend[1] if na(atr[1]) direction := 1 else if prevSuperTrend == prevUpperBand direction := highPrice > upperBand ? -1 : 1 else direction := lowPrice < lowerBand ? 1 : -1 superTrend := direction == -1 ? lowerBand : upperBand [superTrend, direction] // @function An alternate SuperTrend function to `supertrend()`, which allows a "series float" // `atrLength` argument. // @param factor (series int/float) Multiplier for the ATR value. // @param atrLength (series int/float) Length for the ATR smoothing parameter calculation. // @param wicks (simple bool) Condition to determine whether to take candle wicks into account when // reversing trend, or to use the close price. Optional. Default is false. // @returns ([float, int]) A tuple of the superTrend value and trend direction. export supertrend2(series float factor, series float atrLength, simple bool wicks = false) => float source = hl2 int direction = na float superTrend = na float atr = atr2(atrLength) * factor float upperBand = source + atr float lowerBand = source - atr float highPrice = wicks ? high : close float lowPrice = wicks ? low : close float prevLowerBand = nz(lowerBand[1]) float prevUpperBand = nz(upperBand[1]) lowerBand := lowerBand > prevLowerBand or lowPrice[1] < prevLowerBand ? lowerBand : prevLowerBand upperBand := upperBand < prevUpperBand or highPrice[1] > prevUpperBand ? upperBand : prevUpperBand float prevSuperTrend = superTrend[1] if na(atr[1]) direction := 1 else if prevSuperTrend == prevUpperBand direction := highPrice > upperBand ? -1 : 1 else direction := lowPrice < lowerBand ? 1 : -1 superTrend := direction == -1 ? lowerBand : upperBand [superTrend, direction] // @function Calculates the Generalized DEMA (GD) used in the `t3()` function. // @param source (series int/float) Series of values to process. // @param length (simple int) Length for the smoothing parameter calculation. // @param vf (simple float) Volume factor. Affects the responsiveness. // @returns (float) The GD value of the `source`. gd(series float source, simple int length, simple float vf) => float result = ta.ema(source, length) * (1 + vf) - ta.ema(ta.ema(source, length), length) * vf // @function Calculates the value of the Tilson Moving Average (T3). // @param source (series int/float) Series of values to process. // @param length (simple int) Length for the smoothing parameter calculation. // @param vf (simple float) Volume factor. Affects the responsiveness. // @returns (float) The Tilson moving average of the `source`. export t3(series float source, simple int length, simple float vf = 0.7) => float result = gd(gd(gd(source, length, vf), length, vf), length, vf) // @function An alternate Generalized DEMA (GD) function to `gd()`, which allows a "series float" // `length` argument. // @param source (series int/float) Series of values to process. // @param length (series int/float) Length for the smoothing parameter calculation. // @param vf (simple float) Volume factor. Affects the responsiveness. // @returns (float) The GD value of the `source`. gd2(series float source, series float length, simple float vf) => float result = ema2(source, length) * (1 + vf) - ema2(ema2(source, length), length) * vf // @function An alternate Tilson Moving Average (T3) function to `t3()`, which allows a "series float" // `length` argument. // @param source (series int/float) Series of values to process. // @param length (series int/float) Length for the smoothing parameter calculation. // @param vf (simple float) Volume factor. Affects the responsiveness. // @returns (float) The Tilson moving average of the `source`. export t3Alt(series float source, series float length, simple float vf = 0.7) => float result = gd2(gd2(gd2(source, length, vf), length, vf), length, vf) // @function Calculates the value of the Triple Exponential Moving Average (TEMA). // @param source (series int/float) Series of values to process. // @param length (simple int) Length for the smoothing parameter calculation. // @returns (float) The triple exponentially weighted moving average of the `source`. export tema(series float source, simple int length) => float ema1 = ta.ema(source, length) float ema2 = ta.ema(ema1, length) float ema3 = ta.ema(ema2, length) float result = 3 * (ema1 - ema2) + ema3 // @function An alternate Triple Exponential Moving Average (TEMA) function to `tema()`, which allows a // "series float" `length` argument. // @param source (series int/float) Series of values to process. // @param length (series int/float) Length for the smoothing parameter calculation. // @returns (float) The triple exponentially weighted moving average of the `source`. export tema2(series float source, series float length) => float ema1 = ema2(source, length) float ema2 = ema2(ema1, length) float ema3 = ema2(ema2, length) float result = 3 * (ema1 - ema2) + ema3 // @function Calculates the value of the Triangular Moving Average (TRIMA). // @param source (series int/float) Series of values to process. // @param length (series int) Number of bars (length). // @returns (float) The triangular moving average of the `source`. export trima(series float source, series int length) => float result = ta.sma(ta.sma(source, math.ceil(length / 2)), math.floor(length / 2) + 1) // @function Calculates the values of the TRIX indicator. // @param source (series int/float) Series of values to process. // @param length (simple int) Length for the smoothing parameter calculation. // @param signalLength (simple int) Length for smoothing the signal line. // @param exponential (simple bool) Condition to determine whether exponential or simple smoothing is used. // Optional. The default is `true` (exponential smoothing). // @returns ([float, float, float]) A tuple of the TRIX value, the signal value, and the histogram. export trix(series float source, simple int length, simple int signalLength, simple bool exponential = true) => float triple = ta.ema(ta.ema(ta.ema(source, length), length), length) float trix = ta.roc(triple, 1) float signal = exponential ? ta.ema(trix, signalLength) : ta.sma(trix, signalLength) float hist = trix - signal [trix, signal, hist] // @function Calculates the value of the Sentiment Zone Oscillator. // @param source (series int/float) Series of values to process. // @param length (simple int) Length for the smoothing parameter calculation. // @returns (float) The oscillator value. export szo(series float source, simple int length) => float trend = math.sign(ta.change(source)) float sentPos = tema(trend, length) float result = 100 * sentPos / length // @function Calculates the weighted average used in the `uo()` function. // @param bp (series float) A source series representing the "Buying Pressure" value. // @param trange (series float) A source series representing the True Range value. // @param length (simple int) Number of bars (length). // @returns (float) The weighted average value. uoAverage(series float bp, series float trange, simple int length) => float result = math.sum(bp, length) / math.sum(trange, length) // @function Calculates the value of the Ultimate Oscillator. // @param fastLen (series int) Number of bars for the fast smoothing average (length). // @param midLen (series int) Number of bars for the middle smoothing average (length). // @param slowLen (series int) Number of bars for the slow smoothing average (length). // @returns (float) The oscillator value. export uo(simple int fastLen, simple int midLen, simple int slowLen) => float tMax = math.max(high, close[1]) float tMin = math.min(low, close[1]) float tr = tMax - tMin float bp = close - tMin float avg1 = uoAverage(bp, tr, fastLen) float avg2 = uoAverage(bp, tr, midLen) float avg3 = uoAverage(bp, tr, slowLen) float result = 100 * (4 * avg1 + 2 * avg2 + avg3) / 7 // @function Calculates the value of the Vertical Horizontal Filter. // @param source (series int/float) Series of values to process. // @param length (simple int) Number of bars (length). // @returns (float) The oscillator value. export vhf(series float source, simple int length) => float sumChanges = math.sum(math.abs(ta.change(source)), length) float result = math.abs(ta.highest(source, length) - ta.lowest(source, length)) / sumChanges // @function Calculates the values of the Vortex Indicator. // @param length (simple int) Number of bars (length). // @returns ([float, float]) A tuple of the viPlus and viMinus values. export vi(simple int length) => divisor = math.sum(ta.atr(1), length) viPlus = math.sum(math.abs(high - nz(low[1])), length) / divisor viMinus = math.sum(math.abs(low - nz(high[1])), length) / divisor [viPlus, viMinus] // @function Calculates an ATR-based stop value that trails behind the `source`. Can serve as a // possible stop-loss guide and trend identifier. // @param source (series int/float) Series of values that the stop trails behind. // @param atrLength (simple int) Length for the ATR smoothing parameter calculation. // @param atrFactor (series int/float) The multiplier of the ATR value. Affects the maximum distance between // the stop and the `source` value. A value of 1 means the maximum distance is 100% of the // ATR value. Optional. The default is 1. // @returns ([float, bool]) A tuple of the volatility stop value and the trend direction as a "bool". export vStop(series float source, simple int atrLength, series float atrFactor = 1) => float src = nz(source, close) float atrM = nz(ta.atr(atrLength) * atrFactor, ta.tr(true)) var bool trendUp = true var float max = src var float min = src var float stop = 0.0 max := math.max(max, src) min := math.min(min, src) stop := nz(trendUp ? math.max(stop, max - atrM) : math.min(stop, min + atrM), src) trendUp := src - stop >= 0.0 if trendUp != nz(trendUp[1], true) max := src min := src stop := trendUp ? max - atrM : min + atrM [stop, trendUp] // @function An alternate Volatility Stop function to `vStop()`, which allows a "series float" // `atrLength` argument. // @param source (series int/float) Series of values that the stop trails behind. // @param atrLength (series int/float) Length for the ATR smoothing parameter calculation. // @param atrFactor (series int/float) The multiplier of the ATR value. Affects the maximum distance between // the stop and the `source` value. A value of 1 means the maximum distance is 100% of the // ATR value. Optional. The default is 1. // @returns ([float, bool]) A tuple of the volatility stop value and the trend direction as a "bool". export vStop2(series float source, series float atrLength, series float atrFactor = 1) => float src = nz(source, close) float atrM = nz(atr2(atrLength) * atrFactor, ta.tr(true)) var bool trendUp = true var float max = src var float min = src var float stop = 0.0 max := math.max(max, src) min := math.min(min, src) stop := nz(trendUp ? math.max(stop, max - atrM) : math.min(stop, min + atrM), src) trendUp := src - stop >= 0.0 if trendUp != nz(trendUp[1], true) max := src min := src stop := trendUp ? max - atrM : min + atrM [stop, trendUp] // @function Calculates the value of the Volume Zone Oscillator. // @param length (simple int) Length for the smoothing parameter calculation. // @returns (float) The oscillator value. export vzo(simple int length) => float result = zone(volume, length) // @function Detects Williams fractals (used by `williamsFractal()`). // @param source (series int/float) Series of values to process. // @param n (series int) Lookback in bars. // @param direction (simple int) Direction of the fractal to detect (+1 for up, -1 for down). // @returns (series bool) `true` when a fractal was detected, `false` otherwise. flag(series float source, series int n, simple int direction) => float src = source * direction bool flag = true bool flag0 = true bool flag1 = true bool flag2 = true bool flag3 = true bool flag4 = true for i = 1 to n flag := flag and (src[n - i] < src[n]) flag0 := flag0 and (src[n + i] < src[n]) flag1 := flag1 and (src[n + 1] <= src[n] and src[n + i + 1] < src[n]) flag2 := flag2 and (src[n + 1] <= src[n] and src[n + 2] <= src[n] and src[n + i + 2] < src[n]) flag3 := flag3 and (src[n + 1] <= src[n] and src[n + 2] <= src[n] and src[n + 3] <= src[n] and src[n + i + 3] < src[n]) flag4 := flag4 and (src[n + 1] <= src[n] and src[n + 2] <= src[n] and src[n + 3] <= src[n] and src[n + 4] <= src[n] and src[n + i + 4] < src[n]) bool flags = flag0 or flag1 or flag2 or flag3 or flag4 bool result = (flag and flags) // @function Detects Williams Fractals. // @param period (series int) Number of bars (length). // @returns ([bool, bool]) A tuple of an up fractal and down fractal. Variables are true when detected. export williamsFractal(series int period) => bool upFractal = flag(high, period, 1) bool downFractal = flag(low, period, -1) [upFractal, downFractal] // @function Calculates the value of the Wave Period Oscillator. // @param length (simple int) Length for the smoothing parameter calculation. // @returns (float) The oscillator value. export wpo(simple int length) => float tt = 2 * math.pi / math.asin(close[1] / high) float ti = math.sign(ta.change(close)) * tt float result = ta.ema(ti, length) plot(cagr(time[1], close[1], time, close))
ArrayStatistics
https://www.tradingview.com/script/uv5b4tjk-ArrayStatistics/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
24
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 Statistic Functions using arrays. library(title="ArrayStatistics") import RicardoSantos/ArrayExtension/1 as ae import RicardoSantos/ArrayOperationsFloat/1 as aof import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(20) // @function Root Mean Squared // @param sample float array, data sample points. // @returns float export rms(float[] sample) => //{ int _size = array.size(sample) if _size > 0 float _sum2 = array.sum(aof.power(sample, array.from(2.0))) math.sqrt(_sum2 / _size) //{ usage: var float[] rms_a = array.from(10, 4, 6, 8.0)//ae.sequence_float(1.0, 20.0, 1.0) console.queue_one(__C, str.format('Root Mean Squared ({0}) = {1}', str.tostring(rms_a), rms(rms_a))) //{ reference: // https://www.geeksforgeeks.org/program-to-calculate-root-mean-square/ // https://github.com/vjaunet/fortran_lib_ifort/blob/master/SOURCE/lib_stat.f90 //}} // @function Pearson's 1st Coefficient of Skewness. // @param sample float array, data sample. // @returns float export skewness_pearson1 (float[] sample) => //{ (array.avg(sample) - array.mode(sample)) / array.stdev(sample) //{ usage: // plot(skewness_pearson1(array.from(10.0,3,4,5,8,3,5,2))) var float[] sp1_a = array.from(10.0,3,4,5,8,3,5,2) console.queue_one(__C, str.format('Pearson´s 1st Coefficient of Skewness ({0}) = {1}', str.tostring(sp1_a), skewness_pearson1(sp1_a))) //{ reference: // https://www.investopedia.com/terms/s/skewness.asp // https://www.statisticshowto.com/pearsons-coefficient-of-skewness/ //}}} // @function Pearson's 2nd Coefficient of Skewness. // @param sample float array, data sample. // @returns float export skewness_pearson2 (float[] sample) => //{ (3.0 * (array.avg(sample) - array.median(sample))) / array.stdev(sample) //{ usage: console.queue_one(__C, str.format('Pearson´s 2nd Coefficient of Skewness ({0}) = {1}', str.tostring(sp1_a), skewness_pearson2(sp1_a))) // plot(skewness_pearson2(array.from(10.0,3,4,5,8,3,5,2))) //{ reference: // https://www.investopedia.com/terms/s/skewness.asp // https://www.statisticshowto.com/pearsons-coefficient-of-skewness/ //}}} // @function Pearson correlation coefficient measures the linear relationship between two datasets. // @param sample_a float array, sample with data. // @param sample_b float array, sample with data. // @returns float p export pearsonr(float[] sample_a, float[] sample_b) => //{ int _size_a = array.size(id=sample_a) int _size_b = array.size(id=sample_b) if _size_a > 0 and _size_b > 0 float _err_sum_ab = array.covariance(id1=sample_a, id2=sample_b) float _err_sum_a2 = array.stdev(id=sample_a) float _err_sum_b2 = array.stdev(id=sample_b) float _r = _err_sum_ab / (_err_sum_a2 * _err_sum_b2) //{ // usage: float[] pr_a = array.from(1.0, 2.0, 3.0, 4.0, 5.0) float[] pr_b = array.from(10.0, 9.0, 2.5, 6.0, 4.0) // plot(pearsonr(a, b))// 0.74 console.queue_one(__C, str.format('Pearson´s Correlation Coefficient ({0}, {1}) = {2}', str.tostring(pr_a), str.tostring(pr_b), pearsonr(pr_a, pr_b))) //}} // @function Kurtosis of distribution. // @param sample float array, data sample. // @returns float export kurtosis (float[] sample) => //{ int _size = array.size(sample) float _mean = array.avg(sample) if _size > 0 float _m2 = 0.0 float _m4 = 0.0 for _i = 0 to _size-1 float _e = array.get(sample, _i) - _mean _m2 += math.pow(_e, 2) _m4 += math.pow(_e, 4) _m2 /= _size _m4 /= _size _m4 / math.pow(_m2, 2.0) //{ usage: // plot(kurtosis(array.from(42, 20, 38, 78, 54, 26))) // 2.35 console.queue_one(__C, str.format('Kurtosis ({0}) = {1}', str.tostring(sp1_a), kurtosis(sp1_a))) //{ reference: // https://www.educba.com/kurtosis-formula/ //}}} // @function Get range around median containing specified percentage of values. // @param sample int array, Histogram array. // @param percent float, Values percentage around median. // @returns tuple with [int, int], Returns the range which containes specifies percentage of values. export range_int ( int[] sample, float percent ) => //{ int _size = array.size(sample) // switch (_size < 1) => runtime.error('ArrayStatistics -> range_int(): Parameter "sample" needs to have 1 or more elements.') // int _total = array.sum(sample) int _h = int(_total * ( percent + ( 1 - percent ) / 2 )) int _hits = _total int _min = -1 int _max = _size // get range min value for _i = 0 to _size-1 _min += 1 _hits -= array.get(sample, _min) if _hits < _h break // get range max value _hits := _total for _i = _size - 1 to 0 _max -= 1 _hits -= array.get(sample, _max) if _hits < _h break [_min, _max] //{ usage: // create histogram array var int[] r_histogram = array.from(1, 1, 2, 3, 6, 8, 11, 12, 7, 3) [r_min, r_max] = range_int(r_histogram, 0.75) // 75% range around median: ([4, 8]) console.queue_one(__C, str.format('Range ({0}, 75%) = min: {1}, max: {2}', str.tostring(r_histogram), r_min, r_max)) // plot(min), plot(max) //{ remarks: // The input array is treated as histogram, i.e. its indexes are // treated as values of stochastic function, but array values // are treated as "probabilities" (total amount of hits). // The method calculates range of stochastic variable, which summary // probability comprises the specified percentage of histogram's hits. //}}} // @function Computes a weighted average (the mean, where each value is weighted by its relative importance). // @param sample float array, data sample. // @param weights float array, weights to apply to samples. // @returns float export average_weighted (float[] sample, float[] weights) => //{ int _size_s = array.size(id=sample) int _size_w = array.size(id=weights) // switch (_size_s < 1) => runtime.error('ArrayStatistics -> average_weighted(): Parameter "sample" needs to have 1 or more elements.') (_size_s != _size_w) => runtime.error('ArrayStatistics -> average_weighted(): Parameter "sample" and "weights" size must match.') // float _avg = 0. float _count = array.sum(id=weights) for _i = 0 to _size_s - 1 by 1 _avg := _avg + array.get(id=sample, index=_i) * array.get(id=weights, index=_i) // _avg := _avg / _count //{ usage: var float[] aw_a = array.from(1.0, 2, 3, 0, 1, 2, 3) var float[] aw_b = array.from(1.0, 1, 2, 1, 1, 2, 1) console.queue_one(__C, str.format('Average Weighted ({0}, {1}) = {2}', str.tostring(aw_a), str.tostring(aw_b), average_weighted(aw_a, aw_b))) // t0 = average_weighted(array.from(1, 2, 3, 0, 1, 2, 3), array.from(1, 1, 2, 1, 1, 2, 1)) // t1 = average_weighted(array.from(.1, 0.2, .3, .0, .1, .2, .3), array.from(1, 1, 2, 1, 1, 2, 1)) // c(_i) => close[_i] // h = ta.highest(7) // l = ta.lowest(7) // r = h - l // w(_i) => (c(_i) - l) / r // t2y = array.from(c(0), c(1), c(2), c(3), c(4), c(5), c(6)) // t2w = array.from(w(0), w(1), w(2), w(3), w(4), w(5), w(6)) // t2 = average_weighted(t2y, t2w) // more weight to higher values // plot(series=t0) // plot(series=t1) // plot(series=t2) // plot(series=close, color=color.new(color.yellow, 0)) // plot(series=ta.sma(close, 7), color=color.new(color.orange, 0)) //{ remarks: // https://help.smartsheet.com/function/avgw //} // @function Calculate the arithmetic-geometric mean of two numbers (_value_a, _value_b). // @param value_a float, number value. // @param value_b float, number value. // @param tolerance_value float, number value, default=1e-12. // @returns float export arithmetic_geometric_mean_simple (float value_a, float value_b, float tolerance_value=1.0e-12) => //{ float _an = 0.5 * (value_a + value_b) float _gn = math.sqrt(value_a * value_b) while math.abs(_an - _gn) > tolerance_value float _at = _an _an := 0.5 * (_at + _gn) _gn := math.sqrt(_at * _gn) _an //{ usage: console.queue_one(__C, str.format('Arithmetic Geometric Mean Simple (1, 1 / sqrt(2)) = {0, number, #.#########}', arithmetic_geometric_mean_simple(1.0, 1.0 / math.sqrt(2.0)) )) // expected: 0.847213084835 console.queue_one(__C, str.format('Arithmetic Geometric Mean Simple (sqrt(2), 1) = {0, number, #.#########}', arithmetic_geometric_mean_simple(math.sqrt(2.0), 1.0))) // expected: 1.1981402347355922074... //{ remarks: // http://rosettacode.org/wiki/Arithmetic-geometric_mean#Basic_Version //}}} // @function Computes the arithmetic geometric mean of a sequence of values. // @param sample float array, data sample of positive values only. // @returns float export arithmetic_geometric_mean (float[] sample) => //{ int _size = array.size(sample) // switch (_size < 1) => runtime.error('ArrayStatistics -> geometric_mean(): "sample" has the wrong size.') // float _agm = array.get(sample, 0) if _size > 1 for _i = 1 to _size - 1 by 1 _agm *= array.get(sample, _i) nz(math.pow(_agm, (1.0 / _size)), 0.0) //{ usage: if barstate.islast console.queue_one(__C, str.format('Arithmetic Geometric Mean (close)[4] = {0}', arithmetic_geometric_mean(array.from(close, close[1], close[2], close[3])))) // console.queue_one(__C, str.format('Arithmetic Geometric Mean = {0}', arithmetic_geometric_mean(array.from(math.sqrt(2.0), 1.0)))) // console.queue_one(__C, str.format('Arithmetic Geometric Mean = {0}', arithmetic_geometric_mean(array.from(math.sqrt(2.0), -1.0, 2)))) // console.queue_one(__C, str.format('Arithmetic Geometric Mean = {0}', arithmetic_geometric_mean(array.from(50.3, 55.7, 57.1, 54.9, 55.5)))) //{ remarks: // https://www.scribbr.com/statistics/geometric-mean/ //}}} // @function Computes the simple version of the z-score formula. // @param value float, data value. // @param mean float, data mean. // @param deviation float, the standard deviation of the data. // @returns float. export zscore_simple (float value, float mean, float deviation) => //{ (value - mean) / deviation //{ usage: //{ remarks: // https://zscoregeek.com/zscore/ // https://www.statisticshowto.datasciencecentral.com/standardized-values-examples/ //}}} // @function Computes the z-score of a data sample values. // @param sample float array, data values. // @returns float array. export zscore (float[] sample) => //{ int _size_s = array.size(sample) // switch (_size_s < 1) => runtime.error('ArrayStatistics -> zscore(): "sample" has the wrong size.') // float _mean = array.avg(sample) float _std = array.stdev(sample) float[] _zscores = array.new_float(_size_s) for _i = 0 to _size_s - 1 array.set(_zscores, _i, zscore_simple(array.get(sample, _i), _mean, _std)) _zscores //{ usage: var float[] zscore_sample = array.from(6.0, 7, 7, 12, 13, 13, 15, 16, 19, 22) console.queue_one(__C, str.format('Zscores for {0}\n\t\t\t\t\t\t\t\t = {1}', str.tostring(zscore_sample), str.tostring(zscore(zscore_sample)))) //{ remarks: // https://zscoregeek.com/zscore/ // https://www.statisticshowto.datasciencecentral.com/standardized-values-examples/ //}}} console.update(__T, __C)
MathComplexArray
https://www.tradingview.com/script/m4jU2j0z-MathComplexArray/
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 Array methods to handle complex number arrays. library(title='MathComplexArray') // Complex numbers prototype: { // description: // A set of utility functions to handle complex numbers. // references: // https://en.wikipedia.org/wiki/Complex_number // js: https://rosettacode.org/wiki/Fast_Fourier_transform // https://github.com/trekhleb/javascript-algorithms/blob/477f30b0bdac6024874d2976de1eca7afe0176dd/src/algorithms/math/complex-number/ComplexNumber.js#L3 // https://github.com/infusion/Complex.js/ // required imports: import RicardoSantos/MathComplexCore/2 as complex import RicardoSantos/CommonTypesMath/1 as TMath // @function Prototype to initialize a array of complex numbers. // @param size size of the array. // @param initial_complex Complex number to be used as default value, in the form of array [real, imaginary]. // @returns float array, pseudo complex Array in the form of a array [0:real, 1:imaginary, 2:real, 3:imaginary,...] export new (int size=0, TMath.complex initial_complex) => //{ if size > 0 array.new<TMath.complex>(size, initial_complex) else array.new<TMath.complex>(0) //} // @function Get the complex number in a array, in the form of a array [real, imaginary] // @param id float array, ID of the array. // @param index int, Index of the complex number. // @returns float array, pseudo complex number in the form of a array [real, imaginary] export get (array<TMath.complex> id, int index) => //{ array.get(id, index) //} // @function Sets the values complex number in a array. // @param id float array, ID of the array. // @param index int, Index of the complex number. // @param complex_number float array, Complex number, in the form: [real, imaginary]. // @returns Void, updates array id. export set (array<TMath.complex> id, int index, TMath.complex complex_number) => //{ array.set(id, index, complex_number) //} // @function Push the values into a complex number array. // @param id float array, ID of the array. // @param complex_number float array, Complex number, in the form: [real, imaginary]. // @returns Void, updates array id. export push (array<TMath.complex> id, TMath.complex complex_number) => //{ array.push(id, complex_number) //} // @function Pop the values from a complex number array. // @param id float array, ID of the array. // @param complex_number float array, Complex number, in the form: [real, imaginary]. // @returns Void, updates array id. export pop (array<TMath.complex> id) => //{ array.pop(id) //} // @function Reads a array of complex numbers into a string, of the form: "[ [a+bi], ... ]"" // @param id float array, ID of the array. // @param format string, format of the number conversion, default='#.##########'. // @returns string, translated complex array into string. export to_string (array<TMath.complex> id, string format='#.##########') => //{ string _str = '[ ' for _e in id _str += str.format('[ {0} ]', complex.to_string(_e, format)) _str //} if barstate.ishistory[1] and (barstate.isrealtime or barstate.islast) a = new(1, complex.new(0.0, 0.0)) string _text = to_string(a, '#.##') b = new(2, complex.new(1.0, 2.0)) _text += '\n' + to_string(b, '#.##') label.new(x=bar_index, y=0.0, text=_text, style=label.style_label_left, textalign=text.align_left)
FunctionArrayReduce
https://www.tradingview.com/script/utTjkzsv-FunctionArrayReduce/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description A limited method to reduce a array using a mathematical formula. library(title="FunctionArrayReduce") import RicardoSantos/StringEvaluation/4 as stre import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(20) // @function Method to reduce a array using a mathematical formula. // @param formula string, the mathematical formula, accepts some default name codes (index, output, previous, current, integer index of arguments array). // @param samples float array, the data to process. // @param arguments float array, the extra arguments of the formula. // @param initial_value float, default=0, a initial base value for the process. // @returns float. // Notes: // ** if initial value is specified as "na" it will default to the first element of samples. // ** expression needs to have atleast one operation. export float_ (string formula, float[] samples, float[] arguments, float initial_value=0.0) => //{ int _size_f = str.length(formula) int _size_s = array.size(samples) int _size_a = array.size(arguments) // switch (_size_f < 1) => runtime.error('FunctionArrayReduce -> float_(): "formula" is empty.') (_size_s < 1) => runtime.error('FunctionArrayReduce -> float_(): "samples" has the wrong size.') // // index the keywords for the evaluation. string _shape = formula _shape := str.replace_all(_shape, 'index', str.tostring(_size_a + 0, '#')) _shape := str.replace_all(_shape, 'output', str.tostring(_size_a + 1, '#')) _shape := str.replace_all(_shape, 'previous', str.tostring(_size_a + 2, '#')) _shape := str.replace_all(_shape, 'current', str.tostring(_size_a + 3, '#')) // TODO: extra keywords? // float _output = na(initial_value) ? array.get(samples, 0) : initial_value // evaluate first element? if _size_s > 1 for _i = 1 to _size_s - 1 float _previous = array.get(samples, _i - 1) float _current = array.get(samples, _i) _output := stre.eval(_shape, array.concat(array.copy(arguments), array.from(_i, _output, _previous, _current))) _output //{ usage: console.queue_one(__C, str.format('last index: {0}', float_('output - output + current', array.from(0.0, 1, 2, 3, 4), array.new_float(0)))) console.queue_one(__C, str.format('sum of multiplication of value by index: {0}', float_('output + previous * index', array.from(0.0, 1, 2, 3, 4), array.new_float(0), 1))) console.queue_one(__C, str.format('using arguments: {0}', float_('output + previous * 0 - 1', array.from(0.0, 1, 2, 3, 4), array.new_float(3, 3.3)))) console.queue_one(__C, str.format('sum of squares: {0}', float_('output + current ^ 0', array.from(0.0, 1, 2, 3, 4), array.new_float(1, 2)))) console.queue_one(__C, str.format('sum of positive direction of change: {0}', float_('output + current >= previous', array.from(0.0, 1, 2, 3, 4), array.new_float(1, 2)))) console.queue_one(__C, str.format('strenght of direction: {0}', float_('output + (current >= previous) - (current <= previous)', array.from(0.0, 1, 3, 2, 3), array.new_float(1, 2)))) //{ remarks // ** if initial value is specified as "na" it will default to the first element of samples. // ** expression needs to have atleast one operation. //}}} console.update(__T, __C)
MathComplexOperator
https://www.tradingview.com/script/SviW5MRr-MathComplexOperator/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description A set of utility functions to handle complex numbers. library(title='MathComplexOperator') // references: // https://en.wikipedia.org/wiki/Complex_number // js: https://rosettacode.org/wiki/Fast_Fourier_transform // https://github.com/trekhleb/javascript-algorithms/blob/477f30b0bdac6024874d2976de1eca7afe0176dd/src/algorithms/math/complex-number/ComplexNumber.js#L3 // https://github.com/infusion/Complex.js/ // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs //#region -> Imports: import RicardoSantos/DebugConsole/11 as console import RicardoSantos/CommonTypesMath/1 as TMath import RicardoSantos/MathComplexCore/3 as complex import RicardoSantos/MathConstants/1 as mc import RicardoSantos/MathExtension/1 as me //#endregion logger = console.Console.new().init() //#region -> Instance Methods: // conjugate () { // reference: // https://en.cppreference.com/w/c/numeric/complex/conj // @function Computes the conjugate of complex number by reversing the sign of the imaginary part. // @param this complex. // @returns Complex. export method conjugate (TMath.complex this)=> complex.new( this.re , -1 * this.im ) // } // add () { // @function Adds complex number other to this, in the form: // [_a.real + _b.real, _a.imaginary + _b.imaginary]. // @param this pseudo complex number in the form of a array [real, imaginary]. // @param other pseudo complex number in the form of a array [real, imaginary]. // @returns complex export method add(TMath.complex this, TMath.complex other)=> complex.new( this.re + other.re , this.im + other.im ) // } // subtract () { // @function Subtract other from this, in the form: // [_a.real - _b.real, _a.imaginary - _b.imaginary]. // @param this complex. // @param other complex. // @returns complex export method subtract (TMath.complex this, TMath.complex other)=> complex.new( this.re - other.re , this.im - other.im ) // } // multiply () { // @function Multiply this with other, in the form: // [(_a.real * _b.real) - (_a.imaginary * _b.imaginary), (_a.real * _b.imaginary) + (_a.imaginary * _b.real)] // @param this complex. // @param other complex. // @returns complex export method multiply (TMath.complex this, TMath.complex other)=> complex.new( this.re * other.re - this.im * other.im , this.re * other.im + this.im * other.re ) // } // divide () { // @function Divide complex_number _a with _b, in the form: // [(_a.real * _b.real) - (_a.imaginary * _b.imaginary), (_a.real * _b.imaginary) + (_a.imaginary * _b.real)] // @param this complex. // @param other complex. // @returns complex export method divide (TMath.complex this, TMath.complex other)=> TMath.complex _complexDivider = complex.new(other.re, other.im) // Multiply dividend by divider's conjugate. TMath.complex _finalDivident = multiply(this, conjugate(_complexDivider)) // Calculating final divider using formula (a + bi)(a − bi) = a^2 + b^2 float finalDivider = math.pow(_complexDivider.re, 2) + math.pow(_complexDivider.im, 2) complex.new( _finalDivident.re / finalDivider , _finalDivident.im / finalDivider ) // } // reciprocal () { //{ remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L744 // @function Computes the reciprocal or inverse of complex_number. // @param complex_number complex. // @returns complex export method reciprocal (TMath.complex this)=> if this.is_zero() complex.zero() else divide(complex.one(), this) // negative () { // } // @function Negative of complex_number, in the form: [-_a.real, -_a.imaginary] // @param complex_number complex. // @returns complex export method negative (TMath.complex this)=> complex.new( -this.re , -this.im ) // } // inverse () { // @function Inverse of complex_number, in the form: [1/_a.real, 1/_a.imaginary] // @param complex_number complex. // @returns complex export method inverse (TMath.complex this)=> // 1 / 0 = infinity, 1 / infinity = 0 if this.re != 0 and this.im != 0 float _d = this.re * this.re + this.im * this.im complex.new(this.re / _d, (0 - this.im) / _d) else complex.zero() // } // exponential () { // reference: // https://en.cppreference.com/w/c/numeric/complex/cexp // http://cboard.cprogramming.com/c-programming/89116-how-implement-complex-exponential-functions-c.html#post637921 // @function Exponential of complex_number. // @param complex_number pseudo complex number in the form of a array [real, imaginary]. // @returns complex export method exponential (TMath.complex this)=> var _er = math.exp(this.re) complex.new(_er * math.cos(this.im), _er * math.sin(this.im)) // } // ceil () { // @function Ceils complex_number. // @param complex_number complex. // @param digits int, digits to use as ceiling. // @returns // _complex: pseudo complex number in the form of a array [real, imaginary] export method ceil (TMath.complex this, int digits)=> float _places = math.pow(10, digits) complex.new(math.ceil(this.re * _places) / _places, math.ceil(this.im * _places) / _places) // } // radius () { // @function Radius(magnitude) of complex_number, in the form: [sqrt(pow(complex_number))] // This is defined as its distance from the origin (0,0) of the complex plane. // @param complex_number complex. // @returns float value with radius. export method radius (TMath.complex this)=> math.sqrt(math.pow(this.re, 2) + math.pow(this.im, 2)) //{ usage: // logger.queue_one(__C, str.format('radius of complex number "5.2+3.0i" = {0, number, #.####}', radius(new(5.2, 3.0)))) // 6.0 // } // magnitude () { //{ remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L179 // @function magnitude(absolute value) of complex_number, should be the same as the radius. // @param complex_number complex. // @returns float. export method magnitude (TMath.complex this)=> float _a = math.abs(this.re) float _b = math.abs(this.im) if _a > _b float _tmp = _b / _a _a * math.sqrt(1.0 * math.pow(_tmp, 2)) else if _a == 0.0 _b else float _tmp = _a / _b _b * math.sqrt(1.0 * math.pow(_tmp, 2)) //{ usage: // does not seem to be correct.. // logger.queue_one(__C, str.format('magnitude of complex number "5.2+3.0i" = {0, number, #.####} // should be 6', magnitude(new(5.2, 3.0)))) // } // magnitude_squared () { // remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L179 // @function magnitude(absolute value) of complex_number, should be the same as the radius. // @param complex_number complex. // @returns float. export method magnitude_squared (TMath.complex this)=> float _re = math.pow(this.re, 2) float _im = math.pow(this.im, 2) _re + _im //{ usage: // logger.queue_one(__C, str.format('magnitude squared of complex number "5.2+3.0i" = {0, number, #.####}', magnitude_squared(new(5.2, 3.0)))) // 36.0 // } // sign () { // remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L218 // @function Unity of complex numbers. // @param complex_number complex. // @returns float array, complex number. export method sign (TMath.complex this)=> if this.re >= 1.0e307 and this.im >= 1.0e307 complex.new(mc.Sqrt1Over2(), mc.Sqrt1Over2()) else if this.re >= 1.0e307 and this.im <= -1.0e307 complex.new(mc.Sqrt1Over2(), -mc.Sqrt1Over2()) else if this.re <= -1.0e307 and this.im >= 1.0e307 complex.new(-mc.Sqrt1Over2(), mc.Sqrt1Over2()) else if this.re <= -1.0e307 and this.im <= -1.0e307 complex.new(-mc.Sqrt1Over2(), -mc.Sqrt1Over2()) else float _mod = me.hypotenuse(this.re, this.im) if _mod == 0.0 complex.zero() else complex.new(this.re / _mod, this.im / _mod) // usage: // logger.queue_one(__C, str.format('sign of complex number "5.2+3.0i" = {0}', to_string(sign(new(5.2, 3.0)), '#.##'))) // "0.87+0.5i" // } //#endregion if barstate.islastconfirmedhistory A = complex.new(7.0, -6.0) B = complex.new(-3.0, 4.0) logger.queue_one(str.format('input parameters: (A: {0}, B: {1})', complex.to_string(A, '#.##'), complex.to_string(B, '#.##'))) logger.queue_one(str.format('\n## Operators ##\n', '')) logger.queue_one(str.format('A + B = {0}', complex.to_string(add(A, B), '#.##'))) logger.queue_one(str.format('A - B = {0}', complex.to_string(subtract(A, B), '#.##'))) logger.queue_one(str.format('A * B = {0}', complex.to_string(multiply(A, B), '#.##'))) logger.queue_one(str.format('A / B = {0}', complex.to_string(divide(A, B), '#.##'))) logger.queue_one(str.format('\n## Properties ##\n', '')) logger.queue_one(str.format('Conjugate of A: {0}', complex.to_string(conjugate(A), '#.##'))) logger.queue_one(str.format('Reciprocal of A = {0}', complex.to_string(reciprocal(A), '#.##'))) logger.queue_one(str.format('Negative of A = {0}', complex.to_string(negative(A), '#.##'))) logger.queue_one(str.format('Inverse of A = {0}', complex.to_string(inverse(A), '#.##'))) logger.queue_one(str.format('Exponential of A = {0}', complex.to_string(exponential(A), '#.##'))) logger.queue_one(str.format('Ceiling of A = {0}', complex.to_string(ceil(A, 1), '#.##'))) logger.queue_one(str.format('Radius of A = {0}', radius(A))) logger.queue_one(str.format('Magnitude of A = {0} //should be 6.0?', magnitude(A))) logger.queue_one(str.format('Magnitude Squared of A = {0}', magnitude_squared(A))) logger.queue_one(str.format('Sign of A = {0}', complex.to_string(sign(A), '#.##'))) // update log logger.update()
MathComplexCore
https://www.tradingview.com/script/xo2mui5m-MathComplexCore/
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 Core functions to handle complex numbers. library(title='MathComplexCore') // references: // https://en.wikipedia.org/wiki/Complex_number // js: https://rosettacode.org/wiki/Fast_Fourier_transform // https://github.com/trekhleb/javascript-algorithms/blob/477f30b0bdac6024874d2976de1eca7afe0176dd/src/algorithms/math/complex-number/ComplexNumber.js#L3 // https://github.com/infusion/Complex.js/ // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs //#region -> Imports: import RicardoSantos/CommonTypesMath/1 as TMath import RicardoSantos/DebugConsole/11 as console logger = console.Console.new().init() //#endregion //#region -> Constructor: // new () { // @function Creates a new Complex number. // @param real float . Real part of the complex number. default=0. // @param imaginary float . Imaginary part of the complex number. default=0. // @returns Complex. export new (float real=0.0, float imaginary=0.0) => TMath.complex.new(real, imaginary) // } // from { // @function Creates a new Complex number were provided value replaces both real and imaginary parts. // @param value float . Value of real and imaginary parts. // @returns Complex. export from (float value) => new(value, value) // @function Creates a new Complex number from provided `Vector2` coordinate. // @param value Vector2 . Value of real and imaginary parts. // @returns Complex. export from (TMath.Vector2 value) => new(value.x, value.y) // @function Creates a new Complex number from provided `Pole` coordinate. // @param value Pole . Value of real and imaginary parts. // @returns Complex. export from (TMath.Pole value) => new(value.radius * math.cos(value.angle), value.radius * math.sin(value.angle)) // @function Creates a new Complex number from provided value. // @param value string . Value of real and imaginary parts. // @returns Complex. export from (string value) => string _clean = str.replace_all(value, ' ', '') string _reg = '(?:(?:\\+|-|\\.|\\d){1}(?:\\d)*(?:\\.)?(?:\\d)*){1}(?:(?:(?:E|e){1}(?:\\+|-|\\d)?)+(?:\\d)*(?:\\.)?(?:\\d)*)?' string _prefix = str.match(_clean, _reg) string _clean1 = str.replace(_clean, _prefix, '', 0) string _suffix = str.match(_clean1, _reg) if str.length(_suffix) > 0 new(str.tonumber(_prefix), str.tonumber(_suffix)) else new(nz(str.tonumber(_prefix), 0.0), 0.0) // string str = input.string('-1.0+30.0e-2i') // if barstate.islast // _c = from(str) // label.new(bar_index, 0.0, str.format('real:{0}, imaginary:{1}', _c.re, _c.im)) // } // from_polar_coordinates () { // @function Create a complex number from polar coordinates. // @param magnitude float, default=0.0, The magnitude, which is the distance from the origin (the intersection of the x-axis and the y-axis) to the number. // @param phase float, default=0.0, The phase, which is the angle from the line to the horizontal axis, measured in radians. // @returns Complex. export from_polar_coordinates (float magnitude=0.0, float phase=0.0) => new(magnitude * math.cos(phase), magnitude * math.sin(phase)) // } // { // @function Complex number "0+0i". // @returns Complex. export zero () => from(0.0) // } // { // @function Complex number "1+0i". // @returns Complex. export one () => new(1.0, 0.0) // } // { // @function Complex number "0+1i". // @returns Complex. export imaginary_one () => new(0.0, 1.0) // } // { // @function Complex number with `float(na)` parts. // @returns Complex. export nan () => from(float(na)) // } //#endregion // is_complex () { // @function Checks that its a valid complex number. // @param this Complex Source complex number. // @returns bool. export method is_complex (TMath.complex this) => not (na(this.re) or na(this.im)) and this.im != 0.0 // } // { // @function Checks that its empty "na" complex number. // @param this Complex Source complex number. // @returns bool. export method is_nan (TMath.complex this) => na(this.re) or na(this.im) // } // { // @function Checks that the complex_number is real. // @param this Complex Source complex number. // @returns bool. export method is_real (TMath.complex this) => // https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/type_check.py#L210-L244 this.im == 0.0 // } // { // @function Checks that the complex_number is real and not negative. // @param this Complex Source complex number. // @returns bool. export method is_real_non_negative (TMath.complex this) => this.re >= 0.0 and this.im == 0.0 // } // { // @function Checks that the complex_number is zero. // @param this Complex Source complex number. // @returns bool. export method is_zero (TMath.complex this) => this.re + this.im == 0.0 // } // { // @function Compares two complex numbers: // @param this Complex . Source complex number. // @param other Complex . Target complex number // @param eps float . Precision value, default=1e-15. // @returns boolean value representing the equality. export method equals (TMath.complex this, TMath.complex other, float eps=1e-15) => math.abs(other.re - this.re) <= eps and math.abs(other.im - this.im) <= eps // } // { // @function Converts complex number to a string format, in the form: "a+bi" // @param this Complex . Source complex number.. // @param format string, formating to apply. // @returns string. In "a+bi" format export method to_string (TMath.complex this, string format='#.##########') => switch this.im == 0 => str.format('{0,number,'+format+'}' , this.re) this.re == 0 => str.format('{0,number,'+format+'}i' , this.im) this.im < 0 => str.format('{0,number,'+format+'}-{1,number,'+format+'}i', this.re, -this.im) => str.format('{0,number,'+format+'}+{1,number,'+format+'}i', this.re, this.im) // usage: // console.queue_one(__C, str.format('to_string conversion of complex number "5.2+3.0i": {0}', to_string(new(5.2, 3.0), '#.##'))) // // } if barstate.islastconfirmedhistory float _i0 = 1.0 float _i1 = 2.0 float _i2 = 3.0 float _i3 = 4.0 A = new(0.0, 0.0) B = one() logger.queue_one(str.format('input parameters: {0}, {1}, {2}, {3}', _i0, _i1, _i2, _i3)) logger.queue_one(str.format('## Create ##', '')) logger.queue_one(str.format('new complex number A: {0}', to_string(A, '#.##'))) logger.queue_one(str.format('new complex number B: {0}', to_string(A, '#.##'))) logger.queue_one(str.format('new complex number zero(): {0}', to_string(zero(), '#.##'))) logger.queue_one(str.format('new complex number one(): {0}', to_string(one(), '#.##'))) logger.queue_one(str.format('new complex number imaginary_one(): {0}', to_string(imaginary_one(), '#.##'))) logger.queue_one(str.format('new complex number nan(): {0}', to_string(nan(), '#.##'))) logger.queue_one(str.format('new complex number from_polar_coordinates({0}, {1}): {2}', _i2, _i3, to_string(from_polar_coordinates(_i2, _i3), '#.##'))) logger.queue_one(str.format('## Access ##', '')) A.re := _i0 , A.im := _i1 logger.queue_one(str.format('set real and imaginary parts of A with inputs({0}, {1}): {2}', _i0, _i1, to_string(A, '#.##'))) logger.queue_one(str.format('set real and imaginary parts of B with inputs({0}, {1}): {2}', _i2, _i3, to_string(B, '#.##'))) logger.queue_one(str.format('get real and imaginary parts of B:({0}, {1})', B.re, B.im)) logger.queue_one(str.format('## Test ##', '')) logger.queue_one(str.format('Test: is A complex number: {0}', is_complex(A))) logger.queue_one(str.format('Test: is A NaN: {0}', is_nan(A))) logger.queue_one(str.format('Test: is A real: {0}', is_real(A))) logger.queue_one(str.format('Test: is A real non negative: {0}', is_real_non_negative(A))) logger.queue_one(str.format('Test: is A zero: {0}', is_zero(A))) // update console logger.update()
MathExtension
https://www.tradingview.com/script/FsSvXfSR-MathExtension/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Math Extension. library("MathExtension") // reference: // https://github.com/python/cpython/blob/4a42cebf6dd769e2fa4e234a9e91093b3ad1cb63/Modules/mathmodule.c // @function calculate log base 2 // @param _value float, number. // @returns float, base 2 logarithm of value. export log2(float value)=>//{ math.log(value) / 0.693147180559945//math.log(2) aproximation //} // @function float remainder of x divided by y. // @param numerator float, division numerator. // @param denominator float, division denuminator. // @returns float export fmod (float numerator, float denominator) => //{ numerator - (denominator * math.floor(numerator / denominator)) //{ usage: // float a = 20.156, float b = 0.5 // float c = fmod(numerator=a, denominator=b) // plot(c) //}} // @function computes the fractional part of the argument value. // @param value float, value to compute. // @returns float, fractional part. export fractional (float value) => //{<< value - math.floor(value) //} // @function Find the integral of value. // @param value float, value. // @returns float. export integral(float value) => //{ float _new_value = math.abs(value) while _new_value - math.floor(_new_value) != 0 _new_value := _new_value * 10 _new_value //{ usage: // float input_value = input.float(1.2345), plot(integral(input_value)) //}} // @function Find the number of digits in a integer, float or valid number string. // @param value int, value. // @returns int. export ndigit (int value) => //{ int _abs = math.abs(value) int _count = 0 while _abs > 0 _abs := math.floor(_abs / 10) _count := _count + 1 _count // overloads: export ndigit(float value) => ndigit(int(value)) export ndigit(string value) => ndigit(int(str.tonumber(value))) //{ usage: // int input_value0 = input.int(1), plot(ndigit(input_value0)) // float input_value1 = input.float(1.123), plot(ndigit(input_value1)) // string input_value2 = input.string("1"), plot(ndigit(input_value2)) //}} // @function Approximation to atan2 calculation, arc tangent of y/ x in the range (-pi,pi) radians. // @param value_x float, value x. // @param value_y float, value y. // @returns float, value with angle in radians. (negative if quadrante 3 or 4) export atan2 (float value_x, float value_y) => //{<< float _one_qtr_pi = 0.25 * math.pi float _three_qtr_pi = 3.0 * _one_qtr_pi float _abs_y = math.abs(value_y) + 1e-12 // kludge to void zero division float _r = 0.0, float _angle = 0.0 if value_x < 0.0 _r := (value_x + _abs_y) / (_abs_y - value_x) _angle := _three_qtr_pi else _r := (value_x - _abs_y) / (value_x + _abs_y) _angle := _one_qtr_pi _angle := _angle + (0.1963 * _r * _r - 0.9817) * _r math.sign(value_y) * _angle //} // @function Multidimensional euclidean distance from the origin to a point. // @param value_x float, value x. // @param value_y float, value y. // @returns float export hypotenuse (float value_x, float value_y) => //{ math.sqrt(value_x * value_x + value_y * value_y) // usage: // the hypotenuse of a right triangle (3:4:5) // hypot(value_x=3.0, value_y=4.0) // 5.0 // reference: // https://github.com/python/cpython/blob/4a42cebf6dd769e2fa4e234a9e91093b3ad1cb63/Modules/mathmodule.c //} // @function Determine whether two floating point numbers are near in value. // @param value_a float, value to compare with. // @param value_b float, value to be compared against. // @param relative_tolerance float, default (1.0e-09). // @param absolute_tolerance float, default (0.0). // @returns bool export near_equal (float value_a, float value_b, float relative_tolerance=1.0e-09, float absolute_tolerance=0.0) => //{ if relative_tolerance < 0 or absolute_tolerance < 0 bool(na) else if value_a == value_b true else float _diff = math.abs(value_b - value_a) _diff <= math.abs(relative_tolerance * value_b) or _diff <= math.abs(relative_tolerance * value_a) or _diff <= absolute_tolerance // usage: // plot(is_close(value_a=1.0, value_b=1.0 + 1.0e-10) ? 1 : 0) // reference: // https://github.com/python/cpython/blob/4a42cebf6dd769e2fa4e234a9e91093b3ad1cb63/Modules/mathmodule.c //} // @function Factorize a number. // @param value int, positive number. // @returns int export factorize (int value) => //{ if value == 0 or value == 1 1 else if value < 0 or na(value) int(na) else int _value = 1 for _i = 2 to value _value *= _i int(_value) // usage: // plot(factorize(int(na))) // na // plot(factorize(-3)) // na // plot(factorize(0)) // 1 // plot(factorize(1)) // 1 // plot(factorize(2)) // 2 // plot(factorize(3)) // 6 // plot(factorize(5)) // 120 // plot(factorize(10)) // 3628800 // plot(factorize(20)) // 2432902008176640000 // // reference: // https://www.freecodecamp.org/news/how-to-factorialize-a-number-in-javascript-9263c89a4b38/ //} // @function Number of ways to choose k items from n items without repetition and with order. // @param options_size int, number of items to pool from // @param combo_size int, number of items to be chosen // @returns int export permutations (int options_size, int combo_size) => //{ if na(combo_size) factorize(value=options_size) else if na(options_size) int(na) // must have items to select from else if options_size < 0 or combo_size < 0 int(na) // must be positive else if options_size < combo_size 0 else _factor = options_size _result = options_size for _i = combo_size to 2 _factor -= 1 _result *= _factor _result // usage: // plot(permutations(52, 5)) // 311875200 // plot(permutations(10, 2)) // 90 // plot(permutations(5, 3)) // 60 // plot(permutations(3, 5)) // 0 // k > n // plot(permutations(5, int(na))) // 120 //} // @function Find the total number of possibilities to choose k things from n items // @param options_size int, number of items to pool from // @param combo_size int, number of items to be chosen // @returns int export combinations (int options_size, int combo_size) => //{ if na(combo_size) int(na) else if na(options_size) int(na) // must have items to select from else if options_size < 0 or combo_size < 0 int(na) // must be positive else int _temp = options_size - combo_size if _temp < 0 0 else if combo_size == 1 1 else int _k = math.min(combo_size, options_size - combo_size) _factor = options_size _result = options_size for _i = _k to 2 _factor -= 1 _result *= _factor _result := math.floor(_result / _i + 1) _result - 1 // usage: // plot(combinations(7, 5)) // 21 // plot(combinations(10, 2)) // 45 // plot(combinations(5, 3)) // 10 // plot(combinations(3, 5)) // 0 // plot(combinations(5, int(na))) // n/a //}
MathConstantsUniversal
https://www.tradingview.com/script/sbkcPfwh-MathConstantsUniversal/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Mathematical Constants library(title='MathConstantsUniversal') // reference: // https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Constants.cs // A collection of frequently used mathematical constants. // UNIVERSAL CONSTANTS { // @function Speed of Light in Vacuum: c_0 = 2.99792458e8 [m s^-1] (defined, exact; 2007 CODATA) export SpeedOfLight () => //{ 2.99792458e8 //} // @function Magnetic Permeability in Vacuum: mu_0 = 4*Pi * 10^-7 [N A^-2 = kg m A^-2 s^-2] (defined, exact; 2007 CODATA) export MagneticPermeability () => //{ 1.2566370614359172953850573533118011536788677597500e-6 //} // @function Electric Permittivity in Vacuum: epsilon_0 = 1/(mu_0*c_0^2) [F m^-1 = A^2 s^4 kg^-1 m^-3] (defined, exact; 2007 CODATA) export ElectricPermittivity () => //{ 8.8541878171937079244693661186959426889222899381429e-12 //} // @function Characteristic Impedance of Vacuum: Z_0 = mu_0*c_0 [Ohm = m^2 kg s^-3 A^-2] (defined, exact; 2007 CODATA) export CharacteristicImpedanceVacuum () => //{ 376.73031346177065546819840042031930826862350835242 //} // @function Newtonian Constant of Gravitation: G = 6.67429e-11 [m^3 kg^-1 s^-2] (2007 CODATA) export GravitationalConstant () => //{ 6.67429e-11 //} // @function Planck's constant: h = 6.62606896e-34 [J s = m^2 kg s^-1] (2007 CODATA) export PlancksConstant () => //{ 6.62606896e-34 //} // @function Reduced Planck's constant: h_bar = h / (2*Pi) [J s = m^2 kg s^-1] (2007 CODATA) export DiracsConstant () => //{ 1.054571629e-34 //} // @function Planck mass: m_p = (h_bar*c_0/G)^(1/2) [kg] (2007 CODATA) export PlancksMass () => //{ 2.17644e-8 //} // @function Planck temperature: T_p = (h_bar*c_0^5/G)^(1/2)/k [K] (2007 CODATA) export PlancksTemperature () => //{ 1.416786e32 //} // @function Planck length: l_p = h_bar/(m_p*c_0) [m] (2007 CODATA) export PlancksLength () => //{ 1.616253e-35 //} // @function Planck time: t_p = l_p/c_0 [s] (2007 CODATA) export PlancksTime () => //{ 5.39124e-44 //} //}
MathComplexExtension
https://www.tradingview.com/script/bceaalfi-MathComplexExtension/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description A set of utility functions to handle complex numbers. library(title='MathComplexExtension') // references: // https://en.wikipedia.org/wiki/Complex_number // js: https://rosettacode.org/wiki/Fast_Fourier_transform // https://github.com/trekhleb/javascript-algorithms/blob/477f30b0bdac6024874d2976de1eca7afe0176dd/src/algorithms/math/complex-number/ComplexNumber.js#L3 // https://github.com/infusion/Complex.js/ // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs //#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/MathConstants/1 as mc //#endregion //#region -> Methods: // get_phase () { // @function The phase value of complex number complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @param in_radians bool . Value for the type of angle value, default=true, options=(true: radians, false: degrees) // @returns float. Value with phase. export method get_phase (TMath.complex this, bool in_radians=true) => float _phase = math.atan(math.abs(this.im) / math.abs(this.re)) if not in_radians _phase := _phase * (180 / math.pi) // radian to degrees else if this.re < 0 and this.im > 0 _phase := math.pi - nz(_phase) else if this.re < 0 and this.im < 0 _phase := -(math.pi - nz(_phase)) else if this.re > 0 and this.im < 0 _phase := -nz(_phase) else if this.re == 0 and this.im > 0 _phase := math.pi / 2.0 else if this.re == 0 and this.im < 0 _phase := -math.pi / 2.0 else if this.re < 0 and this.im == 0 _phase := math.pi else if this.re > 0 and this.im == 0 _phase := 0.0 else if this.re == 0 and this.im == 0 // More correctly would be to set 'indeterminate'. // But just for simplicity reasons let's set zero. _phase := 0.0 else na _phase // } // natural_logarithm () { // remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L350 // https://www.mathworks.com/help/matlab/ref/log.html // @function Natural logarithm of complex number (base E). // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method natural_logarithm (TMath.complex this) => if complex.is_real_non_negative(this) complex.new(math.log(this.re), 0.0) else float _re = math.pow(this.re, 2) float _im = math.pow(this.im, 2) complex.new(0.5 * math.log(complex_op.magnitude_squared(this)), get_phase(this, true)) // } // common_logarithm () { // remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L350 // https://www.mathworks.com/help/matlab/ref/log10.html // @function Common logarithm of complex number (base 10). // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method common_logarithm (TMath.complex this) => complex_op.divide(natural_logarithm(this), complex.new(mc.Ln10(), 0.0)) // } // logarithm () { // remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L350 // https://www.mathworks.com/help/matlab/ref/log10.html // @function Common logarithm of complex number (custom base). // @param this complex . Complex number in the form `(real, imaginary)`. // @param base float . Base value. // @returns complex. Complex number. export method logarithm (TMath.complex this, float base) => complex_op.divide(natural_logarithm(this), complex.new(math.log(base), 0.0)) // } // power () { // remarks: // https://www.superprof.co.uk/resources/academic/maths/arithmetic/complex-numbers/power-of-a-complex-number.html // @function Raise complex number with complex_exponent. // @param this complex . Complex number in the form `(real, imaginary)`. // @param exponent complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method power (TMath.complex this, TMath.complex exponent) => float _a_re = this.re float _a_im = this.im float _b_re = exponent.re float _b_im = exponent.im if complex.is_zero(this) if complex.is_zero(exponent) complex.one() else if _b_re > 0.0 complex.zero() else if _b_re < 0.0 if _b_im == 0 complex.new(float(na), 0.0) // "+∞+0i" else complex.nan() // "+∞+∞i" complex.nan() else // (exponent * natural_logarithm()).exponential() complex_op.exponential(complex_op.multiply(exponent, natural_logarithm(this))) // } // root () { // remarks: // https://www.intmath.com/complex-numbers/7-powers-roots-demoivre.php // @function Raise complex number with inverse of complex_exponent. // @param this complex . Complex number in the form `(real, imaginary)`. // @param exponent complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method root (TMath.complex this, TMath.complex exponent) => power(this, complex_op.divide(complex.one(), exponent)) // } // square () { // remarks: // https://docs.microsoft.com/en-us/dotnet/api/system.numerics.complex.pow?view=net-5.0 // @function Square of complex number (power 2). // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method square (TMath.complex this) => float _re = this.re if complex.is_real(this) complex.new(math.pow(_re, 2.0), 0.0) else float _im = this.im complex.new(math.pow(_re, 2.0) - math.pow(_im, 2.0), 2.0 * _re * _im) // } // square_root () { // remarks: // https://www.brainkart.com/article/Square-roots-of-a-complex-number_39098/ // @function Square root of complex number (power 1/2). // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method square_root (TMath.complex this) => float _re = this.re if complex.is_real_non_negative(this) complex.new(math.sqrt(_re), 0.0) else float _im = this.im float _abs_re = math.abs(_re) float _abs_im = math.abs(_im) float _w = 0.0 if _abs_re >= _abs_im float _ratio = _im / _re _w := math.sqrt(_abs_re) * math.sqrt(0.5 * (1.0 + math.sqrt(1.0 + math.pow(_ratio, 2)))) else float _ratio = _re / _im _w := math.sqrt(_abs_im) * math.sqrt(0.5 * (math.abs(_ratio) + math.sqrt(1.0 + math.pow(_ratio, 2)))) if _re >= 0.0 complex.new(_w, _im / (2.0 * _w)) else if _im >= 0.0 complex.new(_abs_im / (2.0 * _w), _w) else complex.new(_abs_im / (2.0 * _w), -_w) // } // square_roots () { // remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L492 // @function Square root of complex number (power 1/2). // @param this complex . Complex number in the form `(real, imaginary)`. // @returns `array<complex>`. Array with 2 complex numbers, (positive, negative). export method square_roots (TMath.complex this) => _principal = square_root(this) array.from(_principal, complex_op.negative(_principal)) // } // cubic_roots () { // remarks: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Complex32.cs#L501 // @function Square root of complex number (power 1/2). // @param this complex . Complex number in the form `(real, imaginary)`. // @returns `array<complex>`. Array with 3 complex numbers, (neutral, positive, negative). export method cubic_roots (TMath.complex this) => float _r = math.pow(complex_op.magnitude(this), 1.0 / 3.0) float _theta = get_phase(this, true) float _shift = mc.Pi2() / 3.0 array.from( complex.from_polar_coordinates(_r, _theta) , complex.from_polar_coordinates(_r, _theta + _shift) , complex.from_polar_coordinates(_r, _theta - _shift) ) // } // to_polar_form () { // remarks: // https://www.electronics-tutorials.ws/accircuits/complex-numbers.html // @function The polar form value of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @param in_radians boolean, value for the type of angle value, default=true, options=(true: radians, false: degrees) // @returns complex. Complex number, (radius, phase). export method to_polar_form (TMath.complex this, bool in_radians=true) => complex.new(complex_op.radius(this), get_phase(this, in_radians)) // } //#endregion if barstate.islastconfirmedhistory A = complex.new(7.0, -6.0) B = complex.new(-3.0, 4.0) logger.queue_one(str.format('input parameters: (A: {0}, B: {1})', complex.to_string(A, '#.##'), complex.to_string(B, '#.##'))) logger.queue_one(str.format('\n## Extended ##\n', '')) logger.queue_one(str.format('phase of A = (radeans: {0}, in degrees: {1})', get_phase(A, true), get_phase(A, false))) logger.queue_one(str.format('Natural Logarithm (E) of A = {0}', complex.to_string(natural_logarithm(A), '#.##'))) logger.queue_one(str.format('Common Logarithm (10) of A = {0}', complex.to_string(common_logarithm(A), '#.##'))) logger.queue_one(str.format('Logarithm (base=10) of A = {0}', complex.to_string(logarithm(A, 10.0), '#.##'))) logger.queue_one(str.format('Power of A^B = {0}', complex.to_string(power(A, B), '#.##'))) logger.queue_one(str.format('Root of B√A = {0}', complex.to_string(root(A, B), '#.##'))) logger.queue_one(str.format('Square of A = {0}', complex.to_string(square(A), '#.##'))) logger.queue_one(str.format('Square Root of A = {0}', complex.to_string(square_root(A), '#.##'))) Sr = square_roots(A) Cr = cubic_roots(A) logger.queue_one(str.format('Square Roots of A = ({0}, {1})', complex.to_string(Sr.get(0), '#.##'), complex.to_string(Sr.get(1), '#.##'))) logger.queue_one(str.format('Cubic Roots of A = ({0}, {1}, {2})', complex.to_string(Cr.get(0), '#.##'), complex.to_string(Cr.get(1), '#.##'), complex.to_string(Cr.get(2), '#.##'))) logger.queue_one(str.format('Polar form of A = {0}', complex.to_string(to_polar_form(A), '#.##'))) // update console logger.update()
MathFinancialAbsoluteRiskMeasures
https://www.tradingview.com/script/I0tIBRan-MathFinancialAbsoluteRiskMeasures/
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 Financial Absolute Risk Measures. library(title='MathFinancialAbsoluteRiskMeasures') // reference: // https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Financial/AbsoluteRiskMeasures.cs // Note: The following statistics would be considered an absolute risk statistic in the finance realm as well. // Standard Deviation // Annualized Standard Deviation = Math.Sqrt(Monthly Standard Deviation x ( 12 )) // Skewness // Kurtosis // @function Standard deviation of gains in a data sample. // @param sample float array, data sample. // @returns float. export gain_stdev (float[] sample) => //{ int _size = array.size(sample) if _size > 0 float[] _G = array.new_float() for _i = 0 to _size-1 float _xi = array.get(sample, _i) if _xi >= 0.0 array.push(_G, _xi) array.stdev(_G) //{ usage: // plot(gain_stdev(array.from(250.0, -35, 100, 50, -120, 200))) //{ notes: // Calculation is similar to Standard Deviation , except it calculates an average (mean) return only for periods with a gain // and measures the variation of only the gain periods around the gain mean. Measures the volatility of upside performance. // © Copyright 1996, 1999 Gary L.Gastineau. First Edition. © 1992 Swiss Bank Corporation. //}}} // @function Standard deviation of losses in a data sample. // @param sample float array, data sample. // @returns float. export loss_stdev(float[] sample) => //{ int _size = array.size(sample) if _size > 0 float[] _L = array.new_float() for _i = 0 to _size-1 float _xi = array.get(sample, _i) if _xi < 0.0 array.push(_L, _xi) array.stdev(_L) //{ usage: // plot(loss_stdev(array.from(250.0, -35, 100, 50, -120, 200))) //{ notes: // Similar to standard deviation, except this statistic calculates an average (mean) return for only the periods with a loss and then // measures the variation of only the losing periods around this loss mean. This statistic measures the volatility of downside performance. // http://www.offshore-library.com/kb/statistics.php //}}} // @function Downside standard deviation in a data sample. // @param sample float array, data sample. // @param minimal_acceptable_return float, minimum gain value. // @returns float. export downside_stdev (float[] sample, float minimal_acceptable_return=0.0) => //{ int _size = array.size(sample) if _size > 0 float[] _D = array.new_float() for _i = 0 to _size-1 float _xi = array.get(sample, _i) if _xi < minimal_acceptable_return array.push(_D, _xi) array.stdev(_D) //{ usage: // plot(downside_stdev(array.from(250.0, -35, 100, 50, -120, 200), 100.0)) //{ notes: // This measure is similar to the loss standard deviation except the downside deviation // considers only returns that fall below a defined minimum acceptable return (MAR) rather than the arithmetic mean. // For example, if the MAR is 7%, the downside deviation would measure the variation of each period that falls below // 7%. (The loss standard deviation, on the other hand, would take only losing periods, calculate an average return for // the losing periods, and then measure the variation between each losing return and the losing return average). //}}} // @function Standard deviation of less than average returns in a data sample. // @param sample float array, data sample. // @returns float. export semi_stdev (float[] sample) => //{ int _size = array.size(sample) if _size > 0 float[] _S = array.new_float() float _mean = array.avg(sample) for _i = 0 to _size-1 float _xi = array.get(sample, _i) if _xi < _mean array.push(_S, _xi) array.stdev(_S) //{ usage: // plot(semi_stdev(array.from(250.0, -35, 100, 50, -120, 200))) //{ notes: // A measure of volatility in returns below the mean. It's similar to standard deviation, but it only // looks at periods where the investment return was less than average return. //}}} // @function ratio of average gains of average losses in a data sample. // @param sample float array, data sample. // @returns float. export gain_loss_ratio (float[] sample) => //{ int _size = array.size(sample) if _size > 0 float[] _G = array.new_float() float[] _L = array.new_float() for _i = 0 to _size-1 float _xi = array.get(sample, _i) if _xi >= 0 array.push(_G, _xi) else array.push(_L, _xi) math.abs(array.stdev(_G) / array.stdev(_L)) //{ usage: // plot(gain_loss_ratio(array.from(250.0, -35, 100, 50, -120, 200))) //{ notes: // Measures a fund’s average gain in a gain period divided by the fund’s average loss in a losing // period. Periods can be monthly or quarterly depending on the data frequency. //}}} // @function Compound Risk Score // @param source float, input data, default=close. // @param length int, period of observation, default=12) // @returns float. export compound_risk_score (float source=close, int length=12) => //{ float _total = 0.0 float _absolute = 0.0 if length < 1 runtime.error('MathFinancialAbsoluteMeasures -> compound_risk_score(): "length" must be positive > 0.') float(na) else for _i = 1 to length float _diff = source[0] - source[_i] _total += _diff _absolute += math.abs(_diff) (_total / _absolute) * 100 //{ usage: // int length = input.int(100), int avg_length = input.int(25) // float cr = compound_risk_score(close, length) // float ma = math.avg(ta.sma(cr, avg_length), 50.0) // plot(series=cr, color=color.new(color.red, 0)) // plot(series=ma, color=color.new(color.teal, 0)) // hline(100), hline(50), hline(0), hline(-50), hline(-100) //{ remarks: // if you took a trade for every bars close for the duration of the length // how would those trades fair atm? // values closer to (100 | -100) are better for its (bull | bear), closer to 0 will be closer to break eaven. // this indicator is optimal for trending markets. //}}}
MathOperator
https://www.tradingview.com/script/ZwFeHrgh-MathOperator/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
14
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 handle operators. library(title='MathOperator') //#region Arithmetic: // @function Add value a to b. // @param value_a float, value a. // @param value_b float, value b. // @returns float. export method add (float value_a, float value_b) => value_a + value_b // @function subtract value b from a. // @param value_a float, value a. // @param value_b float, value b. // @returns float. export method subtract (float value_a, float value_b) => value_a - value_b // @function multiply value a with b. // @param value_a float, value a. // @param value_b float, value b. // @returns float. export method multiply (float value_a, float value_b) => value_a * value_b // @function divide value a with b. // @param value_a float, value a. // @param value_b float, value b. // @returns float. export method divide (float value_a, float value_b) => value_a / value_b // @function remainder of a with b. // @param value_a float, value a. // @param value_b float, value b. // @returns float. export method remainder (float value_a, float value_b) => value_a % value_b //#endregion //#region Comparison: // @function equality of value a with b. // @param value_a float, value a. // @param value_b float, value b. // @returns bool. export method equal (float value_a, float value_b) => value_a == value_b // @function inequality of value a with b. // @param value_a float, value a. // @param value_b float, value b. // @returns bool. export method not_equal (float value_a, float value_b) => value_a != value_b // @function value a is over b. // @param value_a float, value a. // @param value_b float, value b. // @returns bool. export method over (float value_a, float value_b) => value_a > value_b // @function value a is under b. // @param value_a float, value a. // @param value_b float, value b. // @returns bool. export method under (float value_a, float value_b) => value_a < value_b // @function value a is over equal b. // @param value_a float, value a. // @param value_b float, value b. // @returns bool. export method over_equal (float value_a, float value_b) => value_a >= value_b // @function value a is under equal b. // @param value_a float, value a. // @param value_b float, value b. // @returns bool. export method under_equal (float value_a, float value_b) => value_a <= value_b //#endregion //#region Unity // @function logical and of a with b // @param value_a bool, value a. // @param value_b bool, value b. // @returns bool. export method and_ (bool value_a, bool value_b) => value_a and value_b // @function logical or of a with b. // @param value_a bool, value a. // @param value_b bool, value b. // @returns bool. export method or_ (bool value_a, bool value_b) => value_a or value_b //#endregion
MathGaussFunction
https://www.tradingview.com/script/vctw4KbJ-MathGaussFunction/
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 Implements multiple gauss methods. library(title='MathGaussFunction') // reference: // https://github.com/andrewkirillov/AForge.NET/blob/master/Sources/Math/Gaussian.cs // imports: import RicardoSantos/ArrayExtension/1 as ae // ArrayExtension.index_2d_to_1d() // @function 1-D Gaussian function. // @param point_x float, x value. // @param sigma float, sigma value, default=1.0. // @returns float, function's value at point_x. export f_1d (float point_x, float sigma=1.0 ) => //{ float _sigma2 = math.pow(sigma, 2) float _x2 = point_x * point_x math.exp(_x2 / (-2 * _sigma2)) / (math.sqrt(2 * math.pi ) * sigma) //{ usage: // s = input.float(0.5) // plot(gauss_1d(1.0/(bar_index%1000), s)) //{ remarks: // The function calculates 1-D Gaussian function: // f(x) = exp( x * x / ( -2 * s * s ) ) / ( s * sqrt( 2 * PI ) ) //}}} // @function 2-D Gaussian function. // @param point_x float, x value. // @param point_y float, y value. // @param sigma float, sigma value, default=1.0. // @returns float, function's value at (point_x, point_y). export f_2d (float point_x, float point_y, float sigma=1.0 ) => //{ float _sigma2 = math.pow(sigma, 2) float _x2 = point_x * point_x float _y2 = point_y * point_y math.exp((_x2 + _y2) / (-2 * _sigma2)) / (2 * math.pi * _sigma2) //{ usage: // s = input.float(0.5) // plot(f_2d(1.0/(bar_index%1000), 1.0/(bar_index%500), s)) //{ remarks: // The function calculates 2-D Gaussian function: // f(x, y) = exp( x * x + y * y / ( -2 * s * s ) ) / ( s * s * 2 * PI ) //}}} // @function 1-D Gaussian kernel. // @param size int, Kernel size (should be odd), [3, 101]. // @param sigma float, sigma value, default=1.0. // @returns float array, Returns 1-D Gaussian kernel of the specified size. export kernel_1d (int size, float sigma=1.0) => //{ // check for even size and for out of range if (((size % 2) == 0) or (size < 3) or (size > 101)) runtime.error('MathGaussFunction -> kernel_1d(): wrong kernal size, should be positive, odd and < 100.') float[] _K = na else // radius int _r = size / 2 // kernel float[] _K = array.new_float(size) // compute kernel for _i = 0 to size-1 int _x = -_r + _i array.set(_K, _i, f_1d(_x, sigma)) _K //{ usage: // int size = input.int(99) // float sigma = input.float(1.0) // float[] K = kernel_1d(size, sigma) // plot(array.get(K, bar_index%size)) //{ remarks: // The function calculates 1-D Gaussian kernel, which is array // of Gaussian function's values in the [-r, r] range of x value, where: // r = floor(size / 2) //}}} // @function 2-D Gaussian kernel. // @param size int, Kernel size (should be odd), [3, 101]. // @param sigma float, sigma value, default=1.0. // @returns float array, Returns 2-D Gaussian kernel of the specified size. export kernel_2d( int size, float sigma=1.0) => //{ // check for even size and for out of range if (((size % 2) == 0) or (size < 3) or (size > 101)) runtime.error('MathGaussFunction -> kernel_2d(): wrong kernal size, should be positive, odd and < 100.') float[] _K = na else // radius int _r = size / 2 // kernel float[] _K = array.new_float(size*size) // compute kernel for _i = 0 to size-1 int _y = _r + _i for _j = 0 to size-1 int _x = -_r + _j array.set(_K, ae.index_2d_to_1d(size, size, _i, _j), f_2d(_x, _y, sigma)) _K //{ usage: // int size = input.int(11) // float sigma = input.float(3.1416) // float[] K = kernel_2d(size, sigma) // plot(array.get(K, bar_index%(size*size))) //{ remarks: // The function calculates 2-D Gaussian kernel, which is array // of Gaussian function's values in the [-r, r] range of x value, where: // r = floor(size / 2) //}}}
MathTrigonometry
https://www.tradingview.com/script/uPvNG85Y-MathTrigonometry/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
19
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 Trigonometric methods. library("MathTrigonometry") // reference: // https://www.brighthubeducation.com/homework-math-help/72270-trigonometry-functions-a-trig-functions-list/ // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Trigonometry.cs // @function Normalized sinc function. // @param value float, value. // @returns float. export sinc (float value) => //{ float _z = math.pi * value if math.abs(_z) <= 1.0e-15 // almost equal 1.0 else math.sin(_z) / _z //} //###################################### // @function Cotangent of value. // @param value float, value. // @returns float. export cot (float value) => //{ 1.0 / math.tan(value) //} // @function Cosecant of value. // @param value float, value. // @returns float. export csc (float value) => //{ 1.0 / math.sin(value) //} // @function Secant of value. // @param value float, value. // @returns float. export sec (float value) => //{ 1.0 / math.cos(value) //} ///################# // @function Arc cotangent of value. // @param value float, adjacent value. // @returns float. export acot (float value) => //{ math.atan(1.0 / value) //} // @function Arc secant of value. // @param value float, hypotenuse value. // @returns float. export asec (float value) => //{ math.acos(1.0 / value) //} // @function Arc cosecant of value. // @param value float, hipotenuse value. // @returns float. export acsc (float value) => //{ math.atan(1.0 / value) //} //################ // @function Hyperbolic sine of angle. // @param angle float, value. // @returns float. export sinh (float angle) => //{ (math.exp(angle) - math.exp(-angle)) / 2.0 //} // @function Hyperbolic cosine of angle. // @param angle float, value. // @returns float. export cosh (float angle) => //{ (math.exp(angle) + math.exp(-angle)) / 2.0 //} // @function Hyperbolic tangent of angle. // @param angle float, value. // @returns float. export tanh (float angle) => //{ if angle > 19.1 1.0 else if angle -19.1 -1.0 else float _e1 = math.exp(angle) float _e2 = math.exp(-angle) (_e1 - _e2) / (_e1 + _e2) //} // @function Hyperbolic cotangent of angle. // @param angle float, value. // @returns float. export coth (float angle) => //{ if angle > 19.1 1.0 else if angle -19.1 -1.0 else float _e1 = math.exp(angle) float _e2 = math.exp(-angle) (_e1 + _e2) / (_e1 - _e2) //} // @function Hyperbolic secant of angle. // @param angle float, value. // @returns float. export sech (float angle) => //{ 1.0 / cosh(angle) //} // @function Hyperbolic cosecant of angle. // @param angle float, value. // @returns float. export csch (float angle) => //{ 1.0 / sinh(angle) //} //############################# // @function Hyperbolic area sine. // @param value float, value. // @returns float. export asinh (float value) => //{ //https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Trigonometry.cs#L711 float _absv = math.abs(value) if _absv >= 268435456.0 math.sign(value) * (math.log(_absv) + math.log(2.0)) else math.sign(value) * math.log(_absv + math.sqrt(1.0 + math.pow(value, 2.0))) //} // @function Hyperbolic area cosine. // @param value float, value. // @returns float. export acosh (float value) => //{ //https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Trigonometry.cs#L737 float _absv = math.abs(value) if _absv >= 268435456.0 math.log(value) + math.log(2.0) else math.log(value + (math.sqrt(value -1.0) * math.sqrt(value + 1.0))) //} // @function Hyperbolic area tangent. // @param value float, value. // @returns float. export atanh (float value) => //{ 0.5 * math.log((value + 1.0) / (value - 1.0)) //} // @function Hyperbolic area cotangent. // @param value float, value. // @returns float. export acoth (float value) => //{ 0.5 * math.log((value + 1.0) / (value - 1.0)) //} // @function Hyperbolic area secant. // @param value float, value. // @returns float. export asech (float value) => //{ acosh(1.0 / value) //} // @function Hyperbolic area cosecant. // @param value float, value. // @returns float. export acsch (float value) => //{ asinh(1.0 / value) //}
MathSpecialFunctionsLogistic
https://www.tradingview.com/script/LewVcQ7L-MathSpecialFunctionsLogistic/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Methods for logistic equation. library(title='MathSpecialFunctionsLogistic') // @function Computes the logistic function. // @param probability float, value to compute the logistic function. // @returns float export logistic (float probability) => //{ 1.0 / (math.exp(-probability) + 1.0) //{ usage: plot(logistic(0.618)) //{ remarks: // http://en.wikipedia.org/wiki/Logistic //}}} // @function Computes the logit function, the inverse of the sigmoid logistic function. // @param probability float, value to compute the logit function. // @returns float export logit (float probability) => //{ if probability < 0.0 or probability > 1.0 runtime.error('MathSpecialFunctionsLogistic -> logit(): "probability" must be within 0 and 1.') math.log(probability / (1.0 - probability)) //{ usage: plot(logit(0.618)) //{ remarks: // http://en.wikipedia.org/wiki/Logistic //}}}
MathSearchDijkstra
https://www.tradingview.com/script/QPcilaZc-MathSearchDijkstra/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Shortest Path Tree Search Methods using Dijkstra Algorithm. library("MathSearchDijkstra") // reference: // https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm // https://blog.quantinsti.com/dijkstra-algorithm/ // https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/ // possible future implementation? multiple point search: https://iopscience.iop.org/article/10.1088/1742-6596/1530/1/012040/pdf import RicardoSantos/ArrayExtension/1 as ae // @function Find the lowest cost/distance. // @param distances float array, data set with distance costs to start index. // @param flagged_vertices bool array, data set with visited vertices flags. // @returns int, lowest cost/distance index. export min_distance (int[] distances, bool[] flagged_vertices) => //{ int _size_d = array.size(distances) int _size_v = array.size(flagged_vertices) if _size_d < 1 runtime.error('MathSearchDijkstra -> min_distance(): "distances" has the wrong size.') int(na) else if _size_d != _size_v runtime.error('MathSearchDijkstra -> min_distance(): "distances" and "flagged_vertices" size does not match.') int(na) else // int __MAXINT__ = 9223372036854776000 // props to @XelArjona!! // Initialize min value int _min = 9223372036854776000 int _min_index = -1 for _i = 0 to _size_d - 1 int _d = array.get(distances, _i) if (not array.get(flagged_vertices, _i)) and _d <= _min _min := _d _min_index := _i _min_index //{ usage: //{ remarks: //}}} // @function Dijkstra Algorithm, perform a greedy tree search to calculate the cost/distance to selected start node at each vertex. // @param matrix_graph int array, matrix holding the graph adjacency list and costs/distances. // @param dim_x int, x dimension of matrix_graph. // @param dim_y int, y dimension of matrix_graph. // @param start int, the vertex index to start search. // @returns int array, set with costs/distances to each vertex from start vertexs. export dijkstra (int[] matrix_graph, int dim_x, int dim_y, int start) => //{ // int __MAXINT__ = 9223372036854776000 // props to @XelArjona!! int _size_m = array.size(matrix_graph) if _size_m < 2 runtime.error('MathSearchDijkstra -> search(): "matrix_graph" has the wrong size.') array.new_int(na) if _size_m != (dim_x * dim_y) runtime.error('MathSearchDijkstra -> search(): dimensions and size does not match.') array.new_int(na) else int[] _distances = array.new_int(dim_x, 9223372036854776000) bool[] _visited = array.new_bool(dim_x, false) array.set(_distances, start, 0) for _i = 0 to dim_x-1 int _nearest_index = min_distance(_distances, _visited) array.set(_visited, _nearest_index, true) for _v = 0 to dim_x-1 bool _is_visited = array.get(_visited, _v) if (not _is_visited) int _distance_between = array.get(matrix_graph, ae.index_2d_to_1d(dim_x, dim_y, _nearest_index, _v)) if (_distance_between != 0) int _distance_to_nearest = array.get(_distances, _nearest_index) int _distance_to_current = array.get(_distances, _v) int _tentative_sum = _distance_to_nearest + _distance_between if (_distance_to_nearest != 9223372036854776000) and (_tentative_sum < _distance_to_current) array.set(_distances, _v, _tentative_sum) _distances //{ usage: //{ remarks: //}}} // @function Retrieves the shortest path between 2 vertices in a graph using Dijkstra Algorithm. // @param start int, the vertex index to start search. // @param end int, the vertex index to end search. // @param matrix_graph int array, matrix holding the graph adjacency list and costs/distances. // @param dim_x int, x dimension of matrix_graph. // @param dim_y int, y dimension of matrix_graph. // @returns int array, set with vertex indices to the shortest path. export shortest_path (int start, int end, int[] matrix_graph, int dim_x, int dim_y) => //{ // start + end + array.size(matrix_graph) + dim_x + dim_y // just to use all param.. int _size_m = array.size(matrix_graph) int[] _distances = dijkstra (matrix_graph, dim_x, dim_y, start) int[] _path = array.new_int(1, end) // build path backwards with the least cost: // 1: end vertex // 2: check adjacent vertex sum + edge cost to current vertex, // 3: if its smaller or equal add it to path, else skip // 4: repeat. _current_vertex = end while _current_vertex != start for _i = 0 to dim_x - 1 _vi = array.get(matrix_graph, ae.index_2d_to_1d(dim_x, dim_y, _current_vertex, _i)) if _vi != 0 _di = array.get(_distances, _i) if _di + _vi <= array.get(_distances, _current_vertex) array.unshift(_path, _i) _current_vertex := _i _path //{ usage: //{ remarks: //}}} int n_vertices = 9 // adjacency list matrix: var int[] graph = array.from( 0, 4, 0, 0, 0, 0, 0, 8, 0, 4, 0, 8, 0, 0, 0, 0, 11, 0, 0, 8, 0, 7, 0, 4, 0, 0, 2, 0, 0, 7, 0, 9, 14, 0, 0, 0, 0, 0, 0, 9, 0, 10, 0, 0, 0, 0, 0, 4, 14, 10, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 6, 8, 11, 0, 0, 0, 0, 1, 0, 7, 0, 0, 2, 0, 0, 0, 6, 7, 0) int start = input.int(defval=0, minval=0, maxval=n_vertices) int end = input.int(defval=8, minval=0, maxval=n_vertices) var int[] dist = dijkstra(graph, n_vertices, n_vertices, start) var int[] path = shortest_path(start, end, graph, n_vertices, n_vertices) var int[] indices = array.from(0,1,2,3,4,5,6,7,8) var label legend = label.new(bar_index, 0.0, str.format('index:{0}\ncosts:{1}\npath :{2}', str.tostring(indices), str.tostring(dist), str.tostring(path)), style=label.style_label_center, textalign=text.align_left) if barstate.isfirst // nodes x, y coordinates: int[] _x = array.from(000, 010, 020, 030, 040, 050, 060, 070, 080) int[] _y = array.from(180, 160, 000, 020, 020, 160, 020, 180, 000) for _i = 0 to n_vertices-1 int _nodexi = array.get(_x, _i) int _nodeyi = array.get(_y, _i) bool _is_ipath = array.includes(path, _i) color _col_ispath = _is_ipath ? color.yellow : color.blue label.new(_nodexi, _nodeyi, '', color=_col_ispath, style=label.style_circle, size=size.large) label.new(_nodexi, _nodeyi, str.tostring(_i), color=color.new(#000000, 100), style=label.style_label_center, size=size.large, tooltip=str.tostring(array.get(dist, _i))) for _j = 0 to _i int _gij = array.get(graph, ae.index_2d_to_1d(n_vertices, n_vertices, _i, _j)) if _gij > 0 int _nodexj = array.get(_x, _j) int _nodeyj = array.get(_y, _j) bool _is_jpath = array.includes(path, _j) if _is_ipath and _is_jpath line.new(_nodexi, _nodeyi, _nodexj, _nodeyj, color=color.new(color.yellow, 30), width=3) else line.new(_nodexi, _nodeyi, _nodexj, _nodeyj, color=color.new(color.gray, 50), width=1) label.new(int((_nodexi+_nodexj)/2), (_nodeyi+_nodeyj)/2, str.tostring(_gij), color=color.gray, style=label.style_label_center, size=size.normal) //#
MathGeometryCurvesChaikin
https://www.tradingview.com/script/hNgC2qUb-MathGeometryCurvesChaikin/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Implements the chaikin algorithm to create a curved path, from assigned points. library("MathGeometryCurvesChaikin") // reference: // https://www.bit-101.com/blog/2021/08/chaikins-algorithm-drawing-curves/ // @function Chaikin algorithm method, uses provided points to generate a smoothed path. // @param points_x float array, the x value of points. // @param points_y float array, the y value of points. // @param closed bool, default=false, is the path closed or not. // @returns tuple with 2 float arrays. export chaikin (float[] points_x, float[] points_y, bool closed=false) => //{ int _size_x = array.size(points_x) int _size_y = array.size(points_y) if _size_x < 2 runtime.error('MathGeometryCurvesChaikin -> chaikin(): "points_x" has the wrong size.') [array.new_float(na), array.new_float(na)] if _size_x != _size_y runtime.error('MathGeometryCurvesChaikin -> chaikin(): "points_x" and "points_y" size does not match.') [array.new_float(na), array.new_float(na)] else float _first_x = array.get(points_x, 0) float _first_y = array.get(points_y, 0) float _last_x = array.get(points_x, _size_x-1) float _last_y = array.get(points_y, _size_x-1) float[] _path_x = array.new_float(0) float[] _path_y = array.new_float(0) if not closed array.push(_path_x, _first_x) array.push(_path_y, _first_y) for _i = 0 to _size_x - 2 float _p0x = array.get(points_x, _i) float _p0y = array.get(points_y, _i) float _p1x = array.get(points_x, _i + 1) float _p1y = array.get(points_y, _i + 1) float _dx = _p1x - _p0x float _dy = _p1y - _p0y array.push(_path_x, _p0x + _dx * 0.25) array.push(_path_y, _p0y + _dy * 0.25) array.push(_path_x, _p0x + _dx * 0.75) array.push(_path_y, _p0y + _dy * 0.75) if not closed array.push(_path_x, _last_x) array.push(_path_y, _last_y) else float _dx = _first_x - _last_x float _dy = _first_y - _last_y array.push(_path_x, _last_x + _dx * 0.25) array.push(_path_y, _last_y + _dy * 0.25) array.push(_path_x, _last_x + _dx * 0.75) array.push(_path_y, _last_y + _dy * 0.75) [_path_x, _path_y] //} // @function Iterate the chaikin algorithm, to smooth a sample of points into a curve path. // @param points_x float array, the x value of points. // @param points_y float array, the y value of points. // @param iterations int, number of iterations to apply the smoothing. // @param closed bool, default=false, is the path closed or not. // @returns array of lines. export smooth (float[] points_x, float[] points_y, int iterations=5, bool closed=false) => //{ int _size_x = array.size(points_x) int _size_y = array.size(points_y) if _size_x < 2 runtime.error('MathGeometryCurvesChaikin -> smooth(): "points_x" has the wrong size.') [array.new_float(na), array.new_float(na)] if _size_x != _size_y runtime.error('MathGeometryCurvesChaikin -> smooth(): "points_x" and "points_y" size does not match.') [array.new_float(na), array.new_float(na)] else _path_x = array.copy(points_x) _path_y = array.copy(points_y) if iterations > 0 for _i = 1 to iterations [_x, _y] = chaikin(_path_x, _path_y, closed) _path_x := _x _path_y := _y [_path_x, _path_y] //} // @function Draw the path. // @param path_x float array, the x value of the path. // @param path_y float array, the y value of the path. // @param closed bool, default=false, is the path closed or not. // @returns array of lines. export draw (float[] path_x, float[] path_y, bool closed=false) => int _size_x = array.size(path_x) int _size_y = array.size(path_y) if _size_x < 2 runtime.error('MathGeometryCurvesChaikin -> smooth(): "points_x" has the wrong size.') array.new_line(na) if _size_x != _size_y runtime.error('MathGeometryCurvesChaikin -> smooth(): "points_x" and "points_y" size does not match.') array.new_line(na) else line[] path_segments = array.new_line(0) for _i = 0 to _size_x - 2 int _p0x = int(array.get(path_x, _i)) float _p0y = array.get(path_y, _i) int _p1x = int(array.get(path_x, _i+1)) float _p1y = array.get(path_y, _i+1) array.push(path_segments, line.new(_p0x, _p0y, _p1x, _p1y)) if closed array.push(path_segments, line.new(int(array.get(path_x, _size_x-1)), array.get(path_y, _size_x-1), int(array.get(path_x, 0)), array.get(path_y, 0))) path_segments int sample_size = input.int(5) var float[] samples_x = array.new_float(sample_size) var float[] samples_y = array.new_float(sample_size) if barstate.isfirst for _i = 0 to sample_size-1 array.set(samples_x, _i, 50.0 + 100.0 * math.random()) array.set(samples_y, _i, 50.0 + 100.0 * math.random()) bool closed = input.bool(true) int iterations = input.int(2) if barstate.islastconfirmedhistory [_x, _y] = smooth(samples_x, samples_y, iterations, closed) draw(_x, _y, closed)
AutoColor
https://www.tradingview.com/script/4B0vjb1O-autocolor/
dmdman
https://www.tradingview.com/u/dmdman/
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/ // © dmdman //@version=5 //testing new version features... // @description Function provides rgb color based on deviation of highest and lowest value for the period from current value library("AutoColor", overlay = true) // @function Calculates rgb color based on deviation of highest and lowest value for the period from current value // @param src1 Series to use (`close` is used if no argument is supplied). // @param len1 Length for highest and lowest series (`10` is used if no argument is supplied). // @returns color for series export fColor(float src1 = close, int len1 = 10) => float libHi = ta.highest(src1,len1) float libLo = ta.lowest(src1,len1) float flt1 = (src1-libLo)/(libHi-libLo) color out = color.rgb(255*(1-flt1),255*flt1,0) out plot(series = hl2,linewidth = 3,color=fColor(hl2,40))
Double_Triple_EMA
https://www.tradingview.com/script/0cCS57GC-Double-Triple-EMA/
KevanoTrades
https://www.tradingview.com/u/KevanoTrades/
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/ // © KevanoTrades //@version=5 // @description Provides the functions to calculate Double and Triple Exponentional Moving Averages (DEMA & TEMA). library("Double_Triple_EMA", true) // @function Calculates Double Exponentional Moving Averages (DEMA) // @param _source -> Open, Close, High, Low, etc ('close' is used if no argument is supplied) // @param _length -> DEMA length // @returns Double Exponential Moving Average (DEMA) of an input source at the specified input length export dema(float _source = close, simple int _length) => float e1 = ta.ema(_source, _length) float e2 = ta.ema(e1, _length) float DEMA = (2 * e1) - e2 DEMA // @function Calculates Triple Exponentional Moving Averages (TEMA) // @param _source -> Open, Close, High, Low, etc ('close' is used if no argument is supplied) // @param _length -> TEMA length // @returns Triple Exponential Moving Average (TEMA) of an input source at the specified input length export tema(float _source = close, simple int _length) => float e1 = ta.ema(_source, _length) float e2 = ta.ema(e1, _length) float e3 = ta.ema(e2, _length) float TEMA = (3 * e1) - (3 * e2) + e3 TEMA // plot demo plot(dema(close, 100), title="Double Exponential Moving Average", color=color.yellow) plot(tema(close, 100), title="Triple Exponential Moving Average", color=color.aqua)