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
X
https://www.tradingview.com/script/SpLFamSD-X/
fikira
https://www.tradingview.com/u/fikira/
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/ // © fikira //@version=5 // @description a collection of 'special' methods/functions ('special' at the time of conception) // Initial functions includes: // • count of a given number in a given array // • array.get() but option added to use negative index // • sum of all digits until the output < 10 // • slope/angle calculation of lines library("X", overlay=true) n = bar_index _ = " ----------------------------- ----------------------------- ----------------------------- ---------------------------- METHODS : FUNCTIONS ----------------------------- ----------------------------- ----------------------------- ---------------------------- " _ = " ----------------------------- ----------------------------- ----------------------------- ---------------------------- Typically, we use loops for counting how many values an array contains. With count_num_in_array(), we don't use a loop, but the build-in functions array.sort(), array.includes(), array.lastindexof() and array.indexof() This should give us better performance due to using less loops ----------------------------- ----------------------------- ----------------------------- ---------------------------- " // @function counts how many times a given number is present in a given array (0 when not present) // @param arr array<int> // @param num Number that needs to be counted (int, float) // @returns count of number in array (0 when not present) export method count_num_in_array(array< int > arr, int num) => arr.sort(), arr.includes(num) ? arr.lastindexof(num) - arr.indexof(num) + 1 : 0 // @function counts how many times a given number is present in a given array (0 when not present) // @param arr array<float> // @param num Number that needs to be counted (int, float) // @returns count of number in array (0 when not present) export method count_num_in_array(array<float> arr, float num) => arr.sort(), arr.includes(num) ? arr.lastindexof(num) - arr.indexof(num) + 1 : 0 _ = " ----------------------------- ----------------------------- ----------------------------- ---------------------------- array.get() can only be used with a positive index, indexes as -1, -2, ... are not allowed. For the ones who want to, the get_() function is able to use negative indexes ----------------------------- ----------------------------- ----------------------------- ---------------------------- " // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<int> // @param idx index // @returns value/object at index, 'na' if index is outside array export method get_(array<int> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<float> // @param idx index // @returns value/object at index, 'na' if index is outside array export method get_(array<float> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<string> // @param idx Index // @returns value/object at index, 'na' if index is outside array export method get_(array<string> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<bool> // @param idx Index // @returns value/object at index, 'na' if index is outside array export method get_(array<bool> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<label> // @param idx Index // @returns value/object at index, 'na' if index is outside array export method get_(array<label> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<line> // @param idx Index // @returns value/object at index, 'na' if index is outside array export method get_(array<line> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<box> // @param idx Index // @returns value/object at index, 'na' if index is outside array export method get_(array<box> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) // @function array.get() but you can use negative index (-1 is last of array, -2 is second last,...) // @param arr array<color> // @param idx Index // @returns value/object at index, 'na' if index is outside array export method get_(array<color> arr, int idx) => sz = arr.size(), sz == 0 or idx < -sz or idx > sz -1 ? na : arr.get(idx + (idx < 0 ? sz : 0)) _ = " ----------------------------- ----------------------------- ----------------------------- ---------------------------- There are people who believe in the power of certain numbers between 0 and 9, they count every digit until they end up with a number between 0 and 9 For example -> count every digit of 123456 -> 1+2+3+4+5+6 = 21, if the sum is higher then 9, repeat -> 2+1 = 3 It was not so easy to create a function which uses as less string manipulation as possible (more string manupulation is greater risk for memory errors) I finally ended up with sumAllNumbers_till_under_10() ----------------------------- ----------------------------- ----------------------------- ---------------------------- " // @function sums all separate digit numbers, it repeats the process until sum < 10 // @param num Number (int) // @returns value between 0 and 9 export method sumAllNumbers_till_under_10(int num) => calc = str.tonumber(str.replace(str.tostring(num), ".", "")) % 9, num == 0 ? 0 : calc == 0 ? 9 : calc // @function sums all separate digit numbers, it repeats the process until sum < 10 // @param num Number (float) // @returns value between 0 and 9 export method sumAllNumbers_till_under_10(float num) => calc = str.tonumber(str.replace(str.tostring(num), ".", "")) % 9, num == 0 ? 0 : calc == 0 ? 9 : calc _ = " ----------------------------- ----------------------------- ----------------------------- ---------------------------- Angle / slope calculation is tricky due to different units in X and Y axis (bar_index vs. price) Also, certain techniques give very different result when comparing historical data, due to price fluctuations. With the techniques in XYaxis() and calculate_slope() I tried to create angles / slopes which are rather similar on all bars. Importantly, XYaxis() always needs to be placed globally, calculate_slope() can be placed locally. The XYratio can be useful for finetuning, since every user has other habits regarding zooming in on the chart. Zooming in/out doesn't change bars/price, but it does change our angle perspective. Therefore XYratio can be very useful (for example as input.float(3, '', minval=0, maxval=10)) ----------------------------- ----------------------------- ----------------------------- ---------------------------- " // @function Global function to calculate Yaxis, which is used in calculate_slope() method // @param width Amount of bars for reference X-axis // @returns Yaxis export method XYaxis(int width) => Xaxis = math.min(math.max(1, n), width), ta.highest(Xaxis) - ta.lowest(Xaxis) // @function Returns a normalised slope // @param width Amount of bars to calculate height // @param XYratio Ratio to calculate height (from width) normalised_slope calculation // @param Yaxis Y-axis from XYaxis() method // @param x1 x1 of line // @param y1 y1 of line // @param x2 x2 of line // @param y2 y2 of line // @returns Tuple of [slope, angle] -> slope = price difference per bar export method calculate_slope(int width, float XYratio, float Yaxis, int x1, float y1, int x2, float y2) => height = width / XYratio diffX = x2 - x1 diffY = y2 - y1 diffY_to_Yaxis = Yaxis / diffY normalised_slope = (height / diffY_to_Yaxis) / diffX slope = diffY / diffX angle = math.round(math.atan(normalised_slope) * 180 / math.pi, 2) [slope, angle] _ = " ----------------------------- ----------------------------- ----------------------------- ---------------------------- EXAMPLES ----------------------------- ----------------------------- ----------------------------- ---------------------------- " import fikira/X/1 as X // count_num_in_array(), get_() & sumAllNumbers_till_under_10() // Typically, we use loops for counting how many values an array contains // With count_num_in_array(), we don't use a loop, but the build-in functions array.sort(), array.includes(), array.lastindexof() and array.indexof() // this should give us better performance due to using less loops aF1 = array.from(3, 4, 3, 0, 1., 2, 3, 4) // array<float> -> becomes sorted by count_num_in_array() aI1 = array.from(3, 4, 3, 0, 1 , 2, 3, 4) // array<int> -> becomes sorted by count_num_in_array() aI2 = array.from(3, 4, 3, 0, 1 , 2, 3, 4) // array<int> -> not sorted plot(X.count_num_in_array(aF1, 3) , color=color.red) // count_num_in_array() used as FUNCTION plot(aF1.count_num_in_array(5) , color=color.blue) // count_num_in_array() used as METHOD plot(aI1.count_num_in_array(0) , color=color.white) plot(aI2.get_(-3) , color=color.yellow) plot(close.sumAllNumbers_till_under_10(), color=color.fuchsia) // XYaxis() & calculate_slope() type p int b float p var aPiv = array.new<p>(2, p.new(na, na)) len = 10 ph = ta.pivothigh(len, len) bars = 500 Yaxis = bars.XYaxis() if not na(ph) [slope, angle] = bars.calculate_slope( XYratio = 3 , Yaxis = Yaxis , x1 = aPiv.first().b , y1 = aPiv.first().p , x2 = n -len , y2 = ph ) line.new (aPiv.first().b, aPiv.first().p, n -len, ph, color=color.fuchsia) label.new( n -len, ph , text = str.format("slope: {0} / bar\nangle: {1}°", slope, angle) , style = label.style_none , textcolor = color.yellow ) aPiv.unshift(p.new(n - len, ph)), aPiv.pop() var label lab = label.new( na , na , color =color.new(color.blue, 100) , style = label.style_label_left , textcolor = chart.fg_color , size = size.large ) if barstate.islast lab.set_xy (n + 1, hl2) lab.set_text( str.format( "4 is x times in array: {0}\narray.get(-3): {1}\nSum digits 'close' till < 10: {2}" , aF1.count_num_in_array(4) , aI2.get_(-3) , close.sumAllNumbers_till_under_10() ) )
TableUtils
https://www.tradingview.com/script/i1uOvZ27-TableUtils/
pmarino84
https://www.tradingview.com/u/pmarino84/
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/ // © pmarino84 //@version=5 // @description TODO: add library description here library("TableUtils", true) const string TABLE_POSITION_TOP_LEFT = "Top left" const string TABLE_POSITION_TOP_RIGHT = "Top right" const string TABLE_POSITION_BOTTOM_LEFT = "Bottom left" const string TABLE_POSITION_BOTTOM_RIGHT = "Bottom right" const string TABLE_POSITION_MIDDLE_LEFT = "Middle left" const string TABLE_POSITION_MIDDLE_RIGHT = "Middle right" // @function Return the position for the table by given label. Useful if you want to control the position of the table with a pine script input selector that use a more human friendly labels // @param tablePosition (string) Label of the table position. Possible values are: "Top left", "Top right", "Bottom left", "Bottom right", "Middle left", "Middle right" // @returns the position for the table by given label. Useful if you want to control the position of the table with a pine script input selector that use a more human friendly labels export getTablePositionByLabel(string tablePosition) => switch tablePosition "Top left" => position.top_left //"Top right" => position.top_right // default "Bottom left" => position.bottom_left "Bottom right" => position.bottom_right "Middle left" => position.middle_left "Middle right" => position.middle_right => position.top_right // EXAMPLE OF USAGE trendToText(trend) => trend == 0 ? "Neutral" : (trend == 1 ? "Bullish" : "Bearish") trendToColorBg(float trend, color bgColor = na) => trend == 1 ? color.green : (trend == -1 ? color.red : bgColor) trendToColorTxt(trend) => trend == 1 or trend == -1 ? color.white : color.black drawTestTable(float trend1D, float trend4H, float trend1H, float trend15, string position = position.top_right, color bgColor = color.gray, color textColor = color.white) => var tableId = table.new(position, 3, 10, border_width = 1) // table header table.cell(tableId, 0, 0, " ") table.cell(tableId, 1, 0, "Trend", bgcolor = bgColor, text_color = textColor) // timeframes info table.cell(tableId, 0, 1, "1D", text_color = textColor, bgcolor = bgColor) table.cell(tableId, 1, 1, trendToText(trend1D), text_color = trendToColorTxt(trend1D), bgcolor = trendToColorBg(trend1D, bgColor)) table.cell(tableId, 0, 2, "4H", text_color = textColor, bgcolor = bgColor) table.cell(tableId, 1, 2, trendToText(trend4H), text_color = trendToColorTxt(trend4H), bgcolor = trendToColorBg(trend4H, bgColor)) table.cell(tableId, 0, 3, "1H", text_color = textColor, bgcolor = bgColor) table.cell(tableId, 1, 3, trendToText(trend1H), text_color = trendToColorTxt(trend1H), bgcolor = trendToColorBg(trend1H, bgColor)) table.cell(tableId, 0, 4, "15m", text_color = textColor, bgcolor = bgColor) table.cell(tableId, 1, 4, trendToText(trend15), text_color = trendToColorTxt(trend15), bgcolor = trendToColorBg(trend15, bgColor)) tableId trendTablePosition = input.string(TABLE_POSITION_TOP_RIGHT, "Table position", options = [TABLE_POSITION_TOP_LEFT, TABLE_POSITION_TOP_RIGHT, TABLE_POSITION_BOTTOM_LEFT, TABLE_POSITION_BOTTOM_RIGHT, TABLE_POSITION_MIDDLE_LEFT, TABLE_POSITION_MIDDLE_RIGHT]) fastMA = ta.ema(close, 8) slowMA = ta.ema(close, 21) [fastMa1D, slowMa1D] = request.security(syminfo.tickerid, "1D", [fastMA, slowMA], barmerge.gaps_off) [fastMa4H, slowMa4H] = request.security(syminfo.tickerid, "240", [fastMA, slowMA], barmerge.gaps_off) [fastMa1H, slowMa1H] = request.security(syminfo.tickerid, "60", [fastMA, slowMA], barmerge.gaps_off) [fastMa15, slowMa15] = request.security(syminfo.tickerid, "15", [fastMA, slowMA], barmerge.gaps_off) trend1D = math.sign(fastMa1D - slowMa1D) trend4H = math.sign(fastMa4H - slowMa4H) trend1H = math.sign(fastMa1H - slowMa1H) trend15 = math.sign(fastMa15 - slowMa15) if barstate.islast drawTestTable(trend1D, trend4H, trend1H, trend15, getTablePositionByLabel(trendTablePosition))
[Library] VAcc
https://www.tradingview.com/script/RpRjfuvX-Library-VAcc/
algotraderdev
https://www.tradingview.com/u/algotraderdev/
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/ // © algotraderdev & Scott Cong // Based on "Stocks & Commodities V. 41:09 (8–15): VAcc: A Momentum Indicator Based On Velocity And Acceleration by Scott Cong, PhD" //@version=5 library('vacc') // @function Caculates the velocity and acceleration with the given length and smoothness. // @param source Series of values to process. // @param length Number of periods to process. // @param smoothness The smoothing period. // @returns A tuple containing the velocity and acceleration. export get(series float source, simple int length, simple int smoothness) => float sumVel = 0 for i = 1 to length sumVel += (source - source[i]) / i vel = ta.ema(sumVel / length, smoothness) float sumAcc = 0 for i = 1 to length sumAcc += (vel - vel[i]) / i acc = sumAcc / length [vel, acc] float SOURCE = input.source(close, 'Source') int LENGTH = input.int(26, 'Length', minval = 2, step = 1) int SMOOTH = input.int(9, 'Smooth', minval = 1, step = 1) color VELOCITY_COLOR = input.color(color.blue, 'Velocity', group = 'Colors') color ABOVE_GROW_COLOR = input.color(#26a69a, 'Above Zero Grow', inline = 'Above', group = 'Colors') color ABOVE_FALL_COLOR = input.color(#b2dfdb, 'Fall', inline = 'Above', group = 'Colors') color BELOW_GROW_COLOR = input.color(#ffcdd2, 'Below Zero Grow', inline = 'Below', group = 'Colors') color BELOW_FALL_COLOR = input.color(#ff5252, 'Fall', inline = 'Below', group = 'Colors') [vel, acc] = get(SOURCE, LENGTH, SMOOTH) color accColor = if acc >= 0 acc[1] < acc ? ABOVE_GROW_COLOR : ABOVE_FALL_COLOR else acc[1] < acc ? BELOW_GROW_COLOR : BELOW_FALL_COLOR plot(acc * 100, 'Acc', color = accColor, style = plot.style_columns) plot(vel / LENGTH * 200, 'Vel', VELOCITY_COLOR)
MyVolatilityBandss
https://www.tradingview.com/script/YQjJuMNE-MyVolatilityBandss/
cryptorepos
https://www.tradingview.com/u/cryptorepos/
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/ // © ClassicScott //@version=5 // @description Just a lil' library of volatility bands that I use in some scripts library("MyVolatilityBandss") // @function Bollinger Bands // @param src float // @param lkbk int // @param mult float // @param basis float // @param band_width float // @returns Bollinger Bands with an outer band of varying thickness adjustable by the band_width input export bollingerbands(float src, int lkbk, float mult, float basis, float band_width) => dev = mult * ta.stdev(src, lkbk) upper = basis + dev lower = basis - dev width = (upper - lower) / band_width inner_upper = upper - width inner_lower = lower + width [basis, upper, lower, inner_upper, inner_lower] // @function Donchian Channels // @param src float // @param lkbk int // @param band_width float // @returns Donchian Channels with an outer band of varying thickness adjustable by the band_width input export donchianchannels(float src, int lkbk, float band_width) => upper = ta.highest(src, lkbk) lower = ta.lowest(src, lkbk) width = (upper - lower) / band_width inner_upper = upper - width inner_lower = lower + width basis = math.avg(upper, lower) [basis, upper, lower, inner_upper, inner_lower] // @function Double Half Donchian Channels // @param src float // @param lkbk int // @param divisor float // @returns two adjustable bases calculated using Donchian Channels calculation that can act as a measure of volatility for below chart indicators export doublehalfdonchianchannels(float src, int lkbk, float divisor) => _high = ta.highest(src, lkbk) _low = ta.lowest(src, lkbk) high_vol = _high / divisor low_vol = _low / divisor [high_vol, low_vol] // @function Keltner Channels // @param src float // @param lkbk int // @param mult float // @param atr_lkbk int // @param basis float // @param band_width float // @returns Keltner Channels with an outer band of varying thickness adjustable by the band_width input export keltnerchannels(int atr_lkbk, float mult, float basis, float band_width) => upper = basis + ta.atr(atr_lkbk) * mult lower = basis - ta.atr(atr_lkbk) * mult width = (upper - lower) / band_width inner_upper = upper - width inner_lower = lower + width [basis, upper, lower, inner_upper, inner_lower]
Table
https://www.tradingview.com/script/GWvI1cvC-Table/
jmosullivan
https://www.tradingview.com/u/jmosullivan/
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/ // © jmosullivan //@version=5 // @description This library provides an easy way to convert arrays and matrixes of data into tables. There are // a few different implementations of each function so you can get more or less control over the appearance of // the tables. The basic rule of thumb is that all matrix rows must have the same number of columns, and if you // are providing multiple arrays/matrixes to specify additional colors (background/text), they must have the // same number of rows/columns as the data array. Finally, you do have the option of spanning cells across rows // or columns with some special syntax in the data cell. Look at the examples to see how the arrays and matrixes // need to be built before they can be used by the functions. library("Table", true) import jmosullivan/Utils/1 // Constants used in the tables (as defaults, they can be overridden by custom scripts) color COLOR_HOT = #e500a4 color COLOR_COOL = #2962ff color COLOR_TEXT = color.white // @type Type for each cell's content and appearance export type Cell string content color bgColor = color.blue color textColor = color.white string align = text.align_center int colspan = 1 int rowspan = 1 // @function Helper function that converts a float array to a Cell array so it can be rendered with the fromArray function // @param floatArray (array<float>) the float array to convert to a Cell array. // @returns array<Cell> The Cell array to return. export floatArrayToCellArray(array<float> floatArray) => cellArray = array.new<Cell>() for item in floatArray array.push(cellArray, Cell.new(str.tostring(item))) cellArray // @function Helper function that converts a string array to a Cell array so it can be rendered with the fromArray function // @param stringArray (array<string>) the array to convert to a Cell array. // @returns array<Cell> The Cell array to return. export stringArrayToCellArray(array<string> stringArray) => cellArray = array.new<Cell>() for item in stringArray array.push(cellArray, Cell.new(item)) cellArray // @function Helper function that converts a float matrix to a Cell matrix so it can be rendered with the fromMatrix function // @param floatMatrix (matrix<float>) the float matrix to convert to a string matrix. // @returns matrix<Cell> The Cell matrix to render. export floatMatrixToCellMatrix(matrix<float> floatMatrix) => rows = matrix.rows(floatMatrix) cols = matrix.columns(floatMatrix) cellMatrix = matrix.new<Cell>(rows, cols) if rows > 0 and cols > 0 for a = 0 to rows - 1 for b = 0 to cols - 1 matrix.set(cellMatrix, a, b, Cell.new(str.tostring(matrix.get(floatMatrix, a, b)))) cellMatrix // @function Helper function that converts a string matrix to a Cell matrix so it can be rendered with the fromMatrix function // @param stringMatrix (matrix<string>) the string matrix to convert to a Cell matrix. // @returns matrix<Cell> The Cell matrix to return. export stringMatrixToCellMatrix(matrix<string> stringMatrix) => rows = matrix.rows(stringMatrix) cols = matrix.columns(stringMatrix) cellMatrix = matrix.new<Cell>(rows, cols) if rows > 0 and cols > 0 for a = 0 to rows - 1 for b = 0 to cols - 1 matrix.set(cellMatrix, a, b, Cell.new(matrix.get(stringMatrix, a, b))) cellMatrix // @function Takes a CellMatrix and renders it as a table. // @param CellMatrix (matrix<Cell>) The Cells to be rendered in a table // @param position (string) Optional. The position of the table. Defaults to position.top_right // @param verticalOffset (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0. // @param transposeTable (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false. // @param textSize (string) Optional. The size of text to render in the table. Defaults to size.small. // @param borderWidth (int) Optional. The width of the border between table cells. Defaults to 2. // @param tableNumRows (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined. // @param blankCellText (string) Optional. Text to use cells when adding blank rows for vertical offsetting. export fromMatrix(matrix<Cell> CellMatrix, string position = position.top_right, int verticalOffset = 0, bool transposeTable = false, string textSize = size.small, int borderWidth = 2, int tableNumRows = -1, string blankCellText = "") => if barstate.islast matrix<Cell> _cellMatrix = CellMatrix int rows = matrix.rows(CellMatrix) int columns = matrix.columns(CellMatrix) // Perform some validation to make sure we have all the things we need if transposeTable _cellMatrix := matrix.transpose(_cellMatrix) rows := matrix.rows(_cellMatrix) columns := matrix.columns(_cellMatrix) // If the table is supposed to be offset from it's top or bottom, add rows to create the displacement _position = Utils.getPositionFromString(position) bool isBottom = _position == position.bottom_left or _position == position.bottom_center or _position == position.bottom_right bool isTop = _position == position.top_left or _position == position.top_center or _position == position.top_right if (verticalOffset > 0) transparentColor = color.rgb(255,255,255,100) blankCell = Cell.new(blankCellText, transparentColor, transparentColor) matrix<Cell> blankRows = matrix.new<Cell>(verticalOffset, columns, blankCell) if (isTop) _cellMatrix := matrix.concat(blankRows, _cellMatrix) else if (isBottom) _cellMatrix := matrix.concat(_cellMatrix, blankRows) Cell cell = na mergeArray = array.new_string() int matrixRows = matrix.rows(_cellMatrix) int tableRows = matrixRows > tableNumRows ? matrixRows : tableNumRows table matrixTable = table.new(position = _position, columns = columns, rows = tableRows, border_width = borderWidth) for i = 0 to matrixRows - 1 for j = 0 to columns - 1 // Check the data for row & colspan specs cell := matrix.get(_cellMatrix, i, j) // Just insert blank cells if the matrix is missing something... if na(cell) cell := Cell.new("") // Build a merge array to be merged after table is complete if (cell.rowspan > 1 or cell.colspan > 1) array.push(mergeArray, str.tostring(j) + ":" + str.tostring(i) + ":" + str.tostring(j+cell.colspan-1) + ":" + str.tostring(i+cell.rowspan-1)) table.cell( matrixTable, j, i, cell.content, text_color=cell.textColor, text_size=textSize, text_halign=cell.align, bgcolor=cell.bgColor ) mergeArraySize = array.size(mergeArray) if mergeArraySize > 0 for i = 0 to mergeArraySize - 1 mergeParts = str.split(array.get(mergeArray, i), ":") if array.size(mergeParts) == 4 table.merge_cells( matrixTable, math.round(str.tonumber(array.get(mergeParts, 0))), math.round(str.tonumber(array.get(mergeParts, 1))), math.round(str.tonumber(array.get(mergeParts, 2))), math.round(str.tonumber(array.get(mergeParts, 3))) ) // @function Renders a float matrix as a table. // @param dataMatrix (matrix_float) The data to be rendered in a table // @param position (string) Optional. The position of the table. Defaults to position.top_right // @param verticalOffset (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0. // @param transposeTable (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false. // @param textSize (string) Optional. The size of text to render in the table. Defaults to size.small. // @param borderWidth (int) Optional. The width of the border between table cells. Defaults to 2. // @param tableNumRows (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined. // @param blankCellText (string) Optional. Text to use cells when adding blank rows for vertical offsetting. export fromMatrix(matrix<float> dataMatrix, string position = position.top_right, int verticalOffset = 0, bool transposeTable = false, string textSize = size.small, int borderWidth = 2, int tableNumRows = -1, string blankCellText = "") => fromMatrix(floatMatrixToCellMatrix(dataMatrix), position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText) // @function Renders a string matrix as a table. // @param dataMatrix (matrix_string) The data to be rendered in a table // @param position (string) Optional. The position of the table. Defaults to position.top_right // @param verticalOffset (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0. // @param transposeTable (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false. // @param textSize (string) Optional. The size of text to render in the table. Defaults to size.small. // @param borderWidth (int) Optional. The width of the border between table cells. Defaults to 2. // @param tableNumRows (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined. // @param blankCellText (string) Optional. Text to use cells when adding blank rows for vertical offsetting. export fromMatrix(matrix<string> dataMatrix, string position = position.top_right, int verticalOffset = 0, bool transposeTable = false, string textSize = size.small, int borderWidth = 2, int tableNumRows = -1, string blankCellText = "") => fromMatrix(stringMatrixToCellMatrix(dataMatrix), position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText) // @function Renders a Cell array as a table. // @param dataArray (array<Cell>) The data to be rendered in a table // @param position (string) Optional. The position of the table. Defaults to position.top_right // @param verticalOffset (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0. // @param transposeTable (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false. // @param textSize (string) Optional. The size of text to render in the table. Defaults to size.small. // @param borderWidth (int) Optional. The width of the border between table cells. Defaults to 2. // @param blankCellText (string) Optional. Text to use cells when adding blank rows for vertical offsetting. export fromArray(array<Cell> dataArray, string position = position.top_right, int verticalOffset = 0, bool transposeTable = false, string textSize = size.small, int borderWidth = 2, string blankCellText = "") => dataMatrix = matrix.new<Cell>() matrix.add_row(dataMatrix, 0, dataArray) fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText=blankCellText) // @function Renders a string array as a table. // @param dataArray (array_string) The data to be rendered in a table // @param position (string) Optional. The position of the table. Defaults to position.top_right // @param verticalOffset (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0. // @param transposeTable (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false. // @param textSize (string) Optional. The size of text to render in the table. Defaults to size.small. // @param borderWidth (int) Optional. The width of the border between table cells. Defaults to 2. // @param blankCellText (string) Optional. Text to use cells when adding blank rows for vertical offsetting. export fromArray(array<string> dataArray, string position = position.top_right, int verticalOffset = 0, bool transposeTable = false, string textSize = size.small, int borderWidth = 2, string blankCellText = "") => fromArray(stringArrayToCellArray(dataArray), position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText=blankCellText) // @function Renders a float array as a table. // @param dataArray (array_float) The data to be rendered in a table // @param position (string) Optional. The position of the table. Defaults to position.top_right // @param verticalOffset (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0. // @param transposeTable (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false. // @param textSize (string) Optional. The size of text to render in the table. Defaults to size.small. // @param borderWidth (int) Optional. The width of the border between table cells. Defaults to 2. // @param blankCellText (string) Optional. Text to use cells when adding blank rows for vertical offsetting. export fromArray(array<float> dataArray, string position = position.top_right, int verticalOffset = 0, bool transposeTable = false, string textSize = size.small, int borderWidth = 2, string blankCellText = "") => fromArray(floatArrayToCellArray(dataArray), position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText=blankCellText) // @function Renders a debug message in a table at the desired location on screen. // @param message (string) The message to render. // @param position (string) Optional. The position of the debug message. Defaults to position.middle_right. export debug(string message, string position = position.middle_right) => debugArray = array.new_string() array.push(debugArray, message) fromArray(debugArray, position=position) // Experiment #1, build a table of RSI values, changing colors when the rsi is extreme // Convenience function for adding to the matrices getRsiCells(length) => rsi = math.round(ta.rsi(close, length)) rsiColor = rsi >= 70 or rsi <= 30 ? COLOR_HOT : COLOR_COOL array.from( Cell.new(str.format("{0}P", length), rsiColor), Cell.new(str.format("{0,number,#}", rsi), rsiColor) ) // Build up the matrix to be rendered dataMatrix = matrix.new<Cell>() matrix.add_row(dataMatrix, 0, getRsiCells(2)) matrix.add_row(dataMatrix, 1, getRsiCells(14)) fromMatrix(dataMatrix, position=position.bottom_right) // Experiment #2, build the multitimeframe rsi table rsi = ta.rsi(close, 2) rsi1 = request.security(symbol=syminfo.tickerid, timeframe="5", expression=rsi, lookahead=barmerge.lookahead_on) rsi2 = request.security(symbol=syminfo.tickerid, timeframe="15", expression=rsi, lookahead=barmerge.lookahead_on) rsi3 = request.security(symbol=syminfo.tickerid, timeframe="60", expression=rsi, lookahead=barmerge.lookahead_on) // Build up the matrix to be rendered mtfDataMatrix = matrix.new<Cell>() matrix.add_row(mtfDataMatrix, 0, array.from(Cell.new(" RSI ", COLOR_HOT))) // Convenience function for adding to the matrices addTimeframe(dataMatrix, timeframe, rsi) => cellArray = array.from(Cell.new( str.format(" {0} \n {1,number,#} ", Utils.timeframeToString(timeframe), rsi), rsi >= 70 or rsi <= 30 ? COLOR_HOT : COLOR_COOL )) matrix.add_row(dataMatrix, matrix.rows(dataMatrix), cellArray) addTimeframe(mtfDataMatrix, "5", rsi1) addTimeframe(mtfDataMatrix, "15", rsi2) addTimeframe(mtfDataMatrix, "60", rsi3) // Add a row that spans all columns spanData = Cell.new("This is a single cell of data") blankData = Cell.new("") spanData.colspan := 4 matrix.add_col(mtfDataMatrix, matrix.columns(mtfDataMatrix), array.from(spanData, blankData, blankData, blankData)) fromMatrix(mtfDataMatrix, position=position.top_right, verticalOffset=1, transposeTable=true) // Experiment #3. Writing a collection of debug messages to the screen, illustrate text alignment rightCell = Cell.new("Right aligned") rightCell.align := text.align_right fromArray(array.from( Cell.new("Center aligned table cell"), rightCell ), position=position.top_left, transposeTable=true, verticalOffset=2) // Experiment #4. Writing a single debug message to another location on the screen debug("This is the last test", position.bottom_left)
Price - TP/SL
https://www.tradingview.com/script/BLqukQSJ-Price-TP-SL/
DinGrogu
https://www.tradingview.com/u/DinGrogu/
4
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © DinGrogu //@version=5 library('price') // ############################################################ // # FUNCTIONS // ############################################################ // Get the limit or stop loss price. f_limit_stop_price(_price, _percentage, _bars_minimum=0, _bars_since_entry=0) => price = 0.0 if (_percentage > 0) if (_bars_minimum == 0) price := _price else if (_bars_minimum > 0) if (_bars_since_entry > _bars_minimum) price := _price else price := na else price := na else price := na response = price // @function - Get the take profit price. f_take_profit_price(_entry_price, _take_profit_percentage, _atr_length=0) => atr_enabled = _atr_length > 0 atr = atr_enabled ? ta.sma(ta.tr, _atr_length) : 0 _take_profit_percentage > 0 ? atr_enabled ? _entry_price + (atr * _take_profit_percentage) : _entry_price + (_entry_price * (_take_profit_percentage / 100)) : na // @function - Get the stop loss price. f_stop_loss_price(_entry_price, _stop_loss_percentage, _atr_length=0) => atr_enabled = _atr_length > 0 atr = atr_enabled ? ta.sma(ta.tr, _atr_length) : 0 _stop_loss_percentage > 0 ? atr_enabled ? _entry_price - (atr * _stop_loss_percentage) : _entry_price - (_entry_price * (_stop_loss_percentage / 100)) : na // Calculate the difference between 2 assets in percentage. f_difference(_src_1, _src_2) => math.abs(((_src_1 - _src_2) / _src_2) * 100) // A condition for percentage differences. f_difference_condition(_src_1, _src_2, _percentage) => _src_2 > _src_1 and f_difference(_src_1, _src_2) > _percentage // Price change up. f_up(_length, _percentage, _src=close, _low=low, _high=high) => _lowest = _low[_length] change = _lowest < _src and math.abs((_high - _lowest) / _lowest * 100) > _percentage // Price change down. f_down(_length, _percentage, _src=close, _low=low, _high=high) => _highest = _high[_length] change = _highest > _src and math.abs((_low - _highest) / _highest * 100) > _percentage // Get the latest price from lower timeframe. f_lower_timeframe(_prices, _last=false) => price = 0.0 if (array.size(_prices) > 0) if (_last) price := array.last(_prices) else price := array.first(_prices) price // Get the order size from properties tab. f_strategy_order_size() => if (strategy.closedtrades > 0) order_size = strategy.initial_capital / strategy.closedtrades.entry_price(0) math.round(strategy.closedtrades.size(0) / order_size, 2) * 100 else order_size = 100 // Get the commission from properties tab. f_strategy_commission() => strategy.closedtrades > 0 ? math.round(strategy.closedtrades.commission(0) / strategy.initial_capital * 100, 2) / 2 : 0 // ############################################################ // # EXPORT FUNCTIONS // ############################################################ // function - Calculate the limit or stop price. // // usage example: // limit_price = price.take_profit_price(take_profit_price, take_profit_percentage, take_profit_atr_length, take_profit_bars, bars_since_opened) // stop_price = price.stop_loss_price(stop_loss_price, stop_loss_percentage, stop_loss_atr_length, stop_loss_bars, bars_since_opened) // strategy.exit(id='TP/SL', comment='TP', from_entry='LONG', limit=limit_price, stop=stop_price) // @param _price <float> - The source input. // @param _percentage <float> - The percentage. // @param _atr_length <int> - ATR length (0 to use percentage). // @param _bars_minimum <int> - The number of bars to compare with elapsed bars. // @param _bars_since_entry <int> - The number of bars elapsed. export take_profit_price(series float _price, float _percentage, int _atr_length=0, int _bars_minimum=0, int _bars_since_entry=0) => price = f_take_profit_price(_price, _percentage, _atr_length) f_limit_stop_price(price, _percentage, _bars_minimum, _bars_since_entry) // @param _price <float> - The source input. // @param _percentage <float> - The percentage. // @param _atr_length <int> - ATR length (0 to use percentage). // @param _bars_minimum <int> - The number of bars to compare with elapsed bars. // @param _bars_since_entry <int> - The number of bars elapsed. export stop_loss_price(series float _price, float _percentage, int _atr_length=0, int _bars_minimum=0, int _bars_since_entry=0) => price = f_stop_loss_price(_price, _percentage, _atr_length) f_limit_stop_price(price, _percentage, _bars_minimum, _bars_since_entry) // function - Get the difference in percentage between 2 prices. // @param _src_1 <series float> - Source 1. // @param _src_2 <series float> - Source 2. export difference(series float _src_1, series float _src_2) => f_difference(_src_1, _src_2) // @param _length <simple int> - Lookback length. // @param _percentage <simple float> - The percentage. // @param _src <series float> - Source. // @param _low <series float> - Low. // @param _high <series float> - High export up(simple int _length, simple float _percentage, series float _src=close, series float _low=low, series float _high=high) => f_up(_length, _percentage, _src, _low, _high) // @param _length <simple int> - Lookback length. // @param _percentage <simple float> - The percentage. // @param _src <series <series float> - Source. // @param _low <series float> - Low. // @param _high <series float> - High. export down(simple int _length, simple float _percentage, series float _src=close, series float _low=low, series float _high=high) => f_down(_length, _percentage, _src, _low, _high) // function - Get lower timeframe price. // // usage example: // price.ltf(request.security_lower_tf(ticker, '1', close)) // // @param _prices <array float> - timeframe. // @param _last <bool> - Show the last bar close instead of first. export ltf(array<float> _prices, bool _last=false) => f_lower_timeframe(_prices, _last) // function - Get the strategy position size price. export position() => math.round_to_mintick(strategy.position_avg_price) // function - Get the order size from the properties tab. export order_size() => f_strategy_order_size() // function - Get the commission from the properties tab. export commission() => f_strategy_commission()
ETFFinderLib
https://www.tradingview.com/script/dsZIQ4MM-ETFFinderLib/
Steversteves
https://www.tradingview.com/u/Steversteves/
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/ //Made for: // (( // ((((( // ((((((((( // ((((((((((((( // (((((((((((((((( // (((((((((((((((((((( // ((((( ((((((((((((( // (((( (((((((((((((( // ######### (( ((( // ################ #### // ################## ####### // ################################# // ##################################### // _____ _ _ _ // | _ |_|___ ___ ___ ___ ___|_|___| |_ // | __| | | -_|_ -| _| _| | . | _| // |__| |_|_|_|___|___|___|_| |_| _|_| // |_| // LAST UPDATE: November 2023 // NEXT SCHEDULED UPDATE: May 2024 // Compendium to the ETFHoldingsLibrary. // This Library permits you to search the ETFHoldingsLibrary by specific tickers and by sectors. // The two main functions provided by this library are to search for a ticker within various ETFs (using the etf_search_ticker) and the // ability to search a breakdown of sectors that each etf in the database contains using the etf_search_sectors function. // You can use this library standalone if you want to search for an ETF of interest in the ETFHoldingsLibrary by ticker. // You will need to export the etf_search_sectors function if you want to search the ETFs by sectors. // © Steversteves //@version=5 // @description TODO: add library description here library("ETFFinderLib") // @function searches the entire ETF library by ticker and identifies which ETFs hold a specific tickers. // @param input string as displayed by the syminfo.ticker function in pinescript. // @returns returns 2 arrays, holding_array (string array) and compo_array(float array) export etf_search_ticker(string ticker) => string[] holding_array = array.new<string>() float[] compo_array = array.new<float>() int inter = 0 spy_holdings = array.from("MSFT", "AAPL", "AMZN", "NVDA", "GOOG", "META", "GOOGL", "BRK.B", "TSLA", "UHN"), spy_comp = array.from(7.14, 7.14, 3.44, 2.86, 2.09, 1.90, 1.80, 1.77, 1.58, 1.41) qqq_holdings = array.from("AAPL", "MSFT", "AMZN", "NVDA", "META", "AVGO", "GOOGL", "GOOG", "TSLA","COST"), qqq_comp = array.from(11.01, 10.36, 5.66, 4.15, 3.87, 3.07, 3.04, 3.00, 2.63, 2.17) arkk_holdings = array.from("COIN", "TSLA", "ZM", "ROKU", "PATH", "SQ", "RBLX", "DKNG", "TWLO", "U"), arkk_comp = array.from(9.07, 8.68, 7.96, 7.80, 7.06, 5.02, 4.48, 4.22, 4.07, 3.46) xle_holdings = array.from("XOM", "CVX", "EOG", "COP", "MPC", "SLB", "PXD", "PSX", "VLO", "WMB"), xle_comp = array.from(22.40, 17.07, 4.85, 4.63, 4.54, 4.43, 4.18, 3.81, 3.37, 3.14) brk_holdings = array.from("HPQ","ATVI", "MCO", "KHC", "OXY", "CVX", "KO", "AXP", "BAC", "AAPL" ), brk_comp = array.from(1.1, 1.3, 2.3, 3.9, 4.1, 6.7, 7.6, 7.7, 9.1, 46.4) ita_holdings = array.from("RTX", "BA", "LMT", "NOC", "GD", "LHX", "TXT", "AXON", "TDG", "HWM"), ita_comp = array.from(18.59, 16.63, 8.38, 5.15, 5.12, 4.88, 4.63, 4.43, 4.34, 4.22) iwm_holdings = array.from("SMCI", "MTDR", "CHRD", "MUR", "XTSLA", "LNW", "WFRD", "FIX", "SIGI", "CHX"), iwm_comp = array.from(0.53, 0.33, 0.33, 0.32, 0.32, 0.32, 0.32, 0.31, 0.30, 0.29) xlf_holdings = array.from("BRK.B", "JPM", "V", "MA", "BAC", "WFC", "SPGI", "GS", "MMC", "PGR"), xlf_comp = array.from(13.85, 8.99, 8.41, 6.97, 4.05, 3.24, 2.53, 2.23, 2.09, 2.06) xlv_holdings = array.from("UNH", "LLY", "JNJ", "MRK", "ABBV", "PFE", "TMO", "ABT", "AMGN", "DHR"), xlv_comp = array.from(10.73, 9.56, 7.73, 5.64, 5.39, 3.73, 3.71, 3.55, 2.96, 2.73) vnq_holdings = array.from("VRTPX", "PLD", "AMT", "EQIX", "PSA", "CCI", "WELL", "SPG", "O", "DLR"), vnq_comp = array.from(12.67, 7.50, 5.55, 4.92, 3.02, 2.89, 2.84, 2.48, 2.43, 2.42) xbi_holdings = array.from("MRTX", "APLS", "BPMC", "IMVT", "IONS", "VRTX", "SGEN", "GILD", "BHVN", "NBIX"), xbi_comp = array.from(2.26, 1.70, 1.60, 1.60, 1.56, 1.53, 1.51, 1.50, 1.47, 1.47) blcr_holdings = array.from("MSFT", "AMZN", "AAPL", "GOOGL", "BRK.B", "META", "CMCSA", "UNH", "AMAT", "NVO"), blcr_comp = array.from(8.28, 5.43, 3.97, 2.89, 2.86, 2.85, 2.54, 2.32, 2.29, 2.20) vgt_holdings = array.from("AAPL", "MSFT", "NVDA", "AVGO", "ADBE", "CSCO", "CRM", "ACN", "ORCL", "AMD"), vgt_comp = array.from(21.23, 17.04, 6.16, 3.18, 2.16, 2.03, 1.87, 1.79, 1.59, 1.53) vwo_holdings = array.from("2330.TW", "0700.HK", "9988.HK", "RELIANCE.NS", "3690.HK", "HDFCBANK.NS", "INFY.NS", "PDD", "00939", "VALE3.SA"), vwo_comp = array.from(4.77, 3.36, 2.56, 1.31, 1.07, 0.97, 0.84, 0.82, 0.73, 0.71) vig_holdings = array.from("MSFT", "AAPL", "XOM", "UNH", "JPM", "JNJ", "V", "PG", "AVGO", "MA"), vig_comp = array.from(4.85, 4.32, 3.39, 3.36, 3.03, 2.70, 2.55, 2.49, 2.39, 2.38) vug_holdings = array.from("AAPL", "MSFT", "AMZN", "NVDA", "GOOGL", "TSLA", "META", "GOOG", "LLY", "V"), vug_comp = array.from(12.78, 11.79, 5.93, 5.13, 3.90, 3.39, 3.35, 3.27, 2.31, 1.80) vtv_holdings = array.from("BRK.B", "XOM", "UNH", "JPM", "JNJ", "PG", "AVGO", "CVX", "ABBV", "MRK"), vtv_comp = array.from(3.81, 2.80, 2.78, 2.51, 2.23, 2.05, 2.04, 1.78, 1.57, 1.56) vea_holdings = array.from("Nestle SA", "Novo Nordisk Class B", "Samsung Electronics Co Ltd", "ASML Holding NV", "Toyota Motor Corp", "Shell PLC", "Novartis AG Registered Shares", "AstraZeneca PLC", "Roche Holding AG", "LVMH Moet Hennessy Louis Vuitton SE"), vea_comp = array.from(1.49, 1.41, 1.18, 1.15, 1.06, 1.05, 1.04, 0.98, 0.93, 0.92) dia_holdings = array.from("UHN", "MSFT", "GS", "HD", "MCD", "AMGN", "V", "CAT", "CRM", "BA"), dia_comp = array.from(10.67, 6.74, 6.05, 5.67, 5.22, 5.09, 4.68, 4.50, 4.00, 3.72) fngg_holdings = array.from("MSFT", "NFLX", "META", "AVGO", "AAPL", "AMZN", "GOOGL", "NVDA", "SNOW"), fngg_comp = array.from(5.76, 5.71, 5.65, 5.64, 5.61, 5.26, 5.19, 5.13, 5.02) fngu_holdings = array.from("META", "TSLA", "NVDA", "AMD", "NFLX", "AAPL", "AMZN", "SNOW", "MSFT", "GOOGL"), fngu_comp = array.from(12.53, 11.71, 10.66, 10.03, 9.65, 9.39, 9.35, 9.10, 8.84, 8.74) bnge_holdings = array.from("NFLX", "NTES", "INTC", "NTDOY", "SONY", "DIS", "PDYPF", "YY", "EA", "TME"), bnge_comp = array.from(5.38, 4.71, 4.68, 4.60, 4.58, 4.57, 4.48, 4.45, 4.45, 4.29) ixp_holdings = array.from("META", "GOOGL", "GOOG", "DIS", "VZ", "NFLX", "CMCSA", "TME", "T", "DTEA"), ixp_comp = array.from(19.12, 11.85, 10.18, 4.64, 4.59, 4.40, 4.38, 4.30, 3.42, 2.35) fcom_holdings = array.from("META", "GOOGL", "GOOG", "VZ", "NFLX", "DIS", "CMCSA", "T", "TMUS", "CHTR"), fcom_comp = array.from(21.46, 12.64, 10.45, 4.91, 4.77, 4.46, 4.19, 3.80, 3.17, 1.74) pnqi_holdings = array.from("MSFT", "META", "AMZN", "ADBE", "GOOG", "DIS", "NFLX", "UBER", "CRM", "BKNG"), pnqi_comp = array.from(8.93, 8.81, 8.34, 8.23, 7.89, 4.22, 4.11, 3.96, 3.92, 3.89) chps_holdings = array.from("INTC", "AVGO", "NVDA", "QCOM", "AMAT", "LRCX", "SMH", "AMD", "MU", "ASML"), chps_comp = array.from(5.69, 4.96, 4.88, 4.72, 4.71, 4.67, 4.42, 4.38, 4.33, 4.22) soxx_holdings = array.from("AMD", "AVGO", "NVDA", "INTC", "TXN", "MU", "QCOM", "KLAC", "MCHP", "AMAT"), soxx_comp = array.from(8.55, 8.37, 7.59, 7.42, 6.04, 4.39, 4.37, 4.30, 4.00, 3.98) xlk_holdings = array.from("MSFT", "AAPL", "AVGO", "NVDA", "ADBE", "CSCO", "CRM", "ACN", "ORCL", "AMD"), xlk_comp = array.from(24.43, 23.15, 4.35, 4.23, 3.04, 2.66, 2.45, 2.35, 2.04, 1.99) jets_holdings = array.from("AAL", "DAL", "LUV", "UAL", "SKYW", "SNCY", "ALK", "ALGT", "AC", "GD"), jets_comp = array.from(9.87, 9.47, 9.15, 9.14, 3.66, 3.32, 2.97, 2.89, 2.78, 2.74) moon_holdings = array.from("NKLA", "COIN", "EH", "S", "DBX", "NNDM", "SNAP", "HOOD", "SQSP", "BIGC"), moon_comp = array.from(5.25, 4.18, 3.74, 3.30, 3.25, 3.21, 2.84, 2.81, 2.75, 2.75) ufo_holdings = array.from("SIRI", "GRMN", "GSAT", "SKPJY", "TRMB", "SES", "DISH", "SATS", "IRDM", "VSAT"), ufo_comp = array.from(5.67, 5.56, 5.31, 5.28, 5.05, 4.69, 4.54, 4.41, 4.33, 4.22) vdc_holdings = array.from("PG", "COST", "WMT", "PEP", "KO", "PM", "MDLZ", "MO", "CL", "STZ"), vdc_comp = array.from(12.42, 8.73, 8.23, 8.14, 8.04, 4.57, 3.78, 3.02, 2.27, 1.72) iedi_holdings = array.from("AMZN", "HD", "COST", "WMT", "TJX", "LOW", "CMG", "ORLY", "ROST", "TGT"), iedi_comp = array.from(14.43, 10.12, 8.01, 6.30, 3.89, 3.81, 2.87, 2.71, 2.14, 1.98) virs_holdings = array.from("AMZN", "WMT", "NVDA", "NFLX", "HD", "ABT", "MRK", "JNJ", "LOW", "SNY"), virs_comp = array.from(5.62, 5.56, 5.49, 5.11, 4.99, 4.85, 4.84, 4.83, 4.64, 4.61) ftxg_holdings = array.from("KHC", "KO", "MDLZ", "PEP", "ADM", "GIS", "USFD", "TAP", "KDP", "STZ"), ftxg_comp = array.from(8.32, 8.26, 8.13, 8.03, 7.90, 4.22, 4.21, 3.98, 3.94, 3.93) iyj_holdings = array.from("V", "MA", "ACN", "UNP", "HON", "RTX", "GE", "CAT", "BA", "LMT"), iyj_comp = array.from(7.86, 6.52, 3.88, 2.61, 2.52, 2.46, 2.43, 2.41, 2.15, 2.12) fxr_holdings = array.from("BWXT", "EME", "KNX", "AGCO", "GPK", "SON", "MDU", "GTES", "TT", "SYF"), fxr_comp = array.from(1.35, 1.34, 1.33, 1.32, 1.31, 1.30, 1.29, 1.28, 1.28, 1.25) iyc_holdings = array.from("AMZN", "TSLA", "COST", "WMT", "HD", "MCD", "NFLX", "DIS", "NKE", "LOW"), iyc_comp = array.from(14.92, 7.60, 4.49, 4.43, 4.31, 4.00, 3.86, 3.28, 2.69, 2.46) xly_holdings = array.from("AMZN", "TSLA", "MCD", "NKE", "HD", "LOW", "SBUX", "TJX", "BKNG", "ORLY"), xly_comp = array.from(24.23, 16.79, 4.62, 4.32, 4.26, 3.83, 3.63, 3.47, 3.42, 1.93) iyk_holdings = array.from("PG", "PEP", "KO", "PM", "MDLZ", "CVS", "MO", "MCK", "CL", "KMB"), iyk_comp = array.from(16.93, 10.85, 10.62, 6.75, 4.46, 4.40, 3.59, 3.14, 3.13, 2.05) fdis_holdings = array.from("AMZN", "TSLA", "HD", "MCD", "NKE", "LOW", "SBUX", "BKNG", "TJX", "ORLY"), fdis_comp = array.from(24.10, 12.93, 6.51, 4.37, 2.89, 2.58, 2.47, 2.42, 2.35, 1.32) pej_holdings = array.from("CMG", "ABNB", "MAR", "BKNG", "LVS", "RCL", "WBD", "DAL", "LGF.A", "SKYW"), pej_comp = array.from(5.80, 5.21, 5.18, 5.07, 4.97, 4.78, 4.44, 4.21, 3.38, 3.20) iyt_holdings = array.from("UNP", "UPS", "UBER", "CSX", "NSC", "FDX", "ODFL", "DAL", "EXPD", "JBHT"), iyt_comp = array.from(18.64, 15.05, 12.72, 4.81, 4.80, 4.72, 4.43, 3.74, 3.19, 2.77) ftxr_holdings = array.from("UNP", "GM", "UPS", "F", "TSLA", "CSX", "PCAR", "NSC", "FDX", "URI"), ftxr_comp = array.from(7.95, 7.70, 7.63, 7.36, 7.12, 4.52, 4.33, 4.26, 4.21, 3.90) xtn_holdings = array.from("ARCB", "XPO", "MATX", "R", "CSX", "RXO", "SKYW", "UNP", "NSC", "EXPD"), xtn_comp = array.from(3.05, 2.89, 2.79, 2.72, 2.71, 2.71, 2.70, 2.67, 2.65, 2.59) sea_holdings = array.from("TNK", "TRMD", "CICOF", "OROVY", "HAFNF", "AMKBY", "NPNYY", "MSLOY", "SITIF", "EVGOF"), sea_comp = array.from(5.21, 5.00, 4.95, 4.81, 4.75, 4.68, 4.45, 4.44, 4.24, 3.92) if array.includes(spy_holdings, ticker) array.push(holding_array, "SPY") inter := array.indexof(spy_holdings, ticker) array.push(compo_array, array.get(spy_comp, inter)) if array.includes(qqq_holdings, ticker) array.push(holding_array, "QQQ") inter := array.indexof(qqq_holdings, ticker) array.push(compo_array, array.get(qqq_comp, inter)) if array.includes(arkk_holdings, ticker) array.push(holding_array, "ARKK") inter := array.indexof(arkk_holdings, ticker) array.push(compo_array, array.get(arkk_comp, inter)) if array.includes(xle_holdings, ticker) array.push(holding_array, "XLE") inter := array.indexof(xle_holdings, ticker) array.push(compo_array, array.get(xle_comp, inter)) if array.includes(brk_holdings, ticker) array.push(holding_array, "BRK.B") inter := array.indexof(brk_holdings, ticker) array.push(compo_array, array.get(brk_comp, inter)) if array.includes(ita_holdings, ticker) array.push(holding_array, "ITA") inter := array.indexof(ita_holdings, ticker) array.push(compo_array, array.get(ita_comp, inter)) if array.includes(iwm_holdings, ticker) array.push(holding_array, "IWM") inter := array.indexof(iwm_holdings, ticker) array.push(compo_array, array.get(iwm_comp, inter)) if array.includes(xlf_holdings, ticker) array.push(holding_array, "XLF") inter := array.indexof(xlf_holdings, ticker) array.push(compo_array, array.get(xlf_comp, inter)) if array.includes(xlv_holdings, ticker) array.push(holding_array, "XLV") inter := array.indexof(xlv_holdings, ticker) array.push(compo_array, array.get(xlv_comp, inter)) if array.includes(vnq_holdings, ticker) array.push(holding_array, "VNQ") inter := array.indexof(vnq_holdings, ticker) array.push(compo_array, array.get(vnq_comp, inter)) if array.includes(xbi_holdings, ticker) array.push(holding_array, "XBI") inter := array.indexof(xbi_holdings, ticker) array.push(compo_array, array.get(xbi_comp, inter)) if array.includes(blcr_holdings, ticker) array.push(holding_array, "BLCR") inter := array.indexof(blcr_holdings, ticker) array.push(compo_array, array.get(blcr_comp, inter)) if array.includes(vgt_holdings, ticker) array.push(holding_array, "VGT") inter := array.indexof(vgt_holdings, ticker) array.push(compo_array, array.get(vgt_comp, inter)) if array.includes(vwo_holdings, ticker) array.push(holding_array, "VWO") inter := array.indexof(vwo_holdings, ticker) array.push(compo_array, array.get(vwo_comp, inter)) if array.includes(vig_holdings, ticker) array.push(holding_array, "VIG") inter := array.indexof(vig_holdings, ticker) array.push(compo_array, array.get(vig_comp, inter)) if array.includes(vug_holdings, ticker) array.push(holding_array, "VUG") inter := array.indexof(vug_holdings, ticker) array.push(compo_array, array.get(vug_comp, inter)) if array.includes(vtv_holdings, ticker) array.push(holding_array, "VTV") inter := array.indexof(vtv_holdings, ticker) array.push(compo_array, array.get(vtv_comp, inter)) if array.includes(vea_holdings, ticker) array.push(holding_array, "VEA") inter := array.indexof(vea_holdings, ticker) array.push(compo_array, array.get(vea_comp, inter)) if array.includes(dia_holdings, ticker) array.push(holding_array, "DIA") inter := array.indexof(dia_holdings, ticker) array.push(compo_array, array.get(dia_comp, inter)) if array.includes(fngg_holdings, ticker) array.push(holding_array, "FNGG") inter := array.indexof(fngg_holdings, ticker) array.push(compo_array, array.get(fngg_comp, inter)) if array.includes(fngu_holdings, ticker) array.push(holding_array, "FNGU") inter := array.indexof(fngu_holdings, ticker) array.push(compo_array, array.get(fngu_comp, inter)) if array.includes(bnge_holdings, ticker) array.push(holding_array, "BNGE") inter := array.indexof(bnge_holdings, ticker) array.push(compo_array, array.get(bnge_comp, inter)) if array.includes(ixp_holdings, ticker) array.push(holding_array, "IXP") inter := array.indexof(ixp_holdings, ticker) array.push(compo_array, array.get(ixp_comp, inter)) if array.includes(fcom_holdings, ticker) array.push(holding_array, "FCOM") inter := array.indexof(fcom_holdings, ticker) array.push(compo_array, array.get(fcom_comp, inter)) if array.includes(pnqi_holdings, ticker) array.push(holding_array, "PNQI") inter := array.indexof(pnqi_holdings, ticker) array.push(compo_array, array.get(pnqi_comp, inter)) if array.includes(chps_holdings, ticker) array.push(holding_array, "CHPS") inter := array.indexof(chps_holdings, ticker) array.push(compo_array, array.get(chps_comp, inter)) if array.includes(soxx_holdings, ticker) array.push(holding_array, "SOXX") inter := array.indexof(soxx_holdings, ticker) array.push(compo_array, array.get(soxx_comp, inter)) if array.includes(xlk_holdings, ticker) array.push(holding_array, "XLK") inter := array.indexof(xlk_holdings, ticker) array.push(compo_array, array.get(xlk_comp, inter)) if array.includes(moon_holdings, ticker) array.push(holding_array, "MOON") inter := array.indexof(moon_holdings, ticker) array.push(compo_array, array.get(moon_comp, inter)) if array.includes(ufo_holdings, ticker) array.push(holding_array, "UFO") inter := array.indexof(ufo_holdings, ticker) array.push(compo_array, array.get(ufo_comp, inter)) if array.includes(vdc_holdings, ticker) array.push(holding_array, "VDC") inter := array.indexof(vdc_holdings, ticker) array.push(compo_array, array.get(vdc_comp, inter)) if array.includes(iedi_holdings, ticker) array.push(holding_array, "IEDI") inter := array.indexof(iedi_holdings, ticker) array.push(compo_array, array.get(iedi_comp, inter)) if array.includes(virs_holdings, ticker) array.push(holding_array, "VIRS") inter := array.indexof(virs_holdings, ticker) array.push(compo_array, array.get(virs_comp, inter)) if array.includes(ftxg_holdings, ticker) array.push(holding_array, "FTXG") inter := array.indexof(ftxg_holdings, ticker) array.push(compo_array, array.get(ftxg_comp, inter)) if array.includes(jets_holdings, ticker) array.push(holding_array, "JETS") inter := array.indexof(jets_holdings, ticker) array.push(compo_array, array.get(jets_comp, inter)) if array.includes(iyj_holdings, ticker) array.push(holding_array, "IYJ") inter := array.indexof(iyj_holdings, ticker) array.push(compo_array, array.get(iyj_comp, inter)) if array.includes(fxr_holdings, ticker) array.push(holding_array, "FXR") inter := array.indexof(fxr_holdings, ticker) array.push(compo_array, array.get(fxr_comp, inter)) if array.includes(iyc_holdings, ticker) array.push(holding_array, "IYC") inter := array.indexof(iyc_holdings, ticker) array.push(compo_array, array.get(iyc_comp, inter)) if array.includes(xly_holdings, ticker) array.push(holding_array, "XLY") inter := array.indexof(xly_holdings, ticker) array.push(compo_array, array.get(xly_comp, inter)) if array.includes(iyk_holdings, ticker) array.push(holding_array, "IYK") inter := array.indexof(iyk_holdings, ticker) array.push(compo_array, array.get(iyk_comp, inter)) if array.includes(fdis_holdings, ticker) array.push(holding_array, "FDIS") inter := array.indexof(fdis_holdings, ticker) array.push(compo_array, array.get(fdis_comp, inter)) if array.includes(pej_holdings, ticker) array.push(holding_array, "PEJ") inter := array.indexof(pej_holdings, ticker) array.push(compo_array, array.get(pej_comp, inter)) if array.includes(iyt_holdings, ticker) array.push(holding_array, "IYT") inter := array.indexof(iyt_holdings, ticker) array.push(compo_array, array.get(iyt_comp, inter)) if array.includes(ftxr_holdings, ticker) array.push(holding_array, "FTXR") inter := array.indexof(ftxr_holdings, ticker) array.push(compo_array, array.get(ftxr_comp, inter)) if array.includes(xtn_holdings, ticker) array.push(holding_array, "XTN") inter := array.indexof(xtn_holdings, ticker) array.push(compo_array, array.get(xtn_comp, inter)) if array.includes(sea_holdings, ticker) array.push(holding_array, "SEA") inter := array.indexof(sea_holdings, ticker) array.push(compo_array, array.get(sea_comp, inter)) [holding_array, compo_array] // @function searches the entire ETF library by sector and pulls by desired sector // @param input string variable for sector, must be one of the following strings "Basic Materials", "Consumer Cyclical", "Financial Services", "Real Estate", "Consumer Defensive", "Healthcare", "Utilities", "Communication Services", "Energy", "Industrials", "Technology" // @returns returns 2 arrays, sector_array (string array) and composition array (float array) export etf_search_sectors(string sector) => string[] sector_array = array.new<string>() float[] composition_array = array.new<float>() int i = 0 spy_sectors = array.from(2.19, 10.74, 12.32, 2.35, 6.58, 13.19, 2.50, 8.71, 4.54, 8.19, 28.69) qqq_sectors = array.from(0, 13.83, 0.50, 0.27, 6.36, 7.00, 1.30, 15.72, 0.56, 4.92, 49.53) arkk_sectors = array.from(0, 12.90, 9.07, 0, 0.23, 24.57, 0, 17.40, 0, 1.07, 34.77) xle_sectors = array.from(0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100, 0.00, 0.00) brk_sectors = array.from(0.18, 1.01, 21.86, 0, 10.94, 1.06, 0, 2.16, 9.34, 0.15, 53.25) ita_sectors = array.from(0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.0, 0.00) iwm_sectors = array.from(4.71, 10.16, 14.43, 7.32, 4.43, 14.37, 2.97, 2.18, 8.47, 15.46, 15.50) xlf_sectors = array.from(0.00, 0.00, 96.59, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.62, 2.80) xlv_sectors = array.from(0.00, 0.00, 0.00, 0.00, 0.00, 100.0, 0.00, 0.00, 0.00, 0.00, 0.00) vnq_sectors = array.from(0.00, 0.00, 0.00, 99.17, 0.00, 0.00, 0.00, 0.82, 0.00, 0.00, 0.00) xbi_sectors = array.from(0.00, 0.00, 0.00, 0.00, 0.00, 100.00, 0.00, 0.00, 0.00, 0.00, 0.00) blcr_sectors = array.from(4.24, 11.88, 13.43, 0.00, 6.30, 15.10, 0.00, 13.56, 5.04, 3.44, 27.01) vgt_sectors = array.from(0.02, 0.00, 0.10, 00.00, 0.00, 0.01, 0.00, 0.19, 0.00, 0.33, 99.35) vwo_sectors = array.from(8.68, 13.39, 21.13, 2.82, 6.38, 4.64, 3.34, 9.04, 5.69, 8.21, 16.67) vig_sectors = array.from(4.15, 7.17, 18.23, 0.00, 12.07, 15.47, 2.67, 1.37, 3.53, 12.97, 22.36) vug_sectors = array.from(1.73, 16.88, 5.99, 1.71, 2.22, 8.76, 0.00, 13.72, 1.36, 3.36, 44.27) vtv_sectors = array.from(2.72, 3.19, 19.92, 3.07, 11.26, 18.99, 5.06, 3.23, 8.45, 13.55, 10.54) vea_sectors = array.from(7.79, 10.85, 19.03, 3.32, 8.08, 11.09, 2.91, 3.97, 5.91, 16.90, 10.14) dia_sectors = array.from(0.96, 12.95, 19.77, 0.00, 7.38, 21.20, 0.00, 2.33, 2.91, 13.70, 18.80) fngg_sectors = array.from(0.00, 17.84, 0.00, 0.00, 0.00, 0.00, 0.00, 31.11, 0.00, 0.00, 51.04) fngu_sectors = array.from(0.00, 21.06, 0.00, 0.00, 0.00, 0.00, 0.00, 30.92, 0.00, 0.00, 48.02) bnge_sectors = array.from(0.00, 21.23, 0.00, 0.00, 0.00, 0.00, 0.00, 59.44, 0.00, 0.00, 19.33) ixp_sectors = array.from(0.00, 0.21, 0.00, 0.54, 0.00, 0.00, 0.00, 99.25, 0.00, 0.00, 0.00) fcom_sectors = array.from(0.00, 0.63, 0.00, 0.00, 0.00, 0.00, 0.00, 96.97, 0.00, 0.09, 2.31) pnqi_sectors = array.from(0.00, 26.74, 3.53, 1.50, 0.05, 0.16, 0.00, 32.38, 0.00, 0.00, 35.64) chps_sectors = array.from(0.30, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.51, 98.19) soxx_sectors = array.from(0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00) xlk_sectors = array.from(0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00) moon_sectors = array.from(0.00, 8.87, 6.63, 0.00, 0.00, 22.66, 0.00, 5.32, 0.00, 16.45, 40.07) ufo_sectors = array.from(0.00, 0.67, 0.00, 0.00, 0.00, 0.00, 0.00, 34.59, 0.00, 31.75, 32.99) vdc_sectors = array.from(0.20, 0.72, 0.00, 0.00, 98.21, 0.71, 0.00, 0.00, 0.00, 0.16, 0.00) iedi_sectors = array.from(0.00, 67.59, 1.16, 0.40, 23.16, 0.48, 0.00, 1.67, 0.08, 3.71, 1.75) virs_sectors = array.from(2.06, 15.28, 0.00, 0.00, 11.37, 52.82, 0.00, 5.12, 0.00, 4.43, 8.92) ftxg_sectors = array.from(0.00, 0.00, 0.00, 0.00, 100.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00) jets_sectors = array.from(0.00, 9.67, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 90.33, 0.00) // Search for sector if sector == "Basic Materials" i := 0 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Consumer Cyclical" i := 1 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Financial Services" i := 2 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Real Estate" i := 3 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Consumer Defensive" i := 4 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Healthcare" i := 5 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Utilities" i := 6 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Communication Services" i := 7 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Energy" i := 8 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Industrials" i := 10 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) if sector == "Technology" i := 10 if array.get(spy_sectors, i) > 0 array.push(sector_array, "SPY") array.push(composition_array, array.get(spy_sectors, i)) if array.get(qqq_sectors, i) > 0 array.push(sector_array, "QQQ") array.push(composition_array, array.get(qqq_sectors, i)) if array.get(arkk_sectors, i) > 0 array.push(sector_array, "ARKK") array.push(composition_array, array.get(arkk_sectors, i)) if array.get(xle_sectors, i) > 0 array.push(sector_array, "XLE") array.push(composition_array, array.get(xle_sectors, i)) if array.get(brk_sectors, i) > 0 array.push(sector_array, "BRK.B") array.push(composition_array, array.get(brk_sectors, i)) if array.get(ita_sectors, i) > 0 array.push(sector_array, "ITA") array.push(composition_array, array.get(ita_sectors, i)) if array.get(iwm_sectors, i) > 0 array.push(sector_array, "IWM") array.push(composition_array, array.get(iwm_sectors, i)) if array.get(xlf_sectors, i) > 0 array.push(sector_array, "XLF") array.push(composition_array, array.get(xlf_sectors, i)) if array.get(xlv_sectors, i) > 0 array.push(sector_array, "XLV") array.push(composition_array, array.get(xlv_sectors, i)) if array.get(vnq_sectors, i) > 0 array.push(sector_array, "VNQ") array.push(composition_array, array.get(vnq_sectors, i)) if array.get(xbi_sectors, i) > 0 array.push(sector_array, "XBI") array.push(composition_array, array.get(xbi_sectors, i)) if array.get(blcr_sectors, i) > 0 array.push(sector_array, "BLCR") array.push(composition_array, array.get(blcr_sectors, i)) if array.get(vgt_sectors, i) > 0 array.push(sector_array, "VGT") array.push(composition_array, array.get(vgt_sectors, i)) if array.get(vwo_sectors, i) > 0 array.push(sector_array, "VWO") array.push(composition_array, array.get(vwo_sectors, i)) if array.get(vig_sectors, i) > 0 array.push(sector_array, "VIG") array.push(composition_array, array.get(vig_sectors, i)) if array.get(vug_sectors, i) > 0 array.push(sector_array, "VUG") array.push(composition_array, array.get(vug_sectors, i)) if array.get(vtv_sectors, i) > 0 array.push(sector_array, "VTV") array.push(composition_array, array.get(vtv_sectors, i)) if array.get(vea_sectors, i) > 0 array.push(sector_array, "VEA") array.push(composition_array, array.get(vea_sectors, i)) if array.get(dia_sectors, i) > 0 array.push(sector_array, "DIA") array.push(composition_array, array.get(dia_sectors, i)) if array.get(fngg_sectors, i) > 0 array.push(sector_array, "FNGG") array.push(composition_array, array.get(fngg_sectors, i)) if array.get(fngu_sectors, i) > 0 array.push(sector_array, "FNGU") array.push(composition_array, array.get(fngu_sectors, i)) if array.get(bnge_sectors, i) > 0 array.push(sector_array, "BNGE") array.push(composition_array, array.get(bnge_sectors, i)) if array.get(ixp_sectors, i) > 0 array.push(sector_array, "IXP") array.push(composition_array, array.get(ixp_sectors, i)) if array.get(fcom_sectors, i) > 0 array.push(sector_array, "FCOM") array.push(composition_array, array.get(fcom_sectors, i)) if array.get(pnqi_sectors, i) > 0 array.push(sector_array, "PNQI") array.push(composition_array, array.get(pnqi_sectors, i)) if array.get(chps_sectors, i) > 0 array.push(sector_array, "CHPS") array.push(composition_array, array.get(chps_sectors, i)) if array.get(soxx_sectors, i) > 0 array.push(sector_array, "SOXX") array.push(composition_array, array.get(soxx_sectors, i)) if array.get(xlk_sectors, i) > 0 array.push(sector_array, "XLK") array.push(composition_array, array.get(xlk_sectors, i)) if array.get(moon_sectors, i) > 0 array.push(sector_array, "MOON") array.push(composition_array, array.get(moon_sectors, i)) if array.get(ufo_sectors, i) > 0 array.push(sector_array, "UFO") array.push(composition_array, array.get(ufo_sectors, i)) if array.get(vdc_sectors, i) > 0 array.push(sector_array, "VDC") array.push(composition_array, array.get(vdc_sectors, i)) if array.get(iedi_sectors, i) > 0 array.push(sector_array, "IEDI") array.push(composition_array, array.get(iedi_sectors, i)) if array.get(virs_sectors, i) > 0 array.push(sector_array, "VIRS") array.push(composition_array, array.get(virs_sectors, i)) if array.get(ftxg_sectors, i) > 0 array.push(sector_array, "FTXG") array.push(composition_array, array.get(ftxg_sectors, i)) if array.get(jets_sectors, i) > 0 array.push(sector_array, "JETS") array.push(composition_array, array.get(jets_sectors, i)) [sector_array, composition_array] // Use as Standalone search_for_ticker = input.bool(true, "Search for Current Ticker in ETFs") current = syminfo.ticker if search_for_ticker [sector, compo] = etf_search_ticker(current) var table results = table.new(position.middle_center, 3, 50, bgcolor = color.black, frame_color = color.white, frame_width = 2) if array.size(sector) > 0 table.cell(results, 1, 1, text = "ETF", bgcolor = color.black, text_color = color.white) table.cell(results, 2, 1, text = "Composition", bgcolor = color.black, text_color = color.white) for i = 0 to array.size(sector) - 1 table.cell(results, 1, 2 + i, text = str.tostring(array.get(sector, i)), bgcolor = color.black, text_color = color.white) table.cell(results, 2, 2 + i, text = str.tostring(array.get(compo, i)), bgcolor = color.black, text_color = color.white)
Polyline Plus
https://www.tradingview.com/script/whitXdWw-Polyline-Plus/
algotraderdev
https://www.tradingview.com/u/algotraderdev/
8
library
5
MPL-2.0
// @license This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // @author algotraderdev // @description This library introduces the `PolylinePlus` type, which is an enhanced version of the built-in PineScript // `polyline`. It enable two features that are absent from the built-in type: // 1. Developers can now dynamically add or remove points from the poyline in an efficient manner. In contrast, the // built-in `polyline` type is immutable, and developers are forced to reconstruct a new instance of the polyline // if they were to add/remove points, which is unwieldy and comes with significant performance penalty. // 2. Each PolylinePlus instance can theoretically hold up to ~1M points, instead of the 10K points allowed by the // built-in `polyline` type, as long as it does not exceed the memory limit of the PineScript runtime. // Under the hood, it stores an array of `line`s and use it as a buffer to hold the lines that are formed by the newly // added points. When this buffer is full, it then flushes the buffer and converts the lines into polylines, // which are expected to be updated much less frequently. // This concept is similar to how "Buffered I/O" works in file and network systems. // @version=5 library('polylineplus', overlay = true) //#region Utilities // @function Asserts the condition is met. Throws an exception if not. // @param cond The condition to check. // @param msg The message to display in the exception. assert(bool cond, string msg) => if not cond runtime.error(msg) //#endregion //#region PolylineWithPoints // @type A helper type that serves as the union of a built-in `polyline` object and the `chart.point`s that back // up the polyline. This object is needed because the built-in `polyline` type does not expose its underlying points // to developers. export type PolylineWithPoints // Determines the field of the chart.point objects in the points array that the polyline will use for its // x-coordinates. If xloc.bar_index, the polyline will use the index field from each point. If xloc.bar_time, // it will use the time field. string xloc = xloc.bar_index // The color of the line segments. color line_color = color.blue // The style of the polyline. Possible values: line.style_solid, line.style_dotted, line.style_dashed, // line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. string line_style = line.style_solid // The width of the line segments, expressed in pixels. int line_width = 1 // The maximum number of points that each built-in `polyline` instance can contain. // NOTE: this is not to be confused with the maximum number of points that each `PolylinePlus` instance can contain. // In fact, each `PolylinePlus` instance can theoretically hold up to 10,000 * 100 + 500 = 1,000,500 points as long // as it does not exceed the memory limit of the PineScript runtime. int max_points_per_builtin_polyline = 10000 // The underlying polyline. polyline polyline // The underlying points that form the polyline. chart.point[] points // @function Gets the size of points in this polyline. method points_size(PolylineWithPoints this) => if na(this.points) 0 else this.points.size() // @function Gets the last point from this polyline. method last_point(PolylineWithPoints this) => if not na(this.points) if this.points.size() > 0 this.points.last() // @function Sets the points for the polyline. // @param points The new points to set. method set_points(PolylineWithPoints this, chart.point[] points) => this.points := points.copy() if not na(this.polyline) this.polyline.delete() this.polyline := polyline.new( this.points, xloc = this.xloc, line_color = this.line_color, line_style = this.line_style, line_width = this.line_width) // @function Checks if this instance has reached the maximum capacity for points. // @returns Whether this instance has reached the maximum capacity for points. method is_full(PolylineWithPoints this) => if na(this.points) false else this.points.size() == this.max_points_per_builtin_polyline // @function Pushes more points into the polyline. If it exceeds the max number of points that each polyline can store, // then the remaining un-stored portion will be returned. // @param new_points An array of points to add into the polyline. // @returns The remaining points that are not added into the polyline, or na if all points were added. method push_points(PolylineWithPoints this, chart.point[] new_points) => // Make sure `this.points` is initialized. if na(this.points) this.points := array.new<chart.point>() int size = this.points.size() int new_size = size + new_points.size() if new_size > this.max_points_per_builtin_polyline // Calculate the remaining capacity of `this.points`. int capacity = this.max_points_per_builtin_polyline - size // Split the `new_points` array into two parts, with the first part being the points that can be added into the // polyline and the second part being the remaining points that cannot be added. chart.point[] to_add = new_points.slice(0, capacity) chart.point[] remaining = new_points.slice(capacity, new_points.size()) // Update `this.points` and `this.polyline`. this.set_points(this.points.concat(to_add)) remaining else // all points can be added into `this.points`. this.set_points(this.points.concat(new_points)) na // @function Pops N points from the polyline. // @param n The number of points to pop. // @returns An array of `chart.point`s that are popped. method pop_points(PolylineWithPoints this, int n) => assert(not na(this.points), '`this.points` should not be na in `PolylineWithPoints#pop_points`.') int size = this.points.size() assert(n <= size, 'The number of points to pop should be less than or equal to the size of `this.points`.') chart.point[] left = if size == n // NOTE: ideally we should be able to do `this.points.slice(0, size - n)` regardless of whether size == n, // but there's seems to be bug that in PineScript that if the second param provided to slice is 0, then // the full array will be returned. e.g. [1, 2, 3].slice(0, 0) is [1, 2, 3] rather than []. array.new<chart.point>() else this.points.slice(0, size - n) chart.point[] right = this.points.slice(size - n, size) this.set_points(left) right // @function Deletes the chart elements from this object and frees up memory. method delete(PolylineWithPoints this) => if not na(this.polyline) this.polyline.delete() this.polyline := na this.points := na //#endregion //#region PolylinePlus // @type A PolylinePlus type is an enhanced version of the built-in PineScript `polyline` type to enable developers to // dynamically add or remove points from the poyline with significantly optimized performance. // Under the hood, it stores an array of `line`s and use it as a buffer to hold the lines that are formed by the newly // added points. When this buffer is full, it then flushes the buffer and converts the lines into polylines, // which are expected to be updated much less frequently. // This concept is similar to how file system buffers and network buffers work. export type PolylinePlus // If true, the drawing will also connect the first point to the last point from the points array, resulting in a // closed polyline. bool closed = false // Determines the field of the chart.point objects in the points array that the polyline will use for its // x-coordinates. If xloc.bar_index, the polyline will use the index field from each point. If xloc.bar_time, // it will use the time field. string xloc = xloc.bar_index // The color of the line segments. color line_color = color.blue // The style of the polyline. Possible values: line.style_solid, line.style_dotted, line.style_dashed, // line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. string line_style = line.style_solid // The width of the line segments, expressed in pixels. int line_width = 1 // The maximum number of points that each built-in `polyline` instance can contain. // NOTE: this is not to be confused with the maximum number of points that each `PolylinePlus` instance can contain. // In fact, each `PolylinePlus` instance can theoretically hold up to 10,000 * 100 + 500 = 1,000,500 points as long as // it does not exceed the memory limit of the PineScript runtime. int max_points_per_builtin_polyline = 10000 // The number of lines to keep in the buffer. If more points are to be added while the buffer is full, then all the // lines in the buffer will be flushed into the poylines. The higher the number, the less frequent we'll need to // flush the buffer, and thus lead to better performance. // NOTE: the maximum total number of lines per chart allowed by PineScript is 500. But given there might be other // places where the indicator or strategy are drawing lines outside this poyline context, we use a conservative // number here to be safe. // NOTE: When specifying a higher number here, please also make sure to use a higher number for the // `max_lines_count` param for the indicator. Otherwise the lines beyond the `max_lines_count` may be automatically // deleted and thus lead to missing points in the polyline. int lines_buffer_size = 50 // [Private] The first point that's added to the polyline. chart.point first_point // [Private] The lines buffer. This buffer holds the most recently added lines until the buffer is full. line[] lines // [Private] The underlying polylines that represent the old-generation lines. PolylineWithPoints[] polylines_with_points // [Private] The line that connects the first point to the last point, if the `closed` property is set to true. // NOTE: using `polyline` instead of `line` here since the polylines can be displayed on the chart even if their // starting points are outside of the viewport. polyline close_line // @function Gets the internal lines property while making sure it's properly initialized. method lines(PolylinePlus this) => if na(this.lines) this.lines := array.new_line() this.lines // @function Gets the internal polylines property while making sure it's properly initialized. method polylines_with_points(PolylinePlus this) => if na(this.polylines_with_points) this.polylines_with_points := array.new<PolylineWithPoints>() this.polylines_with_points // @function Creates a new instance of `PolylineWithPoints`. // @returns The newly created instance. method new_polyline_with_points(PolylinePlus this) => PolylineWithPoints pwp = PolylineWithPoints.new( xloc = this.xloc, line_color = this.line_color, line_style = this.line_style, line_width = this.line_width, max_points_per_builtin_polyline = this.max_points_per_builtin_polyline) PolylineWithPoints[] pwps = this.polylines_with_points() if pwps.size() > 0 pwp.push_points(array.from(pwps.last().last_point())) pwps.push(pwp) pwp // @function Gets the start and end endpoints for the given line. // @param ln The line instance. // @returns A two-element tuple that contains the start and end endpoints (both of the `chart.point` type). method line_endpoints(PolylinePlus this, line ln) => if this.xloc == xloc.bar_index [chart.point.from_index(ln.get_x1(), ln.get_y1()), chart.point.from_index(ln.get_x2(), ln.get_y2())] else [chart.point.from_time(ln.get_x1(), ln.get_y1()), chart.point.from_time(ln.get_x2(), ln.get_y2())] // @function Gets the last point in the polyline. // @returns The last point in the polyline, or na if the polyline is empty. method last_point(PolylinePlus this) => line[] lines = this.lines() chart.point p = if lines.size() > 0 [start, end] = this.line_endpoints(lines.last()) end else PolylineWithPoints[] pwps = this.polylines_with_points() if pwps.size() > 0 pwps.last().last_point() na(p) ? this.first_point : p // @function Updates the close line. method update_close_line(PolylinePlus this) => if this.closed and not na(this.first_point) and not na(this.last_point()) if not na(this.close_line) this.close_line.delete() this.close_line := polyline.new( array.from(this.first_point, this.last_point()), xloc = this.xloc, line_color = this.line_color, line_style = this.line_style, line_width = this.line_width) else if not na(this.close_line) this.close_line.delete() this.close_line := na this // @function Flushes the lines buffer if it's full. method flush_if_full(PolylinePlus this) => line[] lines = this.lines() if lines.size() == this.lines_buffer_size PolylineWithPoints[] pwps = this.polylines_with_points() if pwps.size() == 0 this.new_polyline_with_points() PolylineWithPoints pwp = this.polylines_with_points.last() chart.point[] points = array.new<chart.point>() for [i, ln] in lines [start, end] = this.line_endpoints(ln) // Add the start point of the first line into the points array if the pwp is currently empty. if i == 0 and pwp.points_size() == 0 points.push(start) points.push(end) ln.delete() lines.clear() // Gets the last polyline from the list and try to add the points into it. // If the polyline is full, then create a new polyline. while not na(points) pwp := this.polylines_with_points.last() if pwp.is_full() pwp := this.new_polyline_with_points() chart.point[] remaining = pwp.push_points(points) points := remaining // @function Pushes a new point into this polyline. // @param point A chart.point object that specifies the coordinate. export method push_point(PolylinePlus this, chart.point point) => if na(this.first_point) this.first_point := point else this.flush_if_full() line ln = line.new( first_point = this.last_point(), second_point = point, xloc = this.xloc, color = this.line_color, style = this.line_style, width = this.line_width) this.lines().push(ln) this.update_close_line() // @function Pushes a list of new point into this polyline. // @param points A list of new points to push. export method push_points(PolylinePlus this, chart.point[] points) => for p in points this.push_point(p) // @function Formats the chart.point type. // @returns A string representing the chart.point. method format_point(PolylinePlus this, chart.point point) => string x = if this.xloc == xloc.bar_index str.tostring(point.index) else str.format_time(point.time) str.format('({0}, {1})', x, point.price) // @function Pops the last point from the polyline. export method pop_point(PolylinePlus this) => line[] lines = this.lines() if lines.size() > 0 line ln = lines.pop() ln.delete() else // lines.size() == 0 PolylineWithPoints[] pwps = this.polylines_with_points() if pwps.size() > 0 PolylineWithPoints pwp = pwps.last() if pwp.points_size() > 2 // If there are more than two points in the pwp, then move some points from the pwp into the lines // buffer. int num_points_to_pop = math.min(this.lines_buffer_size + 1, pwp.points_size() - 1) chart.point[] points = pwp.pop_points(num_points_to_pop) points.pop() // Deletes and pop the pwp if it only has one point remaining. if pwp.points_size() == 1 this.polylines_with_points.pop().delete() if this.polylines_with_points.size() == 0 this.first_point := na this.push_points(points) else // pwp.points_size() <= 2 this.polylines_with_points.pop().delete() this.update_close_line() // @function Deletes the chart elements from this object and frees up memory. export method delete(PolylinePlus this) => line[] lines = this.lines() for ln in lines ln.delete() lines.clear() this.lines := na if not na(this.close_line) this.close_line.delete() this.close_line := na PolylineWithPoints[] pwps = this.polylines_with_points() for pwp in pwps pwp.delete() pwps.clear() this.polylines_with_points := na this.first_point := na // @function Sets the point in the polyline. // @param points The points to set. export method set_points(PolylinePlus this, chart.point[] points) => this.delete() this.push_points(points) // @function Generates the debug string for a `PolylineWithPoints` instance. // @returns A string representing the debug information. method pwp_debug_str(PolylinePlus this, PolylineWithPoints pwp) => string[] rows = array.new_string() if not na(pwp.points) for p in pwp.points rows.push(this.format_point(p)) rows.join('\n') // @function Generates the debug string for this instance. // @returns A string representing the debug information. method debug_str(PolylinePlus this) => string[] rows = array.new_string() rows.push(str.format('lines={0} polylines={1}', this.lines().size(), this.polylines_with_points().size())) for [i, pwp] in this.polylines_with_points rows.push(str.format('------- Polyline {0} -------', i)) rows.push(this.pwp_debug_str(pwp)) rows.push('---------- Lines ----------') for ln in this.lines [start, end] = this.line_endpoints(ln) rows.push(str.format('{0} -> {1}', this.format_point(start), this.format_point(end))) rows.join('\n') //#endregion
Fear & Greed Index (Zeiierman)
https://www.tradingview.com/script/qC7RI6cj-Fear-Greed-Index-Zeiierman/
Zeiierman
https://www.tradingview.com/u/Zeiierman/
462
study
5
CC-BY-NC-SA-4.0
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © Zeiierman { //@version=5 indicator("Fear & Greed Index (Zeiierman)",max_bars_back = 500,max_lines_count = 500,precision = 1) //~~} // ~~ Vars { b = bar_index xy = array.new<chart.point>() var poly = array.new<polyline>(20,na) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Funcs { Scales(input) => ((input - ta.min(input)) / (ta.max(input) - ta.min(input))) * 100 Scale(input) => ((input - ta.lowest(input,100)) / (ta.highest(input,100) - ta.lowest(input,100))) * 100 createZone(color _zoneColor, float _startAngle, float _endAngle) => int leftIndex = math.round((_startAngle + 90.0) / 0.01) int rightIndex = math.round((_endAngle + 90.0) / 0.01) zone = xy.slice(leftIndex, rightIndex) zone.push(chart.point.from_index(b, 0)) poly.pop().delete() poly.unshift(polyline.new(zone, false, true, line_color=color.new(_zoneColor, 80), fill_color=color.new(_zoneColor, 50))) zone //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Visual { // Create zones if barstate.islast int x1 = na float y1 = na for i = -90.0 to 90 by 0.01 x2 = b + math.round(100 * math.sin(math.toradians(i))) y2 = 100 * math.cos(math.toradians(i)) xy.push(chart.point.from_index(x1, y1)) xy.push(chart.point.from_index(x2, y2)) x1 := x2 y1 := y2 // Color colors = array.from( color.rgb(255, 0, 0), color.rgb(233, 16, 16), color.rgb(201, 34, 34), color.rgb(197, 51, 51), color.rgb(197, 69, 69), color.rgb(199, 89, 89), color.rgb(227, 113, 113), color.rgb(232, 134, 134), color.rgb(232, 157, 134), color.rgb(255, 185, 80), color.rgb(255, 185, 80), color.rgb(144, 243, 177), color.rgb(144, 243, 177), color.rgb(117, 225, 153), color.rgb(97, 193, 129), color.rgb(79, 189, 116), color.rgb(49, 169, 89), color.rgb(38, 193, 89), color.rgb(21, 224, 88), color.rgb(0, 255, 85)) // Loop through zones int zoneCount = 20 float zoneWidth = 360 / zoneCount for i = 0 to zoneCount-1 startAngle = -90.0 + (i * zoneWidth) endAngle = startAngle + zoneWidth createZone(colors.get(i), startAngle, endAngle) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Fear & Greed { //S&P 500 125-day moving average [spxPrice, spxAverage] = request.security("SPX", "D", [close, ta.sma(close, 125)]) sp125 = Scales(spxPrice - spxAverage) //STOCK PRICE STRENGTH - 52 week high vs 52 week low week52 = request.security("NYSE:NYA","W",close-math.avg(ta.highest(high,52),ta.lowest(low,52)))/100 hl52 = Scales(week52) //STOCK PRICE BREADTH - McClellan adv = ta.sma(request.security("ADVN", "D", close),19) dec = ta.sma(request.security("DECN", "D", close),19) mcsi = Scales(ta.sma(adv-dec, 19)) //PUT AND CALL OPTIONS - Put and Call 5-day average putCallRatio = ta.sma(request.security("USI:PCC", "D", close), 5) putcall = Scale(-putCallRatio) //MARKET VOLATILITY - VIX vs 50day average vix = request.security("CBOE:VIX", "D", close) vixMA = ta.sma(vix, 50) vix50 = Scale(-(vix-vixMA)) //SAFE HAVEN DEMAND - SPX vs Bonds stockReturns = ta.sma(spxPrice - spxPrice[20], 20) [bond,bond20] = request.security("US10Y", "D", [close,close[20]]) safe = Scales(stockReturns-(bond-bond20)) // JUNK BOND DEMAND - Yield spread: junk bonds vs. investment grade junkBondYield = request.security("AMEX:JNK", "D", close) treasuryYield = request.security("US10Y", "D", close) yieldSpread = Scale(junkBondYield - treasuryYield) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Arrow { combined = math.avg(sp125,hl52,vix50,mcsi,putcall,safe,yieldSpread) new = combined>50?200-(combined*2):combined*2 loc = combined>50?b+math.round((combined*2)-100):b-math.round(100-(combined*2)) l1 = line.new(b,0,loc,new,color=chart.fg_color,width=3,style=line.style_arrow_right) lab1 = label.new(b,0,"",style=label.style_circle,color=chart.fg_color,size=size.small) lab2 = label.new(loc,new,str.tostring(math.round(combined)),style=loc>b?label.style_label_left:label.style_label_right,color=color(na),textcolor=chart.fg_color,size=size.normal) (l1[1]).delete() (lab1[1]).delete() (lab2[1]).delete() //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Labels { EF = label.new(b-100,0,"Extreme Fear",color=color(na),textcolor=color.red,style=label.style_label_right) EG = label.new(b+100,0,"Extreme Greed",color=color(na),textcolor=color.green,style=label.style_label_left) F = label.new(b-65,85,"Fear",color=color(na),textcolor=color.red,style=label.style_label_right) G = label.new(b+65,85,"Greed",color=color(na),textcolor=color.green,style=label.style_label_left) N = label.new(b,100,"Neutral",color=color(na),textcolor=chart.fg_color) (EF[1]).delete() (EG[1]).delete() (F[1]).delete() (G[1]).delete() (N[1]).delete() //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PineUnit
https://www.tradingview.com/script/HIQiZXdL/
Guardian667
https://www.tradingview.com/u/Guardian667/
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/ // © Guardian667 //@version=5 // @description A comprehensive testing framework for Pine Script on TradingView. Built with well-known testing paradigms like Assertions, Units and Suites. It offers the ability to log test results in TradingView's built-in Pine Protocol view, as well as displaying them in a compact table directly on your chart, ensuring your scripts are both robust and reliable. library("PineUnit") //#region ===== Equals functionailty equalsNa(bool a, bool b) => na(a) and na(b) or a == b equalsNa(int a, int b) => na(a) and na(b) or a == b decimalPlacesCount(float f) => result = 0 parts = str.split(str.tostring(f), ".") if parts.size() == 2 result := str.length(parts.get(1)) result equalsNa(float a, float b) => epsilon = 0.0000000001 absA = math.abs(a) absB = math.abs(b) diff = math.abs(a - b) if ((na(a) and na(b)) or a == b) true else if (absA < 1.0 and absB < 1.0) diff < epsilon else diff / (absA + absB) < epsilon equalsNa(string a, string b) => na(a) and na(b) or a == b arrayEqualsNa(array<bool> a, array<bool> b) => ana = na(a) bna = na(b) result = true if not (ana and bna) if ana != bna result := false else if array.size(a) != array.size(b) result := false else for [i, v] in a if not equalsNa(v, array.get(b, i)) result := false break result arrayEqualsNa(array<int> a, array<int> b) => ana = na(a) bna = na(b) result = true if not (ana and bna) if ana != bna result :=false else if array.size(a) != array.size(b) result :=false else result := true for [i, v] in a if not equalsNa(v, array.get(b, i)) result := false break result arrayEqualsNa(array<float> a, array<float> b) => ana = na(a) bna = na(b) result = true if not (ana and bna) if ana != bna result := false else if array.size(a) != array.size(b) result := false else for [i, v] in a if not equalsNa(v, array.get(b, i)) result := false break result arrayEqualsNa(array<string> a, array<string> b) => ana = na(a) bna = na(b) result = true if not (ana and bna) if ana != bna result := false else if array.size(a) != array.size(b) result := false else for [i, v] in a if not equalsNa(v, array.get(b, i)) result := false break result //#endregion //#region ===== Results //#region === TestId // @type A unique identifier for a test, composed of the names of the suite, unit, and the test itself. // @field suiteName The name of the Suite // @field unitName The name of the Unit // @field testName The name of the Test export type TestId string suiteName = na string unitName = na string testName = na method equals(TestId a, TestId b) => equalsNa(a.suiteName, b.suiteName) and equalsNa(a.unitName, b.unitName) and equalsNa(a.testName, b.testName) method toString(TestId id) => (na(id.suiteName) ? na : id.suiteName + " / ") + (na(id.unitName) ? na : id.unitName + " / ") + id.testName contains(array<TestId> ids, TestId id) => result = false for [i, v] in ids if equals(v, id) result := true break result contains(array<string> a, string s) => result = false for [i, v] in a if equalsNa(v, s) result := true break result //#endregion //#region === ResultState // @type The result state for a Test, Unit, Suite or Session. a TestResult is directly reflected. For other types those prioritised rules apply: 1. If one or more tests fail -> Failure | 2. If all tests (excluding ignored ones) pass -> Success | 3. If all tests are ignored -> Ignored | 4. If one or more tests aren't executed -> Unexecuted // @field state An internal integer that represents the state export type ResultState int state = 4 Success() => ResultState.new(1) method isSuccess(ResultState this) => this.state == 1 Failure() => ResultState.new(2) method isFailure(ResultState this) => this.state == 2 Ignored() => ResultState.new(3) method isIgnored(ResultState this) => this.state == 3 Unexecuted() => ResultState.new(4) method isUnexecuted(ResultState this) => this.state == 4 //#endregion //#region === TestFailure // @type A TestFailure shows what has been gone wrong on which bar at which time during a test // @field barIndex In case of a test of a series Unit, the bar_index on which the failure was detected // @field stamp In case of a test of a series Unit, the time of the bar on which the failure was detected // @field messages A message, that describes what has been gone wrong export type TestFailure int barIndex = na int stamp = na array<string> messages = na //#endregion //#region === TestResult // @type A TestResult shows if a test was successful or not and cal hold a list of TestFailures that describe what went wrong // @field id A TestId that identifies to which test resul is described // @field state The ResultState of a Test // @field failures A list of TestFailures which describe what went wrong export type TestResult TestId id = na bool isSeries = false ResultState state = na array<TestFailure> failures = na createTestResult(TestId id, bool isSeries) => TestResult.new(id, isSeries, ResultState.new(), failures = array.new<TestFailure>()) method createSimpleFailure(TestResult this) => TestFailure result = TestFailure.new(na, na, array.new_string()) this.failures.push(result) result method getCurrentFailure(TestResult this) => TestFailure result = na if this.failures.size() > 0 last = this.failures.last() if equalsNa(last.barIndex, bar_index) result := last result method getOrCreateCurrentFailure(TestResult this) => TestFailure result = this.getCurrentFailure() if na(result) result := TestFailure.new(bar_index, time, array.new_string()) this.failures.push(result) result //#endregion //#region ReusltCounts // @type A DataCapsule to maintain counts of test results for inner computation // @field successes The number of successful items // @field failures The number of failed items // @field ignoreds The number of ignored items // @field unexecuteds The number of unexecuted items export type ResultCounts int successes = 0 int failures = 0 int ignoreds = 0 int unexecuteds = 0 method add(ResultCounts this, ResultCounts counts) => this.successes += counts.successes this.failures += counts.failures this.ignoreds += counts.ignoreds this.unexecuteds += counts.unexecuteds method getCount(ResultCounts this) => this.successes + this.failures + this.ignoreds + this.unexecuteds method getRun(ResultCounts this) => this.successes + this.failures //#endregion //#region === UnitResult // @type The TestResult of a whole Unit // @field name The name of this Unit // @field state The ResultState of this Unit // @field results All TestResults of the Tests of this Unit // @field testCounts A summary of the TestResult counts export type UnitResult string name ResultState state = na array<TestResult> results ResultCounts testCounts = na method createUnitResult(string name) => UnitResult.new(name, ResultState.new(), array.new<TestResult>(), ResultCounts.new()) method add(UnitResult this, TestResult testResult) => if na(this) or na(testResult) runtime.error("add(UnitResult this, TestResult testResult) " + (na(this) ? "this == na" : na(testResult) ? "testResult == na" : "")) this.results.push(testResult) if testResult.state.isSuccess() this.testCounts.successes += 1 if testResult.state.isFailure() this.testCounts.failures += 1 if testResult.state.isIgnored() this.testCounts.ignoreds += 1 if testResult.state.isUnexecuted() this.testCounts.unexecuteds += 1 method updateState(UnitResult this) => bool atLeastOneExecuted = false for [i, r] in this.results if r.state.isFailure() this.state := Failure() break if not r.state.isUnexecuted() atLeastOneExecuted := true continue counts = this.testCounts if counts.unexecuteds > 0 and counts.getRun() == 0 this.state := Unexecuted() else if counts.ignoreds > 0 and counts.getRun() == 0 this.state := Ignored() else if counts.successes == counts.getCount() - counts.ignoreds this.state := Success() method getResultCounts(UnitResult this) => this.testCounts //#endregion //#region === SuiteResult // @type The TestResult of a whole Suite // @field name The name of this Suite // @field state The ResultState of this Suite // @field results All UnitResults of the Units of this Suite // @field testCounts A summary of the TestResult counts export type SuiteResult string name ResultState state = na array<UnitResult> results ResultCounts testCounts = na method createSuiteResult(string name) => SuiteResult.new(name, ResultState.new(),array.new<UnitResult>(), ResultCounts.new()) method add(SuiteResult this, UnitResult unitResult) => this.results.push(unitResult) this.testCounts.add(unitResult.testCounts) method updateState(SuiteResult this) => bool atLeastOneExecuted = false for [i, r] in this.results if r.state.isFailure() this.state := Failure() break if not r.state.isUnexecuted() atLeastOneExecuted := true continue counts = this.testCounts if counts.unexecuteds > 0 and counts.getRun() == 0 this.state := Unexecuted() else if counts.ignoreds > 0 and counts.getRun() == 0 this.state := Ignored() else if counts.successes == counts.getCount() - counts.ignoreds this.state := Success() //#endregion //#region === SessionResult // @type The overall test reuslt of a TestSession // @field state The overall ResultState of a TestSession // @field All SuiteResults of the Tests of a whole TestSession // @field testCounts A summary of the TestResult counts export type SessionResult ResultState state = na array<SuiteResult> results ResultCounts testCounts = na method add(SessionResult this, SuiteResult suiteResult) => this.results.push(suiteResult) this.testCounts.add(suiteResult.testCounts) method updateState(SessionResult this) => bool atLeastOneExecuted = false for [i, r] in this.results if r.state.isFailure() this.state := Failure() break if not r.state.isUnexecuted() atLeastOneExecuted := true continue counts = this.testCounts if counts.unexecuteds > 0 and counts.getRun() == 0 this.state := Unexecuted() else if counts.ignoreds > 0 and counts.getRun() == 0 this.state := Ignored() else if counts.successes == counts.getCount() - counts.ignoreds this.state := Success() method getResultCounts(SessionResult this) => this.testCounts createSessionResult() => SessionResult.new(ResultState.new(), array.new<SuiteResult>(), ResultCounts.new()) method getSuiteResult(SessionResult sessionResult, string name) => SuiteResult result = na for [i, r] in sessionResult.results if equalsNa(r.name, name) result := r break result method containsSuiteResult(SessionResult sessionResult, string name) => not na(sessionResult.getSuiteResult(name)) method createSuiteResult(SessionResult sessionResult, string name) => if containsSuiteResult(sessionResult, name) runtime.error("createSuiteResult(): SuiteResult " + name + " already contained in SessionResult") result = createSuiteResult(name) sessionResult.results.push(result) result method getOrCreateSuiteResult(SessionResult sessionResult, string name) => SuiteResult result = na for [i, r] in sessionResult.results if equalsNa(r.name, name) result := r break if na(result) result := sessionResult.createSuiteResult(name) result method containsUnitResult(SuiteResult suiteResult, string name) => contains = false for [i, r] in suiteResult.results if equalsNa(r.name, name) contains := true break contains method createUnitResult(SuiteResult suiteResult, string name) => if containsUnitResult(suiteResult, name) runtime.error("createUnitResult(): UnitResult " + name + " already contained in SuiteResult " + suiteResult.name) result = createUnitResult(name) suiteResult.results.push(result) result method getOrCreateUnitResult(SuiteResult suiteResult, string name) => UnitResult result = na for [i, r] in suiteResult.results if equalsNa(r.name, name) result := r break if na(result) result := suiteResult.createUnitResult(name) result //#endregion //#endregion //#region ===== Test Classes //#region === DisplaySettings // @type Configuration of the result table that is shown on the chart // @field show If true an in chart table with the test results is displayed. Default: true // @field position Defines where the Results are displayed. Use Pine Script's position const strings. Default: position.top_right // @field success When true, successful tests are displayed, Default: true // @field failure When true, failures tests are displayed. Default: true // @field ignored When true, ignored tests are displayed, Default: true // @field unexecuted When true, unexecuted tests are displayed. Default: true // @field textSize The textSize within the result display. Use Pine Script's size const string. Default: size.small export type DisplaySettings bool show = true string position = position.top_right string textSize = size.small bool success = true bool failure = true bool ignored = true bool unexecuted = true // @function If set to true an in chart table with the test results is displayed export method setShow(DisplaySettings this, bool show) => this.show := show this // @function The chart table with the test results is not displayed export method hide(DisplaySettings this) => this.setShow(false) // @function Sets the text size within the result display. Use Pine Script's const position string. Default: size-small export method setTextSize(DisplaySettings this, string textSize) => this.textSize := textSize this // @function Sets the position of the result display. Use Pine Script's const position string. Default: position.top_right export method setPosition(DisplaySettings this, string position) => this.position := position this // @function Defines if successful tests are displayed within the result display on the chart export method setShowSuccess(DisplaySettings this, bool show) => this.success := show this // @function Hides successful tests within the result display on the chart export method hideSuccess(DisplaySettings this) => this.setShowSuccess(false) // @function Defines if failed tests are displayed within the result display on the chart export method setShowFailure(DisplaySettings this, bool show) => this.failure := show this // @function Shows only failed tests within the result display on the chart export method showOnlyFailures(DisplaySettings this) => this.success := false this.ignored := false this.unexecuted := false this // @function Defines if ignored tests are displayed within the result display on the chart export method setShowIgnored(DisplaySettings this, bool show) => this.ignored := show this // @function Hides ignored tests within the result display on the chart export method hideIgnored(DisplaySettings this) => this.setShowIgnored(false) // @function Defines if unexeucted tests are displayed within the result display on the chart export method setShowUnexecuted(DisplaySettings this, bool show) => this.unexecuted := show this // @function Hides ignored tests within the result display on the chart export method hideUnexecuted(DisplaySettings this) => this.setShowUnexecuted(false) //#endregion //#region TestSesstion // @type A TestSession encapsulates the configuration of the test and holds all the test results // @field active If and only if true, the assertions are executed and the Results are displayed // @field maxFailingBars The maximum amount of bars on wich a test can fail. If that number is reached not more test results are logged. Default: 1 // @field timezone The timezone in which the bartime when a failure occured is displayed (Examples: "UTC", "Europe/Berlin"). Default: "UTC" // @field logBarOnSeriesTests Defines if the bar_index and the bar time is shown on failed test executions of series-based Tests // @field results A list of all Results which have been created during test executions // @field displaySettings The DisplaySettings define if and how the test results are displayed on the chart // @field containedSuites The Suites which have been created directly on this TestSession // @field containedSuites The Unites which have been created directly on this TestSession // @field containedSuites The Tests which have been created directly on this TestSession export type TestSession bool active = true int maxFailingBars = 1 string timezone = syminfo.timezone bool logBarOnSeriesTests = false array<TestResult> results = na DisplaySettings displaySettings = na array<string> containedSuites = na array<string> containedUnits = na array<string> containedTests = na // @function Activates or deactivates the execution of tests. export method setActive(TestSession this, bool active) => if barstate.isfirst this.active := active this // @function Deactivates or deactivates the execution of tests. export method deactivate(TestSession this) => this.setActive(false) // @function Defines how often series test is executed until a maximum amount of test failures occured. Default: 1 export method setMaxFailingBars(TestSession this, int max) => if max < 1 runtime.error("PineTest.setMaxFailingBars: At least 1 failure must be storable for series based tests, but " + str.tostring(max) + " given") this.maxFailingBars := max this // @function Sets the timezone that is used to display the bartime when a failure occurs export method setTimezone(TestSession this, string timezone) => this.timezone := timezone this // @function Defines if the bar_index and the bar time is shown on failed test executions of series-based Tests export method setLogBarOnSeriesTests(TestSession this, bool logBar) => this.logBarOnSeriesTests := logBar this method containsSuite(TestSession this, string name) => bool result = false for [i, n] in this.containedSuites if equalsNa(n, name) result := true result method containsUnit(TestSession this, string name) => bool result = false for [i, n] in this.containedUnits if equalsNa(n, name) result := true result method containsTest(TestSession this, string name) => bool result = false for [i, n] in this.containedTests if equalsNa(n, name) result := true result method getTestResult(TestSession this, TestId id) => TestResult result = na for [i, r] in this.results if r.id.equals(id) result := r result method getTestIds(TestSession this) => ids = array.new<TestId>(0) for [i, r] in this.results ids.push(r.id) ids method getSuiteNames(TestSession this) => names = array.new_string(0) for [i, r] in this.results if not contains(names, r.id.suiteName) names.push(r.id.suiteName) names.sort() names method getUnitNames(TestSession this, string suiteName) => names = array.new_string(0) for [i, r] in this.results if equalsNa(r.id.suiteName, suiteName) and not contains(names, r.id.unitName) names.push(r.id.unitName) names.sort() names method getTestNames(TestSession this, string suiteName, string unitName) => names = array.new_string(0) for [i, r] in this.results if equalsNa(r.id.suiteName, suiteName) and equalsNa(r.id.unitName, unitName) and not contains(names, r.id.testName) names.push(r.id.testName) names.sort() names method createSessionResult(TestSession this) => sessionResult = createSessionResult() for [si, sn] in this.getSuiteNames() suiteResult = createSuiteResult(sn) for [ui, un] in this.getUnitNames(sn) unitResult = createUnitResult(un) for [ti, tn] in this.getTestNames(sn, un) testResult = this.getTestResult(TestId.new(sn, un, tn)) unitResult.add(testResult) unitResult.updateState() suiteResult.add(unitResult) suiteResult.updateState() sessionResult.add(suiteResult) sessionResult.updateState() sessionResult method matches(ResultState this, DisplaySettings settings) => settings.success and this.isSuccess() or settings.failure and this.isFailure() or settings.ignored and this.isIgnored() or settings.unexecuted and this.isUnexecuted() method getFilteredResults(TestSession this, SessionResult sessionResult) => filtered = createSessionResult() for [si, sr] in sessionResult.results sc = createSuiteResult(sr.name) sc.state := sr.state.copy() for [ui, ur] in sr.results uc = createUnitResult(ur.name) uc.state := ur.state.copy() for [ti, tr] in ur.results tc = tr.copy() if matches(tc.state, this.displaySettings) uc.add(tc) if uc.results.size() > 0 sc.add(uc) if sc.results.size() > 0 filtered.add(sc) filtered.state := sessionResult.state.copy() filtered // @function Creates a new TestSession. Use this function instead of TestSession.new() to create new Sessions, since all required variables are instantiated export createTestSession() => TestSession.new(results=array.new<TestResult>(0), displaySettings = DisplaySettings.new(), containedSuites = array.new_string(), containedUnits = array.new_string(), containedTests = array.new_string()) //#endregion //#region === Suite // @type A Suite bundles Units, so that they are displayed under together and all of them can be executed or not with one command // @field testSession The TestSession in which scope the tests of this Suite are executed // @field name The name of this Suite // @field ignore If true all the tests of all of this Suites Units are not executed // @field containedUnites The Units which have been created directly on this Suite export type Suite TestSession testSession = na string name = na bool ignore = false array<string> containedUnits = na // @function A constructor to easily create a Suite within a TestSession export method createSuite(TestSession this, string name) => if na(name) runtime.error("TestSession.createSuite: A Suite must be named, but namae == na") if contains(this.containedSuites, name) runtime.error("The TestSessoin already contains a Suite with name " + name) this.containedSuites.push(name) Suite.new(this, name, false, array.new_string()) method containsUnit(Suite this, string name) => bool result = false for [i, n] in this.containedUnits if equalsNa(n, name) result := true result // @function If true, all tests of all the Units of this Suite are not executed export method setIgnore(Suite this, bool ignore) => this.ignore := ignore this // @function Deactivates the execution of all tests of all the Units of this Suite export method ignore(Suite this) => this.setIgnore(true) this method isIgnored(Suite suite) => suite.ignore //#endregion //#region === Unit // @type A Unit is some kind of smallest amount of a program that is supposed to be tested, e.g. a function or the functions of a type. It is created by the method createSimpleUnit and createSeriesUnit of TestSession or Suite. // @field testSession The TestSession in which scope the tests of this Unit are executed // @field testSession The Suite in which scope the tests of this Suite are executed // @field name The name of this Unit // @field ignore If true all the tests this Unit are not executed // @field containedTests The Tests which have been created on this Unit export type Unit TestSession testSession = na Suite suite = na string name = na bool ignore = false array<string> containedTests = na // @function Creates a named Unit that is used to execute tests once on simple values export method createUnit(TestSession this, string name) => if na(name) runtime.error("TestSession.createUnit: A Unit must be named, but namae == na") if contains(this.containedUnits, name) runtime.error("The TestSessoin already contains a Unit with name " + name) this.containedUnits.push(name) Unit.new(this, na, name, false, array.new_string()) // @function Creates a named Unit that is used to execute tests once on simple values export method createUnit(Suite this, string name) => if na(name) runtime.error("Suite.createUnit: A Unit must be named, but namae == na") if contains(this.containedUnits, name) runtime.error("Suite " + this.name + " already contains a Unit with name " + name) this.containedUnits.push(name) Unit.new(this.testSession, this, name, false, array.new_string()) method createTestId(Unit unit, string testName) => TestId.new(na(unit.suite) ? na : unit.suite.name, unit.name, testName) method containsTest(Unit this, string name) => bool result = false for [i, n] in this.containedTests if equalsNa(n, name) result := true result // @function If true, all tests this Unit are not executed export method setIgnore(Unit this, bool ignore) => this.ignore := ignore this // @function Deactivates the execution of all tests of this Unit export method ignore(Unit this) => this.setIgnore(true) this method isIgnored(Unit unit) => ignored = unit.ignore if not na(unit.suite) if unit.suite.isIgnored() ignored := true ignored method getSuiteName(Unit unit) => na(unit.suite) ? na : unit.suite.name //#endregion //#region === Test //#region = SimpleTest // @type A SimpleTest targets one functionality based on simple values. It is created by the method createSimpleTest and createSeriesTest of TestSession or Unit. // @field testSession The TestSession in which scope the assertions of this Test are executed // @field unit The Unit in which scope the assertions of this Test are executed // @field name The name of this Test // @field ignore If true this tests is ignored and marked as skipped export type SimpleTest TestSession testSession = na Unit unit = na string name = na bool ignore = false // @function Creates a named Test that is used to execute tests once on simple values export method createSimpleTest(TestSession this, string name) => if na(name) runtime.error("TestSession.createSimpleTest: A Test must be named, but namae == na") if this.containsTest(name) runtime.error("The TestSessoin already contains a Test with name " + name) this.containedTests.push(name) SimpleTest.new(this, na, name, false) // @function Creates a named Test that is used to execute tests once on simple values export method createSimpleTest(Unit this, string name) => if na(name) runtime.error("Unit.createSimpleTest: A Test must be named, but namae == na") if this.containsTest(name) runtime.error("Unit " + this.name + " already contains a Test with name " + name) this.containedTests.push(name) SimpleTest.new(this.testSession, this, name, false) method createTestId(SimpleTest test) => string suiteName = na string unitName = na if not na(test.unit) unitName := test.unit.name if not na(test.unit.suite) suiteName := test.unit.suite.name TestId.new(suiteName, unitName, test.name) method createTestResult(SimpleTest test) => createTestResult(test.createTestId(), false) // @function If true, all tests this Test are not executed export method setIgnore(SimpleTest this, bool ignore) => this.ignore := ignore this // @function Deactivates the execution of all tests of this Test export method ignore(SimpleTest this) => this.setIgnore(true) this method isIgnored(SimpleTest test) => ignored = test.ignore if not na(test.unit) if test.unit.isIgnored() ignored := true if not na(test.unit.suite) if test.unit.suite.isIgnored() ignored := true ignored method getSuiteName(SimpleTest test) => test.unit.getSuiteName() method getUnitName(SimpleTest test) => test.unit.name method getFqn(SimpleTest test) => (na(test.getSuiteName()) ? "" : test.getSuiteName() + " / ") + (na(test.getUnitName()) ? "" : test.getUnitName() + " / ") + test.name //#endregion //#region = SeriesTest // @type A SeriesTest targets one functionality based on series values. It is created by the method createSimpleTest and createSeriesTest of TestSession or Unit. // @field testSession The TestSession in which scope the assertions of this Test are executed // @field unit The Unit in which scope the assertions of this Test are executed // @field name The name of this Test // @field when The scenario under which cirumstances the Test shall be exeucuted // @field sinceBar The earliest Bar on which this Test is executed. Counting begins at 1 // @field untilBar The Bar from which on this Test is not executed anymore. Counting begins at 1 // @field ignore If true this tests is ignored and marked as skipped export type SeriesTest TestSession testSession = na Unit unit = na string name = na bool ignore = false bool when = true int sinceBar = na int untilBar = na // @function Creates a named Test that is used to execute tests on series values on each bar export method createSeriesTest(TestSession this, string name, int sinceBar = na, int untilBar = na) => if na(name) runtime.error("TestSession.createSeriesTest: A Test must be named, but namae == na") if this.containsTest(name) runtime.error("The TestSessoin already contains a Test with name " + name) this.containedTests.push(name) SeriesTest.new(this, na, name, false, true, sinceBar, untilBar) // @function Creates a named Test that is used to execute tests on series values on each bar export method createSeriesTest(Unit this, string name, int sinceBar = na, int untilBar = na) => if na(name) runtime.error("Unit.createSeriesTest: A Test must be named, but namae == na") if this.containsTest(name) runtime.error("Unit " + this.name + " already contains a Test with name " + name) this.containedTests.push(name) SeriesTest.new(this.testSession, this, name, false, true, sinceBar, untilBar) method createTestId(SeriesTest test) => string suiteName = na string unitName = na if not na(test.unit) unitName := test.unit.name if not na(test.unit.suite) suiteName := test.unit.suite.name TestId.new(suiteName, unitName, test.name) method createTestResult(SeriesTest test) => createTestResult(test.createTestId(), true) // @function If true, all tests this Test are not executed export method setIgnore(SeriesTest this, bool ignore) => this.ignore := ignore this // @function Deactivates the execution of all tests of this Test export method ignore(SeriesTest this) => this.setIgnore(true) this method isIgnored(SeriesTest this) => ignored = this.ignore if not na(this.unit) if this.unit.isIgnored() ignored := true if not na(this.unit.suite) if this.unit.suite.isIgnored() ignored := true ignored // @function Configures Sets the earliest Bar on which this Test is executed. Counting begins at 1 export method sinceBar(SeriesTest this, int sinceBar) => if sinceBar < 1 runtime.error("SeriesTest.untilBar: sinceBar must by at least 1, but " + str.tostring(sinceBar) + " given") this.sinceBar := sinceBar this // @function Sets the Bar from which on this Test is not executed anymore. Counting begins at 1 export method untilBar(SeriesTest this, int untilBar) => if untilBar < 1 runtime.error("SeriesTest.untilBar: untilBar must by at least 1, but " + str.tostring(untilBar) + " given") this.untilBar := untilBar this // @function Configures a Test to be only executed on the given bar. The first bar of the chart is bar number 1 export method onBar(SeriesTest this, int bar) => if bar < 1 runtime.error("SeriesTest.onBar: bar number must by at least 1, but " + str.tostring(bar) + " given") this.sinceBar := bar this.untilBar := bar this // @function Configures a Test to be only executed in a special scenario, defined by 'condition' export method when(SeriesTest this, bool condition) => this.when := condition this //#endregion //#endregion //#region ===== Functionality //#endregion method getResult(TestSession testSession, TestId testId, bool isSeries) => TestResult result = na for [i, r] in testSession.results if r.id.equals(testId) result := r if na(result) result := createTestResult(testId, isSeries) testSession.results.push(result) result method getResult(SimpleTest test) => getResult(test.testSession, test.createTestId(), false) method getResult(SeriesTest test) => getResult(test.testSession, test.createTestId(), true) //#endregion //#region ===== Log Failure functions type StringBuilder int maxLength = 4096 string maxLengthExceededSuffix = "" string content = "" bool maxLengthExceeded = false bool appended = false method length(StringBuilder this) => str.length(this.content) method append(StringBuilder this, string s) => if not this.maxLengthExceeded if this.length() + str.length(s) + str.length(this.maxLengthExceededSuffix) > this.maxLength this.maxLengthExceeded := true this.content += this.maxLengthExceededSuffix this.appended := false else this.content += s this.appended := true this method hasAppended(StringBuilder this) => this.appended method toString(StringBuilder this) => this.content method clear(StringBuilder this) => this.content := "" this.maxLengthExceeded := false this method flush(StringBuilder this) => string result = this.toString() this.clear() result accuracy(string interval) => if str.contains(interval, "S") "s" else if interval == "D" "D" else if interval == "W" "W" else if interval == "M" "M" else int minutes = math.round(str.tonumber(interval)) if minutes % 60 == 0 "h" else "m" accuracyWeight(string accuracy) => switch accuracy "s" => 0 "m" => 1 "h" => 2 "D" => 3 "W" => 4 "M" => 5 displayedAccuracy() => accuracy(timeframe.period) twoDigitString(int value) => (value < 10 ? "0" : "") + str.tostring(value) bartimeToString(string timezone, int t) => weight = accuracyWeight(displayedAccuracy()) result = str.tostring(year(t, timezone)) if weight <= 5 result += "-" + twoDigitString(month(t, timezone)) if weight <= 4 result += "-" + twoDigitString(dayofmonth(t, timezone)) if weight <= 2 result += " " + twoDigitString(hour(t, timezone)) + ":" + twoDigitString(minute(t, timezone)) if weight <= 0 result += ":" + twoDigitString(second(t, timezone)) result timestampSecond(string timezone, int year, int month, int day, int hour, int minute, int second) => timestamp(timezone, year, month, day, hour, minute, second) timeToStringIncMillis(string timezone, int t) => timestampSecond = timestampSecond(timezone, year(t), month(t), dayofmonth(t), hour(t), minute(t), second(t)) millis = t - timestampSecond bartimeToString(timezone, t) + ":" + str.tostring(second(t, timezone)) + "." + str.substring(str.tostring(millis), 0, 3) canConcatenate(string s0, string s1) => str.length(s0) + str.length(s1) < 4000 concat(string s0, string s1) => r0 = s0 r1 = s1 concatenated = canConcatenate(s0, s1) if concatenated r0 += s1 r1 := "" [r0, r1, concatenated] method getMessagesText(TestFailure failure) => builder = StringBuilder.new() builder.maxLengthExceededSuffix := "\nAnd more ..." bool first = true for [i, m] in failure.messages if first first := false else builder.append("\n") builder.append(m) builder.toString() getLogText(string timezone, int barIndex, int stamp, string message) => (na(barIndex) ? "" :"[" + str.tostring(barIndex) + " | " + bartimeToString(timezone, stamp) + "]\n") + message getLogText(string timezone, TestFailure failure) => getLogText(timezone, failure.barIndex, failure.stamp, failure.getMessagesText()) method createFailuresText(TestResult this, string timezone, bool logBar) => builder = StringBuilder.new() builder.maxLengthExceededSuffix := "And more ..." linebreak = false for [i, f] in this.failures if linebreak builder.append("\n") else linebreak := true if this.isSeries and logBar builder.append("[Bar " + str.tostring(f.barIndex) + " at " + bartimeToString(timezone, f.stamp) + "]\n") builder.append(f.getMessagesText()) builder.toString() //#endregion //#region ===== Assertions //#region === Helper funcions messagePrefix(string message) => na(message) ? "" : message + " ==> " valueToString(bool value) => (na(value) ? "na" : "<" + str.tostring(value) + ">") valueToString(int value) => (na(value) ? "na" : "<" + str.tostring(value) + ">") valueToString(float value) => (na(value) ? "na" : "<" + str.tostring(value) + ">") valueToString(string value) => (na(value) ? "na" : "<" + value + ">") expectedButWas(string expected, string actual, string message) => messagePrefix(message) + "expected: " + valueToString(expected) + ", but was " + valueToString(actual) expectedButWas(bool expected, bool actual, string message) => messagePrefix(message) + "expected: " + valueToString(expected) + ", but was " + valueToString(actual) expectedButWas(int expected, int actual, string message) => messagePrefix(message) + "expected: " + valueToString(expected) + ", but was " + valueToString(actual) expectedButWas(float expected, float actual, string message) => messagePrefix(message) + "expected: " + valueToString(expected) + ", but was " + valueToString(actual) expectedNotButWas(string expected, string message) => messagePrefix(message) + "expected: " + valueToString(expected) expectedNotButWas(bool expected, string message) => messagePrefix(message) + "expected: " + valueToString(expected) expectedNotButWas(int expected, string message) => messagePrefix(message) + "expected: " + valueToString(expected) expectedNotButWas(float expected, string message) => messagePrefix(message) + "expected: " + valueToString(expected) method assert(SimpleTest test, bool condition, string message) => TestResult result = test.getResult() if test.testSession.active and barstate.isfirst if test.isIgnored() result.state := Ignored() else if condition if not result.state.isFailure() result.state := Success() else result.state := Failure() failure = result.getOrCreateCurrentFailure() failure.messages.push(message) test method assert(SeriesTest test, bool condition, string message) => TestResult result = test.getResult() if test.testSession.active if test.isIgnored() if barstate.isfirst result.state := Ignored() else if not barstate.islast and test.when and (na(test.untilBar) or bar_index < test.untilBar - 1) and (na(test.sinceBar) or bar_index >= test.sinceBar - 1) if condition if not result.state.isFailure() result.state := Success() else failure = result.getCurrentFailure() if not na(failure) failure.messages.push(message) log.error(test.createTestId().toString() + "\n" + message) else if result.failures.size() < test.testSession.maxFailingBars failure := TestFailure.new(bar_index, time, array.new_string()) result.state := Failure() failure.messages.push(message) result.failures.push(failure) log.error(test.createTestId().toString() + "\n" + message) test //#endregion //#region === AssertTrue/False // @function Asserts if a condition is true. If a 'when' scenario is given and this scenario is not met, the assertion is bypassed and yields no result. export method assertTrue(SimpleTest test, bool condition, string message = na) => test.assert(condition, expectedButWas(true, condition, message)) // @function Asserts if a condition is true. If a 'when' scenario is given and this scenario is not met, the assertion is bypassed and yields no result. export method assertTrue(SeriesTest test, bool condition, string message = na) => test.assert(condition, expectedButWas(true, condition, message)) // @function Asserts if a condition is false. If a 'when' scenario is given and this scenario is not met, the assertion is bypassed and yields no result. export method assertFalse(SimpleTest test, bool condition, string message = na) => test.assert(not condition, expectedButWas(false, condition, message)) // @function Asserts if a condition is false. If a 'when' scenario is given and this scenario is not met, the assertion is bypassed and yields no result. export method assertFalse(SeriesTest test, bool condition, string message = na) => test.assert(not condition, expectedButWas(false, condition, message)) //#endregion //#region === NA // @function Asserts that a bool value is na export method assertNa(SimpleTest test, bool actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) // @function Asserts that a bool value is na export method assertNa(SeriesTest test, bool actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) // @function Asserts that an integer value is na export method assertNa(SimpleTest test, int actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) // @function Asserts that an integer value is na export method assertNa(SeriesTest test, int actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) // @function Asserts that a float is na export method assertNa(SimpleTest test, float actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) // @function Asserts that a float is na export method assertNa(SeriesTest test, float actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) // @function Asserts that a string is na export method assertNa(SimpleTest test, string actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) // @function Asserts that a string is na export method assertNa(SeriesTest test, string actual, string message = na) => test.assert(na(actual), expectedButWas(na, actual, message)) //#endregion //#region === Not NA // @function Asserts that a bool value is na export method assertNotNa(SimpleTest test, bool actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) // @function Asserts that a bool value is na export method assertNotNa(SeriesTest test, bool actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) // @function Asserts that an integer value is na export method assertNotNa(SimpleTest test, int actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) // @function Asserts that an integer value is na export method assertNotNa(SeriesTest test, int actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) // @function Asserts that a float is na export method assertNotNa(SimpleTest test, float actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) // @function Asserts that a float is na export method assertNotNa(SeriesTest test, float actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) // @function Asserts that a string is na export method assertNotNa(SimpleTest test, string actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) // @function Asserts that a string is na export method assertNotNa(SeriesTest test, string actual, string message = na) => test.assert(not na(actual), expectedNotButWas(actual, message)) //#endregion //#region === Equals // @function Asserts that two boolean values are equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertEquals(SimpleTest test, bool expected, bool actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) export method assertEquals(SeriesTest test, bool expected, bool actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) // @function Asserts that two integer values are equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertEquals(SimpleTest test, int expected, int actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) // @function Asserts that two integer values are equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertEquals(SeriesTest test, int expected, int actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) // @function Asserts that two float values are equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertEquals(SimpleTest test, float expected, float actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) // @function Asserts that two float values are equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertEquals(SeriesTest test, float expected, float actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) // @function Asserts that two string values are equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertEquals(SimpleTest test, string expected, string actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) // @function Asserts that two string values are equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertEquals(SeriesTest test, string expected, string actual, string message = na) => test.assert(equalsNa(expected, actual), expectedButWas(expected, actual, message)) //#endregion //#region === Not Equals // @function Asserts that two boolean values are not equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertNotEquals(SimpleTest test, bool expected, bool actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) export method assertNotEquals(SeriesTest test, bool expected, bool actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) // @function Asserts that two integer values are not equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertNotEquals(SimpleTest test, int expected, int actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) // @function Asserts that two integer values are not equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertNotEquals(SeriesTest test, int expected, int actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) // @function Asserts that two float values are not equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertNotEquals(SimpleTest test, float expected, float actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) // @function Asserts that two float values are not equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertNotEquals(SeriesTest test, float expected, float actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) // @function Asserts that two string values are not equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertNotEquals(SimpleTest test, string expected, string actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) // @function Asserts that two string values are not equal, considering an optional precondition. If the precondition is not met or is not provided, the test is automatically considered successful. export method assertNotEquals(SeriesTest test, string expected, string actual, string message = na) => test.assert(not equalsNa(expected, actual), expectedNotButWas(expected, message)) //#endregion //#region === Array Equals // @function Asserts if two arrays are equal. export method assertArrayEquals(SimpleTest test, array<bool> expected, array<bool> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") // @function Asserts if two arrays are equal. export method assertArrayEquals(SeriesTest test, array<bool> expected, array<bool> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") // @function Asserts if two arrays are equal. export method assertArrayEquals(SimpleTest test, array<int> expected, array<int> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") // @function Asserts if two arrays are equal. export method assertArrayEquals(SeriesTest test, array<int> expected, array<int> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") // @function Asserts if two arrays are equal. export method assertArrayEquals(SimpleTest test, array<float> expected, array<float> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") // @function Asserts if two arrays are equal. export method assertArrayEquals(SeriesTest test, array<float> expected, array<float> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") // @function Asserts if two arrays are equal. export method assertArrayEquals(SimpleTest test, array<string> expected, array<string> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") // @function Asserts if two arrays are equal. export method assertArrayEquals(SeriesTest test, array<string> expected, array<string> actual, string message = na) => test.assert(arrayEqualsNa(expected, actual),messagePrefix(message) + " expected: <"+ str.tostring(expected) + "> but was: <" + str.tostring(actual) + ">") //#endregion //#region === Array Not Equals // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SimpleTest test, array<bool> expected, array<bool> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SeriesTest test, array<bool> expected, array<bool> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SimpleTest test, array<int> expected, array<int> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SeriesTest test, array<int> expected, array<int> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SimpleTest test, array<float> expected, array<float> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SeriesTest test, array<float> expected, array<float> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SimpleTest test, array<string> expected, array<string> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") // @function Asserts if two arrays are not equal. export method assertArrayNotEquals(SeriesTest test, array<string> expected, array<string> actual, string message = na) => test.assert(not arrayEqualsNa(expected, actual),messagePrefix(message) + " expected not <" + str.tostring(expected) + ">") //#endregion //#endregion //#region ===== Report results //#region Log Results type LogHelper StringBuilder stringBuilder = na createLogHelper() => LogHelper.new(StringBuilder.new()) method clear(LogHelper this) => this.stringBuilder.clear() method flush(LogHelper this) => log.info(this.stringBuilder.toString()) this.clear() method appendLine(LogHelper this, string logLine = "") => t = (this.stringBuilder.length() > 0 ? "\n" : "") + logLine if not this.stringBuilder.append(t).hasAppended() this.flush() this.stringBuilder.append(t) this method log(LogHelper this) => log.info(this.stringBuilder.flush()) method appendSuiteHeader(LogHelper this, SuiteResult result) => this.appendLine() .appendLine("--------------------------------------------------------------") .appendLine("T E S T S " + result.name) .appendLine("--------------------------------------------------------------") method appendOverallHeader(LogHelper this) => this.appendLine() .appendLine("==============================================================") .appendLine("O V E R A L L") .appendLine("==============================================================") logo() => "\n" + ".___. '_ ' ' ' ' ' '_ ' _ ' ' ' _ _\n" + "| ._ \\(_)_ __ ' ___| | | |_ __ (_) |_ \n" + "| |_) | | '_ \\ / _ \\ | | | '_ \\| | __|\n" + "| .__/| | | | | .__/ |_| | | | | | |_ \n" + "|_| . |_|_| |_|\\___|\\___/|_| |_|_|\\__|" createResultsText(ResultCounts counts) => "Tests run: " + str.tostring(counts.getRun()) + ", Failures: " + str.tostring(counts.failures) + ", Not executed: " + str.tostring(counts.unexecuteds) + ", Skipped: " + str.tostring(counts.ignoreds) method logResults(TestSession this) =>//SessionResult sessionResult) => sessionResult = this.createSessionResult() LogHelper logHelper = createLogHelper() .appendLine(logo()) .appendLine() .appendLine("PineUnit by Guardian667. Where reliable Pine Script testing begins") .appendLine() .appendLine("Above you find logs of series-based tests, evaluated on every bar. To inspect a specific bar linked to an assertion, hover over its log message and click the crosshair icon.") sessionCounts = sessionResult.getResultCounts() for [sri, suiteResult] in sessionResult.results logHelper.appendSuiteHeader(suiteResult) UnitResult prevResult = na for [uri, unitResult] in suiteResult.results if not na(prevResult) if prevResult.state.isFailure() or prevResult.state.isUnexecuted() logHelper.appendLine() unitCounts = unitResult.getResultCounts() logHelper .appendLine("Running " + (na(unitResult.name) ? "Default Unit" : unitResult.name)) .appendLine(createResultsText(unitCounts) + (unitResult.state.isFailure() ? " <<< FAILURE! - in" : "")) for [ri, result] in unitResult.results if result.state.isUnexecuted() logHelper.appendLine() .appendLine(result.id.testName + " < NOT EXECUTED!") else if result.state.isFailure() logHelper.appendLine() .appendLine(result.id.testName) .appendLine(result.createFailuresText(this.timezone, this.logBarOnSeriesTests)) prevResult := unitResult suiteCounts = suiteResult.testCounts logHelper .appendLine() .appendLine("Results :") .appendLine(createResultsText(suiteCounts)) logHelper.appendOverallHeader() .appendLine(createResultsText(sessionCounts)) logHelper.log() if 0 < sessionCounts.failures and sessionCounts.failures < 3 log.warning("Go ahead and fix that few bugs, my friend :-)") else if sessionCounts.failures > 0 log.warning("Go ahead and fix those bugs, my friend :-)") log.info("Thanx for using PineUnit") //#endregion //#region Display Reuslts const color okTextColor = color.green const color okBgColor = color.rgb(45, 48, 68) const color failureTextColor = color.red const color failureBgColor = color.rgb(55, 48, 48) getTextColor(ResultState state) => state.isSuccess() ? color.green : state.isFailure() ? color.red : state.isIgnored() ? color.yellow : state.isUnexecuted() ? color.orange : color.black getBackgroundColor(ResultState state) => state.isSuccess() ? color.rgb(45, 48, 68) : state.isFailure() ? color.rgb(55, 48, 48) : state.isIgnored() ? color.rgb(50, 70, 40) : state.isUnexecuted() ? color.rgb(60, 60, 46) : color.black displayResult(table resultDisplay, int column, int row, string content, DisplaySettings settings, ResultState state, string tooltip = na) => table.cell(resultDisplay, column, row, content, text_size=settings.textSize, text_halign=text.align_left, text_valign=text.align_top, text_color=getTextColor(state), bgcolor=getBackgroundColor(state), tooltip=tooltip) method display(TestSession testSession) => displaySettings = testSession.displaySettings unfilteredResult = testSession.createSessionResult() unfilteredCounts = unfilteredResult.getResultCounts() sessionResult = testSession.getFilteredResults(unfilteredResult) counts = sessionResult.getResultCounts() bool displaySuites = false bool displayUnits = false for [si, sr] in sessionResult.results if not na(sr.name) displaySuites := true for [ui, ur] in sr.results if not na(ur.name) displayUnits := true columnCount = 1 if displaySuites columnCount += 1 if displayUnits columnCount += 1 rowCount = 1 + counts.getCount() table resultDisplay = table.new(testSession.displaySettings.position, columnCount, rowCount, bgcolor = color.rgb(0,0,0,100), frame_width = 0, border_width=1, frame_color = color.rgb(0,0,0,100)) table.merge_cells(resultDisplay, 0, 0, columnCount-1, 0) displayResult(resultDisplay, 0, 0, createResultsText(unfilteredCounts), testSession.displaySettings, unfilteredResult.state) nextRowIndex = 1 for [si, sr] in sessionResult.results sCounts = sr.testCounts if displaySuites if sCounts.getCount() > 1 table.merge_cells(resultDisplay, 0, nextRowIndex, 0, nextRowIndex + sCounts.getCount() - 1) displayResult(resultDisplay, 0, nextRowIndex, sr.name, testSession.displaySettings, sr.state) for [ui, ur] in sr.results uCounts = ur.getResultCounts() if displayUnits if uCounts.getCount() > 1 table.merge_cells(resultDisplay, columnCount-2, nextRowIndex, columnCount-2, nextRowIndex + uCounts.getCount() - 1)//displayedTrCount - 1) displayResult(resultDisplay, columnCount-2, nextRowIndex, ur.name, testSession.displaySettings, ur.state) for [ti, tr] in ur.results failureLog = tr.createFailuresText(testSession.timezone, testSession.logBarOnSeriesTests) displayResult(resultDisplay, columnCount-1, nextRowIndex, tr.id.testName, testSession.displaySettings, tr.state, failureLog) nextRowIndex += 1 //#endregion // @function Displays the test results if the TestSession is active. See TestSession for configuring how results are deisplayed export method report(TestSession testSession) => if testSession.active and barstate.islastconfirmedhistory testSession.logResults() if testSession.displaySettings.show testSession.display() testSession //#endregion //#region ===== Demo //#region Create and configure Your TestSession var testSession = createTestSession() // .setActive(false) // .deactivate() // .setMaxFailingBars(3) .setTimezone("Europe/Berlin") // .setLogBarOnSeriesTests(true) var displaySettings = testSession.displaySettings // .setShow(false) // .hide() // .setPosition(position.bottom_center) // .setTextSize(size.normal) // .setShowSuccess(false) // .hideSuccess() // .setShowFailure(false) // .showOnlyFailures() // .setShowIgnored(false) // .hideIgnored() // .setShowUnexecuted(false) // .hideUnexecuted() //#endregion //#region Create Tests and organise them var trueTest = testSession.createSimpleTest("True is always True") trueTest.assertTrue(true) var bullTest = testSession.createSeriesTest("It's allways Bull Market") bullTest.assertTrue(close > open, "Uhoh... it's not always bullish") var universeUnit = testSession.createUnit("Universe Unit") var universeTest = universeUnit.createSimpleTest("Is 42 actually 42?") universeTest.assertEquals(42, 42, "Uhoh... the universe is borken!") var piSuite = testSession.createSuite("Pi (We love ya!)") var piUnit = piSuite.createUnit("Pi Unit") var piTest = piUnit.createSimpleTest("Pi should begin correctly") piTest.assertTrue(str.startswith(str.tostring(math.pi), "3"), "The first digit of Pi is not three!") //#endregion //#region Test series-based functions on each bar highest(int length) => highest = 0.0 for i = 0 to length-1 by 1 highest := (high[i] > highest) ? high[i] : highest highest var highestUnit = testSession.createUnit("Highest") // var highestOfLastThreeTest = highestUnit.createSeriesTest("Should calculate highest of last three bars") var highestOfLastThreeTest = highestUnit.createSeriesTest("Should calculate highest of last three bars").sinceBar(3) highestOfLastThreeTest.assertEquals(math.max(high, high[1], high[2]), highest(3), "That is not the highest price of the last three bars") // var highestNaOnFirstBarsTest = highestUnit.createSeriesTest("Should return na on first bars") var highestNaOnFirstBarsTest = highestUnit.createSeriesTest("Should return na on first bars").untilBar(3) highestNaOnFirstBarsTest.assertNa(highest(3)) //#endregion // //#region Multiple Assertions within one single Test averagePrice(int maLength) => avg = (open + high + low) / 4 avgDiff = avg - close [avg, avgDiff] [actualAverage, actualDiff] = averagePrice(21) var averageUnit = testSession.createUnit("Average Price") var averagePriceTest = averageUnit.createSeriesTest("Should calculate") averagePriceTest.assertEquals(math.avg(open, high, low, close), actualAverage, "Wrong Average") averagePriceTest.assertEquals(math.avg(open, high, low, close) - close, actualDiff, "Wrong Diff") // //#endregion // //#region Define "When" Conditions for Tests momentum() => direction = close > open ? "Up" : close < open ? "Down" : "Side" diff = close - open [direction, diff] var momentumUnit = testSession.createUnit("Momentum") [direction, diff] = momentum() var momentumUpTest = momentumUnit.createSeriesTest("Up") momentumUpTest.when(close > open) momentumUpTest.assertEquals("Up", direction, "Wrong direction") momentumUpTest.assertEquals(close - open, diff, "Wrong distance") var momentumDownTest = momentumUnit.createSeriesTest("Down") momentumDownTest.when(close < open) momentumDownTest.assertEquals("Down", direction, "Wrong direction") momentumDownTest.assertEquals(open - close, diff, "Wrong distance") var momentumSideTest = momentumUnit.createSeriesTest("Side") momentumSideTest.when(close == open) momentumSideTest.assertEquals("Side", direction, "Wrong direction") momentumSideTest.assertEquals(0, diff, "Wrong distance") // //#endregion // //#region var ignoredTest = testSession.createSimpleTest("Ignored Test").ignore() ignoredTest.assertTrue(true) var ignoredUnit = testSession.createUnit("Ignored Unit").ignore() var unignoredTestInIgnoredUnit = ignoredUnit.createSimpleTest("Unignored") unignoredTestInIgnoredUnit.assertTrue(true) var ignoredSuite = testSession.createSuite("Ignored Suite").ignore() var unignoredUnitInIgnoredSuite = ignoredSuite.createUnit("Unignored Unit") var unignoredTestInIgnoredSuite = unignoredUnitInIgnoredSuite.createSimpleTest("Unignored") unignoredTestInIgnoredSuite.assertTrue(true) // //#endregion // //#region Difference between ignored and unexecuted testsne var ignoreAndUnexecuteUnit = testSession.createUnit("IgnoreAndUnexecuteUnit") var myIgnoredTest = ignoreAndUnexecuteUnit.createSeriesTest("My Ignored Test") myIgnoredTest.ignore() myIgnoredTest.assertTrue(false) var myUnexecutedTest = ignoreAndUnexecuteUnit.createSeriesTest("My Unexecuted Test") myUnexecutedTest.when(false) myUnexecutedTest.assertTrue(false) // //#endregion testSession.report() //#endregion
Sentiment Range MA [ChartPrime]
https://www.tradingview.com/script/LVsNPKBe-Sentiment-Range-MA-ChartPrime/
ChartPrime
https://www.tradingview.com/u/ChartPrime/
496
study
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/ // © ChartPrime //@version=5 indicator("Sentiment Range MA [ChartPrime]", overlay = true, timeframe = "", timeframe_gaps = false) simple_filter(float source, int length, bool duel_filter)=> switch duel_filter false => ta.wma(source, length) true => ta.wma(ta.sma(source, length), length) sr_ma(float source = close, int output_smoothing = 3, int trigger_smoothing = 1, int atr_length = 50, float multiplier = 1, string range_switch = "Body", bool duel_filter = false)=> candle_top = range_switch != "Body" ? high : math.max(open, close) candle_bottom = range_switch != "Body" ? low : math.min(open, close) smooth_top = ta.sma(candle_top, trigger_smoothing) smooth_bottom = ta.sma(candle_bottom, trigger_smoothing) tr = candle_top - candle_bottom atr = ta.sma(tr, atr_length) var float sr_ma = na var float current_range = na var float top_range = na var float bottom_range = na flag = smooth_top > top_range or smooth_bottom < bottom_range or na(current_range) if flag sr_ma := source current_range := atr * multiplier top_range := sr_ma + current_range bottom_range := sr_ma - current_range out = simple_filter(sr_ma, output_smoothing, duel_filter) smooth_top_range = simple_filter(top_range, output_smoothing, duel_filter) smooth_bottom_range = simple_filter(bottom_range, output_smoothing, duel_filter) [out, smooth_top_range, smooth_bottom_range] source = input.source(close, "Source", group = "Settings") output_smoothing = input.int(20, "Length", minval = 0, group = "Settings") + 1 use_double = input.bool(true, "Double Filter", group = "Settings") smoothing = input.int(4, "Trigger Smoothing", minval = 0, group = "Settings") + 1 atr_length = input.int(200, "ATR Length", minval = 1, group = "Settings") multiplier = input.float(6, "Range Multiplier", minval = 0, step = 0.125, group = "Settings") range_switch = input.string("Body", "Range Style", ["Body", "Wick"], group = "Settings") style = input.string("MA Direction", "Color Style", ["MA Direction", "MA Cross", "Solid"], group = "Color") bullish_color = input.color(color.rgb(33, 255, 120), "Bullish Color", group = "Color") bearish_color = input.color(color.rgb(255, 33, 33), "Bearish Color", group = "Color") neutral_color = input.color(color.rgb(137, 137, 137), "Neutral Color", "This doubles as the solid color.", group = "Color") [sr_ma, top_range, bottom_range] = sr_ma(source, output_smoothing, smoothing, atr_length, multiplier, range_switch, use_double) var color ma_delta = na var color ma_cross = na plot_neutral = high > sr_ma and low < sr_ma plot_bullish = low > sr_ma plot_bearish = high < sr_ma if plot_bullish ma_cross := bullish_color if plot_bearish ma_cross := bearish_color if plot_neutral ma_cross := neutral_color ma_delta_neutral = sr_ma - nz(sr_ma[1]) == 0 ma_delta_bullish = sr_ma - nz(sr_ma[1]) > 0 ma_delta_bearish = sr_ma - nz(sr_ma[1]) < 0 if ma_delta_bullish ma_delta := bullish_color if ma_delta_bearish ma_delta := bearish_color if ma_delta_neutral ma_delta := neutral_color ma_color = style == "MA Cross"? ma_cross : style == "MA Direction" ? ma_delta : neutral_color alpha = color.new(color.red, 100) ma = plot(sr_ma, "SR MA", ma_color, 3) top = plot(top_range, "Top Range", alpha) bottom = plot(bottom_range, "Bottom Range", alpha) fill(ma, top, top_value = top_range, bottom_value = sr_ma, bottom_color = color.new(ma_color, 82), top_color = alpha) fill(ma, bottom, top_value = sr_ma, bottom_value = bottom_range, top_color = color.new(ma_color, 82), bottom_color = alpha)
Trend Lines [LuxAlgo]
https://www.tradingview.com/script/vE8YNVgM-Trend-Lines-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
1,767
study
5
CC-BY-NC-SA-4.0
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © LuxAlgo //@version=5 indicator("Trend Lines [LuxAlgo]", shorttitle= "LuxAlgo - Trend Lines", max_lines_count = 500, max_labels_count = 500, overlay = true) //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ NN = "Disabled" AB = "Point A - Point B" AC = "Point A - Current bar" length = input.int ( 50 , minval = 2 , group= "Swings" ) toggle = input.string( NN , 'Check breaks between:' , options= [ AB, AC, NN ] , group= "Trendline validation" ) source = input.string( "close" , 'source (breaks)' , options= ["close", "H/L"] , group= "Trendline validation" ) count = input.int ( 3 , 'Minimal bars' , minval = 0 , group= "Trendline breaks" , tooltip= 'Uninterrupted Trendline for at least x bars') showA = input.bool ( true , 'show Angles' , group= "Angles" ) ratio = input.float ( 3 , 'Ratio X-Y axis' , step =0.1 , group= "Angles" ) anglA = input.float ( 0.1 ,'Only Trendlines between:', minval =0.1, inline= 'angle', group= "Angles" ) anglB = input.float ( 90 , ' - ' , minval =0.1, inline= 'angle', group= "Angles" ) upCss = input.color (#2962ff, 'Up' , group= "Colours" ) dnCss = input.color (#f23645, 'Down' , group= "Colours" ) //-----------------------------------------------------------------------------} //Variables //-----------------------------------------------------------------------------{ //Downtrendline var int phx1 = na var float phslope = na var float phy1 = na var float upper = na var float plotH = na var bool isOnH = false //Uptrendline var int plx1 = na var float plslope = na var float ply1 = na var float lower = na var float plotL = na var bool isOnL = false var line testLine = line.new(na, na, na, na, color=color.new(color.blue, 100)) //-----------------------------------------------------------------------------} //Calculations //-----------------------------------------------------------------------------{ n = bar_index bg = chart.bg_color fg = chart.fg_color ph = ta.pivothigh (length, length) pl = ta.pivotlow (length, length) bars = 500 , height = bars / ratio Xaxis = math.min(math.max(1, n), bars) Yaxis = ta.highest(Xaxis) - ta.lowest(Xaxis) srcBl = source == "close" ? close : high srcBr = source == "close" ? close : low //-----------------------------------------------------------------------------} //Function //-----------------------------------------------------------------------------{ calculate_slope(x1, x2, y1, y2) => diffX = x2 - x1, diffY = y2 - y1 diffY_to_Yaxis = Yaxis / diffY normalised_slope = (height / diffY_to_Yaxis) / diffX slope = diffY / diffX angle = math.round(math.atan(normalised_slope) * 180 / math.pi, 2) [normalised_slope, slope, angle] //-----------------------------------------------------------------------------} //Execution //-----------------------------------------------------------------------------{ if not na(ph) if ph < phy1 [normalised_slope, slope, angle]= calculate_slope(phx1, n-length, phy1, ph) testLine.set_xy1(phx1, phy1), testLine.set_xy2(n, ph + slope * length) src = source == "close" ? close : high, max_bars_back(src, 2000) isOnH := false broken = false if math.abs(angle) > anglA and math.abs(angle) < anglB if toggle != NN for i = (toggle == AB ? length : 0) to n - phx1 if src[i] > testLine.get_price(n - i) broken := true break if not broken phslope := slope, isOnH := true, upper := ph + slope * length line.new(phx1, phy1, n, ph + slope * length , color= dnCss, style= line.style_dotted) if showA label.new(phx1, phy1, text= str.tostring(angle) , style = label.style_label_down , color = color.new(bg, 100) , textcolor = dnCss) phy1 := ph phx1 := n-length upper += phslope plotH := not na(ph) and ta.change(phslope) ? na : srcBl[1] > upper[1] ? na : upper bs_H = ta.barssince (na(plotH )) if not na(pl) if pl > ply1 [normalised_slope, slope, angle]= calculate_slope(plx1, n-length, ply1, pl) testLine.set_xy1(plx1, ply1), testLine.set_xy2(n, pl + slope * length) src = source == "close" ? close : low , max_bars_back(src, 2000) isOnL := false broken = false if angle > anglA and angle < anglB if toggle != NN for i = (toggle == AB ? length : 0) to n - plx1 if src[i] < testLine.get_price(n - i) broken := true break if not broken plslope := slope, isOnL := true, lower := pl + slope * length line.new(plx1, ply1, n, pl + slope * length , color= upCss, style= line.style_dotted) if showA label.new(plx1, ply1, text= str.tostring(angle) , style = label.style_label_up , color = color.new(bg, 100) , textcolor = upCss) ply1 := pl plx1 := n-length lower += plslope plotL := not na(pl) and ta.change(plslope) ? na : srcBr[1] < lower[1] ? na : lower bs_L = ta.barssince (na(plotL )) //-----------------------------------------------------------------------------} //Plots //-----------------------------------------------------------------------------{ plot(plotH, 'Down Trendline' , dnCss , 1 , plot.style_linebr) plot(plotL, 'Up Trendline' , upCss , 1 , plot.style_linebr) plotshape( bs_H > count and srcBl > upper and srcBl[1] <= upper[1] , 'Bullish break' , shape.labelup , location.belowbar , dnCss , size = size.tiny) plotshape( bs_L > count and srcBr < lower and srcBr[1] >= lower[1] , 'Bearish break' , shape.labeldown , location.abovebar , upCss , size = size.tiny) //-----------------------------------------------------------------------------}
AGbayLIB
https://www.tradingview.com/script/O81IBvZF-AGbayLIB/
agbay
https://www.tradingview.com/u/agbay/
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/ // © agbay //@version=5 // @description Changes the timeframe period to the given period and returns the data matrix[cyear, cmonth, cday, chour, cminute_, csecond, cfulltime, copen, cclose, chigh, clow, cvolume] and sets the timeframe to the active time period library(title = "AGbayLIB") export type agSetting string symbol = na string period = na int iperiod = na int max_bar_count = 100 int min_trend_count = 0 int tenkansen_count = 9 int kijunsen_count = 26 int order_block_period = 7 float threshold=0.0 //@type Contains candle values //@field timestamp Time value of the candle //@field year Extracted year value from time //@field month Extracted month value from time //@field day Extracted day value from time //@field hour Extracted hour value from time //@field minute Extracted minute value from time //@field second Extracted second value from time //@field open Open value of candle //@field close Close value of candle //@field high High value of candle //@field low Low value of candle //@field volume Volume value of candle //@field trend Calculated trend value of candle //@field trend_count Calculated trending candle count of active candle export type agCandle int timestamp = 0 int year = 0 int month = 0 int day = 0 int dayofweek = 0 int hour = 0 int minute = 0 int second = 0 string fulltime = "" int barindex = -1 float open = 0.0 float close = 0.0 float high = 10.0 float low = 0.0 float volume = 0.0 bool resistantance = false bool supply = false int trend = 0 int trend_count = 0 bool is_order = false bool is_white = false bool is_bullish = false export type agZigZagNode agCandle candle=na int candle_index=-1 int trend=0 agCandle pinnedCandle=na int pinned_candle_index=-1 export type agSymbolCandles agSetting setting = na int count=0 array<agCandle> candles=na array<agZigZagNode> zigzag_nodes=na // @function: Creates an data_set typed object, copies open,close,high,low,volume,time data into records and also calculates trends of records // @param symbol Symbol // @param period Target time period for returning data // @param max_bars The historical bar count to be get // @param opens The historical bars of open data // @param closes The historical bars of open data // @param highs The historical bars of open data // @param lows The historical bars of open data // @param volumes The historical bars of open data // @param times The historical bars of open data // @returns An agSymbolCandles object which contains array of agCandles type which includes [timestamp, year, month, day, hour, minute, second, fulltime, open, close, high, clow, volume, trend] export getTimeFrameValues(agSetting setting=na, series float opens, series float closes, series float highs, series float lows, series float volumes, series int times, series int bar_indexes)=> max_bars=setting.max_bar_count time_period = setting.period symbol = setting.symbol period = setting.period var data = agSymbolCandles.new(setting = setting, count=max_bars, candles = array.new<agCandle>(max_bars), zigzag_nodes = array.new<agZigZagNode>()) int max_bar_count = max_bars //data.candles := array.new<data_row>(max_bar_count) int max1 = max_bar_count-1 int max2 = max1-1 trend = 0 counter = 0 float prev_o = na float prev_c = na float prev_h = na float prev_l = na float prev_min = na float prev_max = na bool prev_white = na for bi=max1 to 0 if na(opens[bi]) continue if na(prev_o) prev_o := opens[bi] prev_c := closes[bi] prev_h := highs[bi] prev_l :=lows[bi] prev_white := prev_o < prev_c ? true : false prev_min := prev_o < prev_c ? prev_o : prev_c prev_max := prev_o > prev_c ? prev_o : prev_c if bi<0 continue //----- Get Current Candle Values o = opens[bi] h = highs[bi] l = lows[bi] c = closes[bi] v = volumes[bi] t = times[bi] b_index = bar_indexes[bi] white = o < c ? true : false //------------ { Trend sequential calculation starts here min = o < c ? o : c max = o > c ? o : c if o==c and prev_o==prev_c trend := 0 counter := 0 else if prev_min < c and c < prev_h and o!=c trend := 0 counter := 0 else if prev_c < c and o!=c if trend > 0 trend := trend + 1 counter := counter + 1 else trend := 1 prev_c := c counter := 0 else if prev_c > c and o!=c if trend > 0 trend := -1 prev_c := c counter := 0 else trend := trend - 1 counter := counter + 1 prev_o := o prev_c := c prev_l := o prev_h := c prev_min := min prev_max := max //------------ } Trend sequential calculation ends here -------- // initialize current candle ty = year(t) tm = month(t) td = dayofmonth(t) tdw = dayofweek(t) th= hour(t) tmin = minute(t) ts = second(t) agCandle ci = agCandle.new() ci.timestamp := 0 ci.year := ty ci.month := tm ci.day := td ci.dayofweek := tdw ci.hour := th ci.minute := tmin ci.second := ts ci.fulltime := str.format("{0}-{1}-{2} {3}:{4}:{5}",ty,tm,td,th,tmin,ts) ci.barindex := b_index ci.open := o ci.close := c ci.high := h ci.low := l ci.volume := v ci.trend := trend ci.trend_count := counter ci.resistantance := false ci.supply := false, ci.barindex := b_index ci.is_white := white //---- Add candle to the array //data.candles.unshift(ci) data.candles.set(bi,ci) for bi = data.candles.size()-2 to 0 if bi<0 break if not na(data.candles.get(bi)) and not na(data.candles.get(bi+1)) ci = data.candles.get(bi) ci2 = data.candles.get(bi+1) if ci.trend>0 and ci2.trend<0 ci.resistantance := true else ci.resistantance := false if not ci2.is_white and ci.is_white and ci.close>ci2.close ci.is_order := true if ci2.is_white and not ci.is_white if ci.high>ci2.high and ci.open<=ci.close and ci.open>=ci2.open and ci.low>ci2.low ci.is_bullish := true data.candles.set(bi,ci) [data] // @function: Searches bearish and bullish order blocks // @param setting setting parameters for calculation // @param oclh Given [open, close, low, high] series tuple // @returns [bullishOB, bearishOB, OB_bull, OB_bull_chigh, OB_bull_clow, OB_bull_avg, OB_bear, OB_bear_chigh, OB_bear_clow,OB_bear_avg] Tuple export isBearishBullish(agSetting setting, series float copen, series float cclose, series float clow, series float chigh )=> periods=setting.order_block_period threshold = setting.threshold ob_period = periods + 1 // Identify location of relevant Order Block candle absmove = ((math.abs(cclose[ob_period] - cclose[1]))/cclose[ob_period]) * 100 // Calculate absolute percent move from potential OB to last candle of subsequent candles relmove = absmove >= threshold // Bullish Order Block Identification bullishOB = cclose[ob_period] < copen[ob_period] // Determine potential Bullish OB candle (red candle) int upcandles = 0 for i = 1 to periods upcandles := upcandles + (cclose[i] > copen[i]? 1 : 0) // Determine color of subsequent candles (must all be green to identify a valid Bearish OB) OB_bull = bullishOB and (upcandles == (periods)) and relmove // Identification logic (red OB candle & subsequent green candles) OB_bull_chigh = OB_bull? chigh[ob_period] : na // Determine OB upper limit (Open or High depending on input) OB_bull_clow = OB_bull? clow[ob_period] : na // Determine OB clower limit (Low) OB_bull_avg = (OB_bull_chigh + OB_bull_clow)/2 // Determine OB middle line // Bearish Order Block Identification bearishOB = cclose[ob_period] > copen[ob_period] // Determine potential Bearish OB candle (green candle) int downcandles = 0 for i = 1 to periods downcandles := downcandles + (cclose[i] < copen[i]? 1 : 0) // Determine color of subsequent candles (must all be red to identify a valid Bearish OB) OB_bear = bearishOB and (downcandles == (periods)) and relmove // Identification logic (green OB candle & subsequent green candles) OB_bear_chigh = OB_bear? chigh[ob_period] : na // Determine OB upper limit (High) OB_bear_clow = OB_bear? clow[ob_period] : na // Determine OB clower limit (Open or Low depending on input) OB_bear_avg = (OB_bear_clow + OB_bear_chigh)/2 // Determine OB middle line [bullishOB, bearishOB, ob_period, OB_bull, OB_bull_chigh, OB_bull_clow, OB_bull_avg, OB_bear, OB_bear_chigh, OB_bear_clow,OB_bear_avg]
WIPFunctionLyaponov
https://www.tradingview.com/script/QxBg9q9S-WIPFunctionLyaponov/
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 // checkpoint // 100 matrix version // 126 map version //@description Lyapunov exponents are mathematical measures used to describe the behavior of a system over // time. They are named after Russian mathematician Alexei Lyapunov, who first introduced the concept in the // late 19th century. The exponent is defined as the rate at which a particular function or variable changes // over time, and can be positive, negative, or zero. // Positive exponents indicate that a system tends to grow or expand over time, while negative exponents // indicate that a system tends to shrink or decay. Zero exponents indicate that the system does not change // significantly over time. Lyapunov exponents are used in various fields of science and engineering, including // physics, economics, and biology, to study the long-term behavior of complex systems. // ~ generated description from vicuna13b // // --- // To calculate the Lyapunov Exponent (LE) of a given Time Series, we need to follow these steps: // 1. Firstly, you should have access to your data in some format like CSV or Excel file. If not, then you can collect it manually using tools such as stopwatches and measuring tapes. // 2. Once the data is collected, clean it up by removing any outliers that may skew results. This step involves checking for inconsistencies within your dataset (e.g., extremely large or small values) and either discarding them entirely or replacing with more reasonable estimates based on surrounding values. // 3. Next, you need to determine the dimension of your time series data. In most cases, this will be equal to the number of variables being measured in each observation period (e.g., temperature, humidity, wind speed). // 4. Now that we have a clean dataset with known dimensions, we can calculate the LE for our Time Series using the following formula: // λ = log(||M^T * M - I||)/log(||v||) // where: // λ (Lyapunov Exponent) is the quantity that will be calculated. // ||...|| denotes an Euclidean norm of a vector or matrix, which essentially means taking the square root of the sum of squares for each element in the vector/matrix. // M represents our Jacobian Matrix whose elements are given by: // J_ij = (∂fj / ∂xj) where fj is the jth variable and xj is the ith component of the initial condition vector x(t). In other words, each element in this matrix represents how much a small change in one variable affects another. // I denotes an identity matrix whose elements are all equal to 1 (or any constant value if you prefer). This term essentially acts as a baseline for comparison purposes since we want our Jacobian Matrix M^T * M to be close to it when the system is stable and far away from it when the system is unstable. // v represents an arbitrary vector whose Euclidean norm ||v|| will serve as a scaling factor in our calculation. The choice of this particular vector does not matter since we are only interested in its magnitude (i.e., length) for purposes of normalization. However, if you want to ensure that your results are accurate and consistent across different datasets or scenarios, it is recommended to use the same initial condition vector x(t) as used earlier when calculating our Jacobian Matrix M. // 5. Finally, once we have calculated λ using the formula above, we can interpret its value in terms of stability/instability for our Time Series data: // - If λ < 0, then this indicates that the system is stable (i.e., nearby trajectories will converge towards each other over time). // - On the other hand, if λ > 0, then this implies that the system is unstable (i.e., nearby trajectories will diverge away from one another over time). // ~ generated description from airoboros33b // // --- // Reference: // https://en.wikipedia.org/wiki/Lyapunov_exponent // https://www.collimator.ai/reference-guides/what-is-a-lyapunov-exponent // https://blog.abhranil.net/2014/07/22/calculating-the-lyapunov-exponent-of-a-time-series-with-python-code/ // https://www.researchgate.net/publication/222460963_Determining_Lyapunov_Exponents_From_a_Time_Series // https://physics.stackexchange.com/questions/102529/calculating-lyapunov-exponents-from-a-multi-dimensional-experimental-time-series // // --- // This is a work in progress, it may contain errors so use with caution. // If you find flaws or suggest something new, please leave a comment bellow. library("WIPFunctionLyaponov") import RicardoSantos/SimilarityMeasures/1 import RicardoSantos/CommonTypesMapUtil/1 // @function helper function to get the name of distance function by a index (0 -> 13).\ // Functions: SSD, Euclidean, Manhattan, Minkowski, Chebyshev, Correlation, Cosine, Camberra, MAE, MSE, Lorentzian, Intersection, Penrose Shape, Meehl. export _measure_function (int i=0) => switch i 00 => 'ssd' 01 => 'euclidean' 02 => 'manhattan' 03 => 'minkowski' 04 => 'chebychev' 05 => 'correlation' 06 => 'cosine' 07 => 'camberra' 08 => 'mae' 09 => 'mse' 10 => 'lorentzian' 11 => 'intersection' 12 => 'penrose' 13 => 'meehl' // @function Calculate the vector distance between two vectors. vdistance (array<float> a, array<float> b, string type = 'ssd') => switch type 'ssd' => SimilarityMeasures.ssd(a, b) 'euclidean' => SimilarityMeasures.euclidean(a, b) 'manhattan' => SimilarityMeasures.manhattan(a, b) 'minkowski' => SimilarityMeasures.minkowski(a, b) 'chebychev' => SimilarityMeasures.chebyshev(a, b) 'correlation' => SimilarityMeasures.correlation(a, b) 'cosine' => SimilarityMeasures.cosine(a, b) 'camberra' => SimilarityMeasures.camberra(a, b) 'mae' => SimilarityMeasures.mae(a, b) 'mse' => SimilarityMeasures.mse(a, b) 'lorentzian' => SimilarityMeasures.lorentzian(a, b) 'intersection' => SimilarityMeasures.intersection(a, b) 'penrose' => SimilarityMeasures.penrose(a, b) 'meehl' => SimilarityMeasures.meehl(a, b) // @function Helper function to test the output exponents state system and outputs description into a string. export _test (array<float> L) => float _sum = 0.0 int _neg_count = 0 bool _is_chaotic = false for _e in L if _e > 0.0 _is_chaotic := true break if _e < 0.0 _neg_count += 1 _sum += _e _is_stable = _neg_count == L.size() switch _is_chaotic => 'System is Chaotic.\n Small differences in initial conditions will lead to vastly different outcomes over time.\n' // atleast one positive exponent. _is_stable => 'System is Stable.\n Small perturbations from equilibrium will decay over time, and the system will return to its original state.\n' // all exponents are negative _sum == 0.0 => 'System is Neutrally Stable.\n Small perturbations from equilibrium will neither converge nor diverge.\n'//the sum of all Lyapunov exponents is zero => 'Unable to determine System.' // reference: arXiv:2308.01013 // Bayesian framework for characterizing // cryptocurrency market dynamics, structural // dependency, and volatility using potential field // by: Anoop C V, Neeraj Negi, Anup Aprem // @function Estimate the Lyaponov Exponents for multiple series in a row matrix. // @param data Data series in a row matrix format (a row represents a 1d series). // @param initial_distance Initial distance limit. // @param distance_function Name of the distance function to be used, default:`ssd`. // @returns List of Lyaponov exponents. export estimate (map<string, CommonTypesMapUtil.ArrayFloat> X, float initial_distance=1.0e6, string distance_function='ssd') => array<string> _series = X.keys() int _N = _series.size()-1 int _length = X.get(_series.get(0)).v.size() array<float> _L = array.new<float>() matrix<float> _lambda = matrix.new<float>(_N+1, _length, 0.0) for [_i, _si] in _series if _i < _N for _j = _i + 1 to _N array<float> _Xi = X.get(_si ).v array<float> _Xj = X.get(_series.get(_j)).v float _dist1 = vdistance(_Xi, _Xj, distance_function) int _Nij = _N - _j // Current distance under initial distance or predetermined. if _dist1 <= initial_distance for _k = 0 to _Nij float _1k = 1.0 / _k array<float> _Sik = X.get(_series.get(_i + _k)).v array<float> _Sjk = X.get(_series.get(_j + _k)).v // Calculate divergence from initial. for _l = 0 to _length-1 float _dist2 = vdistance(_Sik.slice(_l, _length), _Sjk.slice(_l, _length), distance_function) float _div = _1k * math.log(_dist2 / _dist1) _lambda.set(_k, _l, _div) _lambda.set(_i, _j, nz(_lambda.get(_i, _j)) + _div) _L.push(nz(_lambda.get(_i, _j) / _Nij, 0.0)) _L // @function Maximal Lyaponov Exponent. // @param L List of Lyapunov exponents. // @returns Highest exponent. export max (array<float> L) => L.max() import RicardoSantos/DebugConsole/13 as console logger = console.new() logger.table.cell_set_height(0, 0, 80.0) logger.table.cell_set_width(0, 0, 80.0) var matrix<float> mat = matrix.new<float>(5, 10, na) // test with random source: // if barstate.islastconfirmedhistory // for _i = 0 to 4 // for _j = 0 to 9 // mat.set(_i, _j, 1000.0 + 100.0 * math.random(-1.0, 1.0)) // lyap = estimate(mat, array.new<float>(10), e, k, dt) // log.warning('{0}: {1}', test(lyap), lyap) // line.new(bar_index, 0, bar_index+1, lyap.get(0)) // for _i = 1 to 9 // line.new(bar_index+_i, lyap.get(_i-1), bar_index+_i+1, lyap.get(_i)) // test with assets source: string _sym0 = 'BTCUSD' string _sym1 = 'ETHUSD' string _sym2 = 'XRPUSD' string _sym3 = 'SOLUSD' string _sym4 = 'SPX' var array<string> symbols = array.from(_sym0, _sym1, _sym2, _sym3, _sym4) float _s0 = request.security(_sym0, timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_off) float _s1 = request.security(_sym1, timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_off) float _s2 = request.security(_sym2, timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_off) float _s3 = request.security(_sym3, timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_off) float _s4 = request.security(_sym4, timeframe.period, close, barmerge.gaps_on, barmerge.lookahead_off) var map0 = map.new<string, CommonTypesMapUtil.ArrayFloat>() var map1 = map.new<string, CommonTypesMapUtil.ArrayFloat>() var map2 = map.new<string, CommonTypesMapUtil.ArrayFloat>() // mat3 = matrix.new<float>(5, 10, 0.0) // for _i = 0 to 4 // for _j = 0 to 9 // mat.set(_i, _j, nz(sel(_i, _j))) // mat2.set(_i, _j, bar_index[_j]) // mat3.set(_i, _j, math.random(-1.0, 1.0)) int length = input.int(10) if barstate.islastconfirmedhistory for [_si, _sym] in symbols _series = CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0)) map0.put(_sym, _series) map1.put('seq1', CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0))) map1.put('seq2', CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0))) map1.put('seq3', CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0))) map2.put('rng1', CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0))) map2.put('rng2', CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0))) map2.put('rng3', CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0))) map2.put('rng4', CommonTypesMapUtil.ArrayFloat.new(array.new<float>(length, 0.0))) for _i = 0 to length - 1 map0.get(_sym0).v.set(_i, _s0[_i]) map0.get(_sym1).v.set(_i, _s1[_i]) map0.get(_sym2).v.set(_i, _s2[_i]) map0.get(_sym3).v.set(_i, _s3[_i]) map0.get(_sym4).v.set(_i, _s4[_i]) map1.get('seq1').v.set(_i, bar_index[_i]) map1.get('seq2').v.set(_i, bar_index[_i]) map1.get('seq3').v.set(_i, bar_index[_i]) map2.get('rng1').v.set(_i, math.random(-1.0, 1.0)) map2.get('rng2').v.set(_i, math.random(-1.5, 1.0)) map2.get('rng3').v.set(_i, math.random(-2.0, 3.0)) map2.get('rng4').v.set(_i, math.random(-3.0, 5.0)) // logger.queue(str.format('{0}', map0.get(_sym0).v)) lyap0 = estimate(map0, vdistance(map0.get(symbols.get(0)).v, map0.get(symbols.get(1)).v)) logger.queue(str.format('{0}: {1}', _test(lyap0), str.tostring(lyap0, '#.####'))) lyap1 = estimate(map1, vdistance(map1.get('seq1').v, map1.get('seq2').v)) logger.queue(str.format('{0}: {1}', _test(lyap1), str.tostring(lyap1, '#.####'))) lyap2 = estimate(map2, vdistance(map2.get('rng1').v, map2.get('rng2').v)) logger.queue(str.format('{0}: {1}', _test(lyap2), str.tostring(lyap2, '#.####'))) // line.new(bar_index, 0, bar_index+1, lyap.get(0)) // for _i = 1 to 9 // line.new(bar_index+_i, lyap.get(_i-1), bar_index+_i+1, lyap.get(_i)) logger.update()
Contrast Color Library
https://www.tradingview.com/script/cvUcp6x0-Contrast-Color-Library/
algotraderdev
https://www.tradingview.com/u/algotraderdev/
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/ // © algotraderdev // @version=5 // @description This lightweight library provides a utility method that analyzes any provided background color and // automatically chooses the optimal black or white foreground color to ensure maximum visual contrast and readability. library('contrast', overlay = true) // @function Calculates the optimal foreground color for the given background color. // @param bg The background color. // @param threshold The threshold brightness (0-1) above which black text is used. Default is 0.5. // @returns The optimal foreground color. export method contrast(color bg, float threshold = 0.5) => float r = color.r(bg) / 255 float g = color.g(bg) / 255 float b = color.b(bg) / 255 float brightness = math.sqrt( 0.299 * r * r + 0.587 * g * g + 0.114 * b * b) brightness > threshold ? #000000 : #ffffff // Demo code below. They will NOT be run in indicators that uses this library. int rows = 10 int columns = 8 table t = table.new(position.middle_center, columns, rows) for i = 0 to rows - 1 for j = 0 to columns - 1 color bg = color.rgb(math.random(0, 255), math.random(0, 255), math.random(0, 255)) color fg = bg.contrast() t.cell(j, i, 'Test123', width = 10, height = 4, bgcolor = bg, text_color = fg)
Ephemeris
https://www.tradingview.com/script/nB6jxuPn-Ephemeris/
BullRider802
https://www.tradingview.com/u/BullRider802/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © BullRider802 //@version=5 // @description TODO: add library description here library("Ephemeris") // ======================================================================================================================== // PLANETARY KEPLER CONSTANTS // ======================================================================================================================== //ELEMENTS @ J2000: a, e, i, mean longitude (L), longitude of perihelion, longitude of ascending node //https://ssd.jpl.nasa.gov/?planet_pos // a = semi major axis [0] // e = eccentricity [1] // i = orbit inclination [2] // L = mean longitude [3] // w = argument of perihelion [4] // N = longitude of ascending node [5] // Mercury Kepler Elements // @returns Returns constant Mercury orbital elements used to calculate Kepler equations export mercuryElements() => mercuryElements = array.new<float>(6, 0.0) array.insert(mercuryElements, 0, 0.38709927) array.insert(mercuryElements, 1, 0.20563593) array.insert(mercuryElements, 2, 7.00497902) array.insert(mercuryElements, 3, 252.25032350) array.insert(mercuryElements, 4, 77.45779628) array.insert(mercuryElements, 5, 48.33076593) mercuryElements // Mercury Kepler Rates // @returns Returns constant Mercury orbital rates used to calculate Kepler equations export mercuryRates() => mercuryRates = array.new<float>(6, 0.0) array.insert(mercuryRates, 0, 0.00000037) array.insert(mercuryRates, 1, 0.00001906) array.insert(mercuryRates, 2, -0.00594749) array.insert(mercuryRates, 3, 149472.67411175) array.insert(mercuryRates, 4, 0.16047689) array.insert(mercuryRates, 5, -0.12534081) mercuryRates // Venus Kepler Elements // @returns Returns constant Venus orbital elements used to calculate Kepler equations export venusElements() => venusElements = array.new<float>(6, 0.0) array.insert(venusElements, 0, 0.72333566) array.insert(venusElements, 1, 0.00677672) array.insert(venusElements, 2, 3.39467605) array.insert(venusElements, 3, 181.97909950) array.insert(venusElements, 4, 131.60246718) array.insert(venusElements, 5, 76.67984255) venusElements // Venus Kepler Rates // @returns Returns constant Venus orbital rates used to calculate Kepler equations export venusRates() => venusRates = array.new<float>(6, 0.0) array.insert(venusRates, 0, 0.00000390) array.insert(venusRates, 1, -0.00004107) array.insert(venusRates, 2, -0.00078890) array.insert(venusRates, 3, 58517.81538729) array.insert(venusRates, 4, 0.00268329) array.insert(venusRates, 5, -0.27769418) venusRates // Earth Kepler Elements // @returns Returns constant Earth orbital elements used to calculate Kepler equations export earthElements() => earthElements = array.new<float>(6, 0.0) array.insert(earthElements, 0, 1.00000261) array.insert(earthElements, 1, 0.01671123) array.insert(earthElements, 2, -0.00001531) array.insert(earthElements, 3, 100.46457166) array.insert(earthElements, 4, 102.93768193) array.insert(earthElements, 5, 0.0) earthElements // Earth Kepler Rates // @returns Returns constant Earth orbital rates used to calculate Kepler equations export earthRates() => earthRates = array.new<float>(6, 0.0) array.insert(earthRates, 0, -0.00000562) array.insert(earthRates, 1, -0.00004392) array.insert(earthRates, 2, -0.01294668) array.insert(earthRates, 3, 35999.37244981) array.insert(earthRates, 4, 0.32327364) array.insert(earthRates, 5, 0.0) earthRates // Mars Kepler Elements // @returns Returns constant Mars orbital elements used to calculate Kepler equations export marsElements() => marsElements = array.new<float>(6, 0.0) array.insert(marsElements, 0, 1.52371034) array.insert(marsElements, 1, 0.09339410) array.insert(marsElements, 2, 1.84969142) array.insert(marsElements, 3, -4.55343205) array.insert(marsElements, 4, -23.94362959) array.insert(marsElements, 5, 49.55953891) marsElements // @returns Returns constant Mars orbital rates used to calculate Kepler equations export marsRates() => marsRates = array.new<float>(6, 0.0) array.insert(marsRates, 0, 0.00001847) array.insert(marsRates, 1, 0.00007882) array.insert(marsRates, 2, 0.00813131) array.insert(marsRates, 3, 19140.30268499) array.insert(marsRates, 4, 0.44441088) array.insert(marsRates, 5, -0.29257343) marsRates // @returns Returns constant Jupiter orbital elements used to calculate Kepler equations export jupiterElements() => jupiterElements = array.new<float>(6, 0.0) array.insert(jupiterElements, 0, 5.20288700) array.insert(jupiterElements, 1, 0.04838624) array.insert(jupiterElements, 2, 1.30439695) array.insert(jupiterElements, 3, 34.39644051) array.insert(jupiterElements, 4, 14.72847983) array.insert(jupiterElements, 5, 100.47390909) jupiterElements // @returns Returns constant Jupiter orbital rates used to calculate Kepler equations export jupiterRates() => jupiterRates = array.new<float>(6, 0.0) array.insert(jupiterRates, 0, -0.00011607) array.insert(jupiterRates, 1, -0.00013253) array.insert(jupiterRates, 2, -0.00183714) array.insert(jupiterRates, 3, 3034.74612775) array.insert(jupiterRates, 4, 0.21252668) array.insert(jupiterRates, 5, 0.20469106) jupiterRates // @returns Returns constant Saturn orbital elements used to calculate Kepler equations export saturnElements() => saturnElements = array.new<float>(6, 0.0) array.insert(saturnElements, 0, 9.53667594) array.insert(saturnElements, 1, 0.05386179) array.insert(saturnElements, 2, 2.48599187) array.insert(saturnElements, 3, 49.95424423) array.insert(saturnElements, 4, 92.59887831) array.insert(saturnElements, 5, 113.66242448) saturnElements // @returns Returns constant Saturn orbital rates used to calculate Kepler equations export saturnRates() => saturnRates = array.new<float>(6, 0.0) array.insert(saturnRates, 0, -0.00125060) array.insert(saturnRates, 1, -0.00050991) array.insert(saturnRates, 2, 0.00193609) array.insert(saturnRates, 3, 1222.49362201) array.insert(saturnRates, 4, -0.41897216) array.insert(saturnRates, 5, -0.28867794) saturnRates // @returns Returns constant Uranus orbital elements used to calculate Kepler equations export uranusElements() => uranusElements = array.new<float>(6, 0.0) array.insert(uranusElements, 0, 19.18916464) array.insert(uranusElements, 1, 0.04725744) array.insert(uranusElements, 2, 0.77263783) array.insert(uranusElements, 3, 313.23810451) array.insert(uranusElements, 4, 170.95427630) array.insert(uranusElements, 5, 74.01692503) uranusElements // @returns Returns constant Uranus orbital rates used to calculate Kepler equations export uranusRates() => uranusRates = array.new<float>(6, 0.0) array.insert(uranusRates, 0, 0.00196176) array.insert(uranusRates, 1, -0.00004397) array.insert(uranusRates, 2, -0.00242939) array.insert(uranusRates, 3, 428.48202785) array.insert(uranusRates, 4, 0.40805281) array.insert(uranusRates, 5, 0.04240589) uranusRates // @returns Returns constant Neptune orbital elements used to calculate Kepler equations export neptuneElements() => neptuneElements = array.new<float>(6, 0.0) array.insert(neptuneElements, 0, 30.06992276) array.insert(neptuneElements, 1, 0.00859048) array.insert(neptuneElements, 2, 1.77004347) array.insert(neptuneElements, 3, -55.12002969) array.insert(neptuneElements, 4, 44.96476227) array.insert(neptuneElements, 5, 131.78422574) neptuneElements // @returns Returns constant Neptune orbital rates used to calculate Kepler equations export neptuneRates() => neptuneRates = array.new<float>(6, 0.0) array.insert(neptuneRates, 0, 0.00026291) array.insert(neptuneRates, 1, 0.00005105) array.insert(neptuneRates, 2, 0.00035372) array.insert(neptuneRates, 3, 218.45945325) array.insert(neptuneRates, 4, -0.32241464) array.insert(neptuneRates, 5, -0.00508664) neptuneRates // ======================================================================================================================== // CONSTANTS & HELPER FUNCTIONS // ======================================================================================================================== // @function Normalize degrees to within [0, 360) // @param x degrees to be normalized // @returns Normalized degrees export rev360(float x) => float angle = x - math.floor(x / 360.0) * 360.0 if angle < 0.0 angle := angle + 360.0 angle // @function Scale angle in degrees // @param x Angle in degrees // @returns Scaled angle in degrees export scaleAngle(float longitude, float magnitude, int harmonic) => longitude*magnitude + 360*harmonic // @function Constant Julian days per century // @returns 36525 export julianCenturyInJulianDays() => 36525 // @function Julian date on J2000 epoch start (2000-01-01) // @returns 2451545.0 export julianEpochJ2000() => 2451545.0 // @function Mean obliquity of the ecliptic on J2000 epoch start (2000-01-01) // @returns 23.43928 export meanObliquityForJ2000() => 23.43928 // @function Convert calendar date to Julian date // @param Year calendar year as integer (e.g. 2018) // @param Month calendar month (January = 1, December = 12) // @param Day calendar day of month (e.g. January valid days are 1-31) // @param Hour valid values 0-23 // @param Minute valid values 0-60 export getJulianDate(int Year, int Month, int Day, int Hour, int Minute) => y = Year m = Month d = Day h = Hour min = Minute //Adjust if B.C. if y < 0 y := y + 1 //Adjust if JAN or FEB if m == 1 or m == 2 y := y - 1 m := m + 12 //Calculate A & B; ONLY if date is equal or after 1582-Oct-15 float A = math.floor(y/100) //A float B = 2 - A + math.floor(A/4) //B //Added Minute Accuracy ((math.floor(365.25*y)) + (math.floor(30.6001*(m+1))) + d + (0.04166666666666666666666666666667*h) + (0.000694444444444444*min) + 1720994.5 + B) // @function Centuries since Julian Epoch 2000-01-01 // @param date Julian date to conver to Julian centuries // @param epoch_start Julian date of epoch start (e.g. J2000 epoch = 2451545) // @returns Julian date converted to Julian centuries export julianCenturies(float date, float epoch_start) => (date - epoch_start)/36525.0 // @function Calculate Julian centuries since epoch J2000 (2000-01-01) // @param julianDate Julian Date in days // @returns Julian centuries since epoch J2000 (2000-01-01) export julianCenturiesSinceEpochJ2000(float julianDate) => (julianDate - julianEpochJ2000()) / julianCenturyInJulianDays() // ======================================================================================================================== // UTILITY FUNCTIONS // ======================================================================================================================== // @function Specialized arctan function // @param y radians // @param x radians // @returns special arctan of y/x export atan2(float y, float x) => if x > 0 math.atan(y/x) else if x < 0 if y >= 0 math.atan(y/x) + math.pi else math.atan(y/x) - math.pi else if y > 0 math.pi / 2 else if y < 0 1.0 * math.pi / 2 else runtime.error("X and Y cannot both be zero to compute atan2") na //TAKEN FROM: http://www.jgiesen.de/kepler/kepler.html //CREDIT: Juergen Giesen //Used to solve for E // @function Compute eccentricity of the anomaly // @param ec Eccentricity of Orbit // @param m_param Mean Anomaly ? // @param dp Decimal places to round to // @returns Eccentricity of the Anomaly export eccAnom(float ec, float m_param, int dp) => m = m_param // arguments: // ec=eccentricity, m=mean anomaly, // dp=number of decimal places float pi = math.pi float K = pi / 180.0 int maxIter = 30 int i = 0 float delta = math.pow(10,-dp) float E = na float F = na m := m / 360.0 m := 2.0 * pi * (m - math.floor(m)) if ec < 0.8 E := m else E := pi F := E - ec * math.sin(m) - m while math.abs(F) > delta and i < maxIter E := E - F / (1.0 - ec * math.cos(E)) F := E - ec * math.sin(E) - m i := i + 1 E := E / K math.round(E * math.pow(10,dp)) / math.pow(10,dp) // @function Compute planetary ephemeris (longtude relative to Earth or Sun) on a Julian date // @param TGen Julian Date // @param planetElementId All planet orbital elements in an array. This index references a specific planet's elements. // @param planetRatesId All planet orbital rates in an array. This index references a specific planet's rates. // @returns [xGen, yGen, zGen, rGen] X,Y,Z ecliptic rectangular coordinates and R radius from reference body. export planetEphemerisCalc(float TGen, float[] planetElementId, float[] planetRatesId) => float element_a = array.get(planetElementId, 0) float element_e = array.get(planetElementId, 1) float element_i = array.get(planetElementId, 2) float element_L = array.get(planetElementId, 3) float element_w = array.get(planetElementId, 4) float element_N = array.get(planetElementId, 5) float rate_a = array.get(planetRatesId, 0) float rate_e = array.get(planetRatesId, 1) float rate_i = array.get(planetRatesId, 2) float rate_L = array.get(planetRatesId, 3) float rate_w = array.get(planetRatesId, 4) float rate_N = array.get(planetRatesId, 5) //-------------------------------------------------------------------------------------------- //1. //ORBIT SIZE //AU (CONSTANT = DOESN'T CHANGE) aGen = element_a + (rate_a * TGen) //2. //ORBIT SHAPE //ECCENTRICITY (CONSTANT = DOESN'T CHANGE) eGen = element_e + (rate_e * TGen) //-------------------------------------------------------------------------------------------- //3. //ORBIT ORIENTATION //ORBITAL INCLINATION (CONSTANT = DOESN'T CHANGE) iGen = element_i + (rate_i * TGen) iGen := rev360(iGen) // iGen%360 //4. //ORBIT ORIENTATION //LONG OF ASCENDING NODE (CONSTANT = DOESN'T CHANGE) NGen = element_N + (rate_N * TGen) NGen := rev360(NGen) // NGen%360 //5. //ORBIT ORIENTATION //LONGITUDE OF THE PERIHELION wGen = element_w + (rate_w * TGen) wGen := rev360(wGen) // wGen%360 //-------------------------------------------------------------------------------------------- //6. //ORBIT POSITION //MEAN LONGITUDE (DYNAMIC = CHANGES OVER TIME) LGen = element_L + (rate_L * TGen) LGen := rev360(LGen) // LGen%360 //MEAN ANOMALY --> Use this to determine Perihelion (0 degrees = Perihelion of planet) MGen = rev360(LGen - wGen) //ECCENTRIC ANOMALY EGen = eccAnom(eGen, MGen, 6) //ARGUMENT OF TRUE ANOMALY trueAnomalyArgGen = math.sqrt((1+eGen) / (1-eGen)) * (math.tan(math.toradians(EGen)/2)) //TRUE ANOMALY (DYNAMIC = CHANGES OVER TIME) K = math.pi / 180.0 //Radian converter variable float nGen = na if trueAnomalyArgGen < 0 nGen := 2 * (math.atan(trueAnomalyArgGen)/K+180) //ATAN = ARCTAN = INVERSE TAN else nGen := 2 * (math.atan(trueAnomalyArgGen)/K) //-------------------------------------------------------------------------------------------- //CALCULATE RADIUS VECTOR rGen = (aGen * (1 - math.pow(eGen,2)))/(1 + (eGen * (math.cos(math.toradians(nGen))))) //TAKEN FROM: http://www.stargazing.net/kepler/ellipse.html //CREDIT: Keith Burnett //Used to determine Heliocentric Ecliptic Coordinates (this part works!) xGen = rGen * (math.cos(math.toradians(NGen)) * math.cos(math.toradians(nGen+wGen-NGen)) - math.sin(math.toradians(NGen)) * math.sin(math.toradians(nGen+wGen-NGen)) * math.cos(math.toradians(iGen))) yGen = rGen * (math.sin(math.toradians(NGen)) * math.cos(math.toradians(nGen+wGen-NGen)) + math.cos(math.toradians(NGen)) * math.sin(math.toradians(nGen+wGen-NGen)) * math.cos(math.toradians(iGen))) zGen = rGen * (math.sin(math.toradians(nGen+wGen-NGen)) * math.sin(math.toradians(iGen))) //Check rCheck = math.sqrt(math.pow(xGen,2) + math.pow(yGen,2) + math.pow(zGen,2)) [xGen, yGen, zGen, rGen] // @function Calculate right ascension and declination for a planet relative to Earth // @param earthX Earth X ecliptic rectangular coordinate relative to Sun // @param earthY Earth Y ecliptic rectangular coordinate relative to Sun // @param earthZ Earth Z ecliptic rectangular coordinate relative to Sun // @param planetX Planet X ecliptic rectangular coordinate relative to Sun // @param planetY Planet Y ecliptic rectangular coordinate relative to Sun // @param planetZ Planet Z ecliptic rectangular coordinate relative to Sun // @returns [distPlanet, raPlanetDegrees, decPlanet] Planet geocentric orbital radius, geocentric right ascension, and geocentric declination export calculateRightAscensionAndDeclination(float earthX, float earthY, float earthZ, float planetX, float planetY, float planetZ) => //CALCULATE GEOCENTRIC ECLIPTIC COORDINATES //========================================= //TAKEN FROM: http://www.stargazing.net/kepler/ellipse.html#twig06 //CREDIT: Keith Burnett xGeo = planetX - earthX yGeo = planetY - earthY zGeo = planetZ - earthZ //CALCULATE GEOCENTRIC EQUATORIAL COORDINATES //=========================================== //TAKEN FROM: http://www.stargazing.net/kepler/ellipse.html#twig06 //CREDIT: Keith Burnett meanObl = meanObliquityForJ2000() xEq = xGeo //Yq = Y' * cos(ec) - Z' * sin(ec) //NOTE: Hardcoded the earth's obliquity (i.e. axial tilt; angle between orbital plane & equatorial plane) based on what it was on January 1, 2000 (J2000) yEq = (math.cos(math.toradians(meanObl)) * yGeo) - (math.sin(math.toradians(meanObl)) * zGeo ) //Zq = Y' * sin(ec) + Z' * cos(ec) //NOTE: Hardcoded the earth's obliquity (i.e. axial tilt; angle between orbital plane & equatorial plane) based on what it was on January 1, 2000 (J2000) zEq = (math.sin(math.toradians(meanObl)) * yGeo) + (math.cos(math.toradians(meanObl)) * zGeo ) //CALCULATE RIGHT ASCENSION (R.A.) //================================ //TAKEN FROM: http://www.stargazing.net/kepler/ellipse.html#twig06 //CREDIT: Keith Burnett // //Calculate Right Ascension (R.A) --> Horizontal location in sky //360° = 24 hours (15° = 1 hour) // //alpha = math.atan(Yq/Xq) //If Xq is negative then add 180 degrees to alpha //If Xq is positive and Yq is negative then add 360 degrees to alpha float raPlanet = math.todegrees(math.atan(yEq/xEq)) if xEq < 0 raPlanet := raPlanet + 180 else if xEq > 0 and yEq < 0 raPlanet := raPlanet + 360 raPlanetDegrees = raPlanet //Convert right ascension to hours raPlanet := raPlanet / 15.0 //CALCULATE DECLINATION //===================== //TAKEN FROM: http://www.stargazing.net/kepler/ellipse.html#twig06 //CREDIT: Keith Burnett // //Calculate Declination --> Vertical location in sky //delta = arctan( Zq / SQRT(Xq^2 + Yq^2)) decPlanet = math.todegrees( math.atan((zEq / (math.sqrt(math.pow(xEq,2) + math.pow(yEq,2))))) ) //CALCULATE DISTANCE //================== //Calculate Distance distPlanet = math.sqrt( math.pow(xEq,2) + math.pow(yEq,2) + math.pow(zEq,2) ) //CONVERT R.A. FROM DEGREES TO HOURS, MINUTES & SECONDS //===================================================== //Degrees to hours raPlanetH = math.floor(raPlanet) //Degrees to minutes minfloat = (raPlanet - raPlanetH) * 60 raPlanetM = math.floor(minfloat) //Degrees to seconds secfloat = (minfloat - raPlanetM) * 60.0 raPlanetS = math.round(secfloat) //CONVERT DECLINATION FROM DEGREES TO DEGREES, MINUTES & SECONDS //============================================================== //Make value positive for correct calculation negative = false if decPlanet < 0 decPlanet := math.abs(decPlanet) negative := true //Degrees to hours int decPlanetH = math.floor(decPlanet) //Degrees to minutes minfloat := (decPlanet - decPlanetH) * 60 decPlanetM = math.floor(minfloat) //Degrees to seconds secfloat := (minfloat - decPlanetM) * 60 decPlanetS = math.round(secfloat) //Correct degrees back to negative/positive if negative decPlanetH := -1 * decPlanetH decPlanet := -1 * decPlanet [distPlanet, raPlanetDegrees, decPlanet] // ======================================================================================================================== // HELIO EPHEMERIS // ======================================================================================================================== // @function Compute Mercury heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Mercury heliocentric longitude on date export mercuryHelio(float T) => [xMercury, yMercury, zMercury, rMercury] = planetEphemerisCalc(T, mercuryElements(), mercuryRates()) float mercuryHelio = na if yMercury != 0 and xMercury != 0 mercuryHelio := rev360(math.todegrees(atan2(yMercury, xMercury))) mercuryHelio // @function Compute Venus heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Venus heliocentric longitude on date export venusHelio(float T) => [xVenus, yVenus, zVenus, rVenus] = planetEphemerisCalc(T, venusElements(), venusRates()) float venusHelio = na if yVenus != 0 and xVenus != 0 venusHelio := rev360(math.todegrees(atan2(yVenus, xVenus))) venusHelio // @function Compute Earth heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Earth heliocentric longitude on date export earthHelio(float T) => [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) float earthHelio = na if yEarth != 0 and xEarth != 0 earthHelio := rev360(math.todegrees(atan2(yEarth, xEarth))) earthHelio // @function Compute Mars heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Mars heliocentric longitude on date export marsHelio(float T) => [xMars, yMars, zMars, rMars] = planetEphemerisCalc(T, marsElements(), marsRates()) float marsHelio = na if yMars != 0 and xMars != 0 marsHelio := rev360(math.todegrees(atan2(yMars, xMars))) marsHelio // @function Compute Jupiter heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Jupiter heliocentric longitude on date export jupiterHelio(float T) => [xJupiter, yJupiter, zJupiter, rJupiter] = planetEphemerisCalc(T, jupiterElements(), jupiterRates()) float jupiterHelio = na if yJupiter != 0 and xJupiter != 0 jupiterHelio := rev360(math.todegrees(atan2(yJupiter, xJupiter))) jupiterHelio // @function Compute Saturn heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Saturn heliocentric longitude on date export saturnHelio(float T) => [xSaturn, ySaturn, zSaturn, rSaturn] = planetEphemerisCalc(T, saturnElements(), saturnRates()) float saturnHelio = na if ySaturn != 0 and xSaturn != 0 saturnHelio := rev360(math.todegrees(atan2(ySaturn, xSaturn))) saturnHelio // @function Compute Neptune heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Neptune heliocentric longitude on date export neptuneHelio(float T) => [xNeptune, yNeptune, zNeptune, rNeptune] = planetEphemerisCalc(T, neptuneElements(), neptuneRates()) float neptuneHelio = na if yNeptune != 0 and xNeptune != 0 neptuneHelio := rev360(math.todegrees(atan2(yNeptune, xNeptune))) neptuneHelio // @function Compute Uranus heliocentric longitude on date // @param Julian Centuries since epoch J2000 (2000-01-01) // @returns Uranus heliocentric longitude on date export uranusHelio(float T) => [xUranus, yUranus, zUranus, rUranus] = planetEphemerisCalc(T, uranusElements(), uranusRates()) float uranusHelio = na if yUranus != 0 and xUranus != 0 uranusHelio := rev360(math.todegrees(atan2(yUranus, xUranus))) uranusHelio // ======================================================================================================================== // GEO EPHEMERIS // ======================================================================================================================== export sunGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Earth Celestial Coordinates [distEarth, earthGeo, decEarth] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xEarth, yEarth, zEarth) // Sun Geocentric Longitude sunGeo = rev360(earthGeo + 180) sunGeo export mercuryGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Mercury Heliocentric Ecliptic Coordinates [xMercury, yMercury, zMercury, rMercury] = planetEphemerisCalc(T, mercuryElements(), mercuryRates()) // Mercury Celestial Coordinates [distMercury, mercuryGeo, decMercury] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xMercury, yMercury, zMercury) mercuryGeo export venusGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Venus Heliocentric Ecliptic Coordinates [xVenus, yVenus, zVenus, rVenus] = planetEphemerisCalc(T, venusElements(), venusRates()) // Venus Celestial Coordinates [distVenus, venusGeo, decVenus] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xVenus, yVenus, zVenus) venusGeo export marsGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Mars Heliocentric Ecliptic Coordinates [xMars, yMars, zMars, rMars] = planetEphemerisCalc(T, marsElements(), marsRates()) // Mars Celestial Coordinates [distMars, marsGeo, decMars] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xMars, yMars, zMars) marsGeo export jupiterGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Jupiter Heliocentric Ecliptic Coordinates [xJupiter, yJupiter, zJupiter, rJupiter] = planetEphemerisCalc(T, jupiterElements(), jupiterRates()) // Jupiter Celestial Coordinates [distJupiter, jupiterGeo, decJupiter] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xJupiter, yJupiter, zJupiter) jupiterGeo export saturnGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Saturn Heliocentric Ecliptic Coordinates [xSaturn, ySaturn, zSaturn, rSaturn] = planetEphemerisCalc(T, saturnElements(), saturnRates()) // Saturn Celestial Coordinates [distSaturn, saturnGeo, decSaturn] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xSaturn, ySaturn, zSaturn) saturnGeo export neptuneGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Neptune Heliocentric Ecliptic Coordinates [xNeptune, yNeptune, zNeptune, rNeptune] = planetEphemerisCalc(T, neptuneElements(), neptuneRates()) // Neptune Celestial Coordinates [distNeptune, neptuneGeo, decNeptune] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xNeptune, yNeptune, zNeptune) neptuneGeo export uranusGeo(float T) => // Get Earth Heliocentric Ecliptic Coordinates // Need to calculate these values first, as you need them for all following calculations [xEarth, yEarth, zEarth, rEarth] = planetEphemerisCalc(T, earthElements(), earthRates()) // Uranus Heliocentric Ecliptic Coordinates [xUranus, yUranus, zUranus, rUranus] = planetEphemerisCalc(T, uranusElements(), uranusRates()) // Uranus Celestial Coordinates [distUranus, uranusGeo, decUranus] = calculateRightAscensionAndDeclination(xEarth, yEarth, zEarth, xUranus, yUranus, zUranus) uranusGeo // ======================================================================================================================== // MOON EPHEMERIS // ======================================================================================================================== moonSumL() => moonSumL = matrix.new<float>() matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,1,0,6288774)) //1 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,-1,0,1274027)) //2 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,0,0,658314)) //3 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,2,0,213618)) //4 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,1,0,0,-185116)) //5 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,0,2,-114332)) //6 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,-2,0,58793)) //7 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-1,-1,0,57066)) //8 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,1,0,53322)) //9 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-1,0,0,45758))//10 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,1,-1,0,-40923))//11 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(1,0,0,0,-34720))//12 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,1,1,0,-30383))//13 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,0,-2,15327))//14 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,1,2,-12528))//15 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,1,-2,10980))//16 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,0,-1,0,10675))//17 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,3,0,10034))//18 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,0,-2,0,8548))//19 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,1,-1,0,-7888))//20 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,1,0,0,-6766))//21 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(1,0,-1,0,-5163))//22 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(1,1,0,0,4987))//23 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-1,1,0,4036))//24 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,2,0,3994))//25 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,0,0,0,3861))//26 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,-3,0,3665))//27 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,1,-2,0,-2689))//28 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,-1,2,-2602))//29 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-1,-2,0,2390))//30 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(1,0,1,0,-2348))//31 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-2,0,0,2236))//32 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,1,2,0,-2120))//33 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,2,0,0,-2069))//34 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-2,-1,0,2048))//35 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,1,-2,-1773))//36 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,0,2,-1595))//37 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,-1,-1,0,1215))//38 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,2,2,-1110))//39 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(3,0,-1,0,-892))//40 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,1,1,0,-810))//41 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,-1,-2,0,759))//42 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,2,-1,0,-713))//43 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,2,-1,0,-700))//44 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,1,-2,0,691))//45 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-1,0,-2,596))//46 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,0,1,0,549))//47 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,4,0,537))//48 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,-1,0,0,520))//49 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(1,0,-2,0,-487))//50 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,1,0,-2,-399))//51 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,0,2,-2,-381))//52 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(1,1,1,0,351))//53 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(3,0,-2,0,-340))//54 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(4,0,-3,0,330))//55 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,-1,2,0,327))//56 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(0,2,1,0,-323))//57 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(1,1,-1,0,299))//58 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,3,0,294))//59 matrix.add_row(moonSumL, matrix.rows(moonSumL), array.from(2,0,-1,-2,0))//60 moonSumL moonSumB() => moonSumB = matrix.new<float>() matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,0,1,5128122)) //1 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,1,1,280602)) //2 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,1,-1,277693)) //3 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,0,-1,173237)) //4 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,-1,1,55413)) //5 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,-1,-1,46271)) //6 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,0,1,32573)) //7 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,2,1,17198)) //8 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,1,-1,9266)) //9 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,2,-1,8822)) //10 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-1,0,-1,8216)) //11 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,-2,-1,4324)) //12 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,1,1,4200)) //13 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,1,0,-1,-3359)) //14 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-1,-1,1,2463)) //15 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-1,0,1,2211)) //16 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-1,-1,-1,2065)) //17 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,-1,-1,-1870)) //18 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,0,-1,-1,1828)) //19 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,0,1,-1794)) //20 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,0,3,-1749)) //21 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,-1,1,-1565)) //22 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(1,0,0,1,-1491)) //23 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,1,1,-1475)) //24 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,1,-1,-1410)) //25 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,0,-1,-1344)) //26 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(1,0,0,-1,-1335)) //27 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,3,1,1107)) //28 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,0,0,-1,1021)) //29 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,0,-1,1,833)) //30 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,1,-3,777)) //31 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,0,-2,1,671)) //32 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,0,-3,607)) //33 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,2,-1,596)) //34 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-1,1,-1,491)) //35 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,-2,1,-451)) //36 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,3,-1,439)) //37 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,2,1,422)) //38 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,0,-3,-1,421)) //39 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,1,-1,1,-366)) //40 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,1,0,1,-351)) //41 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,0,0,1,331)) //42 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-1,1,1,315)) //43 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-2,0,-1,302)) //44 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,0,1,3,-283)) //45 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,1,1,-1,-229)) //46 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(1,1,0,-1,223)) //47 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(1,1,0,1,223)) //48 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,-2,-1,-220)) //49 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,1,-1,-1,-220)) //50 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(1,0,1,1,-185)) //51 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-1,-2,-1,181)) //52 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(0,1,2,1,-177)) //53 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,0,-2,-1,176)) //54 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,-1,-1,-1,166)) //55 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(1,0,1,-1,-164)) //56 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,0,1,-1,132)) //57 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(1,0,-1,-1,-119)) //58 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(4,-1,0,-1,115)) //59 matrix.add_row(moonSumB, matrix.rows(moonSumB), array.from(2,-2,0,1,10)) //60 moonSumB moonSumNutation() => sumNutation = matrix.new<float>() matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,0,0,1,-171996,-174.2,92025,8.9)) //1 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,0,2,2,-13187,-1.6,5736,-3.1)) //2 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,0,2,2,-2274,-0.2,977,-0.5)) //3 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,0,0,2,2062,0.2,-895,0.5)) //4 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,1,0,0,0,1426,-3.4,54,-0.1)) //5 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,1,0,0,712,0.1,-7,na)) //6 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,1,0,2,2,-517,1.2,224,-0.6)) //7 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,0,2,1,-386,-0.4,200,na)) //8 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,1,2,2,-301,na,129,-0.1)) //9 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,-1,0,2,2,217,-0.5,-95,0.3)) //10 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,1,0,0,-158,na,na,na)) //11 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,0,2,1,129,0.1,-70,na)) //12 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,-1,2,2,123,na,-53,na)) //13 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,0,0,0,63,na,na,na)) //14 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,1,0,1,63,0.1,-33,na)) //15 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,-1,2,2,-59,na,26,na)) //16 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,-1,0,1,-58,-0.1,32,na)) //17 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,1,2,1,-51,na,27,na)) //18 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,2,0,0,48,na,na,na)) //19 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,-2,2,1,46,na,-24,na)) //20 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,0,2,2,-38,na,16,na)) //21 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,2,2,2,-31,na,13,na)) //22 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,2,0,0,29,na,na,na)) //23 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,1,2,2,29,na,-12,na)) //24 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,0,2,0,26,na,na,na)) //25 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,0,2,0,-22,na,na,na)) //26 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,-1,2,1,21,na,-10,na)) //27 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,2,0,0,0,17,-0.1,na,na)) //28 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,-1,0,1,16,na,-8,na)) //29 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,2,0,2,2,-16,0.1,7,na)) //30 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,1,0,0,1,-15,na,9,na)) //31 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,1,0,1,-13,na,7,na)) //32 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,-1,0,0,1,-12,na,6,na)) //33 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,2,-2,0,11,na,na,na)) //34 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,-1,2,1,-10,na,5,na)) //35 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,1,2,2,-8,na,3,na)) //36 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,1,0,2,2,7,na,-3,na)) //37 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,1,1,0,0,-7,na,na,na)) //38 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,-1,0,2,2,-7,na,3,na)) //39 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,0,2,1,-7,na,3,na)) //40 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,1,0,0,6,na,na,na)) //41 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,2,2,2,6,na,-3,na)) //42 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,1,2,1,6,na,-3,na)) //43 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,-2,0,1,-6,na,3,na)) //44 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,0,0,0,1,-6,na,3,na)) //45 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,-1,1,0,0,5,na,na,na)) //46 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,-1,0,2,1,-5,na,3,na)) //47 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,0,0,1,-5,na,3,na)) //48 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,2,2,1,-5,na,3,na)) //49 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,0,2,0,1,4,na,na,na)) //50 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,1,0,2,1,4,na,na,na)) //51 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,1,-2,0,4,na,na,na)) //52 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-1,0,1,0,0,-4,na,na,na)) //53 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-2,1,0,0,0,-4,na,na,na)) //54 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(1,0,0,0,0,-4,na,na,na)) //55 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,1,2,0,3,na,na,na)) //56 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,-2,2,2,-3,na,na,na)) //57 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(-1,-1,1,0,0,-3,na,na,na)) //58 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,1,1,0,0,-3,na,na,na)) //59 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,-1,1,2,2,-3,na,na,na)) //60 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,-1,-1,2,2,-3,na,na,na)) //61 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(0,0,3,2,2,-3,na,na,na)) //62 matrix.add_row(sumNutation, matrix.rows(sumNutation), array.from(2,-1,0,2,2,-3,na,na,na)) //63 sumNutation decimalToHMS(float decimal) => hours = math.round(decimal) minutes = (decimal - math.floor(decimal)) * 60 seconds = (minutes - math.floor(minutes)) * 60 minutes := math.round(minutes) if minutes < 0 minutes := math.abs(minutes) if seconds < 0 seconds := math.abs(seconds) [hours, minutes, seconds] export moonGeo(float T_JD) => // Moon mean longitude L = rev360( 218.3164477 + (481267.88123421 * T_JD) - (0.0015786 * math.pow(T_JD,2)) + (math.pow(T_JD,3) / 538841) - (math.pow(T_JD,4) / 65194000) ) // Moon mean elongation D = rev360( 297.8501921 + (445267.1114034 * T_JD) - (0.0018819 * math.pow(T_JD,2)) + (math.pow(T_JD,3) / 545868) - (math.pow(T_JD,4) / 113065000) ) // Sun mean anomaly M_sun = rev360( 357.5291092 + (35999.0502909 * T_JD) - (0.0001536 * math.pow(T_JD,2)) + (math.pow(T_JD,3) / 24490000) ) // Moon mean anomaly M_moon = rev360( 134.9633964 + (477198.8675055 * T_JD) + (0.0087414 * math.pow(T_JD,2)) + (math.pow(T_JD,3) / 69699) - (math.pow(T_JD,4) / 14712000) ) // Moon argument of latitude F = rev360( 93.2720950 + (483202.0175233 * T_JD) - (0.0036539 * math.pow(T_JD,2)) - (math.pow(T_JD,3) / 3526000) + (math.pow(T_JD,4) / 863310000) ) // Moon longitude of ascending node omega = rev360 ( 125.04452 - (1934.136261 * T_JD) + (0.0020708 * math.pow(T_JD,2)) + (math.pow(T_JD,3) / 450000) ) // Eccentricity due to Venus A1 = rev360( 119.75 + (131.849 + T_JD) ) // Eccentricity due to Jupiter A2 = rev360( 53.09 + (479264.29 * T_JD) ) // ? A3 = rev360( 313.45 + (481266.484 * T_JD) ) // Eccentricity of orbit E = rev360( 1 - (0.002516 * T_JD) - (0.0000074 * math.pow(T_JD,2)) ) // RIGHT ASCENSION // Calculate sum of sigma l float sumL = 0 moonSumL = moonSumL() for int i = 0 to matrix.rows(moonSumL) - 1 // [0] = D, Moon mean elongation // [1] = M, Sun mean anomaly // [2] = M_prime, Moon mean anomaly // [3] = F, Moon arugment of latitude // [4] = Coefficient terms = matrix.row(moonSumL, i) termD = array.get(terms, 0) * D termMSun = array.get(terms, 1) * M_sun termMMoon = array.get(terms, 2) * M_moon termF = array.get(terms, 3) * F term = termD + termMSun + termMMoon + termF term := math.sin(math.toradians(term)) // term M depends on eccentricity of Earth's orbit around Sun if array.get(terms, 1) != 0 // in case of last term, the coefficient does not exist, so exlude it // multiply sum of fundamental arugs by coefficient (include E) if array.get(terms, 4) != 0 term := array.get(terms, 4) * E * term else term := E * term else if array.get(terms, 4) != 0 // multiply sum of fundamental arugs by coefficient (include E) term := array.get(terms, 4) * term sumL := sumL + term sumL := sumL + (3958 + math.sin(math.toradians(A1))) sumL := sumL + (1962 + math.sin(math.toradians(L - F))) sumL := sumL + (318 + math.sin(math.toradians(A2))) // DECLINATION float sumB = 0 moonSumB = moonSumB() for int i = 0 to matrix.rows(moonSumB) - 1 terms = matrix.row(moonSumB, i) termD = array.get(terms, 0) * D termMSun = array.get(terms, 1) * M_sun termMMoon = array.get(terms, 2) * M_moon termF = array.get(terms, 3) * F term = termD + termMSun + termMMoon + termF term := math.sin(math.toradians(term)) if array.get(terms, 1) != 0 if array.get(terms, 4) != 0 term := array.get(terms, 4) * E * term else term := E * term else if array.get(terms, 4) != 0 term := array.get(terms, 4) * term sumB := sumB + term sumB := sumB - (2235 * math.sin(math.toradians(L))) sumB := sumB + (382 * math.sin(math.toradians(A3))) sumB := sumB + (175 * math.sin(math.toradians(A1 - F))) sumB := sumB + (175 * math.sin(math.toradians(A1 + F))) sumB := sumB + (127 * math.sin(math.toradians(L - M_moon))) sumB := sumB - (115 * math.sin(math.toradians(L + M_moon))) moonRADeg = L + (sumL / 1000000) moonDecDeg = sumB / 1000000 // Mean longitude of ascending node of Moon's mean orbit on the ecliptic MLAN = rev360( 125.04452 - (1934.136261 * T_JD) + (0.0020709 * math.pow(T_JD,2)) + (math.pow(T_JD,3) / 450000) ) float sumNutation = 0 float sumObl = 0 moonSumNutation = moonSumNutation() for int i = 0 to matrix.rows(moonSumNutation) - 1 //[0] = D (Moon Mean Elongation) //[1] = M (Sun Mean Anomaly) //[2] = M' (Moon Mean Anomaly) //[3] = F (Moon Argument of latitude) //[4] = Ω (Moon Mean Longitude of the ascending node) //[5] = Coefficient I //[6] = Coefficient II //[7] = e coefficient I //[8] = e coefficient II terms = matrix.row(moonSumNutation, i) termD = array.get(terms, 0) * D termMSun = array.get(terms, 1) * M_sun termMMoon = array.get(terms, 2) * M_moon termF = array.get(terms, 3) * F termPhi = array.get(terms, 4) * MLAN term = termD + termMSun + termMMoon + termF + termPhi termSin = math.sin(math.toradians(term)) termCos = math.cos(math.toradians(term)) if not na(array.get(terms, 6)) termSin := (array.get(terms, 5) + (array.get(terms, 6) * T_JD)) * termSin else termSin := array.get(terms, 5) * termSin if not na(array.get(terms, 7)) if not na(array.get(terms, 8)) termCos := (array.get(terms, 7) + array.get(terms, 8) * T_JD) * termCos else termCos := array.get(terms, 7) * termCos sumNutation := sumNutation + termSin sumObl := sumObl + termCos sumNutation := sumNutation * 0.0001 / 3600 sumObl := sumObl * 0.0001 / 3600 appMoonRADeg = moonRADeg + sumNutation // Mean Obliquitiy of Ecliptic & True Obliquity of Ecliptic float earthObl0 = 23.43929 - (0.01300417 * T_JD) - (0.0000001638889 * math.pow(T_JD,2)) - (0.0000005036111 * math.pow(T_JD,3)) // E0 float earthObl = earthObl0 + sumObl // true obliquity of ecliptic // earthObl0 := decimalToHMS(earthObl0) // convert decimal to H,M,S findY = (math.sin(math.toradians(appMoonRADeg)) * math.cos(math.toradians(earthObl))) - (math.tan(math.toradians(moonDecDeg)) * math.sin(math.toradians(earthObl))) findX = math.cos(math.toradians(appMoonRADeg)) findAtan = math.todegrees(math.atan(findY/findX)) // remove inverse tan ambiguity if findX < 0 findAtan := findAtan + 180 else if findX > 0 and findY < 0 findAtan := findAtan + 360 // calculate right ascension -> horizontal location in sky // convert Moon ecliptic longitude form degrees to H,M,S moonRADeg := findAtan moonRADeg // ======================================================================================================================== // COMPOSITE SINE WAVE // ======================================================================================================================== // @function Mercury orbital period in Earth days // @returns 87.9691 export mercuryOrbitalPeriod() => 87.9691 // @function Venus orbital period in Earth days // @returns 224.701 export venusOrbitalPeriod() => 224.701 // @function Earth orbital period in Earth days // @returns 365.256363004 export earthOrbitalPeriod() => 365.256363004 // @function Mars orbital period in Earth days // @returns 686.980 export marsOrbitalPeriod() => 686.980 // @function Jupiter orbital period in Earth days // @returns 4332.59 export jupiterOrbitalPeriod() => 4332.59 // @function Saturn orbital period in Earth days // @returns 10759.22 export saturnOrbitalPeriod() => 10759.22 // @function Uranus orbital period in Earth days // @returns 30688.5 export uranusOrbitalPeriod() => 30688.5 // @function Neptune orbital period in Earth days // @returns 60195.0 export neptuneOrbitalPeriod() => 60195.0 // @returns Jupiter-Saturn composite sine wave period (period between conjunct dates) in Julian days export jupiterSaturnCompositePeriod() => getJulianDate(2020, 10, 5, 0, 0) - getJulianDate(1961, 6, 23, 0, 0) // @returns Jupiter-Neptune composite sine wave period (period between conjunct dates) in Julian days export jupiterNeptuneCompositePeriod() => (getJulianDate(2020, 3, 23, 0, 0) - getJulianDate(1901, 8, 2, 0, 0)) / 10 // @returns Jupiter-Uranus composite sine wave period (period between conjunct dates) in Julian days export jupiterUranusCompositePeriod() => (getJulianDate(2020, 5, 11, 0, 0) - getJulianDate(1937, 4, 20, 0, 0)) / 7 // @returns Saturn-Neptune composite sine wave period (period between conjunct dates) in Julian days export saturnNeptuneCompositePeriod() => (getJulianDate(1996, 6, 7, 0, 0) - getJulianDate(1908, 1, 15, 0, 0)) / 3 // @returns Saturn-Uranus composite sine wave period (period between conjunct dates) in Julian days export saturnUranusCompositePeriod() => // Uses 1.5 period as the period because Bradley Cowen uses a 45 year cycle in his book... Why is this? // SU_h = getJulianDate(2008, 12, 4, 0, 0) // SU_g = getJulianDate(1997, 5, 6, 0, 0) // SU_f = getJulianDate(1981, 11, 23, 0, 0) // SU_e = getJulianDate(1965, 6, 28, 0, 0) // SU_d = getJulianDate(1952, 6, 2, 0, 0) // SU_c = getJulianDate(1938, 3, 14, 0, 0) // SU_b = getJulianDate(1920, 8, 26, 0, 0) // SU_a = getJulianDate(1908, 8, 31, 0, 0) // SUPeriod = ((SU_h-SU_e) + (SU_g-SU_d) + (SU_f-SU_c) + (SU_e-SU_b) + (SU_d-SU_a)) / 5 SU_g = getJulianDate(1997, 5, 6, 0, 0) SU_e = getJulianDate(1965, 6, 28, 0, 0) SU_c = getJulianDate(1938, 3, 14, 0, 0) SU_a = getJulianDate(1908, 8, 31, 0, 0) SUPeriod_tops = (SU_g - SU_a) / 3 SU_h = getJulianDate(2008, 12, 4, 0, 0) SU_f = getJulianDate(1981, 11, 23, 0, 0) SU_d = getJulianDate(1952, 6, 2, 0, 0) SU_b = getJulianDate(1920, 8, 26, 0, 0) SUPeriod_bottoms = (SU_h - SU_b) / 3 SUPeriod = (SUPeriod_tops + SUPeriod_bottoms) / 2 // @function Convert heliocentric longitude of planet into a sine wave // @param julianDate Julian Date in Julian centuries // @param planetOrbitalPeriod Orbital period of planet in Earth days // @param planetHelio Heliocentric longitude of planet in degrees // @returns Sine of heliocentric longitude on a Julian date export planetSineWave(float julianDateInCenturies, float planetOrbitalPeriod, float planetHelio) => math.sin(( julianDateInCenturies * julianCenturyInJulianDays() / planetOrbitalPeriod ) * math.pi * 2 - math.toradians(planetHelio))
Trade
https://www.tradingview.com/script/GOsuWMni-Trade/
DevLucem
https://www.tradingview.com/u/DevLucem/
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/ // © DevLucem // ( ( // )\ ) )\ ) // (()/( ( ) (()/( ( ( ) // /(_)) ))\ /(( /(_)) ))\ ( ))\ ( // (_))_ /((_)(_))\ (_)) /((_) )\ /((_) )\ ' // | \ (_)) _)((_) | | (_))( ((_)(_)) _((_)) // | |) |/ -_) \ V / | |__| || |/ _| / -_)| ' \() // |___/ \___| \_/ |____|\_,_|\__| \___||_|_|_| //@version=5 // @description A Trade Tracking Library library("Trade", overlay = true) // @function Signal Conditions // @param conditions: Array of sequential conditions to be met for a signal // @param reset: Condition for when to restart scanning the conditions // @returns Boolean: True when all the conditions have occured export method signal(array<bool> conditions, bool reset=false) => var s = 0, signal = array.size(conditions) if reset s := 0 if s==signal s:= 0 for i=signal-1 to 0 by 1 if s==i and array.get(conditions, i) s+= 1 s==signal // @Type Trade holds Parameters export type Trade float stoploss float takeprofit float entry = close active = false bool sl_hit = false bool tp_hit = false open = time // @function Update Trade Parameters // @param this: Trade Object to be updated // @param stoploss: // @param takeprofit: // @param entry: Optional price series for entry // @returns nothing export method update(Trade this, float stoploss = na, float takeprofit = na, float entry = close) => if not na(stoploss) this.stoploss := stoploss if not na(takeprofit) this.takeprofit := takeprofit if not na(entry) this.entry := entry // @function Clear Trade Parameters // @param this: Trade Object to be cleared // @returns nothing export method clear(Trade this) => this.entry := na, this.stoploss := na, this.takeprofit := na, this.active := false // @function Track Trade Parameters // @param this: Trade Object to be tracked // @param _high: Optional price series for high value // @param _low: Optional price series for low value // @returns nothing export method track(Trade this, float _high=high, float _low=low) => this.active := this.active or this.entry == close or (not na(this.entry[1]) and _low <= this.entry and _high >= this.entry ) this.sl_hit := this.active and not na(this.entry[1]) and (this.stoploss < this.takeprofit or this.stoploss < this.entry? _low <= this.stoploss: _high >= this.stoploss) this.tp_hit := this.active and not na(this.entry[1]) and (this.stoploss < this.takeprofit or this.takeprofit > this.entry? _high >= this.takeprofit: _low <= this.takeprofit) if this.sl_hit or this.tp_hit this.clear() // @function New Trade with tracking // @param stoploss: // @param takeprofit: // @param entry: Optional price series for trade entry price // @param _high: Optional price series for high value // @param _low: Optional price series for low value // @param condition: When to update trade parameters // @param update: Update trade parameters if condition is met again // @returns a Trade with targets and updates if stoploss or takeprofit is hit export new(float stoploss, float takeprofit, float entry=close, float _high=high, float _low=low, bool condition=true, bool update=false) => var trade = Trade.new(na, na, na) if condition and (na(trade.entry) or not trade.active or update) trade.update(stoploss, takeprofit, entry) trade.track(_high, _low) trade // @function New Empty Trade // @returns an empty trade export new() => Trade.new(na, na, na) // Sample Usage // ** // Enter a buy trade when RSI // crosses below 70 // then crosses above 80 // before it crosses 40 // // Note: If RSI crosses 40 before 80, No trade will be entered rsi = ta.rsi(close, 21) // Conditions to be met buyConditions = array.new_bool() buyConditions.push(ta.crossunder(rsi, 70)) // buyConditions.push(ta.crossover(rsi, 80)) // // Visual Conditions // bgcolor(ta.crossunder(rsi, 70)? color.rgb(76, 144, 175, 61): na, title="Crossing Below 70") // bgcolor(ta.crossover(rsi, 80)? color.rgb(76, 175, 79, 29): na, title="Crossing Above 80") // bgcolor(ta.crossover(rsi, 40)? color.rgb(175, 76, 76, 29): na, title="Crossing Below 40") // Condition that should not happen buy = signal(buyConditions, ta.crossunder(rsi, 40)) trade = new(close-(100*syminfo.mintick), close +(200*syminfo.mintick), high, condition=buy) plotshape(buy, "Buy", shape.labelup, location.belowbar, color.lime, 0, "BUY", color.black) plot(trade.entry, "Entry", style=plot.style_circles, linewidth=4, color=color.aqua) plot(trade.stoploss, "SL", style=plot.style_circles, linewidth=4, color=color.red) plot(trade.takeprofit, "TP", style=plot.style_circles, linewidth=4, color=color.lime) bgcolor(trade.active? color.rgb(76, 175, 79, 70): na, title="Show When Trade Active") // ********** // If you wish to use the script in conditional statements, // Start the trade with empty parameters // And use track, update or clear to make changes. // © DevLucem // ( ( // )\ ) )\ ) // (()/( ( ) (()/( ( ( ) // /(_)) ))\ /(( /(_)) ))\ ( ))\ ( // (_))_ /((_)(_))\ (_)) /((_) )\ /((_) )\ ' // | \ (_)) _)((_) | | (_))( ((_)(_)) _((_)) // | |) |/ -_) \ V / | |__| || |/ _| / -_)| ' \() // |___/ \___| \_/ |____|\_,_|\__| \___||_|_|_|
Webby's Quick & Grateful Dead RS
https://www.tradingview.com/script/qCW9Jwrv-Webby-s-Quick-Grateful-Dead-RS/
Amphibiantrading
https://www.tradingview.com/u/Amphibiantrading/
186
study
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/ // © Amphibiantrading //@version=5 indicator("Webby's Quick & Grateful Dead RS", overlay = true, shorttitle = 'QGDRS') // inputs var g1 = 'RS Line Options' index = input.symbol(title='Index to Compare', defval='SPX', group = g1) lineCol = input.color(color.blue, 'RS Line Color', group = g1) rsWidth = input.int(title='RS Line Width', defval=2, minval=1, maxval=5, group = g1) var g2 = 'Moving Average Options' ma1Len = input.int(8, 'Quick Moving Average', minval = 3, maxval = 50, step = 1, group = g2, inline = '2') ma2Len = input.int(21, 'Slow Moving Average', minval = 3, maxval = 200, step = 1, group = g2, inline = '3') ma1Color = input.color(color.red, ' ', inline ='2', group = g2) ma2Color = input.color(color.yellow, ' ', inline ='3', group = g2) ma1Type = input.string('SMA', ' ', options = ['EMA', 'SMA'], inline = '2', group = g2) ma2Type = input.string('SMA', ' ', options = ['EMA', 'SMA'], inline = '3', group = g2) maWidth = input.int(title='MA Line Width', defval=1, minval=1, maxval=5, inline = '4', group = g2) var g3 = 'Display Settings' multi = input.int(title='Vertical offset of RS Line', defval=15, minval=1, maxval=500, step=1, group = g3) qbCol = input.color(color.new(color.fuchsia,70), 'Quick Break Color', group = g3) qsCol = input.color(color.new(color.orange,70), 'Quicksand Color', group = g3) gdbCol = input.color(color.new(color.maroon,70), 'Grateful Dead Cross Color', group = g3) //variables var qsLev = 0.0 var qsBool = false //calculations spx = request.security(index, timeframe.period, close) rs = close / spx * 100 ma1 = ma1Type == 'EMA' ? ta.ema(rs,ma1Len) : ta.sma(rs, ma1Len) ma2 = ma2Type == 'EMA' ? ta.ema(rs,ma2Len) : ta.sma(rs, ma2Len) // conditions quickBreak = ta.crossunder(rs, ma1) quickSand = rs < ma1 and rs < qsLev and not qsBool gdb = ta.crossunder(rs, ma2) reset = ta.crossover(rs, ma1) if quickBreak label.new(bar_index, ma1 * multi, ' ', style = label.style_circle, color = qbCol, size = size.tiny) alert('Quick Break - RS Line Crossing Under Fast MA', alert.freq_once_per_bar_close) qsLev := rs if quickSand label.new(bar_index, rs * multi, ' ', style = label.style_circle, color = qsCol, size = size.tiny) alert('Quicksand - RS Line Moving Lower than Quick Break Level', alert.freq_once_per_bar_close) qsBool := true if gdb label.new(bar_index, ma2 * multi, ' ', style = label.style_circle, color = gdbCol, size = size.tiny) alert('Grateful Dead Break - RS Line Crossing Under Slow MA', alert.freq_once_per_bar_close) if reset qsLev := na qsBool := false plot(rs * multi, 'RS', lineCol, rsWidth) plot(ma1 * multi, 'Fast MA', ma1Color, maWidth) plot(ma2 * multi, 'Slow MA', ma2Color, maWidth)
IPDA Standard Deviations [DexterLab x TFO x toodegrees]
https://www.tradingview.com/script/dz03uwWw-IPDA-Standard-Deviations-DexterLab-x-TFO-x-toodegrees/
toodegrees
https://www.tradingview.com/u/toodegrees/
749
study
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/ // © toodegrees, tradeforopp //@version=5 indicator( "IPDA Standard Deviations [DexterLab x TFO x toodegrees]" , shorttitle= "IPDA Stdev [DexterLab x TFO x toodegrees]" , overlay=true , max_bars_back=500 , max_boxes_count=500 , max_labels_count=500 , max_lines_count=500) //#region[User Inputs] dvs = input.text_area("0\n1\n-1\n-1.5\n-2\n-2.5\n-4", title="Insert the Deviations you want to plot, one per line:") label_size = input.string("Small" , title="Label Size" , options = ['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], inline = "lbl") lbl = input.bool(false , title="Hide Labels?", inline="lbl") MLB = input.bool(true , title="Monthly" , group="Fractal IPDA Lookback", inline="M"), lMTF = input.timeframe("D" , title="", group="Fractal IPDA Lookback", inline="M"), hMTF = input.timeframe("D" , title="", group="Fractal IPDA Lookback", inline="M") WLB = input.bool(true , title="Weekly " , group="Fractal IPDA Lookback", inline="W"), lWTF = input.timeframe("240", title="", group="Fractal IPDA Lookback", inline="W"), hWTF = input.timeframe("480", title="", group="Fractal IPDA Lookback", inline="W") DLB = input.bool(true , title="Daily     " , group="Fractal IPDA Lookback", inline="D"), lDTF = input.timeframe("15" , title="", group="Fractal IPDA Lookback", inline="D"), hDTF = input.timeframe("60" , title="", group="Fractal IPDA Lookback", inline="D") ILB = input.bool(true , title="Intraday" , group="Fractal IPDA Lookback", inline="I"), lITF = input.timeframe("1" , title="", group="Fractal IPDA Lookback", inline="I"), hITF = input.timeframe("5" , title="", group="Fractal IPDA Lookback", inline="I") remove = input.bool(false, title="Remove Deviations Once Invalidated?", group="Standard Deviations", tooltip="Once the '1' anchor price line is traded above/below the Deviation will disappear.") tw3_up = input.bool(true, title="TW3 Up     ", group="Standard Deviations", inline="UP"), tw2_up = input.bool(true, title="TW2 Up    ", group="Standard Deviations", inline="UP"), tw1_up = input.bool(true , title="TW1 Up" , group="Standard Deviations", inline="UP") tw3_dw = input.bool(true, title="TW3 Down" , group="Standard Deviations", inline="DW"), tw2_dw = input.bool(true, title="TW2 Down" , group="Standard Deviations", inline="DW"), tw1_dw = input.bool(true , title="TW1 Down", group="Standard Deviations", inline="DW") //#endregion //#region[Global] noColor = color.new(color.white, 100) midnight = hour(time, "America/New_York")==0 and hour(time[1], "America/New_York")!=0 size(string _size) => size = switch _size "Tiny" => size.tiny "Small" => size.small "Normal" => size.normal "Large" => size.large "Huge" => size.huge size tfRange(string LOW, string HIGH)=> timeframe.in_seconds(timeframe.period)>=timeframe.in_seconds(LOW) and timeframe.in_seconds(timeframe.period)<=timeframe.in_seconds(HIGH) var deviations = array.new_float() string[] chrs = str.split(dvs, "") if deviations.size()==0 and chrs.size()>0 var string num = "" for i=0 to chrs.size()-1 c = chrs.get(i) if chrs.get(i)=="\n" deviations.unshift(str.tonumber(num)) num := "" else num += c deviations.unshift(str.tonumber(num)) //#endregion //#region[Functions & Types] type DexterDev string side line[] lines label[] labels type TimeWindow chart.point h chart.point h_stl chart.point l chart.point l_sth line edge DexterDev up DexterDev dw swing_high_point(chart.point prev)=> if (high<high[1] and high[1]>high[2]) or (high<=high[1] and high[1]>high[2]) or (high<high[1] and high[1]>=high[2]) chart.point.from_time(time[1], high[1]) else prev swing_low_point(chart.point prev)=> if (low>low[1] and low[1]<low[2]) or (low>=low[1] and low[1]<low[2]) or (low>low[1] and low[1]<=low[2]) chart.point.from_time(time[1], low[1]) else prev method delete(DexterDev DV)=> lines = DV.lines if lines.size()>0 for i=lines.size()-1 to 0 line.delete(lines.get(i)) lines.clear() labels = DV.labels if labels.size()>0 for i=labels.size()-1 to 0 label.delete(labels.get(i)) labels.clear() method plotDexterDev(TimeWindow TW)=> DexterDev stdev_up = DexterDev.new("UP", array.new_line(), array.new_label()) DexterDev stdev_dw = DexterDev.new("DW", array.new_line(), array.new_label()) if not na(TW.h) and not na(TW.h_stl) rxh = TW.h.time , lxh = TW.h_stl.time zyh = TW.h_stl.price, yh = TW.h.price-zyh stdev_dw.lines.unshift(line.new(chart.point.from_time(lxh, TW.h.price), TW.h, xloc.bar_time, color=chart.fg_color)) stdev_dw.labels.unshift(label.new(rxh, TW.h.price, "1", xloc.bar_time, color=noColor, style=label.style_label_left, textcolor= not lbl ? chart.fg_color : noColor, size=size(label_size), text_font_family=font.family_monospace)) stdev_dw.lines.unshift(line.new(TW.h_stl, chart.point.from_time(rxh, zyh), xloc.bar_time, color=chart.fg_color)) stdev_dw.labels.unshift(label.new(rxh, zyh, "0", xloc.bar_time, color=noColor, style=label.style_label_left, textcolor= not lbl ? chart.fg_color : noColor, size=size(label_size), text_font_family=font.family_monospace)) for dv=0 to deviations.size()-1 dev = deviations.get(dv) price = zyh+(yh*dev) stdev_dw.lines.unshift(line.new(lxh, price, rxh, price, xloc.bar_time, color=chart.fg_color)) stdev_dw.labels.unshift(label.new(rxh, price, str.tostring(dev), xloc.bar_time, color=noColor, style=label.style_label_left, textcolor= not lbl ? chart.fg_color : noColor, size=size(label_size), text_font_family=font.family_monospace)) if not na(TW.l) and not na(TW.l_sth) rxl = TW.l.time , lxl = TW.l_sth.time zyl = TW.l_sth.price, yl = zyl-TW.l.price stdev_up.lines.unshift(line.new(chart.point.from_time(lxl, TW.l.price), TW.l, xloc.bar_time, color=chart.fg_color)) stdev_up.labels.unshift(label.new(rxl, TW.l.price, "1", xloc.bar_time, color=noColor, style=label.style_label_left, textcolor= not lbl ? chart.fg_color : noColor, size=size(label_size), text_font_family=font.family_monospace)) stdev_up.lines.unshift(line.new(TW.l_sth, chart.point.from_time(rxl, zyl), xloc.bar_time, color=chart.fg_color)) stdev_up.labels.unshift(label.new(rxl, zyl, "0", xloc.bar_time, color=noColor, style=label.style_label_left, textcolor= not lbl ? chart.fg_color : noColor, size=size(label_size), text_font_family=font.family_monospace)) for dv=0 to deviations.size()-1 dev = deviations.get(dv) price = zyl-(yl*dev) stdev_up.lines.unshift(line.new(lxl, price, rxl, price, xloc.bar_time, color=chart.fg_color)) stdev_up.labels.unshift(label.new(rxl, price, str.tostring(dev), xloc.bar_time, color=noColor, style=label.style_label_left, textcolor= not lbl ? chart.fg_color : noColor, size=size(label_size), text_font_family=font.family_monospace)) TW.up := stdev_up TW.dw := stdev_dw method delete(TimeWindow TW)=> line.delete(TW.edge) TW.up.delete() TW.dw.delete() method removeDev(array<TimeWindow> A)=> if A.size()>0 for i=0 to A.size()-1 tw=A.get(i) if not na(tw.up) if tw.up.lines.size()>0 if low < tw.up.lines.last().get_y1() tw.up.delete() if not na(tw.dw) if tw.dw.lines.size()>0 if high > tw.dw.lines.last().get_y1() tw.dw.delete() method hideDev(array<TimeWindow> A, int N, bool UP, bool DW)=> if A.size()>N tw=A.get(N) if not na(tw.up) if tw.up.lines.size()>0 for i=0 to tw.up.lines.size()-1 _line=tw.up.lines.get(i) _label=tw.up.labels.get(i) if UP _line.set_color(chart.fg_color) if not lbl _label.set_textcolor(chart.fg_color) else _line.set_color(noColor) _label.set_textcolor(noColor) if not na(tw.dw) if tw.dw.lines.size()>0 for i=0 to tw.dw.lines.size()-1 _line=tw.dw.lines.get(i) _label=tw.dw.labels.get(i) if DW _line.set_color(chart.fg_color) if not lbl _label.set_textcolor(chart.fg_color) else _line.set_color(noColor) _label.set_textcolor(noColor) //#endregion //#region[Find & Plot] var TWA = array.new<TimeWindow>() TF = if MLB and tfRange(lMTF, hMTF) "M" else if WLB and tfRange(lWTF, hWTF) "W" else if DLB and tfRange(lDTF, hDTF) "D" else if ILB and tfRange(lITF, hITF) "240" var chart.point prev_h_stl = na var chart.point prev_l_sth = na prev_h_stl := swing_low_point(prev_h_stl) prev_l_sth := swing_high_point(prev_l_sth) TimeWindow tw = na if TWA.size()>0 tw := TWA.first() if TF=="D"?midnight:timeframe.change(TF) if not na(tw) tw.plotDexterDev() if TWA.size()>3 TWA.pop().delete() TWA.unshift(TimeWindow.new(chart.point.from_time(time, high), na, chart.point.from_time(time, low), na, line.new(time, low, time, high, xloc.bar_time, extend.both, color.new(chart.fg_color, 50), line.style_dotted), na, na)) else if not na(tw) if math.max(tw.h.price,high)==high tw.h := chart.point.from_time(time, high) tw.h_stl := na(prev_h_stl) ? tw.h_stl : prev_h_stl if math.min(tw.l.price,low)==low tw.l := chart.point.from_time(time, low) tw.l_sth := na(prev_l_sth) ? tw.l_sth : prev_l_sth //#endregion //#region[Hide & Remove] TWA.hideDev(1, tw1_up, tw1_dw) TWA.hideDev(2, tw2_up, tw2_dw) TWA.hideDev(3, tw3_up, tw3_dw) if remove TWA.removeDev() //#endregion
RMI Trend Sniper
https://www.tradingview.com/script/rtD9lc5D-RMI-Trend-Sniper/
TZack88
https://www.tradingview.com/u/TZack88/
2,735
study
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/ // © TZack88 //@version=5 indicator('RMI Trend Sniper', overlay=true,max_labels_count = 500) // ** ---> Inputs ------------- { var bool positive = false var bool negative = false string RSI_group = "RMI Settings" string mom_group = "Range Vales" string visual = "Visuals" int Length = input(14,"RMI Length ",inline = "RMI",group = RSI_group) int pmom = input(66," Positive above",inline = "rsi1",group =RSI_group ) int nmom = input(30,"Negative below",inline = "rsi1",group =RSI_group ) bool filleshow = input(true,"Show Range MA ",inline = "002",group =visual ) color bull = input(#00bcd4,"",inline = "002",group =visual ) color bear = input(#ff5252,"",inline = "002",group =visual ) float BarRange = high - low up = ta.rma(math.max(ta.change(close), 0), Length) down = ta.rma(-math.min(ta.change(close), 0), Length) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) mf = ta.mfi(hlc3, Length) rsi_mfi = math.avg(rsi,mf) //------------------- } bool p_mom = rsi_mfi[1] < pmom and rsi_mfi > pmom and rsi_mfi > nmom and ta.change(ta.ema(close,5)) > 0 bool n_mom = rsi_mfi < nmom and ta.change(ta.ema(close,5)) < 0 // // ---> Momentums ------------- { if p_mom positive:= true negative:= false if n_mom positive:= false negative:= true // method _Band(int len)=> math.min (ta.atr (len) * 0.3, close * (0.3/100)) [20] /2 * 8 Band = _Band(30) method rangeMA(float Range,Prd)=> weight = Range / math.sum(Range, Prd) sum = math.sum(close * weight, Prd) tw= math.sum(weight, Prd) sum / tw // Calculate the RWMA rwma = rangeMA(BarRange,20) // Plotting the RWMA. colour = positive ? bull : bear RWMA = positive ? rwma - Band : negative ? rwma + Band : na alpha = color.new(color.black, 100) center = plot(filleshow ? RWMA : na, "RRTH", colour, editable = true) plot(filleshow ? RWMA : na, "RRTH", color.new(colour, 70), 2, editable = true) plot(filleshow ? RWMA : na, "RRTH", color.new(colour, 80), 3, editable = true) plot(filleshow ? RWMA : na, "RRTH", color.new(colour, 90), 4, editable = true) max = RWMA + Band min = RWMA - Band top = plot(filleshow ? max: na, "RRTH", alpha) bottom = plot(filleshow ? min: na, "RRTH", alpha) fill(top, center, top_value = max, bottom_value = RWMA, bottom_color = color.new(colour, 75), top_color = alpha, editable = true) fill(center, bottom, top_value = RWMA, bottom_value = min, bottom_color = alpha, top_color = color.new(colour, 75), editable = true) Barcol = positive ? color.green:color.red if negative and not negative[1] label.new(bar_index,max+(Band/2),"",color = color.red,size=size.small) if positive and not positive[1] label.new(bar_index,min-(Band/2),"",color = color.green,size=size.small,style= label.style_label_up) plotcandle(open, high, low, close,color = Barcol,wickcolor = Barcol,bordercolor = Barcol) barcolor(color = Barcol) // SPOT Trading Alerts alertcondition(positive and not positive[1],"BUY") alertcondition(negative and not negative[1],"SELL")
Multi Timeframe Supply & Demand Zones
https://www.tradingview.com/script/sWLOTs2O-Multi-Timeframe-Supply-Demand-Zones/
Lenny_Kiruthu
https://www.tradingview.com/u/Lenny_Kiruthu/
267
study
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/ // © Lenny_Kiruthu //@version=5 indicator(title = "Multi Timeframe Supply & Demand zones" , shorttitle = "MTF SnD" , overlay = true , max_bars_back = 500 , max_lines_count = 500 , max_boxes_count = 500) // Constants Transparent_Color = color.new(color.white, 100) // Groups General_Settings_group = "-------General Settings-------" Timeframe_1_Group = "-------Timeframe 1 Settings--------" Timeframe_2_Group = "-------Timeframe 2 Settings--------" Timeframe_3_Group = "-------Timeframe 3 Settings--------" // Tooltips Timeframe_Tooltip = "If set to chart is true no need to alter these two inputs." Set_To_Chart_Tooltip = "If set to chart is set to true, there is no need to alter the Timeframe inputs, it will automatically configure itself to the charts timeframe." Lower_Timeframe_Tooltip = "If set to true and chart timeframe is higher than the choosen timeframe, supply and demand will not display. Note plotting ltf structure on a htf will provide inaccurate plots." Mitigation_Tooltip = "If set to true supply zones with a high above them or a demand zone with a low below them will be removed since they are considered mitigated if false the close value will be used for both supply and demand." Alert_Tooltip = "After setting the alert to true or false head over to the alert dialog box and activate the any alert function under the indicator." Hide_Demand = "Hide or show the demand zones of the specific timeframe." Hide_Supply = "Hide or show the supply zones of the specific timeframe." Hide_Timeframe = "Hide or show the entire timeframe." // General Settings Hide_All_Demand = input.bool(defval = false, title = "Hide all demand zones", group = General_Settings_group) Hide_All_Supply = input.bool(defval = false, title = "Hide all supply zones", group = General_Settings_group) Show_Only_On_Lower_Timeframes = input.bool(defval = true, title = "Show Supply and Demand only on Lower Timeframes", group = General_Settings_group, tooltip = Lower_Timeframe_Tooltip) // User Inputs // Timeframe 1 Settings TF_1_Chart_Feature = input.bool(defval = false, title = "Set Timeframe to Chart", group = Timeframe_1_Group, tooltip = Set_To_Chart_Tooltip) TF_1_Use_High_Low = input.bool(defval = false, title = "Use High/Low to mitigates zones", group = Timeframe_1_Group, tooltip = Mitigation_Tooltip) TF_1_Show_Demand = input.bool(defval = true, title = "Show Demand", group = Timeframe_1_Group, tooltip = Hide_Demand) TF_1_Show_Supply = input.bool(defval = true, title = "Show Supply", group = Timeframe_1_Group, tooltip = Hide_Supply) TF_1_Demand_Alert = input.bool(defval = true, title = "Use TF 1 Demand Alert", group = Timeframe_1_Group, tooltip = Alert_Tooltip) TF_1_Supply_Alert = input.bool(defval = true, title = "Use TF 1 Supply Alert", group = Timeframe_1_Group, tooltip = Alert_Tooltip) TF_1_Multip = input.int(defval=2, minval=1, maxval=1440, title="Timeframe 1", group=Timeframe_1_Group, inline="T1") TF_1_Period = input.string(defval="Hour", title="", options=["Minute", "Hour", "Day", "Week", "Month"], group=Timeframe_1_Group, inline="T1", tooltip=Timeframe_Tooltip) TF_1_Swing_Length = input.int(defval = 7, title = "Swing Length", minval = 1, group = Timeframe_1_Group) TF_1_Line_Type = input.string(defval = "Solid", title = "Border Type", options = ["Solid", "Dashed", "Dotted"], group = Timeframe_1_Group) TF_1_Text_Size = input.string(defval = "Small", title = "Text Size", options = ["Normal", "Tiny", "Small", "Large", "Huge", "Auto"], group = Timeframe_1_Group) TF_1_Line_Width = input.int(defval = 1, title = "Border Width", group = Timeframe_1_Group) TF_1_Demand_Show_Last = input.int(defval = 2, title = "Show last (Demand)", group = Timeframe_1_Group) TF_1_Supply_Show_Last = input.int(defval = 2, title = "Show last (Supply)", group = Timeframe_1_Group) TF_1_Demand_Color = input.color(defval = #c6f89560, title = "Demand Color", group = Timeframe_1_Group, inline = "TF 1 Color") TF_1_Supply_Color = input.color(defval = #fb726a60, title = "Supply Color", group = Timeframe_1_Group, inline = "TF 1 Color") TF_1_Text_Color = input.color(defval = color.white, title = "Text Color", group = Timeframe_1_Group) // Timeframe 2 Settings TF_2_Chart_Feature = input.bool(defval = false, title = "Set Timeframe to Chart", group = Timeframe_2_Group, tooltip = Set_To_Chart_Tooltip) TF_2_Use_High_Low = input.bool(defval = false, title = "Use High/Low to mitigates zones", group = Timeframe_2_Group, tooltip = Mitigation_Tooltip) TF_2_Show_Demand = input.bool(defval = true, title = "Show Demand", group = Timeframe_2_Group, tooltip = Hide_Demand) TF_2_Show_Supply = input.bool(defval = true, title = "Show Supply", group = Timeframe_2_Group, tooltip = Hide_Supply) TF_2_Demand_Alert = input.bool(defval = true, title = "Use TF 2 Demand Alert", group = Timeframe_2_Group, tooltip = Alert_Tooltip) TF_2_Supply_Alert = input.bool(defval = true, title = "Use TF 2 Supply Alert", group = Timeframe_2_Group, tooltip = Alert_Tooltip) TF_2_Multip = input.int(defval=30, minval=1, maxval=1440, title="Timeframe 2", group=Timeframe_2_Group, inline="T2") TF_2_Period = input.string(defval="Minute", title="", options=["Minute", "Hour", "Day", "Week", "Month"], group=Timeframe_2_Group, inline="T2", tooltip=Timeframe_Tooltip) TF_2_Swing_Length = input.int(defval = 7, title = "Swing Length", minval = 1, group = Timeframe_2_Group) TF_2_Line_Type = input.string(defval = "Solid", title = "Border Type", options = ["Solid", "Dashed", "Dotted"], group = Timeframe_2_Group) TF_2_Text_Size = input.string(defval = "Small", title = "Text Size", options = ["Normal", "Tiny", "Small", "Large", "Huge", "Auto"], group = Timeframe_2_Group) TF_2_Line_Width = input.int(defval = 1, title = "Border Width", group = Timeframe_2_Group) TF_2_Demand_Show_Last = input.int(defval = 2, title = "Show last (Demand)", group = Timeframe_2_Group) TF_2_Supply_Show_Last = input.int(defval = 2, title = "Show last (Supply)", group = Timeframe_2_Group) TF_2_Demand_Color = input.color(defval = #5794f860, title = "Demand Color", group = Timeframe_2_Group, inline = "TF 2 Color") TF_2_Supply_Color = input.color(defval = #f9c9fe60, title = "Supply Color", group = Timeframe_2_Group, inline = "TF 2 Color") TF_2_Text_Color = input.color(defval = color.white, title = "Text Color", group = Timeframe_2_Group) // General functions // Getting the line type from the user. Line_Type_Control(Type) => Line_Functionality = switch Type "Solid" => line.style_solid "Dashed" => line.style_dashed "Dotted" => line.style_dotted Line_Functionality // Text size from the user Text_Size_Switch(Text_Size) => Text_Type = switch Text_Size "Normal" => size.normal "Tiny" => size.tiny "Small" => size.small "Large" => size.large "Huge" => size.huge "Auto" => size.auto Text_Type // Timeframe functionality // Timeframe for security functions TF(TF_Period, TF_Multip) => switch TF_Period "Minute" => str.tostring(TF_Multip) "Hour" => str.tostring(TF_Multip*60) "Day" => str.tostring(TF_Multip) + "D" "Week" => str.tostring(TF_Multip) + "W" "Month" => str.tostring(TF_Multip) + "M" => timeframe.period // Timeframe shortcut form TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) => if Chart_as_Timeframe == false switch TF_Period "Minute" => str.tostring(TF_Multip) + "Min" "Hour" => str.tostring(TF_Multip) + "H" "Day" => str.tostring(TF_Multip) + "D" "Week" => str.tostring(TF_Multip) + "W" "Month" => str.tostring(TF_Multip) + "M" else if Chart_as_Timeframe == true switch timeframe.isminutes and timeframe.multiplier % 60 != 0 => str.tostring(timeframe.multiplier) + "Min" timeframe.isminutes and timeframe.multiplier % 60 == 0 => str.tostring(timeframe.multiplier/60) + "H" timeframe.isdaily => str.tostring(timeframe.multiplier) + "D" timeframe.isweekly => str.tostring(timeframe.multiplier) + "W" timeframe.ismonthly => str.tostring(timeframe.multiplier) + "M" MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length) => if Chart_as_Timeframe == true Swing_Length else switch TF_Period == "Month" and timeframe.isminutes and timeframe.multiplier % 60 == 0 and (24*5*5/((TF_Multip * 1440*5*5)/timeframe.multiplier)) * 60 == timeframe.multiplier => ((TF_Multip * 1440)*5*5/ timeframe.multiplier)*Swing_Length TF_Period == "Month" and timeframe.isweekly and (5/((TF_Multip * 1440 * 5)/timeframe.multiplier)) * 1440 == timeframe.multiplier => ((TF_Multip * 1440)*5/ 1440)*Swing_Length TF_Period == "Month" and timeframe.isdaily and (5*5/((TF_Multip * 1440 * 5*5)/timeframe.multiplier)) * 1440 == timeframe.multiplier => ((TF_Multip * 1440)*5*5/ 1440)*Swing_Length timeframe.ismonthly and timeframe.multiplier == TF_Multip and TF_Period == "Month" => Swing_Length TF_Period == "Week" and timeframe.isminutes and timeframe.multiplier % 60 == 0 and (24*5/((TF_Multip * 1440*5)/timeframe.multiplier)) * 60 == timeframe.multiplier => ((TF_Multip * 1440)*5/ timeframe.multiplier)*Swing_Length TF_Period == "Week" and timeframe.isdaily and (5/((TF_Multip * 1440 * 5)/timeframe.multiplier)) * 1440 == timeframe.multiplier => ((TF_Multip * 1440)*5/ 1440)*Swing_Length timeframe.isweekly and timeframe.multiplier == TF_Multip and TF_Period == "Week" => Swing_Length TF_Period == "Day" and timeframe.isminutes and timeframe.multiplier % 60 == 0 and (24/((TF_Multip * 1440)/timeframe.multiplier)) * 60 == timeframe.multiplier => (TF_Multip * 1440/ timeframe.multiplier)*Swing_Length timeframe.isdaily and timeframe.multiplier == TF_Multip and TF_Period == "Day" => Swing_Length timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == "Minute" and TF_Multip == timeframe.multiplier => Swing_Length timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == "Minute" and TF_Multip != timeframe.multiplier => ((TF_Multip/60) * 60/timeframe.multiplier)*Swing_Length timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == "Hour" and TF_Multip != timeframe.multiplier => ((TF_Multip * 60 /60) * 60/timeframe.multiplier)*Swing_Length timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == "Hour" and TF_Multip == timeframe.multiplier and timeframe.multiplier * 60 == 60 => ((TF_Multip * 60 /60) * 60/timeframe.multiplier)*Swing_Length timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == "Day" and TF_Multip != timeframe.multiplier => ((TF_Multip * 1440 /60) * 60/timeframe.multiplier)*Swing_Length timeframe.isminutes and timeframe.multiplier % 60 == 0 and TF_Period == "Hour" and TF_Multip * 60 == timeframe.multiplier => Swing_Length timeframe.isminutes and timeframe.multiplier % 60 == 0 and TF_Period == "Hour" and TF_Multip * 60 != timeframe.multiplier => (TF_Multip * 60/timeframe.multiplier)*Swing_Length HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip) => if Chart_as_Timeframe == true true else if Show_Only_On_Lower_Timeframes == false true else switch TF_Period == "Minute" and TF_Multip < timeframe.multiplier and timeframe.isminutes => false TF_Period == "Minute" and TF_Multip >= timeframe.multiplier and timeframe.isminutes => true TF_Period == "Minute" and timeframe.isdaily => false TF_Period == "Minute" and timeframe.isweekly => false TF_Period == "Minute" and timeframe.ismonthly => false TF_Period == "Hour" and TF_Multip * 60 < timeframe.multiplier and timeframe.isminutes => false TF_Period == "Hour" and TF_Multip * 60 >= timeframe.multiplier and timeframe.isminutes => true TF_Period == "Hour" and timeframe.isdaily => false TF_Period == "Hour" and timeframe.isweekly => false TF_Period == "Hour" and timeframe.ismonthly => false TF_Period == "Day" and timeframe.isdaily or timeframe.isminutes => true TF_Period == "Week" and timeframe.isweekly or timeframe.isdaily or timeframe.isminutes => true TF_Period == "Month" and timeframe.ismonthly or timeframe.isweekly or timeframe.isdaily or timeframe.isminutes => true // Arrays var Bullish_SnD_Top_TF_1 = array.new_float(0) var Bullish_SnD_Btm_TF_1 = array.new_float(0) var Bullish_SnD_Left_TF_1 = array.new_int(0) var Bullish_SnD_Type_TF_1 = array.new_int(0) var Bearish_SnD_Top_TF_1 = array.new_float(0) var Bearish_SnD_Btm_TF_1 = array.new_float(0) var Bearish_SnD_Left_TF_1 = array.new_int(0) var Bearish_SnD_Type_TF_1 = array.new_int(0) var Bullish_SnD_Top_TF_2 = array.new_float(0) var Bullish_SnD_Btm_TF_2 = array.new_float(0) var Bullish_SnD_Left_TF_2 = array.new_int(0) var Bullish_SnD_Type_TF_2 = array.new_int(0) var Bearish_SnD_Top_TF_2 = array.new_float(0) var Bearish_SnD_Btm_TF_2 = array.new_float(0) var Bearish_SnD_Left_TF_2 = array.new_int(0) var Bearish_SnD_Type_TF_2 = array.new_int(0) // TF Pivot values // TF_1_Calc_High = ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length) // Getting the high and low values [TF_1_SH, TF_1_SL, TF_1_SH_Low, TF_1_SL_High, TF_1_Atr] = request.security(symbol = syminfo.tickerid, timeframe = (TF_1_Chart_Feature ? timeframe.period : TF(TF_1_Period, TF_1_Multip)) , expression = [ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length) , ta.pivotlow(low, TF_1_Swing_Length, TF_1_Swing_Length) , not na(ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length)) ? low[TF_1_Swing_Length] : 0 , not na(ta.pivotlow(low, TF_1_Swing_Length, TF_1_Swing_Length)) ? high[TF_1_Swing_Length] : 0 , ta.atr(200)] , gaps = barmerge.gaps_on) [TF_2_SH, TF_2_SL, TF_2_SH_Low, TF_2_SL_High, TF_2_Atr] = request.security(symbol = syminfo.tickerid, timeframe = (TF_2_Chart_Feature ? timeframe.period : TF(TF_2_Period, TF_2_Multip)) , expression = [ta.pivothigh(high, TF_2_Swing_Length, TF_2_Swing_Length) , ta.pivotlow(low, TF_2_Swing_Length, TF_2_Swing_Length) , not na(ta.pivothigh(high, TF_2_Swing_Length, TF_2_Swing_Length)) ? low[TF_2_Swing_Length] : 0 , not na(ta.pivotlow(low, TF_2_Swing_Length, TF_2_Swing_Length)) ? high[TF_2_Swing_Length] : 0 , ta.atr(200)] , gaps = barmerge.gaps_on) // [TF_3_SH, TF_3_SL] = request.security(symbol = syminfo.ticker, timeframe = (TF_3_Chart_Feature ? timeframe.period : TF(TF_3_Period, TF_3_Multip)) // , expression = [ta.pivothigh(high, TF_3_Swing_Length, TF_3_Swing_Length), ta.pivotlow(low, TF_3_Swing_Length, TF_3_Swing_Length)], gaps = barmerge.gaps_on) // Functions // // The function below is designed to loop through the arrays holding the box plot values for supply and demand box plots // and remove the mitigated (unnecessary plots) on the chart. Supply_and_Demand_Mitigation(SnD_Top, SnD_Btm, SnD_Left, SnD_Type, SnD_Dir, TF_Use_High_Low) => if SnD_Dir == "Bearish" for i in SnD_Type index = array.indexof(SnD_Type, i) if (TF_Use_High_Low ? high : close) > array.get(SnD_Top, index) array.remove(SnD_Top, index) array.remove(SnD_Btm, index) array.remove(SnD_Left, index) array.remove(SnD_Type, index) // array.set() else if SnD_Dir == "Bullish" for i in SnD_Type index = array.indexof(SnD_Type, i) if (TF_Use_High_Low ? low : close) < array.get(SnD_Btm, index) array.remove(SnD_Top, index) array.remove(SnD_Btm, index) array.remove(SnD_Left, index) array.remove(SnD_Type, index) // The function below is designed to find the necessary swing points in our chart that fit the description // of demand and supply zones Supply_and_Demand_Functionality(TF_SH, TF_SL, TF_SH_Low, TF_SL_High, TF_Atr , Swing_Length, Chart_as_Timeframe, TF_Period, TF_Multip , Bullish_SnD_Top, Bullish_SnD_Btm, Bullish_SnD_Left, Bullish_SnD_Type , Bearish_SnD_Top, Bearish_SnD_Btm, Bearish_SnD_Left, Bearish_SnD_Type , Use_Demand_Alert, Use_Supply_Alert) => // Variables to identify HH, HL, LH, LL var float TF_Prev_High = na var float TF_Prev_Low = na TF_Prev_High_Time = 0 TF_Prev_Low_Time = 0 //Tracking whether previous levels have been broken var bool TF_High_Present = false var bool TF_Low_Present = false // Variables for creating supply and demand boxes bool HH = false bool LH = false bool HL = false bool LL = false // Identify new pivot highs and lows if not na(TF_SH) if TF_SH >= TF_Prev_High HH := true else LH := true TF_Prev_High := TF_SH TF_Prev_High_Time := TF_Prev_High != TF_Prev_High[1] ? time[MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)] : TF_Prev_High_Time[1] TF_High_Present := true if not na(TF_SL) if TF_SL >= TF_Prev_Low HL := true else LL := true TF_Prev_Low := TF_SL TF_Prev_Low_Time := TF_Prev_Low != TF_Prev_Low[1] ? time[MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)] : TF_Prev_Low_Time[1] TF_Low_Present := true // Displaying Swing Level // Demand zones if LL and (math.abs(TF_SL_High - TF_Prev_Low) < TF_Atr * 2) array.unshift(Bullish_SnD_Top, TF_SL_High) array.unshift(Bullish_SnD_Btm, TF_Prev_Low) array.unshift(Bullish_SnD_Left, TF_Prev_Low_Time) array.unshift(Bullish_SnD_Type, 1) if Use_Demand_Alert alert(message = "New demand zone formed on " + + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) if HL and (math.abs(TF_SL_High - TF_Prev_Low) < TF_Atr * 2) array.unshift(Bullish_SnD_Top, TF_SL_High) array.unshift(Bullish_SnD_Btm, TF_Prev_Low) array.unshift(Bullish_SnD_Left, TF_Prev_Low_Time) array.unshift(Bullish_SnD_Type, 1) if Use_Demand_Alert alert(message = "New demand zone formed on " + + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) // Supply zones if HH and (math.abs(TF_Prev_High - TF_SH_Low) < TF_Atr * 2) array.unshift(Bearish_SnD_Top, TF_Prev_High) array.unshift(Bearish_SnD_Btm, TF_SH_Low) array.unshift(Bearish_SnD_Left, TF_Prev_High_Time) array.unshift(Bearish_SnD_Type, -1) if Use_Supply_Alert alert(message = "New supply zone formed on " + + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) if LH and (math.abs(TF_Prev_High - TF_SH_Low) < TF_Atr * 2) array.unshift(Bearish_SnD_Top, TF_Prev_High) array.unshift(Bearish_SnD_Btm, TF_SH_Low) array.unshift(Bearish_SnD_Left, TF_Prev_High_Time) array.unshift(Bearish_SnD_Type, -1) if Use_Supply_Alert alert(message = "New supply zone formed on " + + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) // The function below is designed to sift through our boxes, plot them on the chart and apply the necessary formatting. Display_SnD_Zones(Box_PLot_Type, Box_Top, Box_Btm, Box_Left, Box_Type, Show_Last, Box_Arr_size , TF_Demand_Color, TF_Supply_Color, TF_Text_Color, TF_Text_Size, TF_Border_style, TF_Border_width , Chart_as_Timeframe, TF_Period, TF_Multip)=> for i = 0 to math.min(Show_Last-1, Box_Arr_size-1) get_box = array.get(Box_PLot_Type, i) if HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip) box.set_top(get_box, array.get(Box_Top, i)) box.set_bottom(get_box, array.get(Box_Btm, i)) box.set_left(get_box, array.get(Box_Left,i)) box.set_right(get_box, time_close("W")) if Box_Type == "Bullish" box.set_bgcolor(get_box, TF_Demand_Color) box.set_border_color(get_box, TF_Demand_Color) box.set_text(get_box, TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip)) box.set_text_color(get_box, TF_Text_Color) box.set_text_font_family(get_box, font.family_default) box.set_text_halign(get_box, text.align_right) box.set_text_valign(get_box, text.align_top) box.set_text_size(get_box, TF_Text_Size) box.set_border_style(get_box, TF_Border_style) box.set_border_width(get_box, TF_Border_width) else if Box_Type == "Bearish" box.set_bgcolor(get_box, TF_Supply_Color) box.set_border_color(get_box, TF_Supply_Color) box.set_text(get_box, TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip)) box.set_text_color(get_box, TF_Text_Color) box.set_text_font_family(get_box, font.family_default) box.set_text_halign(get_box, text.align_right) box.set_text_valign(get_box, text.align_bottom) box.set_text_size(get_box, TF_Text_Size) box.set_border_style(get_box, TF_Border_style) box.set_border_width(get_box, TF_Border_width) // Calling functions Supply_and_Demand_Functionality(TF_1_SH, TF_1_SL, TF_1_SH_Low, TF_1_SL_High, TF_1_Atr , TF_1_Swing_Length, TF_1_Chart_Feature, TF_1_Period, TF_1_Multip , Bullish_SnD_Top_TF_1, Bullish_SnD_Btm_TF_1, Bullish_SnD_Left_TF_1 ,Bullish_SnD_Type_TF_1 , Bearish_SnD_Top_TF_1, Bearish_SnD_Btm_TF_1, Bearish_SnD_Left_TF_1, Bearish_SnD_Type_TF_1 , TF_1_Demand_Alert, TF_1_Supply_Alert) Supply_and_Demand_Functionality(TF_2_SH, TF_2_SL, TF_2_SH_Low, TF_2_SL_High, TF_2_Atr , TF_2_Swing_Length, TF_2_Chart_Feature, TF_2_Period, TF_2_Multip , Bullish_SnD_Top_TF_2, Bullish_SnD_Btm_TF_2, Bullish_SnD_Left_TF_2 ,Bullish_SnD_Type_TF_2 , Bearish_SnD_Top_TF_2, Bearish_SnD_Btm_TF_2, Bearish_SnD_Left_TF_2, Bearish_SnD_Type_TF_2 , TF_2_Demand_Alert, TF_2_Supply_Alert) var TF_1_Bullish_Box_PLots = array.new_box(0) var TF_1_Bearish_Box_PLots = array.new_box(0) var TF_2_Bullish_Box_PLots = array.new_box(0) var TF_2_Bearish_Box_PLots = array.new_box(0) TF_1_Bullish_Size = array.size(Bullish_SnD_Top_TF_1) TF_1_Bearish_Size = array.size(Bearish_SnD_Top_TF_1) TF_2_Bullish_Size = array.size(Bullish_SnD_Top_TF_2) TF_2_Bearish_Size = array.size(Bearish_SnD_Top_TF_2) Supply_and_Demand_Mitigation(Bullish_SnD_Top_TF_1, Bullish_SnD_Btm_TF_1, Bullish_SnD_Left_TF_1, Bullish_SnD_Type_TF_1, "Bullish", TF_1_Use_High_Low) Supply_and_Demand_Mitigation(Bearish_SnD_Top_TF_1, Bearish_SnD_Btm_TF_1, Bearish_SnD_Left_TF_1, Bearish_SnD_Type_TF_1, "Bearish", TF_1_Use_High_Low) Supply_and_Demand_Mitigation(Bullish_SnD_Top_TF_2, Bullish_SnD_Btm_TF_2, Bullish_SnD_Left_TF_2, Bullish_SnD_Type_TF_2, "Bullish", TF_2_Use_High_Low) Supply_and_Demand_Mitigation(Bearish_SnD_Top_TF_2, Bearish_SnD_Btm_TF_2, Bearish_SnD_Left_TF_2, Bearish_SnD_Type_TF_2, "Bearish", TF_2_Use_High_Low) if barstate.isfirst for i = 0 to 125 array.push(TF_1_Bullish_Box_PLots, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(TF_1_Bearish_Box_PLots, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(TF_2_Bullish_Box_PLots, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(TF_2_Bearish_Box_PLots, box.new(na,na,na,na, xloc = xloc.bar_time)) if TF_1_Bullish_Size > 0 and TF_1_Show_Demand and not Hide_All_Demand if barstate.islast Display_SnD_Zones(TF_1_Bullish_Box_PLots, Bullish_SnD_Top_TF_1, Bullish_SnD_Btm_TF_1, Bullish_SnD_Left_TF_1, "Bullish", TF_1_Demand_Show_Last, TF_1_Bullish_Size , TF_1_Demand_Color, TF_1_Supply_Color, TF_1_Text_Color, Text_Size_Switch(TF_1_Text_Size), Line_Type_Control(TF_1_Line_Type), TF_1_Line_Width , TF_1_Chart_Feature, TF_1_Period, TF_1_Multip) if TF_1_Bearish_Size > 0 and TF_1_Show_Supply and not Hide_All_Supply if barstate.islast Display_SnD_Zones(TF_1_Bearish_Box_PLots, Bearish_SnD_Top_TF_1, Bearish_SnD_Btm_TF_1, Bearish_SnD_Left_TF_1, "Bearish", TF_1_Supply_Show_Last, TF_1_Bearish_Size , TF_1_Demand_Color, TF_1_Supply_Color, TF_1_Text_Color, Text_Size_Switch(TF_1_Text_Size), Line_Type_Control(TF_1_Line_Type), TF_1_Line_Width , TF_1_Chart_Feature, TF_1_Period, TF_1_Multip) if TF_2_Bullish_Size > 0 and TF_2_Show_Demand and not Hide_All_Demand if barstate.islast Display_SnD_Zones(TF_2_Bullish_Box_PLots, Bullish_SnD_Top_TF_2, Bullish_SnD_Btm_TF_2, Bullish_SnD_Left_TF_2, "Bullish", TF_2_Demand_Show_Last, TF_2_Bullish_Size , TF_2_Demand_Color, TF_2_Supply_Color, TF_2_Text_Color, Text_Size_Switch(TF_2_Text_Size), Line_Type_Control(TF_2_Line_Type), TF_2_Line_Width , TF_2_Chart_Feature, TF_2_Period, TF_2_Multip) if TF_2_Bearish_Size > 0 and TF_2_Show_Supply and not Hide_All_Supply if barstate.islast Display_SnD_Zones(TF_2_Bearish_Box_PLots, Bearish_SnD_Top_TF_2, Bearish_SnD_Btm_TF_2, Bearish_SnD_Left_TF_2, "Bearish", TF_2_Supply_Show_Last, TF_2_Bearish_Size , TF_2_Demand_Color, TF_2_Supply_Color, TF_2_Text_Color, Text_Size_Switch(TF_2_Text_Size), Line_Type_Control(TF_2_Line_Type), TF_2_Line_Width , TF_2_Chart_Feature, TF_2_Period, TF_2_Multip)
lib_plot_composite_objects
https://www.tradingview.com/script/ya26kqMj-lib-plot-composite-objects/
robbatt
https://www.tradingview.com/u/robbatt/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © robbatt //@version=5 import robbatt/lib_plot_objects/32 as D // @description library building on top of lib_plot_objects for composite objects such as Triangles and Polygons library("lib_plot_composite_objects", overlay = true) /////////////////////////////////////////////////////// //#region COMPOSITE OBJECTS /////////////////////////////////////////////////////// //@description Composite object of 3 chart.points and lines //@field a first Corner //@field b second Corner //@field c third Corner //@field args Wrapper for reusable arguments for line.new() //@field plot_ab The line object to be added and plotted via draw() //@field plot_ac The line object to be added and plotted via draw() //@field plot_bc The line object to be added and plotted via draw() export type Triangle chart.point a chart.point b chart.point c D.LineArgs args = na D.Line ab = na D.Line ac = na D.Line bc = na //@description Creates a new linefill object and displays it on the chart, filling the space between the Triangle lines plot_ab and plot_ac with the color specified in fill_color. //@field triangle The Triangle object //@field fill_color The color used to fill the space between the lines. //@field plot The linefill object to be added and plotted via draw() export type TriangleFill Triangle triangle D.LineFill plot = na //@description Composite object of variable amount of chart.points and lines //@field points array of points that make up the Polygon //@field center Center point of the Polygon, can be used for a label and will be center for PolygonFill //@field args Wrapper for reusable arguments for line.new() //@field plot An array of Lines that form Polygon Border export type Polygon chart.point[] points chart.point center = na D.LineArgs args = na D.Line[] plot = na //@description Creates a new line segments toward the Polygon center and linefill objects, filling the space in between with the color specified in fill_color. //@field poly the Polygon //@field fill_color The color used to fill the space between the lines. //@field plot_segments An array of helper lines to create linefills //@field plot_fills An array of linefills that cover the Polygon surface export type PolygonFill Polygon poly color fill_color = #dededede TriangleFill[] plot = na /////////////////////////////////////////////////////// //#endregion COMPOSITE OBJECTS /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// //#region OBJECT INSPECTION / CONVERSION TO JSON read /////////////////////////////////////////////////////// //@function converts object to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(Triangle this, simple string date_format = 'dd-MM-y HH:mm') => na(this)?'null':'{' + str.format('"a": {0}, "b": {1}, "c": "{2}", "args": {3}', this.a.tostring(date_format), this.b.tostring(date_format), this.c.tostring(date_format), this.args.tostring()) + '}' //@function converts object to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(TriangleFill this, simple string date_format = 'dd-MM-y HH:mm') => na(this)?'null':'{' + str.format('"triangle": {0}', this.triangle.tostring(date_format)) + '}' //@function converts object to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(Polygon this, simple string date_format = 'dd-MM-y HH:mm') => na(this)?'null':'{' + str.format('"points": {0}, "center": {1}, "args": {2}', this.points.tostring(date_format), this.center.tostring(date_format), this.args.tostring()) + '}' //@function converts object to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(PolygonFill this, simple string date_format = 'dd-MM-y HH:mm') => na(this)?'null':'{' + str.format('"poly": {0}', this.poly.tostring(date_format)) + '}' tostrings(this, simple string date_format = 'dd-MM-y HH:mm') => strings = array.new<string>(this.size()) for [i,item] in this strings.set(i, item.tostring(date_format)) '[' + strings.join(', ') + ']' //@function converts array of objecta to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(Triangle[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format) //@function converts array of objecta to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(Polygon[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format) //@function converts array of objecta to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(TriangleFill[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format) //@function converts array of objecta to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(PolygonFill[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format) /////////////////////////////////////////////////////// //#endregion OBJECT INSPECTION / CONVERSION TO JSON /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// //#region OBJECT CREATION / FACTORY METHODS create /////////////////////////////////////////////////////// // Triangles //@function Creates a new Triangle object. export method create_triangle(chart.point this, chart.point b, chart.point c, D.LineArgs args = na) => default_args = args.or_default() Triangle.new(this, b, c, default_args, D.Line.new(this, b, default_args), D.Line.new(this, c, default_args), D.Line.new(b, c, default_args)) //@function Creates a new Triangle object. export method create_triangle(D.Line this, chart.point c) => default_args = this.args.or_default() Triangle.new(this.start, this.end, c, default_args, this, D.Line.new(this.start, c, default_args), D.Line.new(this.end, c, default_args)) // Polygons //@function Creates a new Polygon object. export method create_polygon(chart.point[] points, D.LineArgs args = na) => if na(points) ? true : points.size() < 2 na else count = points.size() center = points.create_center() border = array.new<D.Line>(count) border_args = args.or_default() if count > 2 first = points.get(0) last = points.get(count - 1) border.set(0, D.Line.new(last, first, border_args)) for i = 1 to count - 1 prev = points.get(i-1) curr = points.get(i) border.set(i, D.Line.new(prev, curr, border_args)) Polygon.new(points, center, border_args, border) //@function Creates a new Polygon object. export method create_polygon(chart.point start, chart.point[] others, D.LineArgs args = na) =>array.from(start).concat(others).create_polygon(args) //@function Creates a new TriangleFill object. export method create_fill(Triangle this, color fill_color = #dededede) => if not na(this) TriangleFill.new(this, D.create_fill(this.ab, this.ac, fill_color, support = this.bc)) //@function Creates a new PolygonFill object. export method create_fill(Polygon this, color fill_color = #dededede) => if not na(this) segments = array.new<TriangleFill>(0) if not na(this.plot) for border_line in this.plot segments.push(border_line.create_triangle(this.center).create_fill(fill_color = fill_color)) PolygonFill.new(this, fill_color, segments) //@function Creates a new D.Label object. export method create_center_label(Triangle this, string txt = na, D.LabelArgs args = na, string tooltip = na) => if not na(this) points = array.from(this.a, this.b, this.c) D.CenterLabel.new(points, D.Label.new(points.create_center(), txt, na(args) ? D.LabelArgs.new() : args, tooltip)) //@function Creates a new D.Label object. export method create_label(Polygon this, string txt = na, D.LabelArgs args = na, string tooltip = na) => if not na(this) D.CenterLabel.new(this.points, D.Label.new(this.points.create_center(), txt, na(args) ? D.LabelArgs.new() : args, tooltip)) _nz(this, default) => na(this) ? default : this export method nz(Triangle this, Triangle default = na) => not na(default) ? _nz(this, default) : _nz(this, Triangle.new(chart.point.now(), chart.point.now(), chart.point.now(), D.LineArgs.new())) export method nz(TriangleFill this, TriangleFill default = na) => not na(default) ? _nz(this, default) : _nz(this, TriangleFill.new(Triangle.new(chart.point.now(), chart.point.now(), chart.point.now(), D.LineArgs.new()))) export method nz(Polygon this, Polygon default = na) => not na(default) ? _nz(this, default) : _nz(this, Polygon.new(array.from(chart.point.now(), chart.point.now(), chart.point.now()), chart.point.now(), D.LineArgs.new())) export method nz(PolygonFill this, PolygonFill default = na) => not na(default) ? _nz(this, default) : _nz(this, PolygonFill.new(Polygon.new(array.from(chart.point.now(), chart.point.now(), chart.point.now()), chart.point.now(), D.LineArgs.new()))) /////////////////////////////////////////////////////// //#endregion OBJECT CREATION / FACTORY METHODS /////////////////////////////////////////////////////// _enqueue(id, item, int max = 0) => if not na(id) id.unshift(item) if max > 0 and id.size() > max id.pop() id export method enqueue(Triangle[] id, Triangle item, int max = 0) => _enqueue(id, item, max) export method enqueue(Polygon[] id, Polygon item, int max = 0) => _enqueue(id, item, max) export method enqueue(TriangleFill[] id, TriangleFill item, int max = 0) => _enqueue(id, item, max) export method enqueue(PolygonFill[] id, PolygonFill item, int max = 0) => _enqueue(id, item, max) /////////////////////////////////////////////////////// //#region OBJECT UPDATE update /////////////////////////////////////////////////////// //@function Updates a Triangle's chart.point objects with new data. export method update(Triangle this, chart.point a, chart.point b, chart.point c) => if na(this.a) this.a := a else this.a.update(a) if na(this.b) this.b := b else this.b.update(b) if na(this.c) this.c := c else this.c.update(c) this //@function Updates a Polygon's chart.point objects with new data. export method update(Polygon this, chart.point[] points) => if na(this.points) this.points := points else count = points.size() if this.points.size() != count this.points.clear() this.points.concat(points) else for [i,point] in points this.points.get(i).update(point) center = this.points.create_center() this.center := na(this.center) ? center : this.center.update(center) this /////////////////////////////////////////////////////// //#endregion OBJECT UPDATE /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// //#region OBJECT REMOVAL delete /////////////////////////////////////////////////////// safe_delete(this) => if not na(this) this.plot.delete() this safe_delete_items(this) => if not na(this) for item in this item.delete() this //@function Removes an objects representation from the chart. export method delete(Triangle this) => if not na(this) this.ab.delete() this.ac.delete() this.bc.delete() this //@function Removes an objects representation from the chart. export method delete(TriangleFill this) => if not na(this) safe_delete(this.plot) this.triangle.delete() this //@function Removes an objects representation from the chart. export method delete(Polygon this) => safe_delete_items(this.plot) //@function Removes an objects representation from the chart. export method delete(PolygonFill this) => if not na(this) this.poly.delete() if not na(this.plot) for item in this.plot item.delete() this safe_delete_all(this) => if not na(this) for item in this item.delete() this //@function Removes the representations of an array of objects from the chart. export method delete(Triangle[] this) => safe_delete_all(this) //@function Removes the representations of an array of objects from the chart. export method delete(TriangleFill[] this) => safe_delete_all(this) //@function Removes the representations of an array of objects from the chart. export method delete(Polygon[] this) => safe_delete_all(this) //@function Removes the representations of an array of objects from the chart. export method delete(PolygonFill[] this) => safe_delete_all(this) /////////////////////////////////////////////////////// //#endregion OBJECT REMOVAL /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// //#region OBJECT TO BUILTIN draw /////////////////////////////////////////////////////// init_args(this) => if not na(this) this.args := this.args.or_default() this //@function Adds/Updates the representations of an object to the chart. export method draw(Triangle this, D.LineArgs ab_args_override = na, D.LineArgs ac_args_override = na, D.LineArgs bc_args_override = na) => init_args(this) if not na(this) this.ab.draw(extend_only = false) this.ac.draw(extend_only = false) this.bc.draw(extend_only = false) this.ab.apply_style(D.nz(ab_args_override, this.args)) this.ac.apply_style(D.nz(ac_args_override, this.args)) this.bc.apply_style(D.nz(bc_args_override, this.args)) this //@function Adds/Updates the representations of an object to the chart. export method draw(Polygon this)=> init_args(this) if not na(this) this.plot.draw(extend_only = false) // for border in // border.draw() this //@function Adds/Replaces the representations of the object on the chart. export method draw(TriangleFill this)=> if not na(this) this.plot.draw() this //@function Adds/Replaces the representations of the object on the chart. The border lines are drawn in order of the Polygon.points array export method draw(PolygonFill this)=> var args_transp = D.LineArgs.new(#00000000) if not na(this) // no init, doesn't have args this.poly.center.update(this.poly.points.create_center()) // center point update if not na(this.plot) for segment in this.plot segment.triangle.draw(ac_args_override = args_transp, bc_args_override = args_transp) segment.draw() this draw_all(id) => for item in id item.draw() id //@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy export method draw(Triangle[] this) => draw_all(this) //@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy export method draw(TriangleFill[] this) => draw_all(this) //@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy export method draw(Polygon[] this) => draw_all(this) //@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy export method draw(PolygonFill[] this) => draw_all(this) _apply_style(this, args) => if not na(this) this.args := args this.plot.apply_style(args) this //@function updates styles on this objects plot export method apply_style(Triangle this, D.LineArgs args) => if not na(this) this.args := args this.ab.apply_style(args) this.ac.apply_style(args) this.bc.apply_style(args) this //@function updates styles on this objects plot export method apply_style(Polygon this, D.LineArgs args) => init_args(this) if not na(this) this.args := args if not na(this.plot) for l in this.plot //lines l.apply_style(args) this _apply_style_all(this, args) => if not na(this) for i in this i.apply_style(args) this //@function updates styles on these objects' plots export method apply_style(Triangle[] this, D.LineArgs args) => _apply_style_all(this, args) //@function updates styles on these objects' plots export method apply_style(Polygon[] this, D.LineArgs args) => _apply_style_all(this, args) /////////////////////////////////////////////////////// //#endregion OBJECT TO BUILTIN /////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // DEMO ///////////////////////////////////////////////////////// float hhp = ta.highest(high, 30) float llp = ta.lowest(low, 30) int hhi = ta.highestbars(high, 30) int lli = ta.lowestbars(low, 30) plot(bar_index, 'bi', display = display.data_window) plot(hhp, 'hhp', display = display.data_window) plot(llp, 'llp', display = display.data_window) plot(hhi, 'hhi', display = display.data_window) plot(lli, 'lli', display = display.data_window) var chart.point p_dyn = chart.point.now(0) var chart.point p1 = chart.point.now(1) var chart.point p2 = chart.point.now(2) var chart.point pt1 = chart.point.now(3) var chart.point pt2 = chart.point.now(6) var chart.point pt3 = chart.point.now(7) var chart.point hh = chart.point.now(4) var chart.point ll = chart.point.now(5) var D.Line l1 = D.Line.new(p2, p1, D.LineArgs.new(color.fuchsia)) var D.Line l2 = D.Line.new(hh, ll, D.LineArgs.new(color.purple)) if barstate.islast p_dyn.update(chart.point.now()) hh.update(chart.point.new(time[-hhi], bar_index[-hhi], hhp)) ll.update(chart.point.new(time[-lli], bar_index[-lli], llp)) p1.update(time[0], bar_index[0], high[0]) pt1.update(time[10], bar_index[10], high[10] + 3*ta.tr) pt2.update(time[5], bar_index[5], low[5] - 3*ta.tr) pt3.update(time[15], bar_index[15], low[15] - 3*ta.tr) p2.update(time[20], bar_index[20], high[20]) chart.point p3 = chart.point.new(time[30], bar_index[30], high[30]) chart.point p4 = chart.point.new(time[40], bar_index[40], high[40]) var fix3 = p3.copy() var fix4 = p4.copy() var D.Label l_hh = hh.create_label('HH') var D.Label l_ll = ll.create_label('LL', D.LabelArgs.new(style = label.style_label_up)) var D.Label l_p1 = p1.create_label('p1') var D.Label l_pt1 = pt1.create_label('pt1') var D.Label l_pt2 = pt2.create_label('pt2', D.LabelArgs.new(style = label.style_label_up)) var D.Label l_pt3 = pt3.create_label('pt3', D.LabelArgs.new(style = label.style_label_up)) var D.Label l_p2 = p2.create_label('p2') var D.Label l_p3 = p3.create_label('p3') var D.Label l_p4 = p4.create_label('p4') var D.Label l_fixp3 = fix3.create_label('fix 3').draw() // draw once var D.Label l_fixp4 = fix4.create_label('fix 4').draw() // draw once l_hh.draw() l_ll.draw() l_p1.draw() // label updated indirect, still same point, but point that was updated l_pt1.draw() // label updated indirect, still same point, but point that was updated l_pt2.draw() // label updated indirect, still same point, but point that was updated l_pt3.draw() // label updated indirect, still same point, but point that was updated l_p2.draw() // label updated indirect, still same point, but point that was updated l_p3.update(p3).draw() // update label with new point l_p4.update(p4).draw() // update label with new point l1.draw(extend_only = false) // based on instances p1 and p2, which are updated, hence l1.plot is updated as well // var Triangle t1 = p2.create_triangle(p3, p4) // expanding triangle with two fix point p4 and two updating points p2,p3, since the plotted triangle lines l1 and l2 are updated because they have chart.point p2 as member, which is updated, the fill will also update // t1.draw() // var D.Label l_t1 = t1.create_label('triangle') // l_t1.draw() var Triangle t2 = l1.create_triangle(pt1) t2.draw() // fix triangle, created once, with l2 and ll, but only drawn once at init of var var D.CenterLabel l_t2 = t2.create_center_label('triangle 2', D.LabelArgs.new(style = label.style_label_center)) l_t2.draw() var TriangleFill tf_te2 = t2.create_fill(#ff525240) tf_te2.draw() var Polygon p = array.from(p1, pt2, pt3, p2).create_polygon() p.draw() var PolygonFill pf = p.create_fill(#ff99003e) pf.draw() var D.CenterLabel l_pc = p.create_label('poly') l_pc.draw()
Enhanced McClellan Summation Index
https://www.tradingview.com/script/xpnUXbpU-Enhanced-McClellan-Summation-Index/
QuantiLuxe
https://www.tradingview.com/u/QuantiLuxe/
144
study
5
CC-BY-NC-SA-4.0
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © EliCobra //@version=5 indicator("Enhanced McClellan Summation Index", "[Ʌ] - 𝐄𝐧𝐡𝐚𝐧𝐜𝐞𝐝 𝐌𝐒𝐈", false) type bar float o = open float h = high float l = low float c = close method src(bar b, simple string src) => float x = switch src 'oc2' => math.avg(b.o, b.c ) 'hl2' => math.avg(b.h, b.l ) 'hlc3' => math.avg(b.h, b.l, b.c ) 'ohlc4' => math.avg(b.o, b.h, b.l, b.c) 'hlcc4' => math.avg(b.h, b.l, b.c, b.c) x method null(bar b) => na(b) ? bar.new(0, 0, 0, 0) : b method ha(bar b, simple bool p = true) => var bar x = bar.new( ) x.c := b .src('ohlc4') x := bar.new( na(x.o[1]) ? b.src('oc2') : nz(x.src('oc2')[1]), math.max(b.h, math.max(x.o, x.c)) , math.min(b.l, math.min(x.o, x.c)) , x.c ) p ? x : b f_rt(float a, float d, simple int m) => (a - d) / (a + d) * m method macd(float src, simple int flen, simple int slen) => ta.ema(src, flen) - ta.ema(src, slen) method mc(bar r) => var bar mc = bar.new( ) mc := bar.new( ta.cum(r.o.macd(19, 39)), ta.cum(r.h.macd(19, 39)), ta.cum(r.l.macd(19, 39)), ta.cum(r.c.macd(19, 39))) mc var string gm = 'McClellan Summation Index', var string gs = 'MACD' mode = input.string('Heikin-Ashi', "Display Mode" , ['Heikin-Ashi', 'MACD' , 'MACD-H'], group = gm) idx = input.string('NYSE' , "Index" , ['NYSE' , 'NASDAQ', 'AMEX' ], group = gm) mlt = input.int (1000 , "Ratio Multiplier", [1000 , 100 , 10 , 1], group = gm) revs = input.bool (true , "Reversal Doritos", group = gm) len_f = input (12 , "MACD Fast" , group = gs) len_s = input (26 , "MACD Slow" , group = gs) len_m = input.int (9 , "MACD Signal" , 1, 50 , group = gs) [s_adv, s_dec] = switch idx 'NYSE' => ['ADV' , 'DECL' ] 'NASDAQ' => ['ADVQ', 'DECLQ'] 'AMEX' => ['ADVA', 'DECLA'] bar adv = request.security('USI:' + s_adv, '', bar.new()).null() bar dec = request.security('USI:' + s_dec, '', bar.new()).null() bar mc = bar.new( f_rt(adv.o, dec.o, mlt), f_rt(adv.h, dec.h, mlt), f_rt(adv.l, dec.l, mlt), f_rt(adv.c, dec.c, mlt)).mc().ha() float macd = mc.c.macd(len_f, len_s) float sig = ta .ema (macd , len_m) float hist = macd - sig float pos = hist > 0 ? 0 : hist float neg = hist < 0 ? 0 : hist var color colnt = chart.bg_color var color colup = chart.fg_color var color coldn = #d61717 bool dcon = ta.crossunder(mc.c, mc.o) bool ucon = ta.crossover (mc.c, mc.o) color hawcol = switch mc.c > mc.o => colup mc.c < mc.o => coldn color hafcol = switch ucon => colup dcon => colnt mc.c < mc.o => coldn => colnt color habcol = switch dcon => coldn ucon => colup mc.c > mc.o => colup mc.c < mc.o => coldn plotcandle(mode == 'Heikin-Ashi' ? mc.o : na, mode == 'Heikin-Ashi' ? mc.h : na, mode == 'Heikin-Ashi' ? mc.l : na, mode == 'Heikin-Ashi' ? mc.c : na, "𝐌𝐒𝐈", hafcol, hawcol, bordercolor = habcol) plotchar(revs and mode == 'Heikin-Ashi' ? ucon ? mc.o - mlt / 10 : na : na, "Reverse Dip", "▴", location.absolute, colup, size = size.tiny) plotchar(revs and mode == 'Heikin-Ashi' ? dcon ? mc.c + mlt / 10 : na : na, "Reverse Top", "▾", location.absolute, coldn, size = size.tiny) plot(mode == 'MACD-H' ? hist : na, "MACD-H", hist > 0 ? color.new(colup, 90) : color.new(coldn, 90), 1, plot.style_columns ) plot(mode == 'MACD-H' ? hist * 0.7 : na, "Filler", hist > 0 ? color.new(colup, 70) : color.new(coldn, 70), 1, plot.style_columns, display = display.pane, editable = false) plot(mode == 'MACD-H' ? hist * 0.5 : na, "Filler", hist > 0 ? color.new(colup, 60) : color.new(coldn, 60), 1, plot.style_columns, display = display.pane, editable = false) plot(mode == 'MACD-H' ? hist * 0.3 : na, "Filler", hist > 0 ? color.new(colup, 30) : color.new(coldn, 30), 1, plot.style_columns, display = display.pane, editable = false) plot(mode == 'MACD-H' ? hist * 0.1 : na, "Filler", hist > 0 ? color.new(colup, 0 ) : color.new(coldn, 0 ), 1, plot.style_columns, display = display.pane, editable = false) plot(mode == 'MACD-H' ? neg : na, "Filler", color.new(colup, neg == 0 and neg[1] == 0 ? 100 : 0) , 1, plot.style_line , display = display.pane, editable = false) plot(mode == 'MACD-H' ? pos : na, "Filler", color.new(coldn, pos == 0 and pos[1] == 0 ? 100 : 0) , 1, plot.style_line , display = display.pane, editable = false) plot(mode == 'MACD' ? macd : na, "𝐌𝐀𝐂𝐃" , colup , 1, plot.style_line ) plot(mode == 'MACD' ? sig : na, "𝐒𝐢𝐠𝐧𝐚𝐥" , coldn , 1, plot.style_line ) //Source Construction For Indicator\Strategy Exports plot(mc.o , "open" , editable = false, display = display.none) plot(mc.h , "high" , editable = false, display = display.none) plot(mc.l , "low" , editable = false, display = display.none) plot(mc.c , "close", editable = false, display = display.none) plot(mc.src('hl2' ), "hl2" , editable = false, display = display.none) plot(mc.src('hlc3' ), "hlc3" , editable = false, display = display.none) plot(mc.src('ohlc4'), "ohlc4", editable = false, display = display.none) plot(mc.src('hlcc4'), "hlcc4", editable = false, display = display.none)
ICT Times [joshu]
https://www.tradingview.com/script/tpMeVmYH-ICT-Times-joshu/
joshuuu
https://www.tradingview.com/u/joshuuu/
148
study
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/ // © joshuuu //@version=5 indicator("ICT Times [joshu]", overlay = false, max_boxes_count = 500) var box killzone_box = na var box sb_box = na var box macro_box = na is_newbar(string sess) => t = time('D', sess, timezone = "America/New_York") na(t[1]) and not na(t) or t[1] < t is_session(string sess) => not na(time('D', sess, timezone = "America/New_York")) is_over(string sess) => sess_index = 0 sess_over = false if is_session(sess) sess_index := bar_index if bar_index[1] == sess_index[1] and bar_index > sess_index sess_over := true else sess_over := false daily = "0000-1600" asia = "2000-0000" lokz = "0200-0500" nykz = "0700-1000" locl = "1000-1200" nyam = "0830-1100" nypm = "1330-1600" syminfo_type() => var string stype = na if syminfo.type == "forex" stype := "forex" else if syminfo.type == "index" stype := "index" else if syminfo.prefix == "CME_DL" stype := "forex" else if syminfo.prefix == "CME_MINI_DL" stype := "index" in_kz() => var bool in_kz = na if syminfo_type() == "forex" in_kz := is_session(lokz) or is_session(nykz) or is_session(locl) else in_kz := is_session(lokz) or is_session(nyam) or is_session(nypm) in_kz in_sb = is_session("0300-0400") or is_session("1000-1100") or (syminfo_type() != "forex" and is_session("1400-1500")) in_macro = is_session("0233-0300") or is_session("0403-0430") or is_session("0850-0910") or is_session("0950-1010") or is_session("1050-1110") or is_session("1150-1210") or (syminfo_type() != "forex" and is_session("1310-1340")) or (syminfo_type() != "forex" and is_session("1515-1545")) if in_kz() and not in_kz()[1] and timeframe.in_seconds() <= timeframe.in_seconds("60") killzone_box := box.new(bar_index, 1,bar_index,0, border_color = color.new(color.gray,100),bgcolor = color.new(color.gray,50), text = "killzone", text_size = size.tiny, text_color = chart.fg_color) else if in_kz() box.set_right(killzone_box, bar_index) if in_sb and not in_sb[1] and timeframe.in_seconds() <= timeframe.in_seconds("30") sb_box := box.new(bar_index, 2,bar_index,1, border_color = color.new(color.gray,100),bgcolor = color.new(color.gray,65), text = "sb", text_size = size.tiny, text_color = chart.fg_color) else if in_sb box.set_right(sb_box, bar_index) if in_macro and not in_macro[1] and timeframe.in_seconds() <= timeframe.in_seconds("5") macro_box := box.new(bar_index, 3,bar_index,2, border_color = color.new(color.gray,100),bgcolor = color.new(color.gray,85), text = "macro", text_size = size.tiny, text_color = chart.fg_color) else if in_macro box.set_right(macro_box, bar_index)
imlib
https://www.tradingview.com/script/7MP89RMJ-imlib/
sabricat
https://www.tradingview.com/u/sabricat/
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/ // © sabricat //@version=5 // @description: Implements functions to display square images using <table> objects library("imlib", overlay=true) // Custom type to describe image data export type ImgData int w int h string s string pal array<string> data // @function: Decompresses string with data image // @param data: String with image data // @returns: Array of <string> with decompressed data export _decompress(string data) => var arr = array.new<string>(0, na) res = '' num = '' for i = 0 to str.length(data) - 1 char = str.substring(data, i, i + 1) char_is_num = not na(str.tonumber(char)) if char_is_num num := num + char if not char_is_num if num != '' num_int = str.tonumber(num) for j = 0 to num_int - 2 if str.length(res) == 4096 array.push(arr, res) res := '' res := res + char num := '' if num == '' if str.length(res) == 4096 array.push(arr, res) res := '' res := res + char if res != '' array.push(arr, res) arr // @function: Splits the string with image data into components and builds an <ImgData> object // @param data: String with image data // @returns: An <ImgData> object export load(string data) => data_ = str.split(data, '⫝') size = array.get(data_, 0) w_ = str.substring(size, 0, 1) h_ = str.substring(size, 1, 2) p2 = array.get(data_, 1) s = str.substring(p2, 0, 256) pal = str.substring(p2, 256) da = _decompress(array.get(data_, 2)) w = str.pos(s, w_) h = str.pos(s, h_) ImgData.new(w, h, s, pal, da) // @function: Displays an image in a table // @param imgdata: <ImgData> object that contains data about the image // @param table_id: <table> to use for displaying the image // @param image_size: Size of the image; the greatest of <width> and <height> has this size // @param screen_ratio: Width to height ratio (you can set a ratio like "width/height" or a value like "2.0", "3") // @returns: nothing export show(ImgData imgdata, table table_id, float image_size=20.0, string screen_ratio="16/8.5") => cur_col = 0 cur_row = 0 var palette_ = array.new<color>(0, na) var int r = -1 var int g = -1 var int b = -1 var int t = -1 for i = 0 to str.length(imgdata.pal) char = str.substring(imgdata.pal, i, i + 1) done = false if r == -1 r := str.pos(imgdata.s, char) done := true if g == -1 and not done g := str.pos(imgdata.s, char) done := true if b == -1 and not done b := str.pos(imgdata.s, char) done := true if t == -1 and not done t := str.pos(imgdata.s, char) array.push(palette_, color.new(color.rgb(r, g, b), 100 - t)) r := -1 g := -1 b := -1 t := -1 float ratio = na screen_ratio_split = str.split(screen_ratio, "/") if screen_ratio_split.size() == 2 ratio := str.tonumber(screen_ratio_split.get(0)) / str.tonumber(screen_ratio_split.get(1)) else ratio := str.tonumber(screen_ratio_split.get(0)) pixel_size = image_size / math.max(imgdata.h, imgdata.w) for i = 0 to array.size(imgdata.data) - 1 data_ = array.get(imgdata.data, i) for j = 0 to str.length(data_) - 1 char = str.substring(data_, j, j + 1) pos = str.pos(imgdata.s, char) if cur_col == imgdata.w cur_row := cur_row + 1 cur_col := 0 table.cell(table_id, cur_col, cur_row, bgcolor=array.get(palette_, pos), width=pixel_size, text='', height=pixel_size * ratio, text_size=size.tiny) cur_col := cur_col + 1 // @function: Use it as an example of how this library works and how to use it in your own scripts // @returns: nothing export example() => var ImgData imgdata = na var table t = na imgdata_raw = "ℌℌ⫝❢čтIЙñð^īКyкПù{;ДЁȢЛūōpȹÞирчBPç∋⊣èⱬЬƼzюƩE℃gƶ$*≈Ke∱äjžжW∅.Тįk,ãц&ȜƽZлśУъńµ⊆ℌ♠︎Lõż⟡⟢Б⊢Ωбê⊤!+xéßℑnQæАFƷó(ɀɁíƺ∼ОHþЗХV<ш-fНЪvЯ)ё☻сOûbē⟣UпüƱJǮɂaAš=одЧöâШîйƸ:}āаЫЩэеCęòƪ@ƛNïвыrł>áзƻǷdВИу[Mƾ]ǯhн⊐фЮXȣ#ƔćTЖФƹ℉Г∆⊏ℳź|ôꭓ℞cщМСåìЦяÿ_RsгьœmúoGРмDėàȸЕiS%Эluqхwt⊇Yø¿⸘‽¡§†‡¦⁉❢❢❢❢⁉⁉⁉тXXℳЛþɀæшёfV⟡ǮǮǮⱬǯǯƾ{<ОɁƻё-H‡AǮJВaJaéаааи∆∆∆ùǮOЪ@шíƷ‡⟣ûē#)ЪЗe⊐M]gûсс^]ï})a)∼¦)-<d∆⊐dƶłЫA¦Ɂxõ¦é⊢♠¦fɀê‡Хƺ(йƻrry℞нИūMваåшОƺsfHɀż⊐ИNꭓℳ>š¦dï:¦Ω♠ъ¦néxd+⊤⟢ц&bbЙdáłƶФ⊐łƻ℉фd¦щƾ馵kj⁉ТjK⁉⟡ъ.¦+êΩ∆ББżæjj︎yЩооȢU☻)KЧɂƱШЩй=âℳMrбhƻ@ÿǷáƛ¦îƱш¦≈℃E⁉łAþ¦ćęOå_ƾШMРнöǷЕФòэР#йΩG><КÿÿåЛЩ:йЗUсOГГГИȹ=Оõ⁉∆а<¦dƸv⁉℞ïЯ⁉м⊐š†ȸTШ⁉ÿИдℳСƛп=úh=(ℳыüɀ⊐ЫbíòšЪΩб∼бПGååȢЕРЕùǷááżöAп¦ǷCîLźƔ]ℌh]d¦ƪǮХ⊏üшéóïоН&ь]д∱R]âō℉>оКoìåeйоJёa⟣⟣cƛааиȣуNИа:о⁉∱Eи⁉šЪ!⁉DhšЦúЮЧǮ|áîxàƹ@p_ящzMr@UƸUс℃|ǯCõƹэb$ƹ⊐ávВęЧòƷб,⁉òЧ⟣⁉ЖǷе,Иï:ȣИыХ⁉ƼPр⁉z∋è⁉∆∆ЫКƹhCFXИCБгВё⁉d>аÞb>bðР⊏В‡Еåh⁉фǷòс∆йℑ⁉ȣВę⁉XMзЯóóéBMп+⁉úВO⁉dвò>Чпб⁉DRщ¦-Ɂnê|ℳƹ¦ßБц⁉ЭЕD¦àGs¦Г]з|ƽžç⁉яćе⁉⊏Жн¦яìщ¦‽Yх⁉#у@=ууаy[зözсf⟡⁉эöUrэîH⁉оƱ)ēhИf⁉ьcн⁉Щâ⊤⁉б︎Уžǯǯуℑ__С︎<Ɂk⁉ååꭓa⟡л,юЦЦщ@úXò⁉żлãЦjjj;ÿяСФЖэ⟣⁉♠ƽãƛ⊤ż︎лR_Ц<пп☻PGoьꭓМT⊐ǷРььɂc[эCХµТ⁉ꭓƪсmRXł=мРmµAQµ⁉U⊢ц⁉ФдQ⁉ФЧF⁉iгåз%GGþмoRюDDGоSȸDС⁉||ñJ∼А⁉∼︎µ⁉ыёΩ⁉щЖ#âȸȸGxNOæ⁉йɀ,⁉ėėoИƽюю⁉РРРzFц&⁉ęò}⁉РꭓT⁉ėмmшmús⁉ꭓ|∆ûoℳнRꭓꭓℳ⊆o℞Tsė℞фXR℉ȣЪúℳфx⫝673❢č47❢čт24❢IЙñ45❢ðт24❢^2īКyк42❢2П24❢ù4{;Д40❢čЁȢ24❢Лū5{ōД38❢ðЁ25❢pȹ{2Þи{ирчȢ36❢ðB25❢Pçȹр2иÞ2и{∋⊣34❢čЁč25❢ЁèⱬЬ{3Ƽ2иÞ{zюƩ31❢2ð11❢ȢBEB11❢ð℃gƶЬр3Ƽ$*≈ƼиKe∱29❢Пð9❢äjžКжȢ12❢W∅.ⱬЬТрƼ*2į*Þ2k,2ãц&Ȝƽ22❢BZ8❢Eлś3īžč12❢У℃2g3ЬТр*į*ъń2µ⊆ⱬ2ℌ♠︎L2õż⟡⟢Б15❢⊢Z5❢Ωбžê2{ÞрТ⊤14❢!g+ЬµТр2Ти$Ƽ2р≈2ръТ3ⱬℌ♠ℌ2⊆xéß2ℑnQ9❢æZ3❢jАFī{ÞиÞūȹçƷ14❢póЬȹ(ТрÞ2рÞƼ$*ɀ*Ƽи{Т2ūīū2kµ⊆Ɂъⱬ2ℌíцƺ∼ℑО3❢čH2❢Дō2{Þ2иƼрk2ЬþȢ14❢P℃+ȹ(ȹū6Þ3≈иÞрū2ī2Þê(ū2рирµ4♠ℌ2ƶã∼ЗWХVIÞи3ƼиÞūµ2ЬçB15❢ð<.Ьȹ2Тр4Þ2р5ɁрūТūīТīūȹūÞƼ{ⱬℌⱬkȹµȹⱬЬТȹkрƼ$*$≈ƼÞТⱬ3Ьш17❢póƶЬ2µТрÞТ2µТɁÞ≈-ÞрūТ2µȹfТȹ(и{ÞīⱬȹêȹТīТū2ТрƼ$2į2*Þµⱬ2ЬƶⱬН17❢p℃2ƶЪȹµȹЬⱬµū-2≈ÞрɁūТµvµ⊆ƶµȹЬр3īЬⱬЬТ3ū{Т{≈$*Я)įÞµȹЬƶ2gЛč17❢ёХ☻сEжūТЬµɁÞ2≈2ÞūТūkµ2⊆Oƶ⊆Тȹ2Ь2ūЬ2ƶ♠⊆kТūТ2рÞ2$ƼрūТȹ2Ьgóû22❢bАТ2kɁ$≈3Þū2kµkń⊆ƶℌⱬ⊆k2ū2Ьūȹƶē⟣ℌ⊆µkТр2ТɁÞ2≈рТȹЬ2gU24❢ЙūkТр≈ÞɁūТµkµk2п⊆2ℌń2ТЬ{рgȹ(gē♠ℌ3⊆kūрɁ2Т2ÞūµЬü2+Ʊ23❢Jчр2ū-рɁūТk2µ⊆ń3пƶℌǮÞТƶЬÞê.(gēƶ⊆ɂ2⊆µkūÞрµⱬЬ2ȹЬⱬ+að23❢⊣{2Þ2рū4Тµ3ⱬ2⊆п⊆♠A-µ2ƶkТ.ê+š⊆ⱬℌ3⊆2µ3ūЬgⱬ3Ь.E24❢={2Þ2рɁТkТɁµ2ЬⱬЬⱬ2⊆♠µъⱬ2ƶЬТ.ȹоšⱬƶ♠⊆ńⱬµТµūрТⱬƶg2Ь⊤25❢⊣{3рū2ТūɁ3ūрдÞɁµⱬ2ƶµ3ƶⱬЬ2+Чögƶ♠ⱬńⱬƶµТµ2рЬgâèЪû25❢⊣{2р2ū2ТɁрūТÞЯ$и≈Ш≈kƶⱬ2ƶîƶЬйƸ2:šē2ƶ⊆2ƶТр2Тūȹ}Bāаё25❢Й2рūриÞиƼТƶg2ÞТЫр{≈ɀТ2ƶⱬƶⱬgš3:š2ƶⱬ⊆ƶЬТ2µ2ТЩB29❢Дрūр2Ƽ2*ūƶgйрТvэЫ≈рɀ$ȹйƶЬgš4:ƸЬⱬ⊆ⱬЬȹµȹЬТūе30❢ДрÞƼрÞиƼÞȹgйТACvɁ-р≈ɀū2ęƶйЧ3:ЧйȹЬȹТр2Þрȹkр⊣30❢jр≈рɁрīи≈ūȹйƶр2vò2AЫɀū2š2й4:šgЬȹÞ≈$3ɀрūÞƪ30❢Д{рТµūТū2≈рȹēȹЫ2vµvЫ*kšö2ēЧ3:ƸgЬр2≈īÞд$3Þƪ29❢Ω@2ūµэ3ТÞ≈ÞрТgȹɁ2Aр≈иµēöēš3:Ч2ƸЬрɁ≈р2ЫÞµÞ≈ю29❢ƛƸȹТȹ2ТэТр$Ƽ2рūƶgȹТȹkⱬńⱬ⟣ö4:Ч2šȹɁANЫAɁ{ƶȹƼƪ29❢ïƸ.īūТ4ūÞ≈рɁūТЬ2⟣ē2ƶńƶö2Ч3:Чšй2ɁòA2эиȹйЬÞв29❢ыƸg(р≈Ƽ2≈иÞи≈Þ2ū(Ьgйērgš6:Чšⱬ4ɁЫиТйƶТł>28❢ПáƸоЬТÞ≈2$иÞи$и{êЬ.göЧö2Ч6:ЧögkзⱬµkⱬgЬȹрƻ29❢H3ƸйЬȹūрÞр2ū2ÞūЬ.gЧ4:2Ч2:5Чš2ⱬēйg+Т3рǷ29❢dö2Ƹоg+Ь(Тūī3Тê+Ƹ7:2Ч:šо2šЧöšēöƸ2g(3{В28❢ZИЧ2Ƹой3+.Ь2ȹ2Ь.оЧ7:Чšоgо2šƸо2Ч2:Чö+2ТȹE28❢ƛöš2Ƹ2о2+2.ЬȹЬ.gƸЧ6:ЧƸš.ūê.2о+ȹо3ЧöƸ.2ТgуHč26❢[Ч4Ƹой2+3.Ьȹ.Ƹ5:2ЧšȹkÞƼÞ{ūÞūъfй2Ƹоg(ūkń⊆ⱬ︎MWPП21❢ΩИЧ3Ƹо2й2+2.2+.+ƸЧ4:ö⟣šйū2ƾъ3ƾ≈ъūТЬ2gȹūТk6ń]ãǯp19❢h2ö2Ƹ2о2й7+о3Чö2Чš2⟣šgÞ$н⊐ƾ$ÞµɁрµЬ.(k2ǮфЮńƶ3ⱬℌ2ēXȣ#16❢ƔЧš3Ƹо2й5+gйgо2ö2ЧƸоgй2ƸЬÞ2ƾ$ÞЬⱬТɁⱬg+.ȹk3Ǯńⱬēšöš2ö2:ć[æT12❢ΩИЧö2Ƹ2ой7+йg+2о4Ƹ4йgЖƾФТ2Ь3µƶgЬk3ƹk2ǮńƶšЧ6:ЧƸ℉p11❢ГЧö3Ƹ2ой4+.4+й5о2+.2Ь.êрê.2ЬµТµⱬgЬ∆2ƹ⊏2ƹǮńⱬēЧ7:öоâЛ⊤9❢ƔЧö3Ƹ2ой+3.+.Ь+й2о3+2.Ь3ȹê{Т6ȹЬƶgЬµk2ƹ2Ǯ2ƹńēö6:šйg2ⱬȹ8❢ZℳЧš3Ƹ2о4+Ь2(2.+о2+.(3êū{Þ$ź{3(3ȹЬ+gȹɁk2µ2ƹǮk⊆ēö6:Ч2šйgз8❢|öЧš3Ƹой3+Ь2(.(2.Ь2+.êī3Þ2Фô$Ƽūê(2ȹЬ.2gȹkъ⊏ƹ2kƹkⱬēö8:Чšgń8❢h2Чö2Ƹ3ой+.ꭓ2Ь(2Ьê(.2+Ьêū3{2ūрÞīê(ȹЬ.+gй.3Ɂ⊏ъ3k⊆ēö8:Чоⱬз8❢Ɣ2Чö4Ƹо2+3.(.Ь2ê3(2.Ь3(êТê2Тê2ȹ2Ь+4gȹъ2Ɂ⊏ъkńⱬgšЧ6:ö2š℞š7❢Zć:Чö3Ƹой4+(.Ь2ê(3Т(2.2Ьȹ3(4ȹ2Ь.+gйg2ЬµъɁ2ƹkńƶēö10:Чš7❢h4Ч2Ƹ2ой+й+3.3(ê4Т(Ь3.2ȹЬ.4Ь.2+g2й.ȹµkъƹkµƶйšöЧ9:Чš7❢c4ЧöƸ2о2й+2.+Ь3(ê2ТīТê(3.Ь2.4Ь.2+2g2йgȹū2kƹkзgšö2Ч10:Ч6❢ðℳ2:2Чö2Ƹ2ой3+.2Ьꭓ(ê5Тê2(ȹ6Ь.2+2g3йgȹ3k∆kƶšö4Ч10:6❢Zć:4Чщ3Ƹой2+.2Ьꭓ2(2ê(3Тê3(ȹ3Ь.4+g2й2gȹ3kµⱬйö5Ч10:6❢#7Ч4Ƹ2о3+.Ь5(4ê2(2ȹ2Ь2.4+g2йg+Ьȹ2µⱬgšö3Ч12:6❢H7Чö4Ƹой3+.Ь11(3Ь.3+g4йgЬ3ȹⱬйƸ3ö3Ч10:Ч6❢Zö6Ч2ö3Ƹ2ой4+2Ь9(2Ь.4+2gйgйg+2ЬⱬйƸšöЧö3Ч2:2Ч6:Ч6❢ΩáЧö4Чö5Ƹ2ой3+.2Ь6(Ь2ȹЬ.4+3g3й+ЬƶйƸš4ö5Ч6:3Ч7❢d2Ƹ4Чö3Ƹо4й4+3.Ь(7Ь.4+2g5йgйƸš5ö4Ч7:3Ч7❢Hо2Ƹ3öЧö2Ƹо2й7+3.5Ь2.Ь.5+g6й2Ƹš2öЧö10Ч3:Чš7❢PáƸš3öš3Ƹ2о2й6+6.Ь5.4+g4й3о2Ƹš5ö11Ч3š8❢М11Ƹо2й6+10.4+3g3й4о2Ƹ5ö3Ч:6ЧöšйС8❢åо7Ƹо2й3ой5+10.5+3g3й3о2Ƹš4ö9Ч3šìЦ8❢H3о5Ƹйgй3о7+7.8+g+g3й2о3Ƹš4ö6Чöšоуя2ÿ" if barstate.isfirst imgdata := load(imgdata_raw) t := table.new(position.bottom_right, imgdata.w, imgdata.h) if barstate.islast or barstate.isrealtime or barstate.islastconfirmedhistory show(imgdata, t) // @function: Displays logo using image data string // @param imgdata: <ImgData> object that contains data about the image // @param position: position of the image (table) on the chart (you can set a string value like "VerticalPosition HorizontalPosition", for example "Top Right") // @param image_size: Size of the image; the greatest of <width> and <height> has this size // @param screen_ratio: Width to height ratio (you can set a ratio like "width/height" or a value like "2.0", "3") // @returns: nothing export logo(string imgdata, string position, float image_size=20.0, string screen_ratio="16/9") => var ImgData imgdata_obj = na var table t = na if barstate.isfirst imgdata_obj := load(imgdata) tpos = switch position "Top Left" => position.top_left "Top Center" => position.top_center "Top Right" => position.top_right "Middle Left" => position.middle_left "Middle Center" => position.middle_center "Middle Right" => position.middle_right "Bottom Left" => position.bottom_left "Bottom Center" => position.bottom_center "Bottom Right" => position.bottom_right t := table.new(tpos, imgdata_obj.w, imgdata_obj.h) if barstate.islast or barstate.isrealtime or barstate.islastconfirmedhistory show(imgdata_obj, t, image_size, screen_ratio) example()
Oscillator Volume Profile [Trendoscope®]
https://www.tradingview.com/script/f5NtcsZD-Oscillator-Volume-Profile-Trendoscope/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
144
study
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 // ░▒ // ▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒ // ▒▒▒▒▒▒▒░ ▒ ▒▒ // ▒▒▒▒▒▒ ▒ ▒▒ // ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ // ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒ // ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒ ▒▒▒▒▒ // ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗ // ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗ // ▒▒ ▒ //@version=5 indicator("Oscillator Volume Profile", max_lines_count = 500) import HeWhoMustNotBeNamed/arraymethods/1 import HeWhoMustNotBeNamed/ta/1 as eta indicatorType = input.string('rsi', 'Type', ['rsi', 'cmo', 'cog', 'mfi', 'roc', 'cci', 'stoch', 'tsi', 'wpr'], tooltip = 'Oscillator Type', group='Oscillator') length = input.int(14, 'Length', minval=2, step=5, tooltip = 'Oscillator Length', group = 'Oscillator', display = display.none) shortLength = input.int(13, 'Fast Length', minval=2, step=5, tooltip='Fast Length (Used for stochastic osillator, tsi)', group = 'Oscillator', display = display.none) longLength = input.int(25, 'Slow Length', minval=2, step=5, tooltip = 'Slow Length (Used for stochastic oscilator, tsi)', group = 'Oscillator', display = display.none) precision = input.int(2, 'Precision', minval=0, step=1, tooltip = 'Floating point precision of indicator to be used', group = 'Oscillator', display = display.none) rangeMethod = input.string('highlow', 'Calculation Method', ['highlow', 'ema', 'sma', 'rma', 'hma', 'wma', 'vwma', 'linreg', 'median'], 'Calculation method for high/low range', group='Range', display=display.none) rangeLength = input.int(50, 'Length', 20, step=20, tooltip = 'Range Calculation Length', group='Range', display=display.none) sticky = input.bool(true, 'Sticky Borders', 'When enabled, border values will only change during the breakouts.', group='Range', display = display.none) limitLastN = input.bool(true, 'Limit bars', inline='limit', group='Volume Profile', display = display.none) volumeProfileLength = input.int(1000, '', minval=20, step=100, inline='limit', tooltip = 'Limit calculation to last N bars', group='Volume Profile', display = display.none) profileLength = input.int(100, 'Drawing Length', minval=50, step=10, inline='length', group='Volume Profile', tooltip = 'Size of volume profile to be drawn', display = display.none) trendFilter = input.string('any', 'Trend Filter', ['uptrend', 'downtrend', 'any'], 'Trend filter based on the last touch of oscillator', 'tf', 'Volume Profile', display = display.none) profileColor = input.color(color.purple, '', inline='pc', group='Volume Profile', display = display.none) method flush(array<polyline> this)=> while this.size() > 0 this.pop().delete() method add(array<polyline> this, array<chart.point> points)=> ln = polyline.new(points, false, false, xloc.bar_index, color.purple) this.push(ln) points.clear() [osc, overbought, oversold] = eta.oscillator(indicatorType, length, shortLength, longLength, method=rangeMethod, highlowLength=rangeLength, sticky=sticky) type VolumeData float _osc float _volume = volume var array<VolumeData> volumeDataArray = array.new<VolumeData>() method profile(array<VolumeData> this, bool limit = false, bool includeInProfile = true, int length = 20)=> var map<float, float> volumeProfile = map.new<float, float>() if(this.size() > 0 and includeInProfile) last = this.last() if(not na(last._osc)) volumeProfile.put(last._osc, (volumeProfile.contains(last._osc)?volumeProfile.get(last._osc):0.0)+last._volume) if(limit) while(this.size() > length) old = this.shift() volumeProfile.put(old._osc, volumeProfile.get(old._osc)-old._volume) volumeProfile var trend = 0 trend := osc > overbought? 1 : osc < oversold ? -1 : trend includeInProfile = trendFilter == 'any' or (trendFilter == 'uptrend' and trend == 1) or (trendFilter == 'downtrend' and trend == -1) if includeInProfile volumeData = VolumeData.new(math.round(osc, precision), volume*close) volumeDataArray.push(volumeData) volumeProfileData = volumeDataArray.profile(limitLastN, includeInProfile, volumeProfileLength) if(barstate.islast) var profileLineArray = array.new<polyline>() var profilePoints = array.new<chart.point>() profilePoints.clear() profileLineArray.flush() startBar = bar_index +10 keys = volumeProfileData.keys() values = volumeProfileData.values() valueSortKeys = values.sort_indices(order.ascending) for sortedKey in valueSortKeys key = keys.get(sortedKey) value = volumeProfileData.get(key) currentProfileLength = profileLength*value/values.max() endBar = int(startBar + currentProfileLength) profilePoints.push(chart.point.from_index(startBar, key)) if(startBar != endBar) profilePoints.push(chart.point.from_index(endBar, key)) profilePoints.push(chart.point.from_index(startBar, key)) if(profilePoints.size() > 997) profileLineArray.add(profilePoints) profileLineArray.add(profilePoints) plot(osc, 'Oscillator', color.blue) plot(overbought, 'Overbought', color.green) plot(oversold, 'Oversold', color.red)
SuperTrend Toolkit
https://www.tradingview.com/script/dhtT5sK0-SuperTrend-Toolkit/
QuantiLuxe
https://www.tradingview.com/u/QuantiLuxe/
109
study
5
CC-BY-NC-SA-4.0
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © QuantiLuxe //@version=5 indicator("SuperTrend Toolkit", "[Ʌ] -‌ Super Kit", false) type bar float o = na float h = na float l = na float c = na type supertrend float s = na int d = na method src(bar b, simple string src) => float x = switch src 'oc2' => math.avg(b.o, b.c ) 'hl2' => math.avg(b.h, b.l ) 'hlc3' => math.avg(b.h, b.l, b.c ) 'ohlc4' => math.avg(b.o, b.h, b.l, b.c) 'hlcc4' => math.avg(b.h, b.l, b.c, b.c) x method atr(bar b, simple int len) => float tr = na(b.h[1]) ? b.h - b.l : math.max( math.max( b.h - b.l, math.abs(b.h - b.c[1])), math.abs (b.l - b.c[1])) len == 1 ? tr : ta.rma(tr, len) method st(bar b, simple float factor, simple int len) => float atr = b.atr( len ) float up = b.src('hl2') + factor * atr up := up < nz(up[1]) or b.c[1] > nz(up[1]) ? up : nz(up[1]) float dn = b.src('hl2') - factor * atr dn := dn > nz(dn[1]) or b.c[1] < nz(dn[1]) ? dn : nz(dn[1]) float st = na int dir = na dir := switch na(atr[1]) => 1 st[1] == nz(up[1]) => dir := b.c > up ? -1 : +1 => dir := b.c < dn ? +1 : -1 st := dir == -1 ? dn : up supertrend.new(st, dir) var string tp = 'Choose an indicator source of which to base the SuperTrend on.' var string g1 = "SuperTrend Settings", var string gu = "UI Options" src = input.source(close , "Source" , tp , group = g1) len = input.int (10 , "Length" , inline = '1', group = g1) mlt = input.float (5. , "Factor" , 1, 20, 0.5, inline = '1', group = g1) clbl = input.bool (false , "Contrarian Signals", group = gu) colu = input.color (#008cff, "Bull Color" , group = gu) cold = input.color (#ff4800, "Bear Color" , group = gu) bar b = bar.new( nz(src[1]) , math.max(nz(src[1]), src), math.min(nz(src[1]), src), src ) float tr = b .atr( len) supertrend st = b .st (mlt, len) color cst = switch st.d +1 => cold -1 => colu t = plot(st.d > 0 ? st.s : na, 'Bear ST' , cst , 1, plot.style_linebr) d = plot(st.d < 0 ? st.s : na, 'Bull ST' , cst , 1, plot.style_linebr) i = plot(st.d , 'Direction', display = display.none ) c = plot(b.src('oc2') , 'Filler' , display = display.none ) fill(t, c, color.new(cold, 90)) fill(d, c, color.new(colu, 90)) bool scon = clbl and math.sign(ta.change(st.d)) == 1 ? true : false bool bcon = clbl and math.sign(ta.change(st.d)) == -1 ? true : false plotshape(scon ? st.s + tr / 3 : na, 'Sell Signal', shape.labeldown, location.absolute, color.new(cold, 60), 0, '𝓢', chart.fg_color) plotshape(bcon ? st.s - tr / 3 : na, 'Buy Signal' , shape.labelup , location.absolute, color.new(colu, 60), 0, '𝓑', chart.fg_color)
lib_pivot
https://www.tradingview.com/script/IiChJzU6-lib-pivot/
robbatt
https://www.tradingview.com/u/robbatt/
0
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/ // © robbatt //@version=5 // @description Object oriented implementation of Pivot methods. library("lib_pivot", overlay=true) import robbatt/lib_plot_objects/34 as D import robbatt/lib_priceaction/6 as PA //////////////////////////////////////////////////// //#region MODEL //////////////////////////////////////////////////// // @type HLData wraps the data received from ta.highest, ta.highestbars, ta.lowest, ta.lowestbars, as well as the reference sources // @field length lookback length for pivot points // @field highest_offset offset to highest value bar // @field lowest_offset offset to lowest value bar // @field highest highest value within lookback bars // @field lowest lowest value within lookback bars // @field new_highest update() will set this true if the current candle forms a new highest high at the last (current) bar of set period (length) // @field new_lowest update() will set this true if the current candle forms a new lowest low at the last (current) bar of set period (length) // @field new_highest_fractal update() will set this true if the current candle forms a new fractal high at the center of set period (length) // @field new_lowest_fractal update() will set this true if the current candle forms a new fractal low at the center of set period (length) // @field highest_candle ohlc + index data at the bar with the highest value within lookback bars // @field lowest_candle ohlc + index data at the bar with the lowest value within lookback bars // @field highest_point data of the highest point within lookback bars // @field lowest_point data of the lowest point within lookback bars // @field candle_buffer buffers candle data to prevent max_bars_back compiler error (internal use) export type HLData int length = 5 string xloc = xloc.bar_index int highest_offset int lowest_offset float highest float lowest bool new_highest = false bool new_lowest = false bool new_highest_fractal = false bool new_lowest_fractal = false D.Candle highest_candle = na D.Candle lowest_candle = na chart.point highest_point = na chart.point lowest_point = na D.Candle[] candle_buffer = na // @type Pivot colors for different modes // @field hh Color for Pivot mode 2 (HH) // @field lh Color for Pivot mode 1 (LH) // @field hl Color for Pivot mode -1 (HL) // @field ll Color for Pivot mode -2 (LL) export type PivotColors color hh = color.green // mode 2 color lh = color.orange // mode 1 color hl = color.lime // mode -1 color ll = color.red // mode -2 // @type Pivot additional pivot data around basic Point // @field point // @field mode can be -2/-1/1/2 for LL/HL/LH/HH // @field price_movement The price difference between this and the previous pivot point in the opposite direction // @field retracement_ratio The ratio between this price_movement and the previous export type Pivot chart.point point int mode = 1 float price_movement = 0 float retracement_ratio = 0 Pivot prev = na D.Candle candle = na //////////////////////////////////////////////////// //#endregion MODEL //////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region OBJECT INSPECTION / CONVERSION TO JSON read ///////////////////////////////////////////////////////////// // @function Converts HLData to a json string representation // @param this HLData // @param date_format the format for Point bar_time (default: "y-MM-dd HH:mm") // @returns string representation of Pivot export method tostring(HLData this, simple string date_format = "yyyy-MM-dd HH:mm")=> na(this)?'null':'{' + str.format('""length": {0}, "xloc": "{1}"", "highest_offset": {2}, "lowest_offset": {3}, "highest": {4}, "lowest": {5}, "new_highest": {6}, "new_lowest": {7}, "new_highest_fractal": {8}, "new_lowest_fractal": {9}, "highest_point": {10}, "lowest_point": {11}, "highest_candle": {12}, "lowest_candle": {13}', this.length, this.xloc, this.highest_offset, this.lowest_offset, this.highest, this.lowest, this.new_highest, this.new_lowest, this.new_highest_fractal, this.new_lowest_fractal, this.highest_point.tostring(date_format), this.lowest_point.tostring(date_format), this.highest_candle.tostring(date_format), this.lowest_candle.tostring(date_format)) + '}' // @function Converts Pivot to a json string representation // @param this Pivot // @param date_format the format for Point bar_time (default: "y-MM-dd HH:mm") // @returns string representation of Pivot export method tostring(Pivot this, simple string date_format = "yyyy-MM-dd HH:mm") => na(this)?'null':'{' + str.format('"point": {0}, "mode": {1}, "price_movement": {2}, "retracement_ratio": {3}', this.point.tostring(date_format), this.mode, this.price_movement, this.retracement_ratio) + '}' // @function Converts Array of Pivots to a json string representation // @param this Pivot array // @param date_format the format for Point bar_time (default: "y-MM-dd HH:mm") // @returns string representation of Pivot object array export method tostring(array<Pivot> this, simple string date_format = "yyyy-MM-dd HH:mm") => array<string> combinedStr = array.new<string>() if not na(this) for pivot in this combinedStr.push(pivot.tostring(date_format)) '['+array.join(combinedStr, ",")+']' ///////////////////////////////////////////////////////////// //#endregion OBJECT INSPECTION / tostring ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region HELPERS ///////////////////////////////////////////////////////////// //@function returns a color depending on given mode [-2,-1,1,2] export method get_color(PivotColors this, int mode) => switch mode 2 => this.hh 1 => this.lh -1 => this.hl -2 => this.ll => color.gray //@function returns a LineArgs with line_color depending on given mode [-2,-1,1,2] //@field this The PivotColors to chose from //@field mode The selector variable //@field base_line_args The LineArgs, holding the non color related settings export method get_line_args(PivotColors this, int mode, D.LineArgs base_line_args = na) => var default = D.LineArgs.new() args = na(base_line_args) ? default : base_line_args args.copy().set_line_color(this.get_color(mode)) //@function returns a LabelArgs with text_color and bg_color depending on given mode [-2,-1,1,2] //@field this The PivotColors to chose from //@field mode The selector variable //@field base_label_args The LabelArgs, holding the non color related settings //@field bg_colors A second color palette for the label background, if not set, label backgrounds will be transparent export method get_label_args(PivotColors this, int mode, D.LabelArgs base_label_args = na, PivotColors bg_colors = na) => var default = D.LabelArgs.new() args = na(base_label_args) ? default : base_label_args var transparent = PivotColors.new(#00000000, #00000000, #00000000, #00000000) bg_col = na(bg_colors) ? transparent : bg_colors args.copy().set_txt_color(this.get_color(mode)).set_bg_color(bg_col.get_color(mode)).set_style(math.sign(mode) == -1 ? label.style_label_up : label.style_label_down) //@function returns a text depending on mode [-2,-1,1,2] => [LL,HL,LH,HH] export method get_label_text(Pivot this) => switch this.mode 2 => 'HH' 1 => 'LH' -1 => 'HL' -2 => 'LL' => '' // @function mode contains infor about type of the Pivot (HH,LH,HL,LL), this function extracts only the direction (H/L) // @param this Pivot // @returns the signum of the mode (-1,1) export method direction(Pivot this) => na(this) ? 0 : int(math.sign(this.mode)) // @function mode contains infor about type of the Pivot (HH,LH,HL,LL), this function extracts only the direction (H/L) // @param this Pivot // @returns the signum of the mode (-1,1) export method same_direction_as(Pivot this, Pivot other) => na(this) or na(other) ? false : this.direction() == other.direction() // @function multiplies pivot's price with it's direction to allow simplified comparison // @returns product of direction and price level method value(Pivot this) => na(this) ? na : na(this.point) ? na : this.direction() * this.point.price // @function check if a Pivot's price exceeds given price level. Works in both directions (Pivot's direction decides if it has to be greater or less than the price) // @param this Pivot (gives us the pivot price level and direction) // @param price The fix price level to exceed // @returns true if exceeded, false otherwise export method exceeds(Pivot this, float price) => na(this) ? false : this.value() > this.direction() * price // @function check if a Pivot's price level is exceeding the other Pivot's price level. Works in both directions (Pivot's direction decides if it has to be greater or less than the other) // @param this Pivot (gives us the pivot price level and direction) // @param other The other Pivot, whose price level that can be exceeded by this Pivot's price level // @returns true if Pivot price level is exceeding the other Pivot's price level, false otherwise export method exceeds(Pivot this, Pivot other) => na(this) and na(other) ? false : na(other) ? true : na(this) ? false : this.same_direction_as(other) and this.value() > other.value() // @function check if a Pivot's price is exceeded by given price level. Works in both directions (Pivot's direction decides if it has to be greater or less than the price) // @param this Pivot (gives us the pivot price level and direction) // @param price The fix price level that can exceed the Pivot price level // @returns true if Pivot price level is exceeded by given price, false otherwise export method exceeded_by(Pivot this, float price) => na(this) ? true : this.value() <= this.direction() * price // @function check if a Pivot's price level is exceeded by the other Pivot's price level. Works in both directions (Pivot's direction decides if it has to be greater or less than the other) // @param this Pivot (gives us the pivot price level and direction) // @param other The other Pivot, whose price level that can exceed this Pivot's price level // @returns true if Pivot price level is exceeded by other Pivot's price level, false otherwise export method exceeded_by(Pivot this, Pivot other) => na(this) and na(other) ? false : na(this) ? true : na(other) ? false : this.same_direction_as(other) and this.value() <= other.value() // @function check if a Pivot's price level is exceeded by any of the other Pivot's price levels. Works in both directions (Pivot's direction decides if it has to be greater or less than the other) // @param this Pivot (gives us the pivot price level and direction) // @param others The other Pivots, whose price levels can exceed this Pivot's price level // @returns true if Pivot price level is exceeded by any other Pivot's price level, false otherwise export method exceeded_by_any(Pivot this, Pivot[] others) => exceeded = false if not na(this) for p in others if this.exceeded_by(p) exceeded := true break exceeded // @function calculates the retracement ration of this pivot compared to the move between two previous ones // @param this Pivot gives us the current price // @param sec_lastPivot The second to last Pivot, should be in same direction as this one // @param lastPivot The last Pivot, should be in opposite direction to this one // @returns a positive retracement_ratio of the retracement. export method retracement_ratio(Pivot this, Pivot sec_lastPivot, Pivot lastPivot) => float retracement_ratio = na(this) or na(lastPivot) or na(sec_lastPivot) ? na : math.round(PA.retracement_ratio(sec_lastPivot.point.price, lastPivot.point.price, this.point.price), 3) // @function calculate the retracement price level that needs to be reached to achieve the target retracement_ratio // @param this This pivot point, which is the latest fix pivot // @param target_ratio The target retracement retracement_ratio (must be positive) // @returns the retracement target retracement_ratio price level (float) or na if one of the inputs was na export ratio_target(Pivot sec_lastPivot, Pivot lastPivot, float target_ratio) => na(sec_lastPivot) or na(lastPivot) or na(target_ratio) ? na : (lastPivot.point.price + target_ratio * (sec_lastPivot.point.price - lastPivot.point.price)) method rotate(D.Candle[] id, D.Candle item, int max) => id.unshift(item) if id.size() > max id.pop() id export method current_candle(HLData this) => if na(this) ? true : na(this.candle_buffer) ? true : this.candle_buffer.size() == 0 runtime.error('accessed HLData properties before first call to update()') na else this.candle_buffer.get(0) ///////////////////////////////////////////////////////////// //#endregion HELPERS ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region OBJECT UPDATE / update ///////////////////////////////////////////////////////////// method init(HLData this) => var initialized = false if not initialized if na(this.highest_candle) this.highest_candle := D.create_candle() if na(this.lowest_candle) this.lowest_candle := D.create_candle() if na(this.candle_buffer) this.candle_buffer := array.new<D.Candle>() initialized := true this // @function fetches info about highest and lowest values within set length/period, also sets new_xxx flags to indicate conditions for new pivots or fractal confirmation // @param this HLData // @param ref_highest The series highest are calculated on, can be high or low // @param ref_lowest The series lowest are calculated on, can be high or low // @returns self with updated values export method update(HLData this, float ref_highest = high, float ref_lowest = low) => this.init() // offsets are negative, contrary to the offset we have in the ZigZag type and the one we use for the history indicator, so I'm converting this this.highest_offset := -ta.highestbars(ref_highest, this.length) this.lowest_offset := -ta.lowestbars(ref_lowest, this.length) this.highest := ta.highest(ref_highest, this.length) this.lowest := ta.lowest(ref_lowest, this.length) this.new_highest := this.highest_offset == 0 this.new_lowest := this.lowest_offset == 0 this.candle_buffer.rotate(D.Candle.new(time, time_close, bar_index, open, high, low, close, volume), this.length) if this.lowest_offset < this.candle_buffer.size() this.lowest_candle := this.candle_buffer.get(this.lowest_offset) this.lowest_point := na(this.lowest_point) ? chart.point.new(this.lowest_candle.bar_time, this.lowest_candle.bar_idx, this.lowest) : this.lowest_point.update(this.lowest_candle.bar_time, this.lowest_candle.bar_idx, this.lowest) if this.highest_offset < this.candle_buffer.size() this.highest_candle := this.candle_buffer.get(this.highest_offset) this.highest_point := na(this.highest_point) ? chart.point.new(this.highest_candle.bar_time, this.highest_candle.bar_idx, this.highest) : this.highest_point.update(this.highest_candle.bar_time, this.highest_candle.bar_idx, this.highest) var fractal_length = int(this.length / 2) // confirm point as fractal after half of the pivot period / length this.new_highest_fractal := this.highest_offset == fractal_length this.new_lowest_fractal := this.lowest_offset == fractal_length this //@function updates this Pivot's (prev, xloc, price_movement, retracement_ratio and mode) compared to another previous Pivot export method update_relation(Pivot this, Pivot prev) => if not na(this) and not na(prev) this.prev := prev this.price_movement := this.point.price - prev.point.price direction = int(math.sign(this.price_movement)) if direction == 0 direction := prev.direction() != 0 ? -prev.direction() : 1 retracement_ratio_rel = prev.price_movement != 0 ? this.price_movement / prev.price_movement : 0 // avoiding division by 0 this.retracement_ratio := -retracement_ratio_rel hhll = math.abs(direction * -retracement_ratio_rel) > 1 this.mode := int(direction * (hhll ? 2 : 1)) this //@function updates this Pivot's Point coordinates and optional relation to its previous pivot Point export method update(Pivot this, int bar_time, int bar_idx, float price, Pivot prev = na, D.Candle candle = na) => if not na(this) if na(this.point) this.point := chart.point.new(bar_time, bar_idx, price) this.point.update(bar_time, bar_idx, price) if not na(prev) this.update_relation(prev) else // initial just go with bullish this.price_movement := price - this.point.price this.mode := int(math.sign(this.price_movement)) if not na(candle) this.candle := candle this export method update(Pivot this, chart.point update, Pivot prev = na, D.Candle candle = na) => this.update(update.time, update.index, update.price, prev, candle) ///////////////////////////////////////////////////////////// //#endregion OBJECT UPDATE / update ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region OBJECT CREATION / create ///////////////////////////////////////////////////////////// export method create_next(Pivot this, int bar_time, int bar_idx, float price, D.Candle candle = na) => Pivot.new().update(bar_time, bar_idx, price, this, candle) export method create_next(Pivot this, chart.point update, D.Candle candle = na) => Pivot.new().update(update, this, candle) //@function converts Point to Pivot, set it's properties in relation to previously added Pivots (prev, xloc, price_movement, retracement_ratio and mode) and adds it to the array export method add_next(Pivot[] id, chart.point point, int max = 10, D.Candle candle = na) => if not na(id) if id.size() > 0 prev = id.get(0) next = prev.create_next(point, candle) if prev.direction() == next.direction() runtime.error(str.format('Next pivot {0} has the same direction as the previous {1}, use update_last instead of add_next with a new one', next.tostring(), prev.tostring())) id.unshift(next) else id.unshift(Pivot.new().update(point, candle = candle)) if id.size() > max id.pop() id //@function updates latest Pivot in array, in case it's exceeded by the update export method update_last(Pivot[] id, chart.point update, D.Candle candle = na) => if not na(id) and not na(update) if id.size() > 0 last = id.get(0) if last.exceeded_by(update.price) last.update(update, na(last.prev) ? Pivot.new(last.point.copy()) : last.prev, candle) id //@function updates latest Pivot in array, in case it's exceeded by the update price in same direction, else it adds a new Pivot in opposite direciton export method update_last_or_add_next(Pivot[] id, chart.point point, int max = 10, D.Candle candle = na) => if not na(id) and not na(point) if id.size() > 0 Pivot last = id.get(0) if last.exceeded_by(point.price) last.update(point, na(last.prev) ? Pivot.new(last.point.copy()) : last.prev, candle) else id.add_next(point, max, candle) else id.add_next(point, max, candle) id ///////////////////////////////////////////////////////////// //#endregion OBJECT CREATION / create ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region TEST ///////////////////////////////////////////////////////////// import robbatt/lib_log/6 as LOG import robbatt/lib_unit/6 as UNIT var logger = LOG.Logger.new(min_level = 0, color_logs = true, display = LOG.LogDisplay.new(6, position.bottom_left)) var assert = UNIT.Test.new(strict = false, verbose = true, logger = logger) if bar_index == 20000 // regular move p0 = Pivot.new(chart.point.new(time[5], bar_index[5], 150)) logger.debug(p0.tostring()) p1 = p0.create_next(time[4], bar_index[4], 100) logger.debug(p1.tostring()) assert.equals(p1.retracement_ratio, 0, 'expect a 0 retracement ratio after first continuation from 150 to 100') assert.equals(p1.mode, -1, 'expect mode -1 L after first continuation from 150 to 100') assert.equals(p1.price_movement, -50, 'expect -50 price move after first continuation from 150 to 100') p2 = p1.create_next(time[3], bar_index[3], 200) logger.debug(p2.tostring()) assert.equals(p2.retracement_ratio, 2, 'expect 200 to be a 2 retracement ratio after first trend change from 150 to 100 to 200') assert.equals(p2.mode, 2, 'expect 200 to be a mode 2 HH after a move from 150 to 100 to 200') assert.equals(p2.price_movement, 100, 'expect 200 to be a 100 price move after a move from 150 to 100 to 200') p3 = Pivot.new(chart.point.new(time[3], bar_index[3], 1000)).update(time[2], bar_index[2], 150, p2) logger.debug(p3.tostring()) assert.equals(p3.retracement_ratio, 0.5, 'expect 150 to be a 0.5 retracement ratio after a move from 100 to 200') assert.equals(p3.mode, -1, 'expect 150 to be a mode -1 HL after a move from 100 to 200') assert.equals(p3.price_movement, -50, 'expect 150 to be a -50 price move after a move from 100 to 200') // continuation bearish p4 = Pivot.new().update(time[1], bar_index[1], 0, p2) logger.debug(p4.tostring()) assert.equals(p4.retracement_ratio, 2, 'expect 0 to be a 2 retracement ratio after a move from 100 to 200') assert.equals(p4.mode, -2, 'expect 0 to be a mode -2 LL after a move from 100 to 200') assert.equals(p4.price_movement, -200, 'expect 0 to be a -200 price move after a move from 100 to 200') // continuation bearish p5 = Pivot.new().update(time, bar_index, 100, p4) logger.debug(p5.tostring()) assert.equals(p5.retracement_ratio, 0.5, 'expect 100 to be a 0.5 retracement ratio after a move from 200 to 0') assert.equals(p5.mode, 1, 'expect 100 to be a mode 1 LH after a move from 200 to 0') assert.equals(p5.price_movement, 100, 'expect 100 to be a +100 price move after a move from 200 to 0') ///////////////////////////////////////////////////////////// //#endregion TEST ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region DEMO ///////////////////////////////////////////////////////////// var HLData pd = HLData.new(length = 5) var int fractal_offset = 2 // int(pd.length / 2) pd.update(high, low) int max_pivots = 5 var Pivot[] pivots = array.new<Pivot>() var D.Label[] labels = array.new<D.Label>() var D.Line[] lines = array.new<D.Line>() var D.Candle curr_candle = D.create_candle() curr_candle.update() i_add_pivot_at_intermediate_fractal_when_force_adding_pivot = input.bool(true, 'add_pivot_at_intermediate_fractal_when_force_adding_pivot') i_ignore_double_pivots_when_candle_closes_in_trend_direction = input.bool(false, 'ignore_double_pivots_when_candle_closes_in_trend_direction') bool double_pivot = false bool extra_pivot = false bool direction_change = false if pivots.size() < 2 if pd.new_highest pivots.add_next(pd.highest_point, max_pivots) if pd.new_lowest pivots.add_next(pd.lowest_point, max_pivots) else Pivot sec_last = pivots.get(1) Pivot last = pivots.get(0) int trend = last.direction() int bars_since_last = bar_index - last.point.index int bars_since_sec_last = na(sec_last) ? na : bar_index - sec_last.point.index bool candle_in_trend_direction = trend == curr_candle.direction() add_pivot_at_intermediate_fractal_when_force_adding_pivot = i_add_pivot_at_intermediate_fractal_when_force_adding_pivot // changes algorithm to add extra pivots at fractal points when a forced pivot is added ignore_double_pivots_when_candle_closes_in_trend_direction = i_ignore_double_pivots_when_candle_closes_in_trend_direction // changes algorithm to ignore double pivots, when their candle closes in trend direction double_pivot := pd.new_highest and pd.new_lowest and (not ignore_double_pivots_when_candle_closes_in_trend_direction or not candle_in_trend_direction and barstate.isconfirmed) if trend == 1 // force low (sideways, lower highs, no new lowest for trend change) forced_l = not pd.new_lowest and bars_since_last >= pd.length and not last.exceeded_by(pd.highest) and (add_pivot_at_intermediate_fractal_when_force_adding_pivot or pd.new_highest) if forced_l pivots.add_next(pd.lowest_point, max_pivots) direction_change := true // trend continuation if pd.new_highest if forced_l and add_pivot_at_intermediate_fractal_when_force_adding_pivot pivots.add_next(pd.highest_point, max_pivots) extra_pivot := true // trend continuation else if last.exceeded_by(pd.highest) pivots.update_last(pd.highest_point) if pd.new_lowest // double pivot if double_pivot pivots.add_next(pd.lowest_point, max_pivots) direction_change := true double_pivot := true // trend change else if pd.highest_candle.l > pd.lowest pivots.add_next(pd.lowest_point, max_pivots) direction_change := true if trend == -1 // force high (sideways, higher lows, no new highest for trend change) forced_h = not pd.new_highest and bars_since_last >= pd.length and not last.exceeded_by(pd.lowest) and (add_pivot_at_intermediate_fractal_when_force_adding_pivot or pd.new_lowest) if forced_h pivots.add_next(pd.highest_point, max_pivots) direction_change := true if pd.new_lowest // trend change after forced h if forced_h and add_pivot_at_intermediate_fractal_when_force_adding_pivot pivots.add_next(pd.lowest_point, max_pivots) extra_pivot := true // trend continuation else if last.exceeded_by(pd.lowest) pivots.update_last(pd.lowest_point) if pd.new_highest // double pivot if double_pivot pivots.add_next(pd.highest_point, max_pivots) direction_change := true double_pivot := true // trend change else if pd.lowest_candle.h < pd.highest pivots.add_next(pd.highest_point, max_pivots) direction_change := true // update vars for drawing count = pivots.size() live = input.bool(true, 'live plot') var _colors = PivotColors.new() if count >= 3 Pivot last = pivots.get(0) Pivot sec_last = pivots.get(1) Pivot thr_last = pivots.get(2) if live var D.Line current_line = sec_last.point.create_line(last.point).draw() var D.Label current_label = last.point.create_label(last.get_label_text()).draw() // finish previous line and label before switching to double/extra pivot if double_pivot or extra_pivot pivot = extra_pivot ? thr_last : sec_last current_label.txt := pivot.get_label_text() current_label.apply_style(_colors.get_label_args(pivot.mode)).draw() current_line.apply_style(_colors.get_line_args(pivot.mode)).draw(extend_only = false) // continuation of first double pivot as well as pivot before intermediate are confirmed instantly // on dir change create a copy of the old line for the next if direction_change current_line.plot.copy().set_style(line.style_solid) // previous pivot is confirmed current_label.plot.copy() // draw intermediate if extra_pivot current_line.start := thr_last.point current_line.end := sec_last.point current_line.apply_style(_colors.get_line_args(sec_last.mode)).draw(extend_only = false) // itermediate is confirmed instantly current_line.plot.copy() current_label.point := sec_last.point current_label.txt := sec_last.get_label_text() current_label.apply_style(_colors.get_label_args(sec_last.mode)).draw() current_label.plot.copy() // draw last pivot in array current_line.start := sec_last.point current_line.end := last.point current_label.point := last.point current_label.txt := last.get_label_text() current_line.apply_style(_colors.get_line_args(last.mode).set_style(line.style_dashed)).draw(extend_only = false) // new pivot is temporary, make line dashed current_label.apply_style(_colors.get_label_args(last.mode)).draw() else if double_pivot or extra_pivot or direction_change thr_last.point.create_line(sec_last.point).draw(extend_only = false).apply_style(_colors.get_line_args(sec_last.mode)) sec_last.point.create_label(sec_last.get_label_text()).draw().apply_style(_colors.get_label_args(sec_last.mode)) // DEBUG plotshape(pd.new_highest, 'new highest', shape.triangledown, location.abovebar, color.purple, text = 'new highest', size = size.small, display = display.pane + display.data_window) plotshape(pd.new_lowest, 'new lowest', shape.triangleup, location.belowbar, color.blue, text = 'new lowest', size = size.small, display = display.pane + display.data_window) plotshape(pd.new_highest_fractal, 'highest fractal', shape.triangledown, location.abovebar, color.red, size = size.tiny, offset = -fractal_offset, display = display.pane + display.data_window) plotshape(pd.new_lowest_fractal, 'lowest fractal', shape.triangleup, location.belowbar, color.green, size = size.tiny, offset = -fractal_offset, display = display.pane + display.data_window) plotshape(pd.new_highest_fractal, 'new highest fractal', shape.diamond, location.abovebar, color.red, text = 'fractal\nconfirmed', size = size.tiny, display = display.pane + display.data_window) plotshape(pd.new_lowest_fractal, 'new lowest fractal', shape.diamond, location.belowbar, color.green, text = 'fractal\nconfirmed', size = size.tiny, display = display.pane + display.data_window) ///////////////////////////////////////////////////////////// //#endregion DEMO /////////////////////////////////////////////////////////////
gFancyMA
https://www.tradingview.com/script/KgcSguz8-gFancyMA/
GalacticS2021
https://www.tradingview.com/u/GalacticS2021/
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/ // © GalacticS2021 //@version=5 // @description: Contains reusable functions/ labeled moving average library("GalacticS2021", true) // @function : Connects label to ma // @param y : add parameter y coordinate // @param x : add paramete length // @param c : add parameter c add the label color // @param m : add parameter mode of the moving averagee // @param a : add parameter a bool to toggle the ma visibility // @param b : add parameter b bool to toggle the label visibility // @param o : add parameter o bool lablel offset // @returns : function returns the label bool a = true bool b = true color c = na var src = close string m = na float y = na loffset = 5 Xoffset = time_close + loffset * timeframe.multiplier * 60 * 1000 export printLbl(float y,int x,color c,string m,bool b) => var label labelX = na int o = Xoffset if a and b and barstate.isrealtime labelX := label.new(x=o, y=y, xloc=xloc.bar_time,style = label.style_none, textalign=text.align_right,size = size.small) //labelX.set_x(labelX, arg2) label.set_text(labelX, str.tostring(x)+' '+ m) label.set_textcolor(labelX, c) label.delete(labelX[1]) labelX
CandlesGroup_Types
https://www.tradingview.com/script/GhSKKrOj-CandlesGroup-Types/
SteinG
https://www.tradingview.com/u/SteinG/
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/ // © SteinG //@version=5 // @description CandlesGroup Ojbect Type v10 library("CandlesGroup_Types", overlay = true) //#region ****************** CandlesGroup Types ****************** // @type A point on chart // @field price : price value // @field bar : bar index // @field bartime : time in UNIX format of bar export type Point float price int bar int bartime // @type Property object which contains values of all candles // @field name : name of property // @field values : an array stores values of all candles. Size of array = bar_index export type Property string name array<float> values // @type Candles Group object which contains properties of all candles // @field tf : timeframe // @field is_size_increased : if true, size of value array increased at that candle. Default is false // @field propertyNames : an array stores property names. Use as keys to get values // @field properties : array of Property objects export type CandlesGroup string tf = timeframe.period bool is_size_increased = false array<string> propertyNames array<Property> properties //#endregion ****************** //#region ****************** CandlesGroup Methods ****************** export method init(CandlesGroup _self)=> if na(_self.propertyNames) and na(_self.properties) _self.propertyNames := array.from("index", "time", "open", "high", "low", "close", "bodyTop", "bodyBottom", "bodySize", "candleSize", "candleDirection", "oc2" ) _self.properties := array.new<Property>() for i = 0 to _self.propertyNames.size()-1 _self.properties.push(Property.new(_self.propertyNames.get(i), array.new_float())) _self export method init(CandlesGroup _self, string[] propertyNames)=> if na(_self.propertyNames) and na(_self.properties) _self.propertyNames := propertyNames _self.properties := array.new<Property>() for i = 0 to _self.propertyNames.size()-1 _self.properties.push(Property.new(_self.propertyNames.get(i), array.new_float())) _self // @function get values array from a given property name // @param _self : CandlesGroup object // @param key : key name of selected property. Default is "index" // @returns values array export method get(CandlesGroup _self, string key="index")=> propertyID = _self.propertyNames.indexof(key) if propertyID < 0 runtime.error("Get key error. Key not found!") Property property = _self.properties.get(propertyID) property.values // @function get size of values array // @param _self : CandlesGroup object // @returns size of values array export method size(CandlesGroup _self)=>_self.properties.get(0).values.size() // @function get last index of values array // @param _self : CandlesGroup object // @returns last index of values array export method lastIndex(CandlesGroup _self)=> int lastindex = na if _self.size() > 0 lastindex := _self.size()-1 lastindex // @function push single value to specific property // @param _self : CandlesGroup object // @param key : key name of selected property // @param value : property value // @returns CandlesGroup object export method push(CandlesGroup _self, string key, float value)=> _self.get(key).push(value) _self export method push(CandlesGroup _self, array<float> arr)=> if na(_self.properties) runtime.error("Candle Properties not found. Please init() before push!") if arr.size() != _self.propertyNames.size() runtime.error("No. of properties not match!") for i = 0 to arr.size()-1 _self.properties.get(i).values.push(arr.get(i)) _self // @function populate ohlc to CandlesGroup // @param _self : CandlesGroup object // @param ohlc : array of ohlc // @returns CandlesGroup object export method populate(CandlesGroup _self, float[] ohlc)=> if na(ohlc) runtime.error("ohlc not found!") if ohlc.size() != 4 runtime.error("ohlc size must be equal to 4!") _self.init() _open = ohlc.get(0) _high = ohlc.get(1) _low = ohlc.get(2) _close = ohlc.get(3) if not na(_self.propertyNames) and not na(_self.properties) and not (na(_open) or na(_high) or na(_low) or na(_close)) propertyValues = array.from(bar_index, time, _open, _high, _low, _close, math.max(_open, _close), //bodyTop math.min(_open, _close), //bodyBottom math.abs(_open - _close), //bodySize _high - _low, //candleSize _close > _open ? 1 : _close < _open ? -1 : 0, //candleDirection (_open + _close) / 2 //oc2 ) _self.push(propertyValues) _self.is_size_increased := true else _self.is_size_increased := false _self // @function populate values base on given properties Names // @param _self : CandlesGroup object // @param values : array of property values // @param propertiesNames : an array stores property names. Use as keys to get values // @returns CandlesGroup object export method populate(CandlesGroup _self, float[] values, string[] propertiesNames)=> if na(values) runtime.error("values not found!") if na(propertiesNames) runtime.error("propertiesNames not found!") _self.init(propertiesNames) if not na(_self.propertyNames) and not na(_self.properties) propertyValues = values _self.push(propertyValues) _self.is_size_increased := true else _self.is_size_increased := false _self // @function populate values (default setup) // @param _self : CandlesGroup object // @returns CandlesGroup object export method populate(CandlesGroup _self)=> _self.populate(array.from(open, high, low, close)) // @function get property value on previous candles. For current candle, use *.lookback() // @param arr : array of selected property values // @param bars_lookback : number of candles lookback. 0 = current candle. Default is 0 // @returns single property value export method lookback(float[] arr, int bars_lookback=0)=> if arr.size() > bars_lookback arr.get(arr.size() - 1 - bars_lookback) else na // @function get the highest property value between specific candles // @param _self : CandlesGroup object // @param hiSource : key name of selected property // @param start : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true // @param end : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0 // @param useIndex : use index instead of lookback value. Default = false // @returns the highest value within candles export method highest_within_bars(CandlesGroup _self, string hiSource, int start, int end=0, bool useIndex=false)=> int startBar = na int endBar = na if not useIndex _start = start <= 0 ? 0 : start - 1 startBar := _self.lastIndex() - _start endBar := _self.lastIndex() - end else if _self.lastIndex() >= start and _self.lastIndex() >= end and start >= 0 and end >= 0 startBar := start endBar := end float result = na if startBar >= 0 and endBar >= 0 for j = startBar to endBar thisValue = _self.get(hiSource).get(j) if j == startBar result := thisValue continue if result < thisValue result := thisValue result // @function get the highest property value and array index between specific candles // @param _self : CandlesGroup object // @param returnWithIndex : the function only applicable when it is true // @param hiSource : key name of selected property // @param start : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true // @param end : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0 // @param useIndex : use index instead of lookback value. Default = false // @returns [the highest value within candles, Array index of that candle] export method highest_within_bars(CandlesGroup _self, bool returnWithIndex, string hiSource, int start, int end=0, bool useIndex=false)=> int startBar = na int endBar = na if not useIndex _start = start <= 0 ? 0 : start - 1 startBar := _self.lastIndex() - _start endBar := _self.lastIndex() - end else if _self.lastIndex() >= start and _self.lastIndex() >= end and start >= 0 and end >= 0 startBar := start endBar := end float result = na int resultID = na if startBar >= 0 and endBar >= 0 for j = startBar to endBar thisValue = _self.get(hiSource).get(j) if j == startBar resultID := j result := thisValue continue if result < thisValue resultID := j result := thisValue if not returnWithIndex resultID := na [result, resultID] // @function get a Point object which contains highest property value between specific candles // @param _self : CandlesGroup object // @param hiSource : key name of selected property // @param start : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true // @param end : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0 // @param useIndex : use index instead of lookback value. Default = false // @returns Point object contains highest property value export method highest_point_within_bars(CandlesGroup _self, string hiSource, int start, int end=0, bool useIndex=false)=> int startBar = na int endBar = na if not useIndex _start = start <= 0 ? 0 : start - 1 startBar := _self.lastIndex() - _start endBar := _self.lastIndex() - end else if _self.lastIndex() >= start and _self.lastIndex() >= end and start >= 0 and end >= 0 startBar := start endBar := end int pointer = na int resultIndex = na int resultTime = na float result = na if startBar >= 0 and endBar >= 0 for j = startBar to endBar thisIndex = int(_self.get('index').get(j)) thisTime = int(_self.get('time').get(j)) thisValue = _self.get(hiSource).get(j) if j == startBar pointer := j resultIndex := thisIndex resultTime := thisTime result := thisValue continue if result < thisValue pointer := j resultIndex := thisIndex resultTime := thisTime result := thisValue if na(result) or na(pointer) na else Point.new(result, resultIndex, resultTime) // @function get the lowest property value between specific candles // @param _self : CandlesGroup object // @param loSource : key name of selected property // @param start : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true // @param end : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0 // @param useIndex : use index instead of lookback value. Default = false // @returns the lowest value within candles export method lowest_within_bars(CandlesGroup _self, string loSource, int start, int end=0, bool useIndex=false)=> int startBar = na int endBar = na if not useIndex _start = start <= 0 ? 0 : start - 1 startBar := _self.lastIndex() - _start endBar := _self.lastIndex() - end else if _self.lastIndex() >= start and _self.lastIndex() >= end and start >= 0 and end >= 0 startBar := start endBar := end float result = na if startBar >= 0 and endBar >= 0 for j = startBar to endBar thisValue = _self.get(loSource).get(j) if j == startBar result := thisValue continue if result > thisValue result := thisValue result // @function get the lowest property value and array index between specific candles // @param _self : CandlesGroup object // @param returnWithIndex : the function only applicable when it is true // @param loSource : key name of selected property // @param start : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true // @param end : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0 // @param useIndex : use index instead of lookback value. Default = false // @returns [the highest value within candles, Array index of that candle] export method lowest_within_bars(CandlesGroup _self, bool returnWithIndex, string loSource, int start, int end=0, bool useIndex=false)=> int startBar = na int endBar = na if not useIndex _start = start <= 0 ? 0 : start - 1 startBar := _self.lastIndex() - _start endBar := _self.lastIndex() - end else if _self.lastIndex() >= start and _self.lastIndex() >= end and start >= 0 and end >= 0 startBar := start endBar := end float result = na int resultID = na if startBar >= 0 and endBar >= 0 for j = startBar to endBar thisValue = _self.get(loSource).get(j) if j == startBar resultID := j result := thisValue continue if result > thisValue resultID := j result := thisValue if not returnWithIndex resultID := na [result, resultID] // @function get a Point object which contains lowest property value between specific candles // @param _self : CandlesGroup object // @param loSource : key name of selected property // @param start : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true // @param end : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0 // @param useIndex : use index instead of lookback value. Default = false // @returns Point object contains lowest property value export method lowest_point_within_bars(CandlesGroup _self, string loSource, int start, int end=0, bool useIndex=false)=> int startBar = na int endBar = na if not useIndex _start = start <= 0 ? 0 : start - 1 startBar := _self.lastIndex() - _start endBar := _self.lastIndex() - end else if _self.lastIndex() >= start and _self.lastIndex() >= end and start >= 0 and end >= 0 startBar := start endBar := end int pointer = na int resultIndex = na int resultTime = na float result = na if startBar >= 0 and endBar >= 0 for j = startBar to endBar thisIndex = int(_self.get('index').get(j)) thisTime = int(_self.get('time').get(j)) thisValue = _self.get(loSource).get(j) if j == startBar pointer := j resultIndex := thisIndex resultTime := thisTime result := thisValue continue if result > thisValue pointer := j resultIndex := thisIndex resultTime := thisTime result := thisValue if na(result) or na(pointer) na else Point.new(result, resultIndex, resultTime) // @function Convert UNIX time to bar index of active chart // @param _self : CandlesGroup object // @param t : UNIX time // @returns bar index export method time2bar(CandlesGroup _self, int t)=> int result = na start = _self.get('time').size() - 1 end = 0 tf = timeframe.in_seconds() t_by_tf = math.floor(t / 1000 / tf) for i = start to end element = math.floor(_self.get('time').get(i) / 1000 / tf) if(t_by_tf == element) result := int(_self.get('index').get(i)) break if na(result) runtime.error("Bar index not found!") int(result) // @function Convert timestamp to bar index of active chart. User defined timezone required // @param _self : CandlesGroup object // @param timezone : User defined timezone // @param YYYY : Year // @param MMM : Month // @param DD : Day // @param hh : Hour. Default is 0 // @param mm : Minute. Default is 0 // @param ss : Second. Default is 0 // @returns bar index export method time2bar(CandlesGroup _self, string timezone, int YYYY, int MMM, int DD, int hh=0, int mm=0, int ss=0)=> _self.time2bar(timestamp(timezone,YYYY,MMM,DD,hh,mm,ss)) // @function Convert timestamp to bar index of active chart // @param _self : CandlesGroup object // @param YYYY : Year // @param MMM : Month // @param DD : Day // @param hh : Hour. Default is 0 // @param mm : Minute. Default is 0 // @param ss : Second. Default is 0 // @returns bar index export method time2bar(CandlesGroup _self, int YYYY, int MMM, int DD, int hh=0, int mm=0, int ss=0)=> _self.time2bar(syminfo.timezone, YYYY, MMM, DD, hh, mm, ss) // @function Convert bar index of active chart to UNIX time // @param _self : CandlesGroup object // @param index : bar index // @returns UNIX time export method bar2time(CandlesGroup _self, int index)=> int(_self.get('time').get(index)) // @function Get array index of CandlesGroup from bar index of active chart // @param _self : CandlesGroup object // @param index : bar index // @returns array index export method bar2arrID(CandlesGroup _self, int index)=> int result = na start = _self.get('index').size() - 1 end = 0 for i = start to end element = int(_self.get('index').get(i)) if(index == element) result := i break if na(result) runtime.error("ArrayID not found!") result // @function Get array index of CandlesGroup from UNIX time // @param _self : CandlesGroup object // @param t : UNIX time // @returns array index export method time2arrID(CandlesGroup _self, int t)=> int result = na start = _self.get('time').size() - 1 end = 0 for i = start to end element = int(_self.get('time').get(i)) if(t == element) result := i break if na(result) runtime.error("ArrayID not found!") result // @function get single property value from UNIX time // @param _self : CandlesGroup object // @param key : key name of selected property // @param t : UNIX time // @returns single property value export method get_prop_from_time(CandlesGroup _self, string key, int t)=>_self.get(key).get(_self.time2arrID(t)) // @function get single property value from timestamp. User defined timezone required // @param _self : CandlesGroup object // @param key : key name of selected property // @param timezone : User defined timezone // @param YYYY : Year // @param MMM : Month // @param DD : Day // @param hh : Hour. Default is 0 // @param mm : Minute. Default is 0 // @param ss : Second. Default is 0 // @returns single property value export method get_prop_from_time(CandlesGroup _self, string key, string timezone, int YYYY, int MMM, int DD, int hh=0, int mm=0, int ss=0)=> _self.get_prop_from_time(key, timestamp(timezone,YYYY,MMM,DD,hh,mm,ss)) // @function get single property value from timestamp // @param _self : CandlesGroup object // @param key : key name of selected property // @param YYYY : Year // @param MMM : Month // @param DD : Day // @param hh : Hour. Default is 0 // @param mm : Minute. Default is 0 // @param ss : Second. Default is 0 // @returns single property value export method get_prop_from_time(CandlesGroup _self, string key, int YYYY, int MMM, int DD, int hh=0, int mm=0, int ss=0)=> _self.get_prop_from_time(key, syminfo.timezone, YYYY, MMM, DD, hh, mm, ss) // @function The sma function returns the moving average // @param _self : CandlesGroup object // @param key : key name of selected property // @param length : number of bars // @returns float value export method sma(CandlesGroup _self, string key, int length)=> srcArr = _self.get(key) float result = na if srcArr.size() > length - 1 sum = 0.0 for i = 0 to length - 1 sum := sum + srcArr.lookback(i) / length result := sum result // @function The ema function returns the exponentially weighted moving average. // @param _self : CandlesGroup object // @param key : key name of selected property // @param length : number of bars // @returns float value export method ema(CandlesGroup _self, string key, int length)=> srcArr = _self.get(key) alpha = 2 / (length + 1) start = length * 10 float result = na if srcArr.size() > start float ema = na for i = start to 0 if na(ema) ema := srcArr.lookback(i) continue ema := alpha * srcArr.lookback(i) + (1 - alpha) * nz(ema) result := ema result method rma(array<float> src, int length)=> float result = na if src.size() > 0 alpha = 1 / length float rma = na for i = 0 to src.size()-1 element = src.get(i) if i == 0 rma := element continue rma := alpha * src.get(i) + (1 - alpha) * nz(rma) result := rma result // @function Relative Moving Average. Precision up to 4 s.f. // @param _self : CandlesGroup object // @param key : key name of selected property // @param length : number of bars // @returns float value export method rma(CandlesGroup _self, string key, int length)=> srcArr = _self.get(key) alpha = 1 / length start = length * 10 float result = na if srcArr.size() > start float rma = na for i = start to 0 if na(rma) rma := _self.sma(key,length) continue rma := alpha * srcArr.lookback(i) + (1 - alpha) * nz(rma) result := rma result // @function True range // @param _self : CandlesGroup object // @param offset : history bar offset. Default is 0 // @returns float value export method tr(CandlesGroup _self, int offset=0)=> float result = na if _self.size() == 1 result := _self.get('high').lookback(offset) - _self.get('low').lookback(offset) else if _self.size() > 1 result := math.max(_self.get('high').lookback(offset) - _self.get('low').lookback(offset), math.abs(_self.get('high').lookback(offset) - _self.get('close').lookback(offset+1)), math.abs(_self.get('low').lookback(offset) - _self.get('close').lookback(offset+1)) ) result // @function Average true range returns the RMA of true range. Precision up to 4 s.f. // @param _self : CandlesGroup object // @param length : number of bars // @returns float value export method atr(CandlesGroup _self, int length)=> float result = na array<float> trArr = array.new_float() start = length * 10 if _self.size() > start for i = start to 0 tr = _self.tr(i) trArr.push(tr) result := trArr.rma(length) result //#endregion ****************** //#region ———————————————————————————————————————————————————————————— Usage & Examples ———————————————————————————————————————————————————————————— // //declare and init CandlesGroup ojbect // var candles = CandlesGroup.new() // candles.populate() // //These are the same // high10 = high[10] // obj_high10 = candles.get('high').lookback(10) // plot(high10, "high10", color.new(#002FFF,0)) // plot(obj_high10, "high10", color.new(#00FF15,0)) // //These are the same // ta_sma_close20 = ta.sma(close, 20) // obj_sma_close20 = ta.sma(candles.get('close').lookback(), 20) // plot(ta_sma_close20, "ta_sma_close20", color.new(#FFD000,0)) // plot(obj_sma_close20, "obj_sma_close20", color.new(#00F7FF,0)) // //You can use a very large lookback value // ta_sma_low2000 = ta.sma(low, 2000) // obj_sma_low2000 = ta.sma(candles.get('low').lookback(), 2000) // plot(ta_sma_low2000, "ta_sma_low2000", color.new(#C300FF,0)) // plot(obj_sma_low2000, "obj_sma_low2000", color.new(#EEFF00,0)) // //These are the same // ta_highest_10 = ta.highest(high, 10) // obj_highest_10 = candles.highest_within_bars('high', 10) // plot(ta_highest_10, "ta_highest_10", color.new(#61B0DD,0)) // plot(obj_highest_10, "obj_highest_10", color.new(#9CDF30,0)) // //These are the same // ta_lowestbars_20 = ta.lowestbars(low, 20) // [obj_lowestbars_20_value ,obj_lowestbars_20_ID] = candles.lowest_within_bars(true, 'low', 20) // plot(low[-ta_lowestbars_20], "ta_lowestbars_20", color.new(#46D1A3,0), style=plot.style_stepline) // plot(low[bar_index - obj_lowestbars_20_ID], "obj_lowestbars_20", color.new(#DAB03C,0), style=plot.style_stepline) // //These are the same // ta_highest_10_20 = ta.highest(high, 10)[10] // obj_highest_10_20 = candles.highest_within_bars('high', 20, 10) // plot(ta_highest_10_20, "ta_highest_10_20", color.new(#3D11B8,0)) // plot(obj_highest_10_20, "obj_highest_10_20", color.new(#00FF37,0)) // //CandlesGroup types do not have local scope issue. They are explicitly stored in global scope // l1_x1 = bar_index + ta.highestbars(high, 10) // l1_x2 = bar_index + ta.lowestbars(high, 20) // l1_y1 = ta.highest(high,10) // l1_y2 = ta.lowest(20) // if barstate.islast // //This line drawn correctly by using global scope param // var l1 = line.new(l1_x1, l1_y1, l1_x2, l1_y2, xloc.bar_index, color=color.new(#FF0000, 0), width=2) // //This line drawn incorrectly by using local scope param // var l2 = line.new(bar_index+ta.highestbars(high, 10), ta.highest(high,10), // bar_index+ta.lowestbars(high, 20), ta.lowest(20), // xloc.bar_index, color=color.new(#91FF00, 0), width=3) // //You can call CandlesGroup methods in local scope directly // var l3 = line.new(candles.highest_point_within_bars('high',10).bar, candles.highest_point_within_bars('high',10).price, // candles.lowest_point_within_bars('low',20).bar, candles.lowest_point_within_bars('low',20).price, // xloc.bar_index, color=color.new(#00F7FF, 70), width=7) // //You can get any candle properties by timestamp // if barstate.islast // t = timestamp(2023,7,12,10,34) // var lbl1 = label.new(int(candles.get_prop_from_time('index',t)), // candles.get_prop_from_time('high',t), // str.format_time(int(candles.get_prop_from_time('time',t)), "YYYY/MM/dd HH:mm", syminfo.timezone), // xloc.bar_index, // yloc.price, // color.white) // //populate candlesGroup using data of current timeframe by request.security() // [o1, h1, l1, c1] = request.security(syminfo.tickerid, timeframe.period, [open, high, low, close], barmerge.gaps_on, barmerge.lookahead_off) // var candles_1 = CandlesGroup.new() // candles_1.populate(array.from(o1, h1, l1, c1)) // plot(candles_1.get('high').lookback(), "candles_1m_high", color.new(#D1E049,0),style=plot.style_stepline) // plot(candles_1.get('low').lookback(), "candles_1m_low", color.new(#00CCFF,0),style=plot.style_stepline) // //You can declare a new CandlesGroup which contains other timeframe data // tf_30m = '30' // [o30m, h30m, l30m, c30m] = request.security(syminfo.tickerid, tf_30m, [open[1], high[1], low[1], close[1]], barmerge.gaps_on, barmerge.lookahead_on) // var candles_30m = CandlesGroup.new(tf_30m) // candles_30m.populate(array.from(o30m, h30m, l30m, c30m)) // plot(candles_30m.get('high').lookback(), "candles_30m_high", color.new(#D1E049,0),style=plot.style_stepline) // plot(candles_30m.get('low').lookback(), "candles_30m_low", color.new(#00CCFF,0),style=plot.style_stepline) // plot(candles_30m.is_size_increased ? 1 : 0, "is_size_increased", color.new(#FF1E00,0), display=display.status_line) // //You can get any HTF candles' properties by timestamp // if barstate.islast // t = timestamp(2023,10,10,15,00) // var lbl1 = label.new(int(candles_30m.get_prop_from_time('index',t)), // candles_30m.get_prop_from_time('high',t), // str.format_time(int(candles_30m.get_prop_from_time('time',t)), "YYYY/MM/dd HH:mm", syminfo.timezone), // xloc.bar_index, // yloc.price, // color.white) // //handling other timeframe data // ta_highest_5_30m = request.security(syminfo.tickerid, '30', ta.highest(high, 5)[1], barmerge.gaps_on, barmerge.lookahead_on) // [obj_highest_5_30m_value ,obj_highest_5_30m_ID] = candles_30m.highest_within_bars(true, 'high', 5) // Point pt_highest_5_30m = candles_30m.highest_point_within_bars('high', 5) // float series_pt_highest_5_30m = na // if not na(pt_highest_5_30m) // series_pt_highest_5_30m := pt_highest_5_30m.price // plot(ta_highest_5_30m, "ta_highest_5_30m", color.new(#46D1A3,0), style=plot.style_stepline_diamond) // plot(obj_highest_5_30m_value, "obj_highest_5_30m_value", color.new(#933CDA,0), style=plot.style_stepline) // plot(series_pt_highest_5_30m, "pt_highest_5_30m",color.new(#E28D8D,0),style=plot.style_stepline_diamond) // if barstate.islast // var pt_high_lbl = label.new( // x = na, // y = na, // xloc = xloc.bar_index, // yloc = yloc.price, // textcolor = color.white // ) // pt_high_lbl.set_x(pt_highest_5_30m.bar) // pt_high_lbl.set_y(series_pt_highest_5_30m) // pt_high_lbl.set_text("Price : "+str.tostring(series_pt_highest_5_30m)+ // "\nBar Index : "+str.tostring(pt_highest_5_30m.bar)+ // "\nBar Time : "+str.format_time(pt_highest_5_30m.bartime,"Y/M/d HH:mm",syminfo.timezone) // ) // ta_lowest_5_30m = request.security(syminfo.tickerid, '30', ta.lowest(low, 5)[1], barmerge.gaps_on, barmerge.lookahead_on) // [obj_lowest_5_30m_value ,obj_lowest_5_30m_ID] = candles_30m.lowest_within_bars(true, 'low', 5) // Point pt_lowest_5_30m = candles_30m.lowest_point_within_bars('low', 5) // float series_pt_lowest_5_30m = na // if not na(pt_lowest_5_30m) // series_pt_lowest_5_30m := pt_lowest_5_30m.price // plot(ta_lowest_5_30m, "ta_lowest_5_30m", color.new(#46D1A3,0), style=plot.style_stepline_diamond) // plot(obj_lowest_5_30m_value, "obj_lowest_5_30m_value", color.new(#933CDA,0), style=plot.style_stepline) // plot(series_pt_lowest_5_30m, "pt_lowest_5_30m",color.new(#E28D8D,0),style=plot.style_stepline_diamond) // if barstate.islast // var pt_low_lbl = label.new( // x = na, // y = na, // xloc = xloc.bar_index, // yloc = yloc.price, // style = label.style_label_up, // textcolor = color.white // ) // pt_low_lbl.set_x(pt_lowest_5_30m.bar) // pt_low_lbl.set_y(series_pt_lowest_5_30m) // pt_low_lbl.set_text("Price : "+str.tostring(series_pt_lowest_5_30m)+ // "\nBar Index : "+str.tostring(pt_lowest_5_30m.bar)+ // "\nBar Time : "+str.format_time(pt_lowest_5_30m.bartime,"Y/M/d HH:mm",syminfo.timezone) // ) // ta_highestbars_5_30m = request.security(syminfo.tickerid, '30', ta.highestbars(high, 5)[1], barmerge.gaps_on, barmerge.lookahead_on) // [obj_highestbars_5_30m_value ,obj_highestbars_5_30m_ID] = candles_30m.highest_within_bars(true, 'high', 5) // plot(-ta_highestbars_5_30m, "ta_highestbars_5_30m", color.new(#46D1A3,0), style=plot.style_stepline_diamond) // plot(candles_30m.lastIndex() - obj_highestbars_5_30m_ID, "obj_highestbars_5_30m", color.new(#DAB03C,0), style=plot.style_stepline) // ta_lowestbars_5_30m = request.security(syminfo.tickerid, '30', ta.lowestbars(low, 5)[1], barmerge.gaps_on, barmerge.lookahead_on) // [obj_lowestbars_5_30m_value ,obj_lowestbars_5_30m_ID] = candles_30m.lowest_within_bars(true, 'low', 5) // plot(-ta_lowestbars_5_30m, "ta_lowestbars_5_30m", color.new(#46D1A3,0), style=plot.style_stepline_diamond) // plot(candles_30m.lastIndex() - obj_lowestbars_5_30m_ID, "obj_lowestbars_5_30m", color.new(#DAB03C,0), style=plot.style_stepline) // //You can get array index of candlesGroup of other timeframe by bar_index // if candles_30m.size() > 5 // test_bar = int(candles_30m.get('index').lookback(5)) // arrID = candles_30m.bar2arrID(test_bar) // var lbl2 = label.new(na,na,"",xloc.bar_index,yloc.price,color.white) // lbl2.set_xy(int(candles_30m.get('index').get(arrID)), candles_30m.get('high').get(arrID)) // lbl2.set_text("test_bar :"+str.tostring(test_bar)+"\nArrayID : "+str.tostring(arrID)+"\nbar_index : "+str.tostring(int(candles_30m.get('index').get(arrID)))) // //You can get array index of candlesGroup of other timeframe by UNIX time // if candles_30m.size() > 10 // test_time = int(candles_30m.get('time').lookback(10)) // arrID = candles_30m.time2arrID(test_time) // var lbl3 = label.new(na,na,"",xloc.bar_index,yloc.price,color.white) // lbl3.set_xy(int(candles_30m.get('index').get(arrID)), candles_30m.get('high').get(arrID)) // lbl3.set_text("test_time :"+str.format_time(test_time,"YYYY/MM/dd HH:mm", syminfo.timezone)+ // "\nArrayID : "+str.tostring(arrID)+"\ntime : "+ // str.format_time(int(candles_30m.get('time').get(arrID)),"YYYY/MM/dd HH:mm", syminfo.timezone)) // //These are the T.A. methods for multi-timeframe // ta_sma_close20 = request.security(syminfo.tickerid, '30', ta.sma(close,20)[1], barmerge.gaps_on, barmerge.lookahead_on) // obj_sma_close20 = candles_30m.sma('close',20) // plot(ta_sma_close20, "ta_sma_close20", color.new(#002FFF,0),style=plot.style_stepline_diamond) // plot(obj_sma_close20, "obj_sma_close20", color.new(#00FF15,0),style=plot.style_stepline_diamond) // ta_ema_close20 = request.security(syminfo.tickerid, '30', ta.ema(close, 20)[1], barmerge.gaps_on, barmerge.lookahead_on) // obj_ema_close20 = candles_30m.ema('close',20) // plot(ta_ema_close20, "ta_ema_close20", color.new(#002FFF,0),style=plot.style_stepline_diamond) // plot(obj_ema_close20, "obj_ema_close20", color.new(#00FF15,0),style=plot.style_stepline_diamond) // ta_rma_close20 = request.security(syminfo.tickerid, '30', ta.rma(close, 20)[1], barmerge.gaps_on, barmerge.lookahead_on) // obj_rma_close20 = candles_30m.rma('close',20) // plot(ta_rma_close20, "ta_rma_close20", color.new(#002FFF,0),style=plot.style_stepline_diamond) // plot(obj_rma_close20, "obj_rma_close20", color.new(#00FF15,0),style=plot.style_stepline_diamond) // ta_tr_close20 = request.security(syminfo.tickerid, '30', ta.tr(true)[1], barmerge.gaps_on, barmerge.lookahead_on) // obj_tr_close20 = candles_30m.tr() // plot(ta_tr_close20, "ta_tr_close20", color.new(#002FFF,0),style=plot.style_stepline_diamond) // plot(obj_tr_close20, "obj_tr_close20", color.new(#00FF15,0),style=plot.style_stepline_diamond) // ta_atr_close20 = request.security(syminfo.tickerid, '30', ta.atr(20)[1], barmerge.gaps_on, barmerge.lookahead_on) // obj_atr_close20 = candles_30m.atr(20) // plot(ta_atr_close20, "ta_atr_close20", color.new(#002FFF,0),style=plot.style_stepline_diamond) // plot(obj_atr_close20, "obj_atr_close20", color.new(#00FF15,0),style=plot.style_stepline_diamond) // //A table showing all property values in CandlesGroup // testGroup = candles_30m // Candle_showStats = input.bool(true, 'Show Table', group='Candle Info Table', inline='s2') // CandletblPosition = input.string(position.top_right, '', group='Candle Info Table', options=[position.top_right, position.bottom_right, position.top_center, position.top_left, position.bottom_left], inline='s2') // Candle_debugtbl_textSize = input.string(size.small, '', group='Candle Info Table', options=[size.tiny, size.small, size.normal, size.large, size.huge], inline='s2') // candle_info_title_color = color.maroon // candle_info_title_txt_color = color.white // candle_info_no_color = #8BE8FF // candle_info_id_color = #12B7E9 // candle_info_cell_color = #293001 // candle_info_cell_txt_color = color.white // if(barstate.islast and Candle_showStats) // var Candle_debugTbl = table.new(position = CandletblPosition, columns = 15, rows = 21 , border_color=color.black, border_width=2) // //header // headerTextArr = array.from("No.", // "Array INDEX", // "bar_index", // "DIST", // "DATETIME", // "OPEN", // "HIGH", // "LOW", // "CLOSE", // "BODY TOP", // "BODY BOTTOM", // "BODY SIZE", // "CANDLE SIZE", // "CANDLE\nDIRECTION", // "(OPEN+CLOSE)/2" // ) // for i = 0 to headerTextArr.size()-1 // table.cell(Candle_debugTbl, i, 0, headerTextArr.get(i), bgcolor=candle_info_title_color, text_color=candle_info_title_txt_color, text_size=Candle_debugtbl_textSize) // //total inventory <= 20 // if testGroup.size() > 0 and testGroup.size() <= 20 // for i = 0 to testGroup.size() - 1 // //cell values // _str_no = str.tostring(i+1) // _str_arryID = str.tostring(testGroup.lastIndex()-i) // _str_bar_index = str.tostring(testGroup.get().lookback(i)) // _str_dist = str.tostring(bar_index - testGroup.get().lookback(i)) // _str_datetime = str.format_time(int(testGroup.get("time").lookback(i)), "Y/M/d HH:mm", syminfo.timezone) // _str_open = str.tostring(testGroup.get("open").lookback(i)) // _str_high = str.tostring(testGroup.get("high").lookback(i)) // _str_low = str.tostring(testGroup.get("low").lookback(i)) // _str_close = str.tostring(testGroup.get("close").lookback(i)) // _str_bodyTop = str.tostring(testGroup.get("bodyTop").lookback(i)) // _str_bodyBottom = str.tostring(testGroup.get("bodyBottom").lookback(i)) // _str_bodySize = str.tostring(testGroup.get("bodySize").lookback(i)) // _str_candleSize = str.tostring(testGroup.get("candleSize").lookback(i)) // _str_candleDir = str.tostring(testGroup.get("candleDirection").lookback(i)) // _str_oc2 = str.tostring(testGroup.get("oc2").lookback(i)) // cellTextArr = array.from(_str_no, // _str_arryID, // _str_bar_index, // _str_dist, // _str_datetime, // _str_open, // _str_high, // _str_low, // _str_close, // _str_bodyTop, // _str_bodyBottom, // _str_bodySize, // _str_candleSize, // _str_candleDir, // _str_oc2 // ) // //populate cells // for j = 0 to cellTextArr.size()-1 // table.cell(Candle_debugTbl, j, i+1, cellTextArr.get(j), bgcolor=candle_info_cell_color, text_color=candle_info_cell_txt_color, text_size=Candle_debugtbl_textSize) // //specific column color // table.cell_set_bgcolor(Candle_debugTbl, 0, i+1, candle_info_no_color) // table.cell_set_bgcolor(Candle_debugTbl, 1, i+1, candle_info_id_color) // table.cell_set_bgcolor(Candle_debugTbl, 2, i+1, candle_info_no_color) // table.cell_set_bgcolor(Candle_debugTbl, 3, i+1, candle_info_id_color) // for k = 0 to 3 // table.cell_set_text_color(Candle_debugTbl, k, i+1, color.black) // //total inventory > 20 // else if testGroup.size() > 0 // for i = 0 to testGroup.size() - 1 // if i >= 20 // break // //cell values // _str_no = str.tostring(i+1) // _str_arryID = str.tostring(testGroup.lastIndex()-i) // _str_bar_index = str.tostring(testGroup.get().lookback(i)) // _str_dist = str.tostring(bar_index - testGroup.get().lookback(i)) // _str_datetime = str.format_time(int(testGroup.get("time").lookback(i)), "Y/M/d HH:mm", syminfo.timezone) // _str_open = str.tostring(testGroup.get("open").lookback(i)) // _str_high = str.tostring(testGroup.get("high").lookback(i)) // _str_low = str.tostring(testGroup.get("low").lookback(i)) // _str_close = str.tostring(testGroup.get("close").lookback(i)) // _str_bodyTop = str.tostring(testGroup.get("bodyTop").lookback(i)) // _str_bodyBottom = str.tostring(testGroup.get("bodyBottom").lookback(i)) // _str_bodySize = str.tostring(testGroup.get("bodySize").lookback(i)) // _str_candleSize = str.tostring(testGroup.get("candleSize").lookback(i)) // _str_candleDir = str.tostring(testGroup.get("candleDirection").lookback(i)) // _str_oc2 = str.tostring(testGroup.get("oc2").lookback(i)) // cellTextArr = array.from(_str_no, // _str_arryID, // _str_bar_index, // _str_dist, // _str_datetime, // _str_open, // _str_high, // _str_low, // _str_close, // _str_bodyTop, // _str_bodyBottom, // _str_bodySize, // _str_candleSize, // _str_candleDir, // _str_oc2 // ) // //populate cells // for j = 0 to cellTextArr.size()-1 // table.cell(Candle_debugTbl, j, i+1, cellTextArr.get(j), bgcolor=candle_info_cell_color, text_color=candle_info_cell_txt_color, text_size=Candle_debugtbl_textSize) // //specific column color // table.cell_set_bgcolor(Candle_debugTbl, 0, i+1, candle_info_no_color) // table.cell_set_bgcolor(Candle_debugTbl, 1, i+1, candle_info_id_color) // table.cell_set_bgcolor(Candle_debugTbl, 2, i+1, candle_info_no_color) // table.cell_set_bgcolor(Candle_debugTbl, 3, i+1, candle_info_id_color) // for k = 0 to 3 // table.cell_set_text_color(Candle_debugTbl, k, i+1, color.black) //#endregion ————————————————————
ATR_Info
https://www.tradingview.com/script/dlUKaSL2-atr-info/
aks_v
https://www.tradingview.com/u/aks_v/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © aks_v //@version=5 // @description ATR_Info: Calculates ATR without paranormal bars library("ATR_Info", overlay = true) // @function ATR_WPB: Calculates ATR without paranormal bars // @param source ATR_WPB: (series float) The sequence of data on the basis of which the ATP calculation will be made // @param period ATR_WPB: (int) Sequence size for ATR calculation // @param psmall ATR_WPB: (float) Coefficient for paranormally small bar // @param pbig ATR_WPB: (float) Coefficient for paranormally big bar // @returns ATR_WPB: (float) ATR without paranormal bars export ATR_WPB(series float source, int period, float psmall, float pbig) => MaxLoop = period * 2 avg = ta.sma(source[1], MaxLoop) for n = 1 to 3 by 1 nsource = array.new_float(0) for i = 1 to MaxLoop by 1 if source[i] / pbig < avg and source[i] * psmall < avg array.push(nsource, source[i]) if array.size(nsource) >= period break navg = array.avg(nsource) if navg == avg break avg := navg avg // Example code var string GP1 = "ATR parametrs" NumBars = input(5, title='Number of bars to calculate', group = GP1) SizePrnlSmall = input(0.7, title='Size paranormally small bar', group = GP1) SizePrnlLarge = input(1.8, title='Size paranormally large bar', group = GP1) var string GP2 = "Display" string tableYposInput = input.string("top", "Panel position", inline = "11", options = ["top", "middle", "bottom"], group = GP2, display = display.none) string tableXposInput = input.string("right", "", inline = "11", options = ["left", "center", "right"], group = GP2, display = display.none) color bullColorInput = input.color(color.new(color.green, 30), "Bull", inline = "12", group = GP2) color bearColorInput = input.color(color.new(color.red, 30), "Bear", inline = "12", group = GP2) // If the last bar is considered closed, then we take it into account, otherwise we ignore Offset = barstate.islast and barstate.isconfirmed ? 0 : 1 ATR = ATR_WPB(ta.tr[Offset], NumBars, SizePrnlSmall, SizePrnlLarge) // Get the ATR value DailyATR = request.security(syminfo.tickerid, "1D", ATR) // Get daily the ATR value DailyClose = request.security(syminfo.tickerid, "1D", close) // Get daily the Close value PTR = math.round(ta.tr/DailyATR*100) // Percent TrueRunge completed by ATR FilledATR_WPB =math.abs(DailyClose[1]-close) // Current value of ATR PFilledATR_WPB =math.round(100*FilledATR_WPB/DailyATR) // Percent MaxFilledATR = math.abs(((close > close[1]) ? high : low) - close[1]) // How much did the ATR go to the maximum PMaxFilledATR = math.round(100*MaxFilledATR/DailyATR) // Plot table with data row = 0 var table panel = table.new(tableYposInput + "_" + tableXposInput, 2, 5) if barstate.islast // Table data row += 1 table.cell(panel, 0, row, "ATR:", text_halign = text.align_left, text_size = size.normal) table.cell(panel, 1, row, str.tostring(DailyATR), text_halign = text.align_left, text_size = size.normal) if (timeframe.isdwm) row += 1 table.cell(panel, 0, row, "True Range:", text_halign = text.align_left, text_size = size.small) table.cell(panel, 1, row, str.tostring(ta.tr) + " (" + str.tostring(PTR) + "%)", bgcolor = color.new(PTR < 50 ? bullColorInput : bearColorInput, 80), text_halign = text.align_left, text_size = size.small) row += 1 table.cell(panel, 0, row, "Filled ATR:", text_halign = text.align_left, text_size = size.small) table.cell(panel, 1, row, str.tostring(FilledATR_WPB) + " (" + str.tostring(PFilledATR_WPB) + "%)", bgcolor = color.new(PFilledATR_WPB < 50 ? bullColorInput : bearColorInput, 80), text_halign = text.align_left, text_size = size.small) if (timeframe.isdwm) row += 1 table.cell(panel, 0, row, "Max filled ATR:", text_halign = text.align_left, text_size = size.small) table.cell(panel, 1, row, str.tostring(MaxFilledATR) + " (" + str.tostring(PMaxFilledATR) + "%)", bgcolor = color.new(MaxFilledATR < 50 ? bullColorInput : bearColorInput, 80), text_halign = text.align_left, text_size = size.small)
Stablecoin Supply Ratio Oscillator
https://www.tradingview.com/script/4yIVcZS3-Stablecoin-Supply-Ratio-Oscillator/
QuantiLuxe
https://www.tradingview.com/u/QuantiLuxe/
234
study
5
CC-BY-NC-SA-4.0
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © EliCobra //@version=5 indicator("Stablecoin Supply Ratio Oscillator", "[Ʌ] -‌ SSRO", false) type bar float o = open float h = high float l = low float c = close method src(bar b, simple string src) => float x = switch src 'oc2' => math.avg(b.o, b.c ) 'hl2' => math.avg(b.h, b.l ) 'hlc3' => math.avg(b.h, b.l, b.c ) 'ohlc4' => math.avg(b.o, b.h, b.l, b.c) 'hlcc4' => math.avg(b.h, b.l, b.c, b.c) x method data(simple string coin) => bar x = request.security('CRYPTOCAP:' + coin, '', bar.new()) na(x) ? bar.new(0, 0, 0, 0) : x method srcget(array<bar> stbl, string src) => array<float> srcs = array.new<float>() for coin in stbl val = switch src 'o' => coin.o 'h' => coin.h 'l' => coin.l 'c' => coin.c srcs.unshift(val) srcs method ssro(float src, array<float> stblsrc, simple int len) => float ssr = src / stblsrc.sum() (ssr - ta.sma(ssr, len)) / ta.stdev(ssr, len) method adj(color col, simple int lvl) => color x = color.new(col, lvl) x var string gs = 'SSRO', var string gc = 'Colors' len = input.int (200 , "Length" , group = gs) chart = input.bool (true , "Use Chart As Main Coin", group = gs) osc = input.string('Candles', "Display As" , ['Candles', 'Line'], group = gs) colup = input.color (#16bb9f, "Bull" , group = gc) coldn = input.color (#b3212d, "Bear" , group = gc) var string main = syminfo.type != 'crypto' ? 'BTC' : chart ? syminfo.basecurrency : 'BTC' bar coin = main .data( ) array<bar> stbl = array.from( 'USDT'.data(), 'USDC'.data(), 'TUSD'.data(), 'BUSD'.data(), 'DAI' .data(), 'FRAX'.data()) bar ssro = bar .new ( coin.o.ssro(stbl.srcget('o'), len), coin.h.ssro(stbl.srcget('h'), len), coin.l.ssro(stbl.srcget('l'), len), coin.c.ssro(stbl.srcget('c'), len)) color col = ssro.c > ssro.o ? na : coldn plotcandle(osc == 'Candles' ? ssro.o : na, osc == 'Candles' ? ssro.h : na, osc == 'Candles' ? ssro.l : na, osc == 'Candles' ? ssro.c : na, "SSRO", col, chart.fg_color, bordercolor = chart.fg_color) hline(0 , "Mid-Line", chart.fg_color) plot (osc == 'Line' ? ssro.c : na, "SSRO" , chart.fg_color) max = hline(4 , display = display.none) hh = hline(3 , display = display.none) lh = hline(2 , display = display.none) min = hline(-4, display = display.none) ll = hline(-3, display = display.none) hl = hline(-2, display = display.none) fill(hl, min, coldn.adj(75)) fill(ll, min, coldn.adj(75)) fill(lh, max, colup.adj(75)) fill(hh, max, colup.adj(75)) //Source Construction For Indicator\Strategy Exports plot(osc == 'Candles' ? ssro.o : na, "open" , editable = false, display = display.none) plot(osc == 'Candles' ? ssro.h : na, "high" , editable = false, display = display.none) plot(osc == 'Candles' ? ssro.l : na, "low" , editable = false, display = display.none) plot(osc == 'Candles' ? ssro.c : na, "close", editable = false, display = display.none) plot(osc == 'Candles' ? ssro.src('hl2' ) : na, "hl2" , editable = false, display = display.none) plot(osc == 'Candles' ? ssro.src('hlc3' ) : na, "hlc3" , editable = false, display = display.none) plot(osc == 'Candles' ? ssro.src('ohlc4') : na, "ohlc4", editable = false, display = display.none) plot(osc == 'Candles' ? ssro.src('hlcc4') : na, "hlcc4", editable = false, display = display.none)
COSTAR [SS]
https://www.tradingview.com/script/ZbCu84zD-COSTAR-SS/
Steversteves
https://www.tradingview.com/u/Steversteves/
49
study
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/ // ______ ______ _______.___________. ___ .______ // / | / __ \ / | | / \ | _ \ //| ,----'| | | | | (----`---| |----` / ^ \ | |_) | //| | | | | | \ \ | | / /_\ \ | / //| `----.| `--' | .----) | | | / _____ \ | |\ \----. // \______| \______/ |_______/ |__| /__/ \__\ | _| `._____| // 7^ // 7BG~ // ?P.7B~ // ^YJ.^^?B! // .~JY~:^~^^!PY^ // ^77!!77?JJ?~:^^^^^^^^7YYJ?7!!~~~~. // :?PPY7!~~^^^~~!!~!7!!!!~~!!7JPB5!. // .!JY7^^!77????77!!~^^^^?5Y!: // .:^~!77: :J5~^~777!!!!!~^^^!PY~. // ?^ :^!!!~^: :~^ ~B:^!!!!!!~~^^^!#7. // ....!7?!77!^. :~77!^. JY.^^~~~!!~^^^^~PY. // :~?Y?^!?7!: .^!7~: ?P :^~7Y5J?JY?~^^~B?. // :^~^:7?7 .~!!^. :~!. !P.:7Y5J~. .!YJ~^7B~. // .^ :~~^. .J .~!~: .^!7~^. ~G^?5Y!. ~YJ~Y5: // ...7J!!~. ^~~: .^!!^. !&5Y7: ~Y5&!. // ^7Y7!J7^ .~!^!. :~!^. !G?^. ^J~. // :^:.JJ. :~~: ~??^!!: .~ // .. .^^: :: :~^^~7?!^!JJ!: // :^??!~. :~^ ~J7?: // ^7Y?~. :!:^: :~:^5. // .:: ~: :^~77J!: .^^ . // . .::. :~J777^: ^^. // :~7?~: :^ ?7 .^. // .^?~. .^: . :: // . . :: .:. // .~!^: .. // ^!??7: .. // .7^ // :. // .. // .. // COSTAR by © Steversteves // // ___ _ _ // | _ \___ __ _ __| | _ __ ___| | // | / -_) _` / _` | | ' \/ -_)_| // |_|_\___\__,_\__,_| |_|_|_\___(_) // // COSTAR provides another, more neutral way to determine whether an equity is overbought or oversold. // Instead of relying on the traditional oscillator based ways, such as using RSI, Stocahstics and MFI, which can be somewhat biased and narrow sided, COSTAR attempts to take a neutral, unbaised approached // to determing overbought and oversold conditions. It does this through using a co-integrated partner, or "pair" that is closely linked to the underlying equity and succeeds on both having a high correlation and // a high t-statistic on the ADF test. It then references this underlying, co-integrated partner as the "benchmark" for the co-integration relationship. // How this succeeds as being "unbiased" and "neutral" is because it is responsive to underlying drivers. If there is a market catalyst or just general bullish or bearish momentum in the market, the indicator // will be referencing the integrated relationship between the two pairs and referencing that as a baseline. If there is a sustained rally on the integrated partner of the underlying ticker that is holding, // but the other ticker is lagging, it will indicate that the other ticker is likely to be under-valued and thus "oversold" because it is underperforming its benchmark partner. // This is in contrast to traditional approaches to determining overbought and oversold conditions, which rely completely on a single ticker, with no external reference to other tickers and no control over // whether the move could potentially be a fundamental move based on an industry or sector, or whether it is a fluke or a squeeze. // The control for this giving "false" signals comes from its extent of modelling and assessment of the degree of integration of the relationship. The parameters are set by default to asess over a 1 year period, both // the correlation and the integration. Anything that passes this degree of integration is likely to have a solid, co-integrated state and not likely to be a "fluke". Thus, the reliability of the assessment // is augmented by the degree of statistical significance found within the relationship. The indicator is not going to prompt you to rely on a relationship that is statistically weak, and will warn you of such. // The indicator will show you all the information you require regarding the relationship and whether it is reliable or not, so you do not need to worry! //@version=5 indicator("Cointegration, Overbought, and Oversoldness ST [SS]", shorttitle = "COSTAR [SS]", max_labels_count = 500) import Steversteves/SPTS_StatsPakLib/3 as spts // _ _ _____ _ //| | | | |_ _| | | //| | | |___ ___ _ __ | | _ __ _ __ _ _| |_ ___ //| | | / __|/ _ \ '__| | || '_ \| '_ \| | | | __/ __| //| |_| \__ \ __/ | _| || | | | |_) | |_| | |_\__ \ // \___/|___/\___|_| \___/_| |_| .__/ \__,_|\__|___/ // | | // |_| cip = input.symbol("AMEX:SPY", "Benchmark Ticker"), plt_type = input.string("Z-Score Price Ratio", "Plot Type", ["Z-Score Price Ratio", "Raw Price Ratio", "Co-Integration Price"]) reg_len = input.int(252, "Regression Length"), info_table = input.bool(true, "Show Statistics Table") cor_len = input.int(252, "Length of Correlation"), show_entry_exit = input.bool(false, "Show Entries and Exits") z_len = input.int(75, "Z-Score Length") // ___ _ _ // | __| _ _ _ __| |_(_)___ _ _ ___ // | _| || | ' \/ _| _| / _ \ ' \(_-< // |_| \_,_|_||_\__|\__|_\___/_||_/__/ // This section provides the fundamental functions for the indicator. The remaning functions are pulled from the SPTS library. f_arr() => // Create a new float array array.new_float() cor(variable1, variable2) => // Perform a correlation assessment on two variables referencing the cor_len input ta.correlation(variable1, variable2, cor_len) z_info(variable) => // Creates all parameters for Z-score assessment, the z-score itself and the SD and Avg value. float z = 0.0 float sd = 0.0 float avg = 0.0 avg := ta.sma(variable, z_len) sd := ta.stdev(variable, z_len) z := (variable - avg) / sd [z, avg, sd] sc(ticker, variable) => // Pulls a security request for the desired ticker and expression. request.security(ticker, "", variable, gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_on) f_cointegration(dependent_ticker, independent_ticker, len) => float result = 0.0 dep_array = array.new<float>() indep_array = array.new<float>() for i = 0 to len array.push(dep_array, dependent_ticker[i]) array.push(indep_array, independent_ticker[i]) // Average dep_avg = array.avg(dep_array) indep_avg = array.avg(indep_array) // Covariance integration_covariance = array.covariance(dep_array, indep_array) variance = array.variance(indep_array) slope = (integration_covariance / variance) intercept = dep_avg - (indep_avg * slope) result := (independent_ticker * slope) + intercept // ___ _ _ _ // |_ _|_ _| |_ ___ __ _ _ _ __ _| |_(_)___ _ _ // | || ' \ _/ -_) _` | '_/ _` | _| / _ \ ' \ // |___|_||_\__\___\__, |_| \__,_|\__|_\___/_||_| // |___/ // This section conducts the integration of the two variables. It does this through first testing for statistical significance via the DF test. If the DF tests returns "True", it will create a linear regression model, // that will serve as the initial basis for determining the fair market value or expected value of the co-integrated pair as a reference point. ip_coef = f_arr() ip_int = f_arr() i_c = sc(cip, close) dp_c = sc(syminfo.tickerid, close) [reg_r, pear_cor, r2, se, co_ef, i_r] = spts.f_linear_regression(i_c, dp_c, reg_len, i_c) // Test for Significance of integration dif_i_d = reg_r - dp_c delta_x = dif_i_d - dif_i_d[1] lagged_x = dif_i_d[1] [t_stat, t_stat_s] = spts.f_dickey_fuller_test(delta_x, lagged_x, reg_len) for i = 0 to 50 array.push(ip_coef, co_ef[i]) array.push(ip_int, i_r[i]) // ___ ___ _ _ _ ___ _ _ // / __|___ __|_ _|_ _| |_ ___ __ _ _ _ __ _| |_(_)___ _ _ | _ \___ ____ _| | |_ // | (__/ _ \___| || ' \ _/ -_) _` | '_/ _` | _| / _ \ ' \ | / -_|_-< || | | _| // \___\___/ |___|_||_\__\___\__, |_| \__,_|\__|_\___/_||_| |_|_\___/__/\_,_|_|\__| // |___/ cor_r = cor(i_c, dp_c) coint_r = (i_c * co_ef) + i_r coint_coef_avg = array.avg(ip_coef) coint_int_avg = array.avg(ip_int) //coint_r_plot = (i_c * coint_coef_avg) + coint_int_avg coint_r_plot = f_cointegration(dp_c, i_c, reg_len) // |_ /__/ __| __ ___ _ _ ___ // / /___\__ \/ _/ _ \ '_/ -_) // /___| |___/\__\___/_| \___| pr = i_c / dp_c [z, avg, sd] = z_info(pr) max_z = ta.highest(z, z_len) min_z = ta.lowest(z, z_len) bool overbought = z >= max_z and dp_c > coint_r bool oversold = z <= min_z and dp_c < coint_r color green = color.lime, color black = color.rgb(0, 0, 0) color red = color.red, color redfill = color.new(color.red, 85) color greenfill = color.new(color.lime, 85), color white = color.white color transp = color.new(color.white, 100), color fadedteal = color.new(color.aqua, 85) color whitefill = color.new(color.white, 85), color purplefill = color.new(color.purple, 55) // ___ _ _ // | _ \ |___| |_ ___ // | _/ / _ \ _(_-< // |_| |_\___/\__/__/ zsma = ta.sma(z, 14) color assess = overbought ? red : oversold ? green : zsma > 2 ? fadedteal : zsma < -2 ? fadedteal : color.aqua color coint_col = coint_r_plot > dp_c ? greenfill : coint_r_plot > dp_c and oversold ? purplefill : coint_r_plot < dp_c ? redfill : coint_r_plot < dp_c and overbought ? purplefill : transp a = plot(plt_type == "Z-Score Price Ratio" ? zsma : na, "Z-Score of Price Ratio", color = assess, style = plot.style_histogram, linewidth=3) plot(plt_type == "Raw Price Ratio" ? pr : na, "Price Ratio (Raw)", color = color.aqua, linewidth = 3) d = plot(plt_type == "Co-Integration Price" ? ta.sma(coint_r_plot, 14) : na, "Co-Integration Price", color = color.aqua, linewidth=2) e = plot(plt_type == "Co-Integration Price" ? ta.sma(dp_c, 14) : na, "Dependent Closing Price", color = color.yellow, linewidth = 2) fill(d, e, color = plt_type == "Co-Integration Price" ? coint_col : na) var int overbought_c = 0 var int oversold_c = 0 if overbought and plt_type == "Z-Score Price Ratio" overbought_c += 1 if overbought_c >= 10 label.new(bar_index, y = zsma + 2, text = "Overbought, \n Expected Price = \n " + str.tostring(math.round(coint_r,2)), color = redfill, textcolor = white) overbought_c := 0 if oversold and plt_type == "Z-Score Price Ratio" oversold_c += 1 if oversold_c >= 10 label.new(bar_index, y = zsma - 2, text = "Oversold, \n Expected Price = \n " + str.tostring(math.round(coint_r,2)), color = greenfill, textcolor = white, style=label.style_label_up) oversold_c := 0 // ___ __ _____ _ _ // |_ _|_ _ / _|___ |_ _|_ _| |__| |___ // | || ' \| _/ _ \ | |/ _` | '_ \ / -_) // |___|_||_|_| \___/ |_|\__,_|_.__/_\___| if info_table var table stats_table = table.new(position.middle_right, 5, 6, bgcolor = black, frame_color = white, frame_width = 3) table.cell(stats_table, 1, 1, text = "Statistics Table", bgcolor = black, text_color = white) table.cell(stats_table, 1, 2, text = "Dependent Ticker: " + str.tostring(syminfo.ticker) + "\n Independent Ticker: " + str.tostring(cip), bgcolor = black, text_color = white) table.cell(stats_table, 1, 3, text = "T-Statistic: " + str.tostring(math.round(t_stat, 2)), bgcolor = black, text_color = white) table.cell(stats_table, 1, 4, text = "Stationary Data? " + str.tostring(t_stat_s) , bgcolor = black, text_color = white) table.cell(stats_table, 1, 5, text = "Correlation: " + str.tostring(math.round(cor_r,2)), bgcolor = black, text_color = white) // ___ _ _ _ ___ _ _ // | __|_ _| |_ _ _(_)___ ___ __ _ _ _ __| | | __|_ _(_) |_ ___ // | _|| ' \ _| '_| / -_|_-< / _` | ' \/ _` | | _|\ \ / | _(_-< // |___|_||_\__|_| |_\___/__/ \__,_|_||_\__,_| |___/_\_\_|\__/__/ // Entries and exits var int entry_wait = 0 var int long_entry_wait = 0 var label long_entry_lbl = na var label exit_long_lbl = na var label exit_short_lbl = na if overbought and show_entry_exit entry_wait += 1 if entry_wait >= 10 label.new(bar_index, y = close, text = "Short Entry", color = redfill, style = label.style_circle) entry_wait := 0 if ta.crossunder(close, coint_r_plot) and show_entry_exit label.delete(exit_short_lbl) exit_short_lbl := label.new(bar_index, y = close, text = "Exit Short", color = whitefill, style = label.style_circle) if oversold and show_entry_exit long_entry_wait += 1 if long_entry_wait >= 10 long_entry_lbl := label.new(bar_index, y = close, text = "Long Entry", color = greenfill, style = label.style_circle) long_entry_wait := 0 if ta.crossover(close, coint_r_plot) and show_entry_exit label.delete(exit_long_lbl) exit_long_lbl := label.new(bar_index, y = close, text = "Exit Long", color = whitefill, style = label.style_circle)
Donchian Trend Signals
https://www.tradingview.com/script/ntV1kMLS-Donchian-Trend-Signals/
OmegaTools
https://www.tradingview.com/u/OmegaTools/
68
study
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/ // © OmegaTools //@version=5 indicator("Donchian Trend Signals", "DTS", overlay = true) lnt = input(21, "Length") cmp = input.bool(false, "Complex mode", "Transform the average line into the average of multiple length average line, respectively of half the length you have chosen, the length, and double the length") lnt05 = math.round(lnt / 2) lnt1 = math.round(lnt * 2) h0 = ta.highest(close, lnt) l0 = ta.lowest(close, lnt) m0 = math.avg(h0, l0) h05 = ta.highest(close, lnt05) l05 = ta.lowest(close, lnt05) m05 = math.avg(h05, l05) h1 = ta.highest(close, lnt1) l1 = ta.lowest(close, lnt1) m1 = math.avg(h1, l1) m = cmp == false ? m0 : math.avg(m0, m05, m1) h = cmp == false ? h0 : math.avg(h0, h05, h1) l = cmp == false ? l0 : math.avg(l0, l05, l1) trend = 0 trend := if m > m[1] trend := 1 else if m < m[1] trend := -1 else if m == m[1] trend := trend[1] col = trend == 1 ? #2962ff : trend == -1 ? #e91e63 : color.gray vol = volume > ta.sma(volume, 9) sgrab = high > h and close < h and vol bgrab = low < l and close > l and vol rng = math.avg(high - low, math.abs(close-open)) enb = rng > rng[1] and close > open ens = rng > rng[1] and close < open buy = true sell = true lbr = close > h[1] sbr = close < l[1] lastbs = 0 lastbs := lbr ? nz(lastbs[1]) + 1 : sbr ? 0 : nz(lastbs[1]) lastss = 0 lastss := sbr ? nz(lastss[1]) + 1 : lbr ? 0 : nz(lastss[1]) if lastbs[1] > 0 buy := false if lastss[1] > 0 sell := false filt = (math.abs(close - open) * 1.25) > (high - low) plot(h, "Higher price", color.gray, 1, plot.style_linebr) plot(l, "Lower price", color.gray, 1, plot.style_linebr) plot(m, "Average price", col, 2) barcolor(col, title = "Trend coloring") plotshape(bgrab, "Liquidity buy", shape.diamond, location.belowbar, enb ? #2962ff : color.gray) plotshape(sgrab, "Liquidity sell", shape.diamond, location.abovebar, ens ? #e91e63 : color.gray) plotshape(lbr and buy and vol, "Breakout buy", shape.triangleup, location.belowbar, filt ? #2962ff : color.gray) plotshape(sbr and sell and vol, "Breakout sell", shape.triangledown, location.abovebar, filt ? #2962ff : color.gray)
lib_zig
https://www.tradingview.com/script/CNJ8VO2I-lib-zig/
robbatt
https://www.tradingview.com/u/robbatt/
1
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/ // © robbatt //@version=5 // @description Object oriented implementation of Pivot methods. library("lib_zig", overlay=true) import robbatt/lib_log/6 as LOG import robbatt/lib_priceaction/6 as PA import robbatt/lib_plot_objects/34 as D import robbatt/lib_pivot/47 as P //////////////////////////////////////////////////// //#region MODEL //////////////////////////////////////////////////// export type ZigzagConfig D.LineArgs hh_line_args D.LineArgs lh_line_args D.LineArgs hl_line_args D.LineArgs ll_line_args D.LabelArgs hh_label_args D.LabelArgs lh_label_args D.LabelArgs hl_label_args D.LabelArgs ll_label_args export type ZigzagSignals bool double_pivot = false bool extra_pivot = false bool direction_change = false bool extra_abstract_pivot = false bool last_updated = false export type Zigzag int max_pivots = 30 P.HLData hldata ZigzagConfig config int level = 0 array<P.Pivot> pivots ZigzagSignals signals //////////////////////////////////////////////////// //#endregion MODEL //////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region OBJECT INSPECTION / CONVERSION TO JSON read ///////////////////////////////////////////////////////////// //@function converts object to json representation export method tostring(ZigzagSignals this) => na(this) ? 'null' : '{' + str.format('"double_pivot": {0}, "extra_pivot": {1}, "direction_change": {2}', this.double_pivot, this.extra_pivot, this.direction_change) + '}' //@function converts object to json representation //@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm') export method tostring(Zigzag this, simple string date_format = 'dd-MM-y HH:mm') => na(this) ? 'null' : '{' + str.format('"max_pivots": {0}, "hldata": {1}, "pivots": {2}, "signals": {3}', this.max_pivots, this.hldata.tostring(), this.pivots.tostring(date_format), this.signals.tostring()) + '}' ///////////////////////////////////////////////////////////// //#endregion OBJECT INSPECTION / tostring ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region HELPERS ///////////////////////////////////////////////////////////// method add_next(Zigzag this, chart.point point, D.Candle candle) => if na(this) or na(point) ? false : not na(this.pivots) this.pivots.add_next(point, this.max_pivots, candle) this.signals.direction_change := true this method add_next_lowest(Zigzag this) => this.add_next(this.hldata.lowest_point, this.hldata.lowest_candle) method add_next_highest(Zigzag this) => this.add_next(this.hldata.highest_point, this.hldata.highest_candle) export method has_new_pivot(ZigzagSignals this) => this.extra_pivot or this.double_pivot or this.direction_change export method has_new_pivot(Zigzag this) => this.signals.has_new_pivot() export create_config(D.LineArgs base_line_args, D.LabelArgs base_label_args, P.PivotColors line_colors, P.PivotColors label_text_colors = na, P.PivotColors label_colors = na) => var lbl_colors = na(label_colors) ? P.PivotColors.new(#00000000, #00000000, #00000000, #00000000) : label_colors var txt_colors = na(label_text_colors) ? line_colors : label_text_colors ZigzagConfig.new( base_line_args.copy().set_line_color(line_colors.get_color(2)), base_line_args.copy().set_line_color(line_colors.get_color(1)), base_line_args.copy().set_line_color(line_colors.get_color(-1)), base_line_args.copy().set_line_color(line_colors.get_color(-2)), base_label_args.copy().set_bg_color(lbl_colors.get_color(2)).set_txt_color(txt_colors.get_color(2)).set_style(label.style_label_down), base_label_args.copy().set_bg_color(lbl_colors.get_color(1)).set_txt_color(txt_colors.get_color(1)).set_style(label.style_label_down), base_label_args.copy().set_bg_color(lbl_colors.get_color(-1)).set_txt_color(txt_colors.get_color(-1)).set_style(label.style_label_up), base_label_args.copy().set_bg_color(lbl_colors.get_color(-2)).set_txt_color(txt_colors.get_color(-2)).set_style(label.style_label_up) ) export create_config(D.LineArgs base_line_args, D.LabelArgs base_label_args, color simple_color) => create_config(base_line_args, base_label_args, P.PivotColors.new(simple_color, simple_color, simple_color, simple_color)) export method set_config(Zigzag this, ZigzagConfig config) => this.config := config this export method get_line_args(Zigzag this, int mode) => switch mode 2 => this.config.hh_line_args 1 => this.config.lh_line_args -1 => this.config.hl_line_args -2 => this.config.ll_line_args => na export method get_label_args(Zigzag this, int mode) => switch mode 2 => this.config.hh_label_args 1 => this.config.lh_label_args -1 => this.config.hl_label_args -2 => this.config.ll_label_args => na ///////////////////////////////////////////////////////////// //#endregion HELPERS ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region OBJECT UPDATE / update ///////////////////////////////////////////////////////////// export method init(Zigzag this) => if not na(this) if na(this.pivots) this.pivots := array.new<P.Pivot>() if na(this.hldata) this.hldata := P.HLData.new() if na(this.signals) this.signals := ZigzagSignals.new() if na(this.config) this.config := ZigzagConfig.new( D.LineArgs.new(), D.LineArgs.new(), D.LineArgs.new(), D.LineArgs.new(), D.LabelArgs.new(), D.LabelArgs.new(), D.LabelArgs.new().set_style(label.style_label_up), D.LabelArgs.new().set_style(label.style_label_up) ) // reset signals this.signals.double_pivot := false this.signals.extra_pivot := false this.signals.direction_change := false this.signals.extra_abstract_pivot := false this.signals.last_updated := false this export method initPivots(Zigzag this) => if this.pivots.size() == 0 and not na(this.hldata.lowest) and not na(this.hldata.highest) if this.hldata.lowest_offset > this.hldata.highest_offset this.add_next_lowest() this.add_next_highest() else this.add_next_highest() this.add_next_lowest() this.signals.extra_pivot := true this.signals.direction_change := true //@function update the current Zigzag, call this on every iteration, for parameters of length/period and input source series, pass a HLData instance //@param ref_highest The seriest to detect high pivots from //@param ref_lowest The seriest to detect low pivots from //@param add_intermediate_fractals_on_force when forcing a trend change during an ongoing sideways trend, this adds intermediate fractals as additional pivots between the last pivot and the forced pivot ( default: true) //@param ignore_double_pivots_in_trend_direction ignores a double pivot when it's candle aligns with the trend direction (e.g. double pivot in bullish trend, but the candle closes bullish, means inside the candle there was a significant move down, but it was already mitigated and the candle closed bullish with a hh, so chances are higher that trend is continued) export method update(Zigzag this, float ref_highest = high, float ref_lowest = low, bool add_intermediate_fractals_on_force = true, bool ignore_double_pivots_in_trend_direction = true) => this.init() pd = this.hldata.update(ref_highest, ref_lowest) this.initPivots() count = this.pivots.size() if count >= 2 P.Pivot sec_last = this.pivots.get(1) P.Pivot last = this.pivots.get(0) int trend = last.direction() int bars_since_last = bar_index - last.point.index bool stalling = bars_since_last >= pd.length and barstate.isconfirmed bool double_pivot = pd.new_highest and pd.new_lowest and (not ignore_double_pivots_in_trend_direction or pd.current_candle().direction() != trend and barstate.isconfirmed) if trend == 1 // force low (sideways, lower highs, no new lowest for trend change) forced_l = stalling and not pd.new_lowest and not last.exceeded_by(pd.highest) and (add_intermediate_fractals_on_force or pd.new_highest) if forced_l this.add_next_lowest() // trend continuation if pd.new_highest if forced_l and add_intermediate_fractals_on_force this.add_next_highest() this.signals.extra_pivot := true // trend continuation else if last.exceeded_by(pd.highest) this.pivots.update_last(pd.highest_point, pd.highest_candle) this.signals.last_updated := true // double pivot if double_pivot this.add_next_lowest() this.signals.double_pivot := true // trend change else if pd.new_lowest and pd.highest_candle.l > pd.lowest this.add_next_lowest() if trend == -1 // force high (sideways, higher lows, no new highest for trend change) forced_h = stalling and not pd.new_highest and not last.exceeded_by(pd.lowest) and (add_intermediate_fractals_on_force or pd.new_lowest) if forced_h this.add_next_highest() if pd.new_lowest // trend change after forced h if forced_h and add_intermediate_fractals_on_force this.add_next_lowest() this.signals.extra_pivot := true // trend continuation else if last.exceeded_by(pd.lowest) this.pivots.update_last(pd.lowest_point, pd.lowest_candle) this.signals.last_updated := true // double pivot if double_pivot this.add_next_highest() this.signals.double_pivot := true // trend change else if pd.new_highest and pd.lowest_candle.h < pd.highest this.add_next_highest() this // @function remove intermediate HL and LH // @param this Zigzag object // @returns Higher level abstraction Zigzag object export method get_abstraction(Zigzag this, ZigzagConfig config = na) => // TODO speed optimize if not live, only update when [1] changed, if live when [0] change abstraction = Zigzag.new(this.max_pivots, this.hldata, na(config) ? this.config : config, this.level + 1) abstraction.init() count = this.pivots.size() if count >= 1 P.Pivot possible_trend_change_pivot_bullish = na P.Pivot possible_trend_change_pivot_bearish = na for i = count-1 to 0 P.Pivot pivot = P.Pivot.copy(this.pivots.get(i)) if abstraction.pivots.size() > 0 // if there are already other higher level pivot points P.Pivot last = abstraction.pivots.get(0) pivot_dir = pivot.direction() trend = last.direction() is_hhll = math.abs(pivot.mode) == 2 if is_hhll // (only interested in HH/LLs) if trend == pivot_dir // and the current pivot is the same direction as the previous one if last.exceeded_by(pivot.point.price) // ignore lower level direction abstraction.pivots.update_last(pivot.point) else // or confirmation of a set-aside trend change temp_pivot = pivot_dir == 1 ? possible_trend_change_pivot_bearish : possible_trend_change_pivot_bullish if not na(temp_pivot) abstraction.add_next(temp_pivot.point, temp_pivot.candle) abstraction.add_next(pivot.point, pivot.candle) else // if there's none set aside, drop this pivot continue else // if not the same direction as the previous pivot, this COULD be a trend change // collect the last pivots that were set aside P.Pivot temp_pivot_same_direction = pivot_dir == 1 ? possible_trend_change_pivot_bullish : possible_trend_change_pivot_bearish P.Pivot temp_pivot_other_direction = pivot_dir == 1 ? possible_trend_change_pivot_bearish : possible_trend_change_pivot_bullish if not temp_pivot_same_direction.exceeded_by(pivot.point.price) abstraction.add_next(temp_pivot_same_direction.point, temp_pivot_same_direction.candle) abstraction.add_next(temp_pivot_other_direction.point, temp_pivot_other_direction.candle) abstraction.add_next(pivot.point, pivot.candle) abstraction.signals.extra_pivot := true abstraction.signals.extra_abstract_pivot := true else abstraction.add_next(pivot.point, pivot.candle) // store the current one, reset the set aside ones possible_trend_change_pivot_bullish := na possible_trend_change_pivot_bearish := na // if the current pivot is not a HH/LL but something in between, set it aside for now, see what the next ones bring else temp_pivot = pivot_dir == 1 ? possible_trend_change_pivot_bullish : possible_trend_change_pivot_bearish // if there is already one set aside, check if the current one exceeds that then replace the one set aside if na(temp_pivot) ? true : temp_pivot.exceeded_by(pivot) if pivot_dir == 1 possible_trend_change_pivot_bullish := pivot else possible_trend_change_pivot_bearish := pivot // else there's already a temp and pivot doesn't exceed it, ignore pivot // else if there are no others yet, and the current one is a HH/LL, then store that else if math.abs(pivot.mode) == 2 if not na(pivot.prev) abstraction.pivots.unshift(pivot.prev) abstraction.add_next(pivot.point, pivot.candle) else abstraction.pivots.unshift(pivot) abstraction.add_next(pivot.point, pivot.candle) // else just skip this one abstraction ///////////////////////////////////////////////////////////// //#endregion OBJECT UPDATE / update ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region OBJECT CONVERSION / draw ///////////////////////////////////////////////////////////// //@function draw the Zigzag on the chart, continously export method draw_continous(Zigzag this, bool live = false) => var D.Line current_line = D.Line.new() var D.Label current_label = D.Label.new() var current_line_style_backup = line.style_solid if this.pivots.size() >= 3 P.Pivot last = this.pivots.get(0) P.Pivot sec_last = this.pivots.get(1) P.Pivot thr_last = this.pivots.get(2) if live // finish previous line and label before switching to double/extra pivot if this.signals.double_pivot or this.signals.extra_pivot pivot = this.signals.extra_pivot ? thr_last : sec_last current_label.txt := pivot.get_label_text() current_label.apply_style(this.get_label_args(pivot.mode)).draw() current_line.apply_style(this.get_line_args(pivot.mode)).draw(extend_only = false) // continuation of first double pivot as well as pivot before intermediate are confirmed instantly // on dir change create a copy of the old line for the next if this.signals.direction_change current_line.plot.copy().set_style(current_line_style_backup) // previous pivot is confirmed current_label.plot.copy() // draw intermediate if this.signals.extra_pivot current_line.start := thr_last.point current_line.end := sec_last.point current_line.apply_style(this.get_line_args(sec_last.mode)).draw(extend_only = false) // itermediate is confirmed instantly current_line.plot.copy() current_label.point := sec_last.point current_label.txt := sec_last.get_label_text() current_label.apply_style(this.get_label_args(sec_last.mode)).draw() current_label.plot.copy() // draw last pivot in array current_line.start := sec_last.point current_line.end := last.point current_label.point := last.point current_label.txt := last.get_label_text() current_line_style_backup := this.get_line_args(last.mode).style current_line.apply_style(this.get_line_args(last.mode)).draw(extend_only = false).plot.set_style(line.style_dashed) // new pivot is temporary, make line dashed current_label.apply_style(this.get_label_args(last.mode)).draw() else if this.has_new_pivot() thr_last.point.create_line(sec_last.point).draw(extend_only = false).apply_style(this.get_line_args(sec_last.mode)) sec_last.point.create_label(sec_last.get_label_text()).draw().apply_style(this.get_label_args(sec_last.mode)) this //@function draw the Zigzag on the chart, all at once export method draw(Zigzag this, bool live = false)=> var line[] lines = array.new<line>() var label[] labels = array.new<label>() count = na(this) ? 0 : this.pivots.size() if barstate.islast and count >= 3 lines.delete().clear() labels.delete().clear() // draw from present to past for i = (live?0:1) to count - 2 curr = this.pivots.get(i) prev = this.pivots.get(i+1) line_args = this.get_line_args(curr.mode) label_args = this.get_label_args(curr.mode) lines.push(line.new(prev.point, curr.point, this.hldata.xloc, line_args.extend, line_args.line_color, i == 0 ? line.style_dashed : line_args.style, line_args.width)) labels.push(label.new(curr.point, curr.get_label_text(), this.hldata.xloc, label_args.yloc, label_args.bg_color, label_args.style, label_args.text_color, label_args.size, label_args.text_align, label_args.text_font_family)) prev := curr this ///////////////////////////////////////////////////////////// //#endregion OBJECT CONVERSION / draw ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //#region DEMO ///////////////////////////////////////////////////////////// var lenth = input.int(5, 'length') var depth = input.int(50, 'depth') var highlight_level = input.int(0, 'highlight level', 0, 2) var P.PivotColors l0_colors = P.PivotColors.new() var P.PivotColors l1_colors = P.PivotColors.new(color.blue, color.fuchsia, color.aqua, color.purple) var D.LineArgs highlight_line_args = D.LineArgs.new(chart.fg_color, line.style_solid, 2) var D.LineArgs background_line_args = D.LineArgs.new(chart.fg_color, line.style_dotted, 1) var D.LabelArgs highlight_label_args = D.LabelArgs.new(chart.fg_color, chart.bg_color, size = size.normal) var D.LabelArgs background_label_args = D.LabelArgs.new(chart.fg_color, chart.bg_color) var ZigzagConfig zz0_config = create_config(highlight_level == 0 ? highlight_line_args : background_line_args, highlight_level == 0 ? highlight_label_args : background_label_args, l0_colors) var ZigzagConfig zz1_config = create_config(highlight_level == 1 ? highlight_line_args : background_line_args, highlight_level == 1 ? highlight_label_args : background_label_args, l1_colors) var ZigzagConfig zz2_config = create_config(highlight_level == 2 ? highlight_line_args : background_line_args, highlight_level == 2 ? highlight_label_args : background_label_args, color.black) var Zigzag zz = Zigzag.new(depth, P.HLData.new(lenth, xloc.bar_time), zz0_config) live = input.bool(false, 'live plot') zz.update() Zigzag zz1 = zz.get_abstraction(zz1_config) Zigzag zz2 = zz1.get_abstraction(zz2_config) if input.bool(true, 'level 0') zz.draw_continous(live) if barstate.islast if input.bool(true, 'level 1') zz1.draw(live) if input.bool(true, 'level 2') zz2.draw(live) ///////////////////////////////////////////////////////////// //#endregion DEMO /////////////////////////////////////////////////////////////
KNN Regression [SS]
https://www.tradingview.com/script/dWKzL2Xi-KNN-Regression-SS/
Steversteves
https://www.tradingview.com/u/Steversteves/
35
study
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/ // /$$$$$$ /$$ /$$ // /$$__ $$ | $$ | $$ //| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$ //| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/ // \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$ // /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$ //| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/ // \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/ // ___________________ // / \ // / _____ _____ \ // / / \ / \ \ // __/__/ \____/ \__\_____ //| ___________ ____| // \_________/ \_________/ // \ /////// / // \///////// // © Steversteves //@version=5 indicator("KNN Regression [SS]", overlay=true) len = input.int(500, "Assessment Length") regtp = input.string("Autoregression of Source", "Regression Type", ["Autoregression of Source", "Regression of Another Ticker"]) sym = input.symbol("", "Alternate Ticker") smoth = input.bool(true, "Smoothe Results?") bands = input.bool(true, "Plot Outerbands") src = input.source(close, "Source") reg_type = input.string("Cluster", "KNN Regression Type", ["Last Instance", "Avg", "Cluster"]) clust = input.int(3, "KNN Clusters") tol = input.float(20, "Tolerance for Clusters") // Security request at = request.security(sym, "", src, lookahead = barmerge.lookahead_on) // KNN Regresion // Inputs // // Input #1 y variable (dependent) // Input #2 x variable (independent) // Input #3 Length (assessment length) // Input #4 String variable determining the type of KNN regression, must be entered as either "Last Instance", "Cluster" or "Average" // Input #5 interger for number of clusters you want to include // Input #6 float of tolerance, because of the lookback limitations, clusters are done within a tolerance range (i.e. 0.05 or 0.5 etc.) // Outputs // // Output #1: Result (the result of the KNN regression) // Output #2: Error of Estimates // Output #3: Correlation of Model // Output #4: Simple R2 of model knn_regression(float y, float x, int len, string last_instance_or_cluster_or_avg, int clusters, float tolerance) => int index_of = 0 float result = 0.0 float error = 0.0 int inst = 0 float y_result = 0.0 float cor = 0.0 float r2 = 0.0 y_in = y[1] ed_y = math.abs(math.sqrt(math.pow(y[1] - x[1],2))) ed_x = math.abs(math.sqrt(math.pow(y - x, 2))) ed_array = array.new<float>() y_array = array.new<float>() cluster_array = array.new<float>() cluster_avg = array.new<float>() for i = 0 to len array.push(ed_array, ed_y[i]) array.push(y_array, y_in[i]) // Find KNN if last_instance_or_cluster_or_avg == "Last Instance" if array.includes(ed_array, ed_x) index_of := array.indexof(ed_array, ed_x) result := array.get(y_array, index_of) else if result[1] > 0 result := result[1] else if result[2] > 0 result := result[2] else if result[3] > 0 result := result[3] else na else if last_instance_or_cluster_or_avg == "Avg" for i = 0 to array.size(ed_array) - 1 if array.get(ed_array, i) == ed_x y_result += array.get(y_array, i) inst += 1 result := y_result / inst else if last_instance_or_cluster_or_avg == "Cluster" for i = 0 to array.size(ed_array) - 1 if array.get(ed_array, i) >= ed_x - tolerance and array.get(ed_array, i) <= ed_x + tolerance array.push(cluster_array, array.get(y_array, i)) if array.size(cluster_array) - 1 > clusters for i = 0 to clusters array.push(cluster_avg, array.get(cluster_array, i)) result := array.avg(cluster_avg) // Error bool above_result = y > result bool below_result = y < result above_arr = array.new<float>() below_arr = array.new<float>() above_dif = y - result below_dif = result - y for i = 0 to len if above_result[i] array.push(above_arr, above_dif[i]) else if below_result[i] array.push(below_arr, below_dif[i]) else na avg1 = array.avg(above_arr) avg2 = array.avg(below_arr) error := math.avg(avg1, avg2) // Correlation result_array = array.new<float>() for i = 0 to array.size(y_array) - 1 array.push(result_array, result[i]) cov = array.covariance(result_array, y_array) y_sd = array.stdev(y_array) r_sd = array.stdev(result_array) cor := cov / (y_sd * r_sd) // R2 r2 := math.pow(cor, 2) [result, error, cor, r2] float result = 0.0 float err = 0.0 float cor_r = 0.0 float r2_r = 0.0 if regtp == "Autoregression of Source" [reg, er, cor, r2] = knn_regression(src, src[1], len, str.tostring(reg_type), clust, tol) result := reg err := er cor_r := cor r2_r := r2 else if regtp == "Regression of Another Ticker" [tick, ter, tcor, tr2] = knn_regression(src, at, len, str.tostring(reg_type), clust, tol) result := tick err := ter cor_r := tcor r2_r := tr2 float result_plot = 0.0 float ucl_plot = 0.0 float lcl_plot = 0.0 if smoth result_plot := ta.sma(result, 14) ucl_plot := ta.sma(result + err, 14) lcl_plot := ta.sma(result- err, 14) else result_plot := result ucl_plot := result + err lcl_plot := result - err plot(result_plot, linewidth=2) plot(bands ? ucl_plot : na, linewidth=2) plot(bands ? lcl_plot : na, linewidth=2) var table data = table.new(position.top_right, 5, 5, bgcolor = color.black) table.cell(data, 1, 1, text = "Regression Type: " + str.tostring(reg_type), bgcolor = color.black, text_color = color.white) if reg_type == "Cluster" table.cell(data, 1, 2, text = "# of Clusters: " + str.tostring(clust), bgcolor = color.black, text_color = color.white) table.cell(data, 1, 3, text = "Correlation: " + str.tostring(math.round(cor_r, 2)), bgcolor = color.black, text_color = color.white) table.cell(data, 1, 4, text = "R2: " + str.tostring(math.round(r2_r, 2)), bgcolor = color.black, text_color = color.white)
Japanese Candle Patterns Detector in Potential Price Zone
https://www.tradingview.com/script/Y9fTWPZZ-Japanese-Candle-Patterns-Detector-in-Potential-Price-Zone/
MoriFX
https://www.tradingview.com/u/MoriFX/
82
study
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/ // © MoriFX //@version=5 indicator('Japanese Candle Patterns Detector in Potential Price Zone', shorttitle='Japanese Patterns', overlay=true) // User inputs HamStar = input(title='Hammer and ShootingStar', defval=true) DojiInput = input(title='Doji', defval=true) EngulfInput = input(title='Engulfing Candle', defval=true) MarubozuInput = input(title='Marubozu', defval=true) TweezersInput = input(title='Tweezers Top / Buttom', defval=true) ThreeWhiteSoldiersInput = input(title='Three White Soldiers / Black Crows', defval=true) HaramiInput = input(title='Harami', defval=true) // Candle calculator bodySize = math.abs(open - close) HlowerShadow = math.abs(low - open) HupperShadow = math.abs(high - close) SlowerShadow = math.abs(low - close) SupperShadow = math.abs(high - open) rsiValue = ta.rsi(close, 14) atrValue = ta.atr(12) dojiBodySize = atrValue * 5 / 100 EngulfBodySize = atrValue * 20 / 100 HamStarBodySize = atrValue * 15 / 100 // Patterns detector Hammer = HlowerShadow > bodySize * 2.5 and low <= ta.lowest(low, 12) and HlowerShadow > HupperShadow * 2.5 and close <= open[1] and bodySize > HamStarBodySize Star = SupperShadow > bodySize * 2.5 and high >= ta.highest(high, 12) and SupperShadow > SlowerShadow * 2.5 and open <= close[1] and bodySize > HamStarBodySize Doji = bodySize <= dojiBodySize and (low <= ta.lowest(low, 12) or high >= ta.highest(high, 12)) BullEng = close > high[1] and close[1] < open[1] and bodySize[1] > EngulfBodySize and rsiValue < 50 BearEng = close < open[1] and close[1] > open[1] and bodySize[1] > EngulfBodySize and rsiValue > 50 Marubozu = open == high and close == low or open == low and close == high TweezerTop = high == high[1] and rsiValue > 50 TweezerBut = low == low[1] and rsiValue < 50 ThreeWhiteSoldiers = close[3] < open[3] and close[2] > open[2] and close[1] > open[1] and close > open and rsiValue[2] < 50 and bodySize[2] > dojiBodySize * 2 and bodySize[1] > dojiBodySize * 3 and bodySize > dojiBodySize * 4 ThreeBlackCrows = close[3] > open[3] and close[2] < open[2] and close[1] < open[1] and close < open and rsiValue[2] > 50 and bodySize[2] > dojiBodySize * 2 and bodySize[1] > dojiBodySize * 3 and bodySize > dojiBodySize * 4 BullHarami = close[2] < open[2] and close[1] < open[1] and bodySize[1] >= atrValue[1] and open > close[1] and close < open[1] BearHarami = close[2] > open[2] and close[1] > open[1] and bodySize[1] <= atrValue[1] and open < close[1] and close > open[1] // Plot signal on chart plotshape(HamStar ? Hammer : na, style=shape.triangleup, location=location.belowbar, textcolor=color.new(color.green, 0), text='Ham') plotshape(HamStar ? Star : na, style=shape.triangledown, location=location.abovebar, textcolor=color.new(color.red, 0), text='Star') plotshape(DojiInput ? Doji : na, style=shape.cross, location=location.abovebar, textcolor=color.new(color.gray, 0), text='Doji') plotshape(EngulfInput ? BullEng : na, style=shape.triangleup, location=location.belowbar, textcolor=color.new(color.green, 0), text='BulEng') plotshape(EngulfInput ? BearEng : na, style=shape.triangledown, location=location.abovebar, textcolor=color.new(color.red, 0), text='BerEng') plotshape(MarubozuInput ? Marubozu : na, style=shape.diamond, location=location.abovebar, textcolor=color.new(color.fuchsia, 0), text='Marubozu') plotshape(TweezersInput ? TweezerTop : na, style=shape.triangledown, location=location.abovebar, textcolor=color.new(color.red, 0), text='TwzrTop') plotshape(TweezersInput ? TweezerBut : na, style=shape.triangleup, location=location.belowbar, textcolor=color.new(color.green, 0), text='TwzrBut') plotshape(ThreeWhiteSoldiersInput ? ThreeWhiteSoldiers : na, style=shape.triangleup, location=location.belowbar, textcolor=color.new(color.green, 0), offset=-2, text='3Sol') plotshape(ThreeWhiteSoldiersInput ? ThreeBlackCrows : na, style=shape.triangledown, location=location.abovebar, textcolor=color.new(color.red, 0), offset=-2, text='3Crow') plotshape(HaramiInput ? BullHarami : na, style=shape.triangleup, location=location.belowbar, textcolor=color.new(color.green, 0), text='BullHarami') plotshape(HaramiInput ? BearHarami : na, style=shape.triangledown, location=location.abovebar, textcolor=color.new(color.red, 0), text='BearHarami') // Alert alertcondition(Doji or Hammer or Star or BullEng or BearEng or Marubozu or TweezerTop or TweezerBut or ThreeWhiteSoldiers or ThreeBlackCrows or BullHarami or BearHarami, title='All type of Japanese candles', message='Japanese Pattern found for {{ticker}}') alertcondition(DojiInput ? Doji : na, title='Doji candle ', message='Japanese Pattern found for {{ticker}}') alertcondition(HamStar ? Hammer or Star : na, title='Hammer/Star candle ', message='Japanese Pattern found for {{ticker}}') alertcondition(EngulfInput ? BullEng or BearEng : na, title='Engulfing candle ', message='Japanese Pattern found for {{ticker}}') alertcondition(MarubozuInput ? Marubozu : na, title='Marubozu candle ', message='Japanese Pattern found for {{ticker}}') alertcondition(TweezersInput ? TweezerTop or TweezerBut : na, title='TweezerTop/But candle ', message='Japanese Pattern found for {{ticker}}') alertcondition(ThreeWhiteSoldiersInput ? ThreeWhiteSoldiers or ThreeBlackCrows : na, title='ThreeWhiteSoldiers/BlackCrows candle ', message='Japanese Pattern found for {{ticker}}') alertcondition(HaramiInput ? BullHarami or BearHarami : na, title='Harami candle ', message='Japanese Pattern found for {{ticker}}')
lib_statemachine
https://www.tradingview.com/script/jVX7YbB6-lib-statemachine/
robbatt
https://www.tradingview.com/u/robbatt/
4
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © robbatt //@version=5 // @description simple state machine that allows tracking a state an manipulating it with conditions library("lib_statemachine", overlay = true) export type StateMachine int state = 0 int neutral = 0 bool enabled = true int reset_counter = 0 // @function will step the state of the state machine from one to the next in case of condition // @param this (StateMachine) the state machine to use // @param before (int) from state // @param after (int) to state // @param condition (bool) if condition is true // @returns true (bool) if the state of the statemachine changed export method step(StateMachine this, int before, int after, bool condition = true) => if condition and this.enabled and this.state == before this.state := after this.reset_counter := 0 true else false // @function will change the state of the state machine to the next in case of condition (not depending on previous state) // @param this (StateMachine) the state machine to use // @param after (int) to state // @param condition (bool) if condition is true // @returns true (bool) if the state of the statemachine changed export method step(StateMachine this, int after, bool condition = true) => this.step(this.state, after, condition) // @function will return true if the state of the state machine was changed in this iteration // @param this (StateMachine) the state machine to use // @returns true (bool) if the state of the statemachine changed export method changed(StateMachine this, int within_bars = 1) => bars = ta.barssince(this.state[1] != this.state) na(bars) ? this.state != this.neutral : bars < within_bars // @function will reset the state machine if a certain 'condition' appears 'min_occurrences' times // @param this (StateMachine) the state machine to use // @param condition (bool) reset condition // @param min_occurrences (int) min times 'condition' must appear for the reset to happen // @returns true (bool) if the state of the statemachine changed export method reset(StateMachine this, bool condition = true, int min_occurrences = 1) => if this.reset_counter + 1 < min_occurrences and this.state != this.neutral and condition this.reset_counter := this.reset_counter + 1 false else if this.reset_counter + 1 == min_occurrences this.reset_counter := 0 this.state := this.neutral true else false ////////////////////////////////////// // TEST ////////////////////////////////////// // import robbatt/lib_log/2 as LOG // import robbatt/lib_unit/3 as UNIT // var UNIT.Test assert = UNIT.Test.new(strict = true, verbose = true) // assert.init() // var s = StateMachine.new() // assert.equals(s.state, 0, 'state initially 0') // assert.is_true(s.enabled, 'statemachine initially enabled') // // positive // s.step(0, 1) // assert.equals(s.state, 1, 'state 0->1') // assert.is_true(s.changed(), 'state should be marked as changed after step 0->1') // s.step(1, 5) // assert.equals(s.state, 5, 'state 1->5') // s.step(5, 0) // assert.equals(s.state, 0, 'state 5->0') // // negative // s.step(0, -1) // assert.equals(s.state, -1, 'state 0->-1') // s.step(-1, -5) // assert.equals(s.state, -5, 'state -1->-5') // // reset // s.reset() // assert.equals(s.state, 0, 'reset state -5->0') // s.step(0, 1) // s.reset(min_occurrences = 2) // assert.equals(s.state, 1, 'this reset requires 2 calls to reset') // s.reset(min_occurrences = 2) // assert.equals(s.state, 0, 'this reset requires 2 calls to reset, should be reset after second call') // plot(s.state, 'State')
Zig-Zag Open Interest Footprint [Kioseff Trading]
https://www.tradingview.com/script/bSm3Vfyx-Zig-Zag-Open-Interest-Footprint-Kioseff-Trading/
KioseffTrading
https://www.tradingview.com/u/KioseffTrading/
106
study
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/ // © KioseffTrading //@version=5 indicator("Zig-Zag Open Interest Footprint [Kioseff Trading]", max_lines_count = 500, max_labels_count = 500, overlay= true, max_polylines_count = 100, max_boxes_count = 500) import TradingView/ZigZag/6 as ZigZagLib import RicardoSantos/MathOperator/2 show1 = input.bool (defval = true, title = "Up OI Up Price Profile" , group = "Profiles", inline = "Up") show2 = input.bool (defval = true, title = "Down OI Up Price Profile" , group = "Profiles", inline = "Up") show3 = input.bool (defval = true, title = "Up OI Dn Price Profile" , group = "Profiles", inline = "Dn") show4 = input.bool (defval = true, title = "Down OI Down Price Profile", group = "Profiles", inline = "Dn") ROWS = input.int (defval = 2000, maxval = 9998, minval = 10, step = 10, title = "Profile Rows", group = "Profile Settings") factor = input.float (defval = 2.5, minval = 1.1, step = 0.1, title = "Scaling Factor", group = "Profile Settings") offset = input.int (defval = 1, title = "Offset Placement", minval = 1, group = "Profile Settings") curve = input.bool (defval = false, title = "Curved Profiles", group = "Profile Settings") same = input.string(defval = "Middle", title = "VP Plot Type", options = ["Middle", "Opposing Side"], group = "Profile Settings") upCol = input.color (defval = #14D990, title = "Up OI Up Price Color", group = "Profile Settings", inline = "Up3") dnCol = input.color (defval = #F2B807, title = "Dn OI Up Price Color", group = "Profile Settings", inline = "Up3") upCol2 = input.color (defval = #6929F2, title = "Up OI Dn Price Color", group = "Profile Settings", inline = "Dn3") dnCol2 = input.color (defval = #F24968, title = "Dn OI Dn Price Color", group = "Profile Settings", inline = "Dn3") transp = input.int (defval = 90, minval = 0, maxval = 100, group = "Profile Settings", title = "Pofile Fill Transparency") transp2 = input.int (defval = 0 , minval = 0, maxval = 100, group = "Profile Settings", title = "Pofile Line Transparency") showL = input.bool (defval = true, title = "Show Sum Labels", group = "Summed OI") delta = input.bool (defval = false, title = "Show Footprints", group = "Summed OI") deltaRows = input.int (defval = 20, minval = 5, title = "Rows", group = "Summed OI") deltaSz = input.string(defval = "Tiny", title = "Delta Text Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = "Summed OI") transpd1 = input.int (defval = 70, title = "Trasnparency For Low OI Levels", group = "Summed OI", minval = 0, maxval = 100) transpd2 = input.int (defval = 0, title = "Trasnparency For High OI Levels", group = "Summed OI", minval = 0, maxval = 100) neon = input.bool (defval = true, title = "Neon Highlight Highest OI Levels", group = "Summed OI") poc = input.bool (defval = false, title = "Use POCs", group = "POC Settings") delet = input.bool (defval = false, title = "Delete Violated POCs", group = "POC Settings") useGen = input.bool (defval = false, title = "Use General POC", group = "POC Settings") sp1 = input.bool (defval = true , title = "Show Up OI Up POC", group = "POC Settings", inline = "Up2") sp2 = input.bool (defval = true , title = "Show Dn OI Up POC", group = "POC Settings", inline = "Up2") sp3 = input.bool (defval = true , title = "Show Up OI Dn POC", group = "POC Settings", inline = "Dn2") sp4 = input.bool (defval = true , title = "Show Dn OI Dn POC", group = "POC Settings", inline = "Dn2") show = input.int (defval = 20, title = "POCs To Show", maxval = 250, minval = 1, group = "POC Settings") generalPOCcol = input.color (defval = color.yellow, title = "Normal POC Col", group = "POC Settings") transp3 = input.int (defval = 66, minval = 0, maxval = 100, group = "POC Settings", title = "POC Line Transparency") N = bar_index, atr = ta.atr(14) show := switch useGen true => show + 1 => show * 4 if curve ROWS := 60 if same == "Middle" offset := 0 var max = 0., var min = 0. if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time max := math.max(max, high), min := math.min(min, low) req() => cont = switch str.contains(syminfo.ticker, ".P") true => syminfo.ticker + "_OI" => str.endswith(syminfo.ticker, "USDT") ? syminfo.ticker + ".P_OI" : syminfo.ticker + "T.P_OI" switch syminfo.type "crypto" => cont => string(na) oi = request.security(req(), timeframe.period, close - close[1] , ignore_invalid_symbol = false) // Create Zig Zag instance from user settings. var zigZag = ZigZagLib.newInstance( ZigZagLib.Settings.new( input.float(0.00001, "Price deviation for reversals (%)", 0.00001, 100.0, 0.5, "0.00001 - 100", group = "Zig Zag Settings"), input.int(100, "Pivot legs", 2, group = "Zig Zag Settings"), input(color.new(color.white,50), "Line color", group = "Zig Zag Settings"), false, // input(false, "Extend to last bar"), input(false, "Display reversal price", group = "Zig Zag Settings"), input(false, "Display cumulative volume", group = "Zig Zag Settings"), input(false, "Display reversal price change", inline = "priceRev", group = "Zig Zag Settings"), input.string("Absolute", "", ["Absolute", "Percent"], inline = "priceRev", group = "Zig Zag Settings"), true) ) zigZag.update() type dataStore matrix <float> timeOIMat matrix <float> HLmat array <int> retArr array <box> pocs matrix <float> tickLevels array <float> priceArr array <box> OIMeasures matrix <label> deltaLabels matrix <float> mappedLevel var data = dataStore.new(matrix.new<float>(2, 0), matrix.new<float>(2, 0), array.new_int(), array.new_box(), priceArr = array.new_float(), OIMeasures = array.new_box()), //kioseff tLevels = dataStore.new(tickLevels = matrix.new<float>(5, ROWS, 0.0)) determine( a, b) => result = switch same "Opposing Side" => a "Middle" => b method double_binary_search_leftmost(array <float> id, i) => n = id .binary_search_leftmost (data.HLmat.get(0, i)) n1 = id .binary_search_leftmost (data.HLmat.get(1, i)) [n, n1] method double_binary_search_leftmost_delta(array <float> id, top, btm) => n = id .binary_search_leftmost (top) n1 = id .binary_search_rightmost (btm) [n, n1] method effSwitch(matrix<float> id, i, x, div, subtract) => if data.priceArr.get(i) == 1 switch data.retArr.get(i) 1 => id.set(1, x, id.get(1, x) + data.timeOIMat.get(1, i - subtract) / div) -1 => id.set(2, x, id.get(2, x) + math.abs(data.timeOIMat.get(1, i - subtract) / div)) if data.priceArr.get(i) == -1 switch data.retArr.get(i) 1 => id.set(3, x, id.get(3, x) + data.timeOIMat.get(1, i - subtract) / div) -1 => id.set(4, x, id.get(4, x) + math.abs(data.timeOIMat.get(1, i - subtract) / div)) method pocCheck(array<box> id, array<float> timeRow, getx2) => for i = 0 to timeRow.indexof(getx2) - 1 if data.HLmat.get(0, i) >= id.last().get_top() and data.HLmat.get(1, i) <= id.last().get_top() id.last().set_right(N - i) if not useGen for x = 2 to 4 if data.HLmat.get(0, i) >= id.get(id.size() - x).get_top() and data.HLmat.get(1, i) <= id.get(id.size() - x).get_top() id.get(id.size() - x).set_right(N - i) method drawPOC(array<box> id, difference, idrow, check, newRowUp, newRowUp2, newRowDn, newRowDn2, remove, array<float> timeRow = na, int getx2 = na, int getx = na, cond1 = false) => if remove if id.size() > 0 for i = 0 to id.size() - 1 id.shift().delete() if poc start = switch same == "Middle" => cond1 ? math.round(math.avg(last_bar_index, last_bar_index - timeRow.indexof(line.all.last().get_x2()))) : N - math.round(math.avg(timeRow.indexof(getx), timeRow.indexof(getx2))) + 1 => difference + offset - 1 if not useGen if sp1 id.push(box.new(start, idrow.get(newRowUp.indexof(newRowUp.max())), N, idrow.get(newRowUp.indexof(newRowUp.max())) , bgcolor = #00000000, border_color = color.new(upCol, transp3))) if sp2 id.push(box.new(start, idrow.get(newRowUp2.indexof(newRowUp2.max())), N, idrow.get(newRowUp2.indexof(newRowUp2.max())), bgcolor = #00000000, border_color = color.new(dnCol, transp3))) if sp3 id.push(box.new(start, idrow.get(newRowDn.indexof(newRowDn.max())), N, idrow.get(newRowDn.indexof(newRowDn.max())), bgcolor = #00000000, border_color = color.new(upCol2, transp3))) if sp4 id.push(box.new(start, idrow.get(newRowDn2.indexof(newRowDn2.max())), N, idrow.get(newRowDn2.indexof(newRowDn2.max())), bgcolor = #00000000, border_color = color.new(dnCol2, transp3))) else for i = 0 to newRowUp.size() - 1 newRowUp.set(i, newRowUp.get(i) + newRowDn.get(i) + newRowUp2.get(i) + newRowDn2.get(i)) id.push(box.new(start, idrow.get(newRowUp.indexof(newRowUp.max())), N, idrow.get(newRowUp.indexof(newRowUp.max())) , bgcolor = #00000000, border_color = color.new(generalPOCcol, transp3))) if check id.pocCheck(timeRow, getx2) method setLevels(matrix<float> id, float gety, float gety2, cond) => rows = math.abs(gety2 - gety) / (ROWS - 1) start = switch cond false => math.min(gety, gety2) => gety for i = 0 to ROWS - 1 id.set(0, i, start + rows * i) method quickSet(matrix <label> id, int row, int col, array<float> timeRow, float avg, int offset, int middle, string dsz) => id.set(row, col, label.new(chart.point.from_index(middle - offset, avg), textcolor = color.white, style = label.style_none, color = #00000000, size = dsz )) method calcDelta(array<float> id, array<float> newRowUp, array<float> newRowUp2, array<float> newRowDn, array<float> newRowDn2, float getY, float getY2, int middle, array<float> timeRow) => if delta var dsz = switch deltaSz "Tiny" => size.tiny "Small" => size.small "Normal" => size.normal "Large" => size.large "Huge" => size.huge db = dataStore.new(mappedLevel = matrix.new<float>(deltaRows, 4, 0), deltaLabels = matrix.new<label>(deltaRows, 4)) newSlice = (math.max(getY, getY2) - math.min(getY, getY2)) / deltaRows for i = 0 to deltaRows - 1 btm = math.min(getY, getY2) + (newSlice * i) top = math.min(getY, getY2) + (newSlice * (i + 1)) avg = math.avg(top, btm) db.deltaLabels.quickSet(i, 0, timeRow, avg, 8 , middle, dsz) db.deltaLabels.quickSet(i, 1, timeRow, avg, 4 , middle, dsz) db.deltaLabels.quickSet(i, 2, timeRow, avg, -4, middle, dsz) db.deltaLabels.quickSet(i, 3, timeRow, avg, -8, middle, dsz) [topCol, btmCol] = id.double_binary_search_leftmost_delta(top, btm) for x = btmCol to topCol for j = 0 to 3 loopID = switch j == 0 => newRowUp j == 1 => newRowUp2 j == 2 => newRowDn j == 3 => newRowDn2 db.mappedLevel.set(i, j, db.mappedLevel.get(i, j) + loopID.get(x)) valArr = db.mappedLevel.col(0), valArr1 = db.mappedLevel.col(1), valArr2 = db.mappedLevel.col(2), valArr3 = db.mappedLevel.col(3) for i = 0 to deltaRows - 1 for x = 0 to 3 [loopID, loopCol] = switch x == 0 => [valArr , upCol ] x == 1 => [valArr1, dnCol ] x == 2 => [valArr2, upCol2] x == 3 => [valArr3, dnCol2] col = color.from_gradient(loopID.get(i), loopID.min(), loopID.max(), color.new(loopCol, transpd1), color.new(loopCol, transpd2)) db.deltaLabels.get(i, x).set_textcolor (col), db.deltaLabels.get(i, x).set_text(str.tostring(loopID.get(i) * (x == 1 or x == 3 ? -1 : 1), format.volume)) if neon if loopID.get(i) == loopID.max() db.deltaLabels.get(i, x).set_style (label.style_text_outline) db.deltaLabels.get(i, x).set_textcolor(color.white) db.deltaLabels.get(i, x).set_color (col) method createPoly(matrix<chart.point> id, array<float> timeRow, int add, int getx2, int getx, bool cond, int difference, array<float> idrow, array<float> lows, array<float> highs) => avg = switch cond false => math.round(math.avg(timeRow.indexof(getx2), timeRow.indexof(getx))) => math.round(math.avg(last_bar_index, last_bar_index - timeRow.indexof(line.all.last().get_x2()))) add2 = determine(N - timeRow.indexof(getx2), add) oper = switch cond false => determine(add2 - offset + 1, N - avg + 1) => determine(N - offset + 1, avg) [finx, finDn, finUp] = if same != "Middle" switch cond false => [add + offset - 1, idrow.min(), idrow.max()] => [difference + offset - 1, lows.min(), highs.max()] else switch cond false => [N - avg + 1, idrow.min(), idrow.max()] => [avg, lows.min(), highs.max()] id.add_col(0, array.from( chart.point.from_index(finx, finDn), chart.point.from_index(finx, finDn), chart.point.from_index(oper, finDn), chart.point.from_index(oper, finDn))) id.add_col(id.columns(), array.from( chart.point.from_index(finx, finUp),chart.point.from_index(finx, finUp), chart.point.from_index(oper, finUp),chart.point.from_index(oper, finUp))) if show1 polyline.new(id.row(0), fill_color = color.new(upCol , transp), line_color = color.new(upCol, transp2) , curved = curve) if show2 polyline.new(id.row(1), fill_color = color.new(dnCol , transp), line_color = color.new(dnCol, transp2) , curved = curve) if show3 polyline.new(id.row(2), fill_color = color.new(upCol2, transp), line_color = color.new(upCol2, transp2), curved = curve) if show4 polyline.new(id.row(3), fill_color = color.new(dnCol2, transp), line_color = color.new(dnCol2, transp2), curved = curve) norm(newRowUp, newRowUp2, newRowDn, newRowDn2, oldMin, oldMax, newRange, i) => calcUp = 1 + ((newRowUp .get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1) calcUp2 = 1 + ((newRowUp2.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1) calcDn = 1 + ((newRowDn .get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1) calcDn2 = 1 + ((newRowDn2.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1) [calcUp, calcUp2, calcDn, calcDn2] method setCoordsHistory(matrix<chart.point> id, newRowUp, newRowDn, newRowUp2, newRowDn2, oldMin, oldMax, newRange, timeRow, getx, getx2, idrow) => avg = math.round(math.avg(timeRow.indexof(getx), timeRow.indexof(getx2))) // for i = 0 to newRowUp.size() - 1 [calcUp, calcUp2, calcDn, calcDn2] = norm(newRowUp, newRowUp2, newRowDn, newRowDn2, oldMin, oldMax, newRange, i) [newSwitchUp, newSwitchUp2] = switch same "Middle" => [N - avg + calcUp, N - avg + calcUp2] => [N - timeRow.indexof(getx) + offset - calcUp, N - timeRow.indexof(getx) + offset - calcUp2] [newXUp, newXUp2] = switch same "Middle" => [math.min(newSwitchUp, N - avg), math.min(newSwitchUp2, N - avg)] => [math.max(newSwitchUp, N - timeRow.indexof(getx) + offset), math.max(newSwitchUp2, N - timeRow.indexof(getx) + offset)] [newSwitchDn, newSwitchDn2] = switch same "Middle" => [N - avg - calcDn, N - avg - calcDn2] => [N - timeRow.indexof(getx2) - offset + calcDn, N - timeRow.indexof(getx2) - offset + calcDn2] [newXDn, newXDn2] = switch same "Middle" => [math.max(newSwitchDn, N - avg) + 2, math.max(newSwitchDn2, N - avg) + 2] => [math.min(newSwitchDn, N - timeRow.indexof(getx2) - offset), math.min(newSwitchDn2, N - timeRow.indexof(getx2) - offset)] id.set(0, i, chart.point.from_index(math.round(newXUp ), idrow.get(i))), id.set(1, i, chart.point.from_index(math.round(newXUp2), idrow.get(i))) id.set(2, i, chart.point.from_index(math.round(newXDn ), idrow.get(i))), id.set(3, i, chart.point.from_index(math.round(newXDn2), idrow.get(i))) method setCoordsLive(matrix<chart.point> id, newRowUp, newRowDn, newRowUp2, newRowDn2, oldMin, oldMax, newRange, difference, newLevelsMat, timeRow) => avg = math.round(math.avg(last_bar_index, last_bar_index - timeRow.indexof(line.all.last().get_x2()))) for i = 0 to newRowUp.size() - 1 [calcUp, calcUp2, calcDn, calcDn2] = norm(newRowUp, newRowDn, newRowUp2, newRowDn2, oldMin, oldMax, newRange, i) [newSwitchUp, newSwitchUp2] = switch same "Middle" => [avg - calcUp, avg - calcUp2] => [difference + offset + calcUp - 1, difference + offset + calcUp2 - 1] [newXUp, newXUp2] = switch same "Middle" => [math.min(newSwitchUp, avg - 1), math.min(newSwitchUp2, avg - 1)] => [math.max(newSwitchUp, difference + offset), math.max(newSwitchUp2, difference + offset)] [newSwitchDn, newSwitchDn2] = switch same "Middle" => [avg + calcDn - 1, avg + calcDn2 - 1] => [N - offset - calcDn, N - offset - calcDn2] [newXDn, newXDn2] = switch same "Middle" => [math.max(newSwitchDn, avg + 1), math.max(newSwitchDn2, avg + 1)] => [math.min(newSwitchDn, N - offset - 1), math.min(newSwitchDn2, N - offset - 1)] id.add_col(id.columns(), array.from( chart.point.from_index(math.round(newXUp), newLevelsMat.get(0, i)), chart.point.from_index(math.round(newXUp2), newLevelsMat.get(0, i)), chart.point.from_index(math.round(newXDn), newLevelsMat.get(0, i)), chart.point.from_index(math.round(newXDn2), newLevelsMat.get(0, i)))) method deltaBoxes(array<box> id, newRowUp, newRowUp2, newRowDn, newRowDn2, array<float> timeRow, int getx, int getx2, float gety, float gety2, bool cond = false, array<float> highs = na) => if showL f = format.volume cols = switch cond false => (timeRow.indexof(getx) - timeRow.indexof(getx2)) / 6, => (N - (N - timeRow.indexof(line.all.last().get_x2()))) / 6 strArr = array.from( str.tostring(newRowUp .sum(), f), str.tostring(newRowUp2.sum() * -1, f), str.tostring(newRowDn .sum(), f), str.tostring(newRowDn2.sum() * -1, f)) colArr = array.from(upCol, dnCol, upCol2, dnCol2) for i = 0 to 3 start = math.round(N -timeRow.indexof(line.all.last().get_x2())) [left, right, top, bottom] = switch cond false => [N - timeRow.indexof(getx) + ((i + 1) * cols), N - timeRow.indexof(getx) + ((i + 2) * cols), math.max(gety, gety2) + atr, math.max(gety, gety2) + atr * 2] => [start + ((i + 1) * cols), start + ((i + 2) * cols), highs.max() + atr, highs.max() + atr * 2] id.push(box.new(left, top, right, bottom, text = strArr.get(i), bgcolor = color.new(colArr.get(i), 80), border_color = colArr.get(i), text_color = color.white)) method update(matrix<float> id) => if syminfo.type != "crypto" var tabl = table.new(position.top_right, 5, 5, bgcolor = #00000000, frame_color = color.white, border_color = color.white, frame_width = 1, border_width = 1) tabl.cell(0, 0, "No OI Data For This Asset Type!\nUnpredictable Results", text_color = color.red, text_size = size.large) data.timeOIMat .add_col(0, array.from(time, oi)) data.HLmat .add_col(0, array.from(high, low)) data.retArr .unshift(int(math.sign(oi))) data.priceArr .unshift(int(math.sign(close - open))) change = line.all.size() > line.all.size()[1] and line.all.size() > 2 if last_bar_index - N <= 10000 barCond = barstate.islastconfirmedhistory [minus, minus1] = switch barCond true => [2, 1] => [3, 2] if change or barCond all = line.all, allSize = all.size() getx = all.get(allSize - minus) .get_x2(), gety = all.get(allSize - minus) .get_y2() getx2 = all.get(allSize - minus1).get_x2(), gety2 = all.get(allSize - minus1).get_y2() id.setLevels(gety, gety2, false) timeRow = data.timeOIMat.row(0), idrow = id.row(0) for i = timeRow.indexof(getx) to timeRow.indexof(getx2) [l1, l2] = idrow.double_binary_search_leftmost(i) // div = math.abs(l1 - l2) + 1 for x = l1 to l2 id.effSwitch(i, x, div, 0) newRange = math.floor((timeRow.indexof(getx2) - timeRow.indexof(getx)) / factor) newRowUp = id.row(1), newRowUp2 = id.row(2), newRowDn = id.row(3), newRowDn2 = id.row(4) oldMin = math.min(newRowUp.min(), newRowDn.min(), newRowUp2.min(), newRowDn2.min()) oldMax = math.max(newRowUp.max(), newRowDn.max(), newRowUp2.max(), newRowDn2.max()) coordinates = matrix.new<chart.point>(4, newRowUp.size()) add = N - timeRow.indexof(getx) middle = N - math.round(math.avg(timeRow.indexof(getx), timeRow.indexof(getx2))) + 1 coordinates .setCoordsHistory(newRowUp, newRowUp2, newRowDn, newRowDn2, oldMin, oldMax, newRange, timeRow, getx, getx2, idrow) coordinates .createPoly(timeRow, add, getx2, getx, false, na, idrow, na, na) idrow.calcDelta(newRowUp, newRowUp2, newRowDn, newRowDn2, gety, gety2, middle, timeRow) data.OIMeasures.deltaBoxes(newRowUp, newRowUp2, newRowDn, newRowDn2, timeRow, getx, getx2, gety, gety2) data.pocs .drawPOC(add, idrow, true, newRowUp, newRowUp2, newRowDn, newRowDn2, false, timeRow, getx2, getx) realtime () => if barstate.islast var pocsLive = dataStore.new(pocs = array.new_box(), OIMeasures = array.new_box()) var coordinates = matrix.new<chart.point>(4, 0) if coordinates.columns() > 0 for i = 0 to 1 polyline.all.pop().delete() for i = 0 to coordinates.columns() - 1 coordinates.remove_col() timeRow = data.timeOIMat.row(0) startIndex = timeRow.indexof(line.all.last().get_x2()) highs = data.HLmat.row(0).slice(0, startIndex + 1) lows = data.HLmat.row(1).slice(0, startIndex + 1) newLevelsMat = matrix.new<float>(5, ROWS, 0.0) newLevelsMat.setLevels(lows.min(), highs.max(), true) levelsArr = newLevelsMat.row(0) for i = 0 to startIndex [l1, l2] = levelsArr.double_binary_search_leftmost(i) div = math.abs(l1 - l2) + 1 for x = l1 to l2 newLevelsMat.effSwitch(i, x, div, 0) difference = N - startIndex newRange = math.floor((N - difference) / factor) newRowUp = newLevelsMat.row(1), newRowUp2 = newLevelsMat.row(2) newRowDn = newLevelsMat.row(3), newRowDn2 = newLevelsMat.row(4) oldMin = math.min(newRowUp.min(), newRowDn.min()) oldMax = math.max(newRowUp.max(), newRowDn.max()) // coordinates.setCoordsLive(newRowUp, newRowUp2, newRowDn, newRowDn2, oldMin, oldMax, newRange, difference, newLevelsMat, timeRow) coordinates.createPoly(timeRow, na, na, na, true, difference, na, lows, highs) pocsLive.OIMeasures.deltaBoxes(newRowUp, newRowUp2, newRowDn, newRowDn2, timeRow, na, na, na, na, true, highs) levelsArr.calcDelta(newRowUp, newRowUp2, newRowDn, newRowDn2, lows.min(), highs.max(), math.round(math.avg(N, N - startIndex)), timeRow) pocsLive.pocs.drawPOC(difference, levelsArr, false, newRowUp, newRowUp2, newRowDn, newRowDn2, true, timeRow = timeRow, cond1 = true) method pocUpdate(array<box> id) => if id.size() > 0 for i = 0 to id.size() - 1 if high < id.get(i).get_top() or low > id.get(i).get_top() if id.get(i).get_right() == N - 1 id.get(i).set_right(N) else if delet id.get(i).delete() if delet if id.get(i).get_right() != N id.get(i).delete() if barstate.islast if data.pocs.size() > show for i = 0 to data.pocs.size() - show data.pocs.get(i).delete() tLevels.tickLevels.update(), data.pocs.pocUpdate(), realtime()
lib_color
https://www.tradingview.com/script/1TaXd8ko-lib-color/
robbatt
https://www.tradingview.com/u/robbatt/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © robbatt //@version=5 // @description library("lib_color", overlay = true) // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © robbatt // @function get offset color // @param original original color // @param offset offset for new color // @param transparency transparency for new color // @returns offset color export offset_mono(simple color original, float offset, float transparency = na) => var r = color.r(original) var g = color.g(original) var b = color.b(original) var t = na(transparency) ? color.t(original) : transparency // oscillating values between 0 and 256 with a rising input r_off = int(127 * (math.sin(math.toradians(offset + r)) + 1)) g_off = int(127 * (math.sin(math.toradians(offset + g)) + 1)) b_off = int(127 * (math.sin(math.toradians(offset + b)) + 1)) color c_off = color.rgb(r_off, g_off, b_off, t) //@description automatic detection of dark/light user layout //@returns boolean status, true: dark mode, false: light mode is_dark_mode() => var is_dark = color.r(chart.bg_color) < 128 or color.g(chart.bg_color) < 128 or color.b(chart.bg_color) < 128 is_dark /////////////////////////////////////////////////////////// // TEST /////////////////////////////////////////////////////////// var test_color = input.color(color.blue, 'base color') color off_color = offset_mono(test_color, bar_index) // plot(color.r(off_color) , 'offset color', off_color, linewidth = 4) // plot(-255, 'fg color, offset -255', offset_mono(test_color, -255), linewidth = 4) // plot(-224, 'fg color, offset -224', offset_mono(test_color, -224), linewidth = 4) // plot(-192, 'fg color, offset -192', offset_mono(test_color, -192), linewidth = 4) // plot(-160, 'fg color, offset -160', offset_mono(test_color, -160), linewidth = 4) // plot(-128, 'fg color, offset -128', offset_mono(test_color, -128), linewidth = 4) // plot(-96, 'fg color, offset -96', offset_mono(test_color, -96), linewidth = 4) // plot(-64, 'fg color, offset -64', offset_mono(test_color, -64), linewidth = 4) // plot(-32, 'fg color, offset -32', offset_mono(test_color, -32), linewidth = 4) plot(128, 'fg color', test_color, linewidth = 4) // plot(3, 'fg color, offset 0', offset_mono(test_color, 0), linewidth = 4) // plot(32, 'fg color, offset 32', offset_mono(test_color, 32), linewidth = 4) // plot(64, 'fg color, offset 64', offset_mono(test_color, 64), linewidth = 4) // plot(96, 'fg color, offset 96', offset_mono(test_color, 96), linewidth = 4) // plot(128, 'fg color, offset 128', offset_mono(test_color, 128), linewidth = 4) // plot(160, 'fg color, offset 160', offset_mono(test_color, 160), linewidth = 4) // plot(192, 'fg color, offset 192', offset_mono(test_color, 192), linewidth = 4) // plot(224, 'fg color, offset 224', offset_mono(test_color, 224), linewidth = 4) // plot(255, 'fg color, offset 255', offset_mono(test_color, 255), linewidth = 4) plotshape(true, 'oscilating indefinite', shape.circle, location.bottom, offset_mono(test_color, bar_index), size = size.small) plotshape(true, 'is dark mode', shape.circle, location.top, is_dark_mode() ? color.white : color.black, size = size.small)
lib_priceaction
https://www.tradingview.com/script/74JjWBvw-lib-priceaction/
robbatt
https://www.tradingview.com/u/robbatt/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © robbatt //@version=5 // @description a library for everything related to price action, starting off with displacements library("lib_priceaction", overlay = true) // @function calculate if there is a displacement and how strong it is // @param len The amount of candles to consider for the deviation // @param min_strength The minimum displacement strength to trigger a signal // @param o The source series on which calculations are based // @param c The source series on which calculations are based // @returns a tuple of (bool signal, float displacement_strength) export displacement(int len = 20, float min_strength = 2, float o = open, float c = close) => float bar_diff = c-o float bar_size = math.abs(bar_diff) float bar_dir = math.sign(bar_diff) float stddev = ta.stdev(bar_size, len) float strength = bar_size / stddev bool is_displacement = strength >= min_strength [is_displacement, strength * bar_dir] // @function calculate a ratio how far a price has retraced compared to a move between two reference levels // @param price_start The start price level of the reference move // @param price_end The end price level of the reference move // @param price_retracement The retraced price level // @returns the retracement ratio (float, always positive) or na if one of the inputs was na export retracement_ratio(float price_start, float price_end, float price_retracement) => na(price_start) or na(price_end) or na(price_retracement) ? na : math.abs(price_end - price_retracement)/math.abs(price_start - price_end) // @function calculate a ratio how far a price has retraced compared to a move between two reference levels // @param price_start The start price level of the reference move // @param price_end The end price level of the reference move // @param target_ratio The target retracement ratio (must be positive) // @returns the retracement target ratio price level (float) or na if one of the inputs was na export target_ratio_price(float price_start, float price_end, float target_ratio) => na(price_start) or na(price_end) or na(target_ratio) ? na : price_end + target_ratio * (price_start - price_end) // @function check if a price is in a certain range, e.g. to check if price reached a target zone // @param x the price variable // @param a one range limit (sign agnostic) // @param b other range limit (sign agnostic) // @returns true if x is between a and b (inclusive) export in_range(float x, float a, float b) => na(x) or na(a) or na(b) ? false : x >= math.min(a,b) and x <= math.max(a,b) // @function check if two price ranges overlap, e.g. to check if a target is price is possible that fits both target zones // @param x the price variable // @param a1 one limit of range 1 // @param b1 other limit of range 1 // @param a2 one limit of range 2 // @param b2 other limit of range 2 // @returns true if x is between a and b (inclusive export range_overlap(float a1, float b1, float a2, float b2) => na(a1) or na(b1) or na(a2) or na(b2) ? false : math.min(a1, b1) <= math.max(a2,b2) and math.max(a1,b1) >= math.min(a2,b2) var g_displace = "Displacement" stddev_len = input.int(10, minval = 1, title = "Length", tooltip = "Lookback for bar size stddev", group = g_displace) stddev_min = input.float(3, minval = 0, step = 0.1, title = "Min Displacement Strength", group = g_displace) disp_color = input.color(color.yellow, "Signal Marker", group = g_displace) [signal, strength] = displacement(stddev_len, stddev_min) dir = math.sign(close - open) bgcolor(signal ? disp_color : na) plotshape(signal and dir == 1, 'Signal Up', shape.triangleup, location.belowbar, color.green, size = size.small) plotshape(signal and dir == -1, 'Signal Down', shape.triangledown, location.abovebar, color.red, size = size.small) if signal and dir == 1 label.new(bar_index, na, str.tostring(strength), yloc = yloc.belowbar, color = #00000000, style = label.style_label_up, textcolor = color.black) if signal and dir == -1 label.new(bar_index, na, str.tostring(-strength), yloc = yloc.abovebar, color = #00000000, style = label.style_label_down, textcolor = color.black)
NewsEventsCad
https://www.tradingview.com/script/vBz4Rsl4-NewsEventsCad/
wppqqppq
https://www.tradingview.com/u/wppqqppq/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © wppqqppq //@version=5 // @description This library provides date and time data of the high impact news events on CAD. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script. library("NewsEventsCad") // @function CAD high impact news date and time from 2015 to 2023 export cadNews2015To2023() => array.from( timestamp("2015-01-09T13:30:00"), timestamp("2015-01-09T13:30:00"), timestamp("2015-01-21T15:00:00"), timestamp("2015-01-21T15:00:00"), timestamp("2015-01-21T15:00:00"), timestamp("2015-01-21T16:15:00"), timestamp("2015-01-23T13:30:00"), timestamp("2015-01-23T13:30:00"), timestamp("2015-02-06T13:30:00"), timestamp("2015-02-06T13:30:00"), timestamp("2015-02-24T19:00:00"), timestamp("2015-02-26T13:30:00"), timestamp("2015-02-26T13:30:00"), timestamp("2015-03-03T13:30:00"), timestamp("2015-03-04T15:00:00"), timestamp("2015-03-04T15:00:00"), timestamp("2015-03-13T12:30:00"), timestamp("2015-03-13T12:30:00"), timestamp("2015-03-20T12:30:00"), timestamp("2015-03-20T12:30:00"), timestamp("2015-03-26T13:30:00"), timestamp("2015-04-10T12:30:00"), timestamp("2015-04-10T12:30:00"), timestamp("2015-04-15T14:00:00"), timestamp("2015-04-15T14:00:00"), timestamp("2015-04-15T14:00:00"), timestamp("2015-04-15T15:15:00"), timestamp("2015-04-17T12:30:00"), timestamp("2015-04-17T12:30:00"), timestamp("2015-04-20T14:05:00"), timestamp("2015-04-24T14:30:00"), timestamp("2015-04-28T12:45:52"), timestamp("2015-05-08T12:30:00"), timestamp("2015-05-08T12:30:00"), timestamp("2015-05-19T15:45:00"), timestamp("2015-05-22T12:30:00"), timestamp("2015-05-27T14:00:00"), timestamp("2015-05-27T14:00:00"), timestamp("2015-06-05T12:30:00"), timestamp("2015-06-05T12:30:00"), timestamp("2015-06-19T12:30:00"), timestamp("2015-06-19T12:30:00"), timestamp("2015-06-19T12:30:00"), timestamp("2015-06-19T12:30:00"), timestamp("2015-07-10T12:30:00"), timestamp("2015-07-10T12:30:00"), timestamp("2015-07-15T14:00:00"), timestamp("2015-07-15T14:00:00"), timestamp("2015-07-15T15:15:00"), timestamp("2015-07-17T12:30:00"), timestamp("2015-07-17T12:30:00"), timestamp("2015-07-23T12:30:00"), timestamp("2015-08-07T12:30:00"), timestamp("2015-08-07T12:30:00"), timestamp("2015-08-21T12:30:00"), timestamp("2015-08-21T12:30:00"), timestamp("2015-09-04T12:30:00"), timestamp("2015-09-04T12:30:00"), timestamp("2015-09-09T14:00:00"), timestamp("2015-09-09T14:00:00"), timestamp("2015-09-18T12:30:00"), timestamp("2015-09-18T12:30:00"), timestamp("2015-09-21T18:45:00"), timestamp("2015-10-09T12:30:00"), timestamp("2015-10-09T12:30:00"), timestamp("2015-10-10T18:45:00"), timestamp("2015-10-12T17:20:00"), timestamp("2015-10-21T14:00:00"), timestamp("2015-10-21T14:00:00"), timestamp("2015-10-21T14:00:00"), timestamp("2015-10-21T15:15:00"), timestamp("2015-10-23T12:30:00"), timestamp("2015-10-23T12:30:00"), timestamp("2015-11-06T13:30:00"), timestamp("2015-11-06T13:30:00"), timestamp("2015-11-20T13:30:00"), timestamp("2015-11-20T13:30:00"), timestamp("2015-12-01T13:30:00"), timestamp("2015-12-02T15:00:00"), timestamp("2015-12-02T15:00:00"), timestamp("2015-12-04T13:30:00"), timestamp("2015-12-04T13:30:00"), timestamp("2015-12-08T17:50:00"), timestamp("2015-12-15T16:45:00"), timestamp("2015-12-18T13:30:00"), timestamp("2015-12-18T13:30:00"), timestamp("2016-01-07T13:25:00"), timestamp("2016-01-08T13:30:00"), timestamp("2016-01-08T13:30:00"), timestamp("2016-01-08T13:30:00"), timestamp("2016-01-20T15:00:00"), timestamp("2016-01-20T15:00:00"), timestamp("2016-01-20T15:00:00"), timestamp("2016-01-20T16:15:00"), timestamp("2016-02-05T13:30:00"), timestamp("2016-02-05T13:30:00"), timestamp("2016-02-19T13:30:00"), timestamp("2016-02-19T13:30:00"), timestamp("2016-03-09T15:00:00"), timestamp("2016-03-11T13:30:00"), timestamp("2016-03-11T13:30:00"), timestamp("2016-03-18T12:30:00"), timestamp("2016-03-18T12:30:00"), timestamp("2016-04-04T14:00:00"), timestamp("2016-04-13T14:00:00"), timestamp("2016-04-13T14:00:00"), timestamp("2016-04-13T14:00:00"), timestamp("2016-04-13T15:15:00"), timestamp("2016-04-19T15:00:00"), timestamp("2016-04-20T20:15:00"), timestamp("2016-04-22T12:30:00"), timestamp("2016-04-22T12:30:00"), timestamp("2016-04-22T12:30:00"), timestamp("2016-04-22T12:30:00"), timestamp("2016-04-22T12:30:00"), timestamp("2016-04-26T12:40:00"), timestamp("2016-05-03T16:30:00"), timestamp("2016-05-20T12:30:00"), timestamp("2016-05-20T12:30:00"), timestamp("2016-05-25T14:00:00"), timestamp("2016-05-25T14:00:00"), timestamp("2016-06-09T15:15:00"), timestamp("2016-06-15T23:40:00"), timestamp("2016-06-17T12:30:00"), timestamp("2016-06-17T12:30:00"), timestamp("2016-07-13T14:00:00"), timestamp("2016-07-13T14:00:00"), timestamp("2016-07-13T14:00:00"), timestamp("2016-07-13T15:15:00"), timestamp("2016-07-22T12:30:00"), timestamp("2016-07-22T12:30:00"), timestamp("2016-08-19T12:30:00"), timestamp("2016-08-19T12:30:00"), timestamp("2016-08-19T12:30:00"), timestamp("2016-08-19T12:30:00"), timestamp("2016-08-19T12:30:00"), timestamp("2016-08-19T12:30:00"), timestamp("2016-08-19T12:30:00"), timestamp("2016-09-07T14:00:00"), timestamp("2016-09-07T14:00:00"), timestamp("2016-09-23T12:30:00"), timestamp("2016-10-19T14:00:00"), timestamp("2016-10-19T14:00:00"), timestamp("2016-10-19T14:00:00"), timestamp("2016-10-19T15:15:00"), timestamp("2016-10-19T20:15:00"), timestamp("2016-10-24T18:30:00"), timestamp("2016-11-01T16:00:00"), timestamp("2016-11-04T12:30:00"), timestamp("2016-11-04T12:30:00"), timestamp("2016-11-11T15:50:00"), timestamp("2016-12-07T15:00:00"), timestamp("2016-12-07T15:00:00"), timestamp("2016-12-15T16:15:00"), timestamp("2017-01-18T15:00:00"), timestamp("2017-01-18T15:00:00"), timestamp("2017-01-18T15:00:00"), timestamp("2017-01-18T16:15:00"), timestamp("2017-01-31T22:35:00"), timestamp("2017-02-10T13:30:00"), timestamp("2017-02-10T13:30:00"), timestamp("2017-02-22T13:30:00"), timestamp("2017-03-01T15:00:00"), timestamp("2017-03-01T15:00:00"), timestamp("2017-03-10T13:30:00"), timestamp("2017-03-10T13:30:00"), timestamp("2017-04-07T12:30:00"), timestamp("2017-04-07T12:30:00"), timestamp("2017-04-12T14:00:00"), timestamp("2017-04-12T14:00:00"), timestamp("2017-04-12T14:00:00"), timestamp("2017-04-12T15:15:00"), timestamp("2017-04-12T20:15:00"), timestamp("2017-04-13T14:30:00"), timestamp("2017-05-04T20:25:00"), timestamp("2017-05-05T12:30:00"), timestamp("2017-05-05T12:30:00"), timestamp("2017-05-24T14:00:00"), timestamp("2017-05-24T14:00:00"), timestamp("2017-06-08T15:15:00"), timestamp("2017-06-09T12:30:00"), timestamp("2017-06-09T12:30:00"), timestamp("2017-06-28T13:30:00"), timestamp("2017-07-07T12:30:00"), timestamp("2017-07-07T12:30:00"), timestamp("2017-07-12T14:00:00"), timestamp("2017-07-12T14:00:00"), timestamp("2017-07-12T14:00:00"), timestamp("2017-07-12T15:15:00"), timestamp("2017-07-21T12:30:00"), timestamp("2017-08-04T12:30:00"), timestamp("2017-08-04T12:30:00"), timestamp("2017-09-06T14:00:00"), timestamp("2017-09-06T14:00:00"), timestamp("2017-09-08T12:30:00"), timestamp("2017-09-08T12:30:00"), timestamp("2017-09-27T15:45:00"), timestamp("2017-10-06T12:30:00"), timestamp("2017-10-06T12:30:00"), timestamp("2017-10-25T14:00:00"), timestamp("2017-10-25T14:00:00"), timestamp("2017-10-25T14:00:00"), timestamp("2017-10-25T15:15:00"), timestamp("2017-10-31T19:30:00"), timestamp("2017-11-01T20:15:00"), timestamp("2017-11-03T12:30:00"), timestamp("2017-11-03T12:30:00"), timestamp("2017-11-07T17:55:00"), timestamp("2017-11-28T16:30:00"), timestamp("2017-12-01T13:30:00"), timestamp("2017-12-01T13:30:00"), timestamp("2017-12-01T13:30:00"), timestamp("2017-12-06T15:00:00"), timestamp("2017-12-06T15:00:00"), timestamp("2017-12-14T17:25:00"), timestamp("2018-01-05T13:30:00"), timestamp("2018-01-05T13:30:00"), timestamp("2018-01-17T15:00:00"), timestamp("2018-01-17T15:00:00"), timestamp("2018-01-17T15:00:00"), timestamp("2018-01-17T16:15:00"), timestamp("2018-01-25T13:30:00"), timestamp("2018-02-09T13:30:00"), timestamp("2018-02-09T13:30:00"), timestamp("2018-02-22T13:30:00"), timestamp("2018-02-23T13:30:00"), timestamp("2018-02-23T13:30:00"), timestamp("2018-03-02T13:30:00"), timestamp("2018-03-07T15:00:00"), timestamp("2018-03-07T15:00:00"), timestamp("2018-03-08T16:00:00"), timestamp("2018-03-09T13:30:00"), timestamp("2018-03-09T13:30:00"), timestamp("2018-03-13T14:30:00"), timestamp("2018-03-23T12:30:00"), timestamp("2018-03-23T12:30:00"), timestamp("2018-04-06T12:30:00"), timestamp("2018-04-06T12:30:00"), timestamp("2018-04-18T14:00:00"), timestamp("2018-04-18T14:00:00"), timestamp("2018-04-18T14:00:00"), timestamp("2018-04-18T15:15:00"), timestamp("2018-04-20T12:30:00"), timestamp("2018-04-20T12:30:00"), timestamp("2018-04-23T19:30:00"), timestamp("2018-04-25T20:15:00"), timestamp("2018-05-01T18:30:00"), timestamp("2018-05-11T12:30:00"), timestamp("2018-05-11T12:30:00"), timestamp("2018-05-18T12:30:00"), timestamp("2018-05-18T12:30:00"), timestamp("2018-05-30T14:00:00"), timestamp("2018-05-30T14:00:00"), timestamp("2018-05-31T12:30:00"), timestamp("2018-06-07T15:15:00"), timestamp("2018-06-08T12:30:00"), timestamp("2018-06-08T12:30:00"), timestamp("2018-06-22T12:30:00"), timestamp("2018-06-22T12:30:00"), timestamp("2018-06-27T19:00:00"), timestamp("2018-07-06T12:30:00"), timestamp("2018-07-06T12:30:00"), timestamp("2018-07-11T14:00:00"), timestamp("2018-07-11T14:00:00"), timestamp("2018-07-11T14:00:00"), timestamp("2018-07-11T15:15:00"), timestamp("2018-07-20T12:30:00"), timestamp("2018-07-20T12:30:00"), timestamp("2018-08-10T12:30:00"), timestamp("2018-08-10T12:30:00"), timestamp("2018-08-17T12:30:00"), timestamp("2018-08-22T12:30:00"), timestamp("2018-08-25T16:25:00"), timestamp("2018-08-30T12:30:00"), timestamp("2018-09-05T14:00:00"), timestamp("2018-09-05T14:00:00"), timestamp("2018-09-07T12:30:00"), timestamp("2018-09-07T12:30:00"), timestamp("2018-09-21T12:30:00"), timestamp("2018-09-21T12:30:00"), timestamp("2018-09-27T21:45:00"), timestamp("2018-10-05T12:30:00"), timestamp("2018-10-05T12:30:00"), timestamp("2018-10-19T12:30:00"), timestamp("2018-10-19T12:30:00"), timestamp("2018-10-24T14:00:00"), timestamp("2018-10-24T14:00:00"), timestamp("2018-10-24T14:00:00"), timestamp("2018-10-24T15:15:00"), timestamp("2018-10-30T19:30:00"), timestamp("2018-10-31T20:15:00"), timestamp("2018-11-02T12:30:00"), timestamp("2018-11-02T12:30:00"), timestamp("2018-11-05T13:10:00"), timestamp("2018-11-23T13:30:00"), timestamp("2018-11-23T13:30:00"), timestamp("2018-11-30T13:30:00"), timestamp("2018-12-05T15:00:00"), timestamp("2018-12-05T15:00:00"), timestamp("2018-12-06T13:50:00"), timestamp("2018-12-07T13:30:00"), timestamp("2018-12-07T13:30:00"), timestamp("2018-12-19T13:30:00"), timestamp("2018-12-21T13:30:00"), timestamp("2019-01-04T13:30:00"), timestamp("2019-01-04T13:30:00"), timestamp("2019-01-09T15:00:00"), timestamp("2019-01-09T15:00:00"), timestamp("2019-01-09T15:00:00"), timestamp("2019-01-09T16:15:00"), timestamp("2019-01-18T13:30:00"), timestamp("2019-01-23T13:30:00"), timestamp("2019-02-08T13:30:00"), timestamp("2019-02-08T13:30:00"), timestamp("2019-02-21T17:35:00"), timestamp("2019-02-22T13:30:00"), timestamp("2019-02-27T13:30:00"), timestamp("2019-03-01T13:30:00"), timestamp("2019-03-06T15:00:00"), timestamp("2019-03-06T15:00:00"), timestamp("2019-03-08T13:30:00"), timestamp("2019-03-08T13:30:00"), timestamp("2019-03-22T12:30:00"), timestamp("2019-03-22T12:30:00"), timestamp("2019-04-01T18:55:00"), timestamp("2019-04-05T12:30:00"), timestamp("2019-04-05T12:30:00"), timestamp("2019-04-17T12:30:00"), timestamp("2019-04-18T12:30:00"), timestamp("2019-04-24T14:00:00"), timestamp("2019-04-24T14:00:00"), timestamp("2019-04-24T14:00:00"), timestamp("2019-04-24T15:15:00"), timestamp("2019-04-30T15:00:00"), timestamp("2019-05-01T20:15:00"), timestamp("2019-05-06T17:45:00"), timestamp("2019-05-10T12:30:00"), timestamp("2019-05-10T12:30:00"), timestamp("2019-05-15T12:30:00"), timestamp("2019-05-16T15:15:00"), timestamp("2019-05-22T12:30:00"), timestamp("2019-05-29T14:00:00"), timestamp("2019-05-29T14:00:00"), timestamp("2019-05-31T12:30:00"), timestamp("2019-06-07T12:30:00"), timestamp("2019-06-07T12:30:00"), timestamp("2019-06-19T12:30:00"), timestamp("2019-06-21T12:30:00"), timestamp("2019-07-05T12:30:00"), timestamp("2019-07-05T12:30:00"), timestamp("2019-07-10T14:00:00"), timestamp("2019-07-10T14:00:00"), timestamp("2019-07-10T14:00:00"), timestamp("2019-07-10T15:15:00"), timestamp("2019-07-17T12:30:00"), timestamp("2019-07-19T12:30:00"), timestamp("2019-08-09T12:30:00"), timestamp("2019-08-09T12:30:00"), timestamp("2019-08-21T12:30:00"), timestamp("2019-08-23T12:30:00"), timestamp("2019-08-30T12:30:00"), timestamp("2019-09-04T14:00:00"), timestamp("2019-09-04T14:00:00"), timestamp("2019-09-06T12:30:00"), timestamp("2019-09-06T12:30:00"), timestamp("2019-09-18T12:30:00"), timestamp("2019-09-20T12:30:00"), timestamp("2019-10-11T12:30:00"), timestamp("2019-10-11T12:30:00"), timestamp("2019-10-16T12:30:00"), timestamp("2019-10-22T12:30:00"), timestamp("2019-10-30T14:00:00"), timestamp("2019-10-30T14:00:00"), timestamp("2019-10-30T14:00:00"), timestamp("2019-10-30T15:15:00"), timestamp("2019-11-08T13:30:00"), timestamp("2019-11-08T13:30:00"), timestamp("2019-11-15T02:45:00"), timestamp("2019-11-20T13:30:00"), timestamp("2019-11-21T13:40:00"), timestamp("2019-11-22T13:30:00"), timestamp("2019-11-29T13:30:00"), timestamp("2019-12-04T15:00:00"), timestamp("2019-12-04T15:00:00"), timestamp("2019-12-04T16:15:00"), timestamp("2019-12-06T13:30:00"), timestamp("2019-12-06T13:30:00"), timestamp("2019-12-12T17:45:00"), timestamp("2019-12-18T13:30:00"), timestamp("2019-12-20T13:30:00"), timestamp("2020-01-09T19:00:00"), timestamp("2020-01-10T13:30:00"), timestamp("2020-01-10T13:30:00"), timestamp("2020-01-22T13:30:00"), timestamp("2020-01-22T15:00:00"), timestamp("2020-01-22T15:00:00"), timestamp("2020-01-22T15:00:00"), timestamp("2020-01-22T16:15:00"), timestamp("2020-01-24T13:30:00"), timestamp("2020-02-07T13:30:00"), timestamp("2020-02-07T13:30:00"), timestamp("2020-02-13T00:15:00"), timestamp("2020-02-19T13:30:00"), timestamp("2020-02-21T13:30:00"), timestamp("2020-02-28T13:30:00"), timestamp("2020-03-04T15:00:00"), timestamp("2020-03-04T15:00:00"), timestamp("2020-03-05T17:45:00"), timestamp("2020-03-06T13:30:00"), timestamp("2020-03-06T13:30:00"), timestamp("2020-03-13T18:00:00"), timestamp("2020-03-13T18:00:00"), timestamp("2020-03-18T12:30:00"), timestamp("2020-03-18T15:15:00"), timestamp("2020-03-20T12:30:00"), timestamp("2020-03-27T13:00:00"), timestamp("2020-03-27T13:00:00"), timestamp("2020-03-27T13:15:00"), timestamp("2020-04-09T12:30:00"), timestamp("2020-04-09T12:30:00"), timestamp("2020-04-15T14:00:00"), timestamp("2020-04-15T14:00:00"), timestamp("2020-04-15T14:00:00"), timestamp("2020-04-15T14:30:00"), timestamp("2020-04-16T20:00:00"), timestamp("2020-04-21T12:30:00"), timestamp("2020-04-22T12:30:00"), timestamp("2020-05-08T12:30:00"), timestamp("2020-05-08T12:30:00"), timestamp("2020-05-20T12:30:00"), timestamp("2020-05-22T12:30:00"), timestamp("2020-05-25T17:30:00"), timestamp("2020-05-26T21:00:00"), timestamp("2020-05-29T12:30:00"), timestamp("2020-06-03T14:00:00"), timestamp("2020-06-03T14:00:00"), timestamp("2020-06-05T12:30:00"), timestamp("2020-06-05T12:30:00"), timestamp("2020-06-17T12:30:00"), timestamp("2020-06-19T12:30:00"), timestamp("2020-06-19T12:30:30"), timestamp("2020-06-22T15:00:00"), timestamp("2020-07-10T12:30:00"), timestamp("2020-07-10T12:30:00"), timestamp("2020-07-15T14:00:00"), timestamp("2020-07-15T14:00:00"), timestamp("2020-07-15T14:00:00"), timestamp("2020-07-15T15:15:00"), timestamp("2020-07-21T12:30:00"), timestamp("2020-07-21T12:30:05"), timestamp("2020-07-22T12:30:00"), timestamp("2020-08-07T12:30:00"), timestamp("2020-08-07T12:30:00"), timestamp("2020-08-19T12:30:00"), timestamp("2020-08-21T12:30:00"), timestamp("2020-08-21T12:30:10"), timestamp("2020-08-27T15:15:00"), timestamp("2020-08-28T12:30:00"), timestamp("2020-09-04T12:30:00"), timestamp("2020-09-04T12:30:00"), timestamp("2020-09-09T14:00:00"), timestamp("2020-09-09T14:00:00"), timestamp("2020-09-10T16:30:00"), timestamp("2020-09-16T12:30:00"), timestamp("2020-09-18T12:30:00"), timestamp("2020-09-18T12:30:10"), timestamp("2020-10-08T12:30:00"), timestamp("2020-10-09T12:30:00"), timestamp("2020-10-09T12:30:00"), timestamp("2020-10-21T12:30:00"), timestamp("2020-10-21T12:30:00"), timestamp("2020-10-21T12:30:10"), timestamp("2020-10-28T14:00:00"), timestamp("2020-10-28T14:00:00"), timestamp("2020-10-28T14:00:00"), timestamp("2020-10-28T15:15:00"), timestamp("2020-11-06T13:30:00"), timestamp("2020-11-06T13:30:00"), timestamp("2020-11-06T14:00:00"), timestamp("2020-11-17T19:00:00"), timestamp("2020-11-18T13:30:00"), timestamp("2020-11-20T13:30:00"), timestamp("2020-11-20T13:30:10"), timestamp("2020-12-01T13:30:00"), timestamp("2020-12-04T13:30:00"), timestamp("2020-12-04T13:30:00"), timestamp("2020-12-09T15:00:00"), timestamp("2020-12-09T15:00:00"), timestamp("2020-12-15T19:30:00"), timestamp("2020-12-16T13:30:00"), timestamp("2020-12-18T13:30:00"), timestamp("2021-01-08T13:30:00"), timestamp("2021-01-08T13:30:00"), timestamp("2021-01-20T13:30:00"), timestamp("2021-01-20T15:00:00"), timestamp("2021-01-20T15:00:00"), timestamp("2021-01-20T15:00:00"), timestamp("2021-01-20T16:15:00"), timestamp("2021-01-22T13:30:00"), timestamp("2021-02-05T13:30:00"), timestamp("2021-02-05T13:30:00"), timestamp("2021-02-17T13:30:00"), timestamp("2021-02-19T13:30:00"), timestamp("2021-02-23T17:30:00"), timestamp("2021-03-02T13:30:00"), timestamp("2021-03-10T15:00:00"), timestamp("2021-03-10T15:00:00"), timestamp("2021-03-12T13:30:00"), timestamp("2021-03-12T13:30:00"), timestamp("2021-03-17T12:30:00"), timestamp("2021-03-19T12:30:00"), timestamp("2021-03-25T09:30:00"), timestamp("2021-04-09T12:30:00"), timestamp("2021-04-09T12:30:00"), timestamp("2021-04-21T12:30:00"), timestamp("2021-04-21T14:00:00"), timestamp("2021-04-21T14:00:00"), timestamp("2021-04-21T14:00:00"), timestamp("2021-04-21T15:00:00"), timestamp("2021-04-27T20:00:00"), timestamp("2021-04-28T12:30:00"), timestamp("2021-05-05T22:30:00"), timestamp("2021-05-07T12:30:00"), timestamp("2021-05-07T12:30:00"), timestamp("2021-05-13T15:00:00"), timestamp("2021-05-19T12:30:00"), timestamp("2021-05-21T12:30:00"), timestamp("2021-06-01T12:30:00"), timestamp("2021-06-04T12:30:00"), timestamp("2021-06-04T12:30:00"), timestamp("2021-06-09T14:00:00"), timestamp("2021-06-09T14:00:00"), timestamp("2021-06-16T12:30:00"), timestamp("2021-06-16T22:30:00"), timestamp("2021-06-23T12:30:00"), timestamp("2021-07-09T12:30:00"), timestamp("2021-07-09T12:30:00"), timestamp("2021-07-14T14:00:00"), timestamp("2021-07-14T14:00:00"), timestamp("2021-07-14T14:00:00"), timestamp("2021-07-14T15:15:00"), timestamp("2021-07-23T12:30:00"), timestamp("2021-07-28T12:30:00"), timestamp("2021-08-06T12:30:00"), timestamp("2021-08-06T12:30:00"), timestamp("2021-08-18T12:30:00"), timestamp("2021-08-20T12:30:00"), timestamp("2021-08-31T12:30:00"), timestamp("2021-09-08T14:00:00"), timestamp("2021-09-08T14:00:00"), timestamp("2021-09-09T16:00:00"), timestamp("2021-09-10T12:30:00"), timestamp("2021-09-10T12:30:00"), timestamp("2021-09-15T12:30:00"), timestamp("2021-09-23T12:30:00"), timestamp("2021-10-07T16:00:00"), timestamp("2021-10-08T12:30:00"), timestamp("2021-10-08T12:30:00"), timestamp("2021-10-20T12:30:00"), timestamp("2021-10-22T12:30:00"), timestamp("2021-10-27T14:00:00"), timestamp("2021-10-27T14:00:00"), timestamp("2021-10-27T14:00:00"), timestamp("2021-10-27T15:00:00"), timestamp("2021-11-05T12:30:00"), timestamp("2021-11-05T12:30:00"), timestamp("2021-11-09T22:45:00"), timestamp("2021-11-17T13:30:00"), timestamp("2021-11-19T13:30:00"), timestamp("2021-11-29T19:00:00"), timestamp("2021-11-30T13:30:00"), timestamp("2021-12-03T13:30:00"), timestamp("2021-12-03T13:30:00"), timestamp("2021-12-08T15:00:00"), timestamp("2021-12-08T15:00:00"), timestamp("2021-12-13T15:00:00"), timestamp("2021-12-13T15:30:00"), timestamp("2021-12-15T13:30:00"), timestamp("2021-12-15T17:00:00"), timestamp("2021-12-21T13:30:00"), timestamp("2022-01-07T13:30:00"), timestamp("2022-01-07T13:30:00"), timestamp("2022-01-19T13:30:00"), timestamp("2022-01-21T13:30:00"), timestamp("2022-01-26T15:00:00"), timestamp("2022-01-26T15:00:00"), timestamp("2022-01-26T15:00:00"), timestamp("2022-01-26T16:00:00"), timestamp("2022-02-02T20:00:00"), timestamp("2022-02-04T13:30:00"), timestamp("2022-02-04T13:30:00"), timestamp("2022-02-09T17:00:00"), timestamp("2022-02-16T13:30:00"), timestamp("2022-02-18T13:30:00"), timestamp("2022-03-01T13:30:00"), timestamp("2022-03-02T15:00:00"), timestamp("2022-03-02T15:00:00"), timestamp("2022-03-03T16:30:00"), timestamp("2022-03-03T20:30:00"), timestamp("2022-03-11T13:30:00"), timestamp("2022-03-11T13:30:00"), timestamp("2022-03-16T12:30:00"), timestamp("2022-03-18T12:30:00"), timestamp("2022-04-08T12:30:00"), timestamp("2022-04-08T12:30:00"), timestamp("2022-04-13T14:00:00"), timestamp("2022-04-13T14:00:00"), timestamp("2022-04-13T14:00:00"), timestamp("2022-04-13T15:00:00"), timestamp("2022-04-20T12:30:00"), timestamp("2022-04-22T12:30:00"), timestamp("2022-04-25T15:00:00"), timestamp("2022-04-27T22:30:00"), timestamp("2022-05-06T12:30:00"), timestamp("2022-05-06T12:30:00"), timestamp("2022-05-18T12:30:00"), timestamp("2022-05-26T12:30:00"), timestamp("2022-05-31T12:30:00"), timestamp("2022-06-01T14:00:00"), timestamp("2022-06-01T14:00:00"), timestamp("2022-06-10T12:30:00"), timestamp("2022-06-10T12:30:00"), timestamp("2022-06-21T12:30:00"), timestamp("2022-06-22T12:30:00"), timestamp("2022-07-08T12:30:00"), timestamp("2022-07-08T12:30:00"), timestamp("2022-07-13T14:00:00"), timestamp("2022-07-13T14:00:00"), timestamp("2022-07-13T14:00:00"), timestamp("2022-07-13T15:00:00"), timestamp("2022-07-20T12:30:00"), timestamp("2022-07-22T12:30:00"), timestamp("2022-08-05T12:30:00"), timestamp("2022-08-05T12:30:00"), timestamp("2022-08-16T12:30:00"), timestamp("2022-08-19T12:30:00"), timestamp("2022-08-31T12:30:00"), timestamp("2022-09-07T14:00:00"), timestamp("2022-09-07T14:00:00"), timestamp("2022-09-09T12:30:00"), timestamp("2022-09-09T12:30:00"), timestamp("2022-09-20T12:30:00"), timestamp("2022-09-23T12:30:00"), timestamp("2022-10-06T15:35:00"), timestamp("2022-10-07T12:30:00"), timestamp("2022-10-07T12:30:00"), timestamp("2022-10-19T12:30:00"), timestamp("2022-10-21T12:30:00"), timestamp("2022-10-26T14:00:00"), timestamp("2022-10-26T14:00:00"), timestamp("2022-10-26T14:00:00"), timestamp("2022-10-26T15:00:00"), timestamp("2022-11-01T22:30:00"), timestamp("2022-11-04T12:30:00"), timestamp("2022-11-04T12:30:00"), timestamp("2022-11-10T16:50:00"), timestamp("2022-11-16T13:30:00"), timestamp("2022-11-22T13:30:00"), timestamp("2022-11-23T21:30:00"), timestamp("2022-11-29T13:30:00"), timestamp("2022-12-02T13:30:00"), timestamp("2022-12-02T13:30:00"), timestamp("2022-12-07T15:00:00"), timestamp("2022-12-07T15:00:00"), timestamp("2022-12-12T20:25:00"), timestamp("2022-12-20T13:30:00"), timestamp("2022-12-21T13:30:00"), timestamp("2023-01-06T13:30:00"), timestamp("2023-01-06T13:30:00"), timestamp("2023-01-10T10:10:00"), timestamp("2023-01-17T13:30:00"), timestamp("2023-01-20T13:30:00"), timestamp("2023-01-25T15:00:00"), timestamp("2023-01-25T15:00:00"), timestamp("2023-01-25T15:00:00"), timestamp("2023-01-25T16:00:00"), timestamp("2023-02-07T17:30:00"), timestamp("2023-02-10T13:30:00"), timestamp("2023-02-10T13:30:00"), timestamp("2023-02-16T16:00:00"), timestamp("2023-02-21T13:30:00"), timestamp("2023-02-21T13:30:00"), timestamp("2023-02-28T13:30:00"), timestamp("2023-03-08T15:00:00"), timestamp("2023-03-08T15:00:00"), timestamp("2023-03-10T13:30:00"), timestamp("2023-03-10T13:30:00"), timestamp("2023-03-21T12:30:00"), timestamp("2023-03-24T12:30:00"), timestamp("2023-04-06T12:30:00"), timestamp("2023-04-06T12:30:00"), timestamp("2023-04-12T14:00:00"), timestamp("2023-04-12T14:00:00"), timestamp("2023-04-12T14:00:00"), timestamp("2023-04-12T15:00:00"), timestamp("2023-04-13T13:00:00"), timestamp("2023-04-18T12:30:00"), timestamp("2023-04-18T15:30:00"), timestamp("2023-04-20T15:30:00"), timestamp("2023-04-21T12:30:00"), timestamp("2023-05-04T16:50:00"), timestamp("2023-05-05T12:30:00"), timestamp("2023-05-05T12:30:00"), timestamp("2023-05-16T12:30:00"), timestamp("2023-05-19T12:30:00"), timestamp("2023-05-31T12:30:00"), timestamp("2023-06-07T14:00:00"), timestamp("2023-06-07T14:00:00"), timestamp("2023-06-09T12:30:00"), timestamp("2023-06-09T12:30:00"), timestamp("2023-06-21T12:30:00"), timestamp("2023-06-27T12:30:00"), timestamp("2023-06-27T12:30:00"), timestamp("2023-07-07T12:30:00"), timestamp("2023-07-07T12:30:00"), timestamp("2023-07-12T14:00:00"), timestamp("2023-07-12T14:00:00"), timestamp("2023-07-12T14:00:00"), timestamp("2023-07-12T15:00:00"), timestamp("2023-07-19T12:30:00"), timestamp("2023-07-19T12:30:00"), timestamp("2023-08-04T12:30:00"), timestamp("2023-08-04T12:30:00"), timestamp("2023-08-16T12:30:00"), timestamp("2023-08-16T12:30:00"), timestamp("2023-08-31T12:30:00"), timestamp("2023-09-06T14:00:00"), timestamp("2023-09-06T14:00:00"), timestamp("2023-09-08T12:30:00"), timestamp("2023-09-08T12:30:00"), timestamp("2023-09-20T12:30:00"), timestamp("2023-09-20T12:30:00"), timestamp("2023-10-06T12:30:00"), timestamp("2023-10-06T12:30:00"), timestamp("2023-10-18T12:30:00"), timestamp("2023-10-18T12:30:00"), timestamp("2023-10-25T14:00:00"), timestamp("2023-10-25T14:00:00"), timestamp("2023-10-25T14:00:00"), timestamp("2023-10-25T15:00:00"), timestamp("2023-11-03T12:30:00"), timestamp("2023-11-03T12:30:00"), timestamp("2023-11-15T13:30:00"), timestamp("2023-11-15T13:30:00"), timestamp("2023-11-30T13:30:00"), timestamp("2023-12-01T13:30:00"), timestamp("2023-12-01T13:30:00"), timestamp("2023-12-06T15:00:00"), timestamp("2023-12-06T15:00:00"), timestamp("2023-12-13T13:30:00"), timestamp("2023-12-13T13:30:00") )
NewsEventsUsd
https://www.tradingview.com/script/nPdurDTe-NewsEventsUsd/
wppqqppq
https://www.tradingview.com/u/wppqqppq/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © wppqqppq //@version=5 // @description This library provides date and time data of the high impact news events on USD. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script. library("NewsEventsUsd") // @function USD high impact news date and time from 2015 to 2019 export usdNews2015To2019() => array.from( timestamp("2015-01-02T15:00:00"), timestamp("2015-01-06T15:00:00"), timestamp("2015-01-07T19:00:00"), timestamp("2015-01-09T13:30:00"), timestamp("2015-01-09T13:30:00"), timestamp("2015-01-14T13:30:00"), timestamp("2015-01-16T13:30:00"), timestamp("2015-01-16T13:30:00"), timestamp("2015-01-27T13:30:00"), timestamp("2015-01-27T15:00:00"), timestamp("2015-01-28T19:00:00"), timestamp("2015-01-28T19:00:00"), timestamp("2015-01-30T13:30:00"), timestamp("2015-02-02T15:00:00"), timestamp("2015-02-04T15:00:00"), timestamp("2015-02-06T13:30:00"), timestamp("2015-02-06T13:30:00"), timestamp("2015-02-12T13:30:00"), timestamp("2015-02-18T19:00:00"), timestamp("2015-02-24T15:00:00"), timestamp("2015-02-24T15:00:00"), timestamp("2015-02-25T15:00:00"), timestamp("2015-02-26T13:30:00"), timestamp("2015-02-26T13:30:00"), timestamp("2015-02-26T13:30:00"), timestamp("2015-02-27T13:30:00"), timestamp("2015-03-02T15:00:00"), timestamp("2015-03-04T15:00:00"), timestamp("2015-03-06T13:30:00"), timestamp("2015-03-06T13:30:00"), timestamp("2015-03-11T20:30:00"), timestamp("2015-03-12T12:30:00"), timestamp("2015-03-18T18:00:00"), timestamp("2015-03-18T18:00:00"), timestamp("2015-03-18T18:30:00"), timestamp("2015-03-24T12:30:00"), timestamp("2015-03-24T12:30:00"), timestamp("2015-03-25T12:30:00"), timestamp("2015-03-27T12:30:00"), timestamp("2015-03-31T14:00:00"), timestamp("2015-04-01T14:00:00"), timestamp("2015-04-03T12:30:00"), timestamp("2015-04-03T12:30:00"), timestamp("2015-04-06T14:00:00"), timestamp("2015-04-08T18:00:00"), timestamp("2015-04-14T12:30:00"), timestamp("2015-04-17T12:30:00"), timestamp("2015-04-17T12:30:00"), timestamp("2015-04-24T12:30:00"), timestamp("2015-04-28T14:00:00"), timestamp("2015-04-29T12:30:00"), timestamp("2015-04-29T18:00:00"), timestamp("2015-05-01T14:00:00"), timestamp("2015-05-05T14:00:00"), timestamp("2015-05-08T12:30:00"), timestamp("2015-05-08T12:30:00"), timestamp("2015-05-13T12:30:00"), timestamp("2015-05-13T12:30:00"), timestamp("2015-05-20T18:00:00"), timestamp("2015-05-22T12:30:00"), timestamp("2015-05-22T12:30:00"), timestamp("2015-05-22T17:00:00"), timestamp("2015-05-26T12:30:00"), timestamp("2015-05-26T12:30:00"), timestamp("2015-05-29T12:30:00"), timestamp("2015-06-01T14:00:00"), timestamp("2015-06-05T12:30:00"), timestamp("2015-06-05T12:30:00"), timestamp("2015-06-11T12:30:00"), timestamp("2015-06-11T12:30:00"), timestamp("2015-06-17T18:00:00"), timestamp("2015-06-17T18:00:00"), timestamp("2015-06-17T18:30:00"), timestamp("2015-06-18T12:30:00"), timestamp("2015-06-18T12:30:00"), timestamp("2015-06-23T12:30:00"), timestamp("2015-06-23T12:30:00"), timestamp("2015-06-24T12:30:00"), timestamp("2015-06-24T12:30:00"), timestamp("2015-07-01T14:00:00"), timestamp("2015-07-02T12:30:00"), timestamp("2015-07-02T12:30:00"), timestamp("2015-07-08T18:00:00"), timestamp("2015-07-14T12:30:00"), timestamp("2015-07-14T12:30:00"), timestamp("2015-07-16T18:30:00"), timestamp("2015-07-17T12:30:00"), timestamp("2015-07-17T12:30:00"), timestamp("2015-07-27T12:30:00"), timestamp("2015-07-27T12:30:00"), timestamp("2015-07-29T18:00:00"), timestamp("2015-07-29T18:00:00"), timestamp("2015-07-30T12:30:00"), timestamp("2015-07-30T12:30:00"), timestamp("2015-08-03T14:00:00"), timestamp("2015-08-03T14:00:00"), timestamp("2015-08-07T12:30:00"), timestamp("2015-08-07T12:30:00"), timestamp("2015-08-13T12:30:00"), timestamp("2015-08-13T12:30:00"), timestamp("2015-08-19T12:30:00"), timestamp("2015-08-19T12:30:00"), timestamp("2015-08-19T18:00:00"), timestamp("2015-08-26T12:30:00"), timestamp("2015-08-27T00:00:00"), timestamp("2015-08-27T12:30:00"), timestamp("2015-08-27T12:30:00"), timestamp("2015-08-27T12:30:00"), timestamp("2015-08-27T12:30:00"), timestamp("2015-08-28T00:00:00"), timestamp("2015-08-29T00:00:00"), timestamp("2015-08-29T04:25:00"), timestamp("2015-09-04T12:30:00"), timestamp("2015-09-04T12:30:00"), timestamp("2015-09-04T12:30:00"), timestamp("2015-09-15T12:30:00"), timestamp("2015-09-15T12:30:00"), timestamp("2015-09-16T12:30:00"), timestamp("2015-09-16T12:30:00"), timestamp("2015-09-17T18:00:00"), timestamp("2015-09-17T18:30:00"), timestamp("2015-09-25T12:30:00"), timestamp("2015-09-28T12:30:00"), timestamp("2015-10-01T14:00:00"), timestamp("2015-10-01T14:00:00"), timestamp("2015-10-02T12:30:00"), timestamp("2015-10-02T12:30:00"), timestamp("2015-10-08T18:00:00"), timestamp("2015-10-14T12:30:00"), timestamp("2015-10-14T12:30:00"), timestamp("2015-10-15T12:30:00"), timestamp("2015-10-15T12:30:00"), timestamp("2015-10-16T14:00:00"), timestamp("2015-10-27T12:30:00"), timestamp("2015-10-27T14:00:00"), timestamp("2015-10-28T18:00:00"), timestamp("2015-10-28T18:00:00"), timestamp("2015-10-29T12:30:00"), timestamp("2015-10-29T12:30:00"), timestamp("2015-10-29T12:30:00"), timestamp("2015-11-02T15:00:00"), timestamp("2015-11-04T15:00:00"), timestamp("2015-11-06T13:30:00"), timestamp("2015-11-06T13:30:00"), timestamp("2015-11-13T13:30:00"), timestamp("2015-11-13T13:30:00"), timestamp("2015-11-17T13:30:00"), timestamp("2015-11-17T13:30:00"), timestamp("2015-11-18T19:00:00"), timestamp("2015-11-25T13:30:00"), timestamp("2015-11-25T13:30:00"), timestamp("2015-12-03T15:00:00"), timestamp("2015-12-04T13:30:00"), timestamp("2015-12-04T13:30:00"), timestamp("2015-12-11T13:30:00"), timestamp("2015-12-11T13:30:00"), timestamp("2015-12-15T13:30:00"), timestamp("2015-12-15T13:30:00"), timestamp("2015-12-16T19:00:00"), timestamp("2015-12-16T19:30:00"), timestamp("2015-12-22T13:30:00"), timestamp("2015-12-22T13:30:00"), timestamp("2015-12-23T13:30:00"), timestamp("2015-12-23T13:30:00"), timestamp("2016-01-04T15:00:00"), timestamp("2016-01-04T15:00:00"), timestamp("2016-01-06T19:00:00"), timestamp("2016-01-08T13:30:00"), timestamp("2016-01-08T13:30:00"), timestamp("2016-01-15T13:30:00"), timestamp("2016-01-20T13:30:00"), timestamp("2016-01-20T13:30:00"), timestamp("2016-01-27T19:00:00"), timestamp("2016-01-27T19:00:00"), timestamp("2016-01-28T13:30:00"), timestamp("2016-01-28T13:30:00"), timestamp("2016-01-29T13:30:00"), timestamp("2016-01-29T13:30:00"), timestamp("2016-02-05T13:30:00"), timestamp("2016-02-05T13:30:00"), timestamp("2016-02-10T14:00:00"), timestamp("2016-02-11T15:00:00"), timestamp("2016-02-12T13:30:00"), timestamp("2016-02-12T13:30:00"), timestamp("2016-02-12T13:30:00"), timestamp("2016-02-17T19:00:00"), timestamp("2016-02-19T13:30:00"), timestamp("2016-02-19T13:30:00"), timestamp("2016-02-23T15:00:00"), timestamp("2016-02-25T13:30:00"), timestamp("2016-02-25T13:30:00"), timestamp("2016-02-26T13:30:00"), timestamp("2016-02-26T13:30:00"), timestamp("2016-02-26T13:30:00"), timestamp("2016-02-26T15:00:00"), timestamp("2016-03-01T15:00:00"), timestamp("2016-03-01T15:00:00"), timestamp("2016-03-04T13:30:00"), timestamp("2016-03-04T13:30:00"), timestamp("2016-03-15T12:30:00"), timestamp("2016-03-16T18:00:00"), timestamp("2016-03-16T18:00:00"), timestamp("2016-03-16T18:30:00"), timestamp("2016-03-28T12:30:00"), timestamp("2016-03-29T14:00:00"), timestamp("2016-04-01T12:30:00"), timestamp("2016-04-01T12:30:00"), timestamp("2016-04-01T14:00:00"), timestamp("2016-04-01T14:00:00"), timestamp("2016-04-06T18:00:00"), timestamp("2016-04-11T13:30:00"), timestamp("2016-04-13T12:30:00"), timestamp("2016-04-26T12:30:00"), timestamp("2016-04-27T18:00:00"), timestamp("2016-04-27T18:00:00"), timestamp("2016-05-02T14:00:00"), timestamp("2016-05-06T12:30:00"), timestamp("2016-05-06T12:30:00"), timestamp("2016-05-13T12:30:00"), timestamp("2016-05-18T18:00:00"), timestamp("2016-05-26T12:30:00"), timestamp("2016-05-26T12:30:00"), timestamp("2016-06-01T14:00:00"), timestamp("2016-06-01T14:00:00"), timestamp("2016-06-03T12:30:00"), timestamp("2016-06-03T12:30:00"), timestamp("2016-06-14T12:30:00"), timestamp("2016-06-14T12:30:00"), timestamp("2016-06-14T12:30:00"), timestamp("2016-06-15T18:00:00"), timestamp("2016-06-15T18:00:00"), timestamp("2016-06-15T18:00:00"), timestamp("2016-06-15T18:30:00"), timestamp("2016-06-21T14:00:00"), timestamp("2016-06-22T14:00:00"), timestamp("2016-06-29T20:30:00"), timestamp("2016-07-01T14:00:00"), timestamp("2016-07-06T18:00:00"), timestamp("2016-07-08T12:30:00"), timestamp("2016-07-08T12:30:00"), timestamp("2016-07-15T12:30:00"), timestamp("2016-07-27T12:30:00"), timestamp("2016-07-27T18:00:00"), timestamp("2016-07-27T18:00:00"), timestamp("2016-07-29T12:30:00"), timestamp("2016-07-29T12:30:00"), timestamp("2016-08-01T14:00:00"), timestamp("2016-08-01T14:00:00"), timestamp("2016-08-05T12:30:00"), timestamp("2016-08-05T12:30:00"), timestamp("2016-08-12T12:30:00"), timestamp("2016-08-17T18:00:00"), timestamp("2016-08-25T00:00:00"), timestamp("2016-08-26T00:00:00"), timestamp("2016-08-26T12:30:00"), timestamp("2016-08-26T14:00:00"), timestamp("2016-09-01T14:00:00"), timestamp("2016-09-01T14:00:00"), timestamp("2016-09-02T12:30:00"), timestamp("2016-09-02T12:30:00"), timestamp("2016-09-06T14:00:00"), timestamp("2016-09-15T12:30:00"), timestamp("2016-09-16T12:30:00"), timestamp("2016-09-16T12:30:00"), timestamp("2016-09-16T14:00:00"), timestamp("2016-09-21T18:00:00"), timestamp("2016-09-21T18:00:00"), timestamp("2016-09-21T18:00:00"), timestamp("2016-09-21T18:30:00"), timestamp("2016-09-28T12:30:00"), timestamp("2016-09-28T14:00:00"), timestamp("2016-09-28T14:30:00"), timestamp("2016-09-29T12:30:00"), timestamp("2016-09-29T20:00:00"), timestamp("2016-10-03T14:00:00"), timestamp("2016-10-03T14:00:00"), timestamp("2016-10-07T12:30:00"), timestamp("2016-10-07T12:30:00"), timestamp("2016-10-12T18:00:00"), timestamp("2016-10-14T12:30:00"), timestamp("2016-10-14T14:00:00"), timestamp("2016-10-14T17:30:00"), timestamp("2016-10-27T12:30:00"), timestamp("2016-10-27T12:30:00"), timestamp("2016-10-28T12:30:00"), timestamp("2016-11-01T14:00:00"), timestamp("2016-11-01T14:00:00"), timestamp("2016-11-02T18:00:00"), timestamp("2016-11-02T18:00:00"), timestamp("2016-11-04T12:30:00"), timestamp("2016-11-04T12:30:00"), timestamp("2016-11-08T13:00:00"), timestamp("2016-11-11T15:00:00"), timestamp("2016-11-15T13:30:00"), timestamp("2016-11-15T13:30:00"), timestamp("2016-11-15T13:30:00"), timestamp("2016-11-16T15:30:00"), timestamp("2016-11-17T15:00:00"), timestamp("2016-11-23T13:30:00"), timestamp("2016-11-23T13:30:00"), timestamp("2016-11-23T15:30:00"), timestamp("2016-11-23T19:00:00"), timestamp("2016-11-29T13:30:00"), timestamp("2016-11-30T16:00:00"), timestamp("2016-12-01T15:00:00"), timestamp("2016-12-02T13:30:00"), timestamp("2016-12-02T13:30:00"), timestamp("2016-12-02T13:30:00"), timestamp("2016-12-14T13:30:00"), timestamp("2016-12-14T19:00:00"), timestamp("2016-12-14T19:00:00"), timestamp("2016-12-14T19:00:00"), timestamp("2016-12-14T19:30:00"), timestamp("2016-12-15T13:30:00"), timestamp("2016-12-15T13:30:00"), timestamp("2016-12-19T18:30:00"), timestamp("2016-12-21T15:30:00"), timestamp("2016-12-22T13:30:00"), timestamp("2016-12-22T13:30:00"), timestamp("2016-12-22T13:30:00"), timestamp("2016-12-22T13:30:00"), timestamp("2017-01-03T15:00:00"), timestamp("2017-01-03T15:00:00"), timestamp("2017-01-04T19:00:00"), timestamp("2017-01-06T13:30:00"), timestamp("2017-01-06T13:30:00"), timestamp("2017-01-06T13:30:00"), timestamp("2017-01-11T16:00:00"), timestamp("2017-01-13T13:30:00"), timestamp("2017-01-17T15:00:00"), timestamp("2017-01-18T13:30:00"), timestamp("2017-01-18T13:30:00"), timestamp("2017-01-20T18:00:00"), timestamp("2017-01-27T13:30:00"), timestamp("2017-01-27T15:00:00"), timestamp("2017-02-01T15:00:00"), timestamp("2017-02-01T15:00:00"), timestamp("2017-02-01T19:00:00"), timestamp("2017-02-01T19:00:00"), timestamp("2017-02-03T13:30:00"), timestamp("2017-02-03T13:30:00"), timestamp("2017-02-15T13:30:00"), timestamp("2017-02-15T13:30:00"), timestamp("2017-02-15T15:00:00"), timestamp("2017-02-22T19:00:00"), timestamp("2017-02-27T13:30:00"), timestamp("2017-02-27T13:30:00"), timestamp("2017-02-28T13:30:00"), timestamp("2017-03-01T02:00:00"), timestamp("2017-03-01T15:00:00"), timestamp("2017-03-03T18:00:00"), timestamp("2017-03-10T13:30:00"), timestamp("2017-03-10T13:30:00"), timestamp("2017-03-15T12:30:00"), timestamp("2017-03-15T12:30:00"), timestamp("2017-03-15T12:30:00"), timestamp("2017-03-15T18:00:00"), timestamp("2017-03-15T18:00:00"), timestamp("2017-03-15T18:00:00"), timestamp("2017-03-15T18:30:00"), timestamp("2017-03-17T16:30:00"), timestamp("2017-03-23T12:45:00"), timestamp("2017-03-24T20:15:00"), timestamp("2017-03-30T12:30:00"), timestamp("2017-04-03T14:00:00"), timestamp("2017-04-03T14:00:00"), timestamp("2017-04-05T18:00:00"), timestamp("2017-04-06T22:00:00"), timestamp("2017-04-07T12:30:00"), timestamp("2017-04-07T12:30:00"), timestamp("2017-04-07T14:00:00"), timestamp("2017-04-10T20:10:00"), timestamp("2017-04-12T10:00:00"), timestamp("2017-04-14T12:30:00"), timestamp("2017-04-14T12:30:00"), timestamp("2017-04-14T12:30:00"), timestamp("2017-04-20T17:15:00"), timestamp("2017-04-22T20:15:00"), timestamp("2017-04-27T12:30:00"), timestamp("2017-04-27T12:30:00"), timestamp("2017-04-28T12:30:00"), timestamp("2017-04-28T12:30:00"), timestamp("2017-05-01T14:00:00"), timestamp("2017-05-01T14:00:00"), timestamp("2017-05-01T14:45:00"), timestamp("2017-05-03T18:00:00"), timestamp("2017-05-03T18:00:00"), timestamp("2017-05-05T12:30:00"), timestamp("2017-05-05T12:30:00"), timestamp("2017-05-05T17:30:00"), timestamp("2017-05-12T12:30:00"), timestamp("2017-05-12T12:30:00"), timestamp("2017-05-12T12:30:00"), timestamp("2017-05-18T14:00:00"), timestamp("2017-05-24T18:00:00"), timestamp("2017-05-25T12:00:00"), timestamp("2017-05-25T15:00:00"), timestamp("2017-05-26T12:30:00"), timestamp("2017-05-26T12:30:00"), timestamp("2017-05-26T12:30:00"), timestamp("2017-06-01T14:00:00"), timestamp("2017-06-01T14:00:00"), timestamp("2017-06-02T12:30:00"), timestamp("2017-06-02T12:30:00"), timestamp("2017-06-02T12:30:00"), timestamp("2017-06-14T12:30:00"), timestamp("2017-06-14T12:30:00"), timestamp("2017-06-14T12:30:00"), timestamp("2017-06-14T18:00:00"), timestamp("2017-06-14T18:00:00"), timestamp("2017-06-14T18:00:00"), timestamp("2017-06-14T18:30:00"), timestamp("2017-06-22T20:30:00"), timestamp("2017-06-26T12:30:00"), timestamp("2017-06-26T12:30:00"), timestamp("2017-06-27T17:00:00"), timestamp("2017-06-29T12:30:00"), timestamp("2017-07-03T14:00:00"), timestamp("2017-07-03T14:00:00"), timestamp("2017-07-05T18:00:00"), timestamp("2017-07-06T11:00:00"), timestamp("2017-07-07T11:00:00"), timestamp("2017-07-07T12:30:00"), timestamp("2017-07-07T12:30:00"), timestamp("2017-07-07T12:30:00"), timestamp("2017-07-12T14:00:00"), timestamp("2017-07-13T14:00:00"), timestamp("2017-07-13T15:00:00"), timestamp("2017-07-14T12:30:00"), timestamp("2017-07-14T12:30:00"), timestamp("2017-07-14T12:30:00"), timestamp("2017-07-19T14:30:00"), timestamp("2017-07-26T18:00:00"), timestamp("2017-07-26T18:00:00"), timestamp("2017-07-28T12:30:00"), timestamp("2017-08-01T14:00:00"), timestamp("2017-08-01T14:00:00"), timestamp("2017-08-04T12:30:00"), timestamp("2017-08-04T12:30:00"), timestamp("2017-08-11T12:30:00"), timestamp("2017-08-11T12:30:00"), timestamp("2017-08-15T12:30:00"), timestamp("2017-08-15T12:30:00"), timestamp("2017-08-16T18:00:00"), timestamp("2017-08-24T08:00:00"), timestamp("2017-08-25T00:00:00"), timestamp("2017-08-25T14:00:00"), timestamp("2017-08-26T00:00:00"), timestamp("2017-08-30T12:30:00"), timestamp("2017-08-30T12:30:00"), timestamp("2017-08-31T12:30:00"), timestamp("2017-08-31T12:30:00"), timestamp("2017-09-01T12:30:00"), timestamp("2017-09-01T12:30:00"), timestamp("2017-09-01T12:30:00"), timestamp("2017-09-01T14:00:00"), timestamp("2017-09-01T14:00:00"), timestamp("2017-09-13T12:30:00"), timestamp("2017-09-14T12:30:00"), timestamp("2017-09-14T12:30:00"), timestamp("2017-09-15T12:30:00"), timestamp("2017-09-20T18:00:00"), timestamp("2017-09-20T18:00:00"), timestamp("2017-09-20T18:30:00"), timestamp("2017-09-26T16:45:00"), timestamp("2017-09-27T19:00:00"), timestamp("2017-09-28T12:30:00"), timestamp("2017-09-28T12:30:00"), timestamp("2017-09-29T12:30:00"), timestamp("2017-09-29T12:30:00"), timestamp("2017-10-02T14:00:00"), timestamp("2017-10-02T14:00:00"), timestamp("2017-10-04T19:15:00"), timestamp("2017-10-06T12:30:00"), timestamp("2017-10-06T12:30:00"), timestamp("2017-10-06T12:30:00"), timestamp("2017-10-11T18:00:00"), timestamp("2017-10-13T12:30:00"), timestamp("2017-10-13T12:30:00"), timestamp("2017-10-13T12:30:00"), timestamp("2017-10-20T23:30:00"), timestamp("2017-10-27T12:30:00"), timestamp("2017-10-27T12:30:00"), timestamp("2017-10-30T12:30:00"), timestamp("2017-10-30T12:30:00"), timestamp("2017-11-01T14:00:00"), timestamp("2017-11-01T14:00:00"), timestamp("2017-11-01T18:00:00"), timestamp("2017-11-01T18:00:00"), timestamp("2017-11-02T19:00:00"), timestamp("2017-11-03T12:30:00"), timestamp("2017-11-03T12:30:00"), timestamp("2017-11-07T19:30:00"), timestamp("2017-11-14T10:00:00"), timestamp("2017-11-15T13:30:00"), timestamp("2017-11-15T13:30:00"), timestamp("2017-11-15T13:30:00"), timestamp("2017-11-22T19:00:00"), timestamp("2017-11-28T20:45:00"), timestamp("2017-11-29T13:30:00"), timestamp("2017-11-29T13:30:00"), timestamp("2017-11-29T15:00:00"), timestamp("2017-11-30T13:30:00"), timestamp("2017-11-30T13:30:00"), timestamp("2017-12-01T15:00:00"), timestamp("2017-12-01T15:00:00"), timestamp("2017-12-08T13:30:00"), timestamp("2017-12-08T13:30:00"), timestamp("2017-12-13T13:30:00"), timestamp("2017-12-13T13:30:00"), timestamp("2017-12-13T19:00:00"), timestamp("2017-12-13T19:00:00"), timestamp("2017-12-13T19:30:00"), timestamp("2017-12-14T13:30:00"), timestamp("2017-12-21T13:30:00"), timestamp("2017-12-21T13:30:00"), timestamp("2017-12-22T00:00:00"), timestamp("2017-12-22T13:30:00"), timestamp("2017-12-22T13:30:00"), timestamp("2017-12-22T13:30:00"), timestamp("2018-01-03T15:00:00"), timestamp("2018-01-03T15:00:00"), timestamp("2018-01-03T19:00:00"), timestamp("2018-01-05T13:30:00"), timestamp("2018-01-05T13:30:00"), timestamp("2018-01-12T13:30:00"), timestamp("2018-01-12T13:30:00"), timestamp("2018-01-12T13:30:00"), timestamp("2018-01-26T13:30:00"), timestamp("2018-01-26T13:30:00"), timestamp("2018-01-29T13:30:00"), timestamp("2018-01-29T13:30:00"), timestamp("2018-01-31T02:00:00"), timestamp("2018-01-31T19:00:00"), timestamp("2018-01-31T19:00:00"), timestamp("2018-02-01T15:00:00"), timestamp("2018-02-01T15:00:00"), timestamp("2018-02-02T13:30:00"), timestamp("2018-02-02T13:30:00"), timestamp("2018-02-02T13:30:00"), timestamp("2018-02-14T13:30:00"), timestamp("2018-02-14T13:30:00"), timestamp("2018-02-14T13:30:00"), timestamp("2018-02-21T19:00:00"), timestamp("2018-02-27T13:30:00"), timestamp("2018-02-27T13:30:00"), timestamp("2018-02-28T13:30:00"), timestamp("2018-02-28T13:30:00"), timestamp("2018-03-01T13:30:00"), timestamp("2018-03-01T13:30:00"), timestamp("2018-03-01T15:00:00"), timestamp("2018-03-01T15:00:00"), timestamp("2018-03-01T15:00:00"), timestamp("2018-03-09T13:30:00"), timestamp("2018-03-09T13:30:00"), timestamp("2018-03-13T12:30:00"), timestamp("2018-03-14T12:30:00"), timestamp("2018-03-14T12:30:00"), timestamp("2018-03-21T18:00:00"), timestamp("2018-03-21T18:00:00"), timestamp("2018-03-21T18:00:00"), timestamp("2018-03-21T18:00:00"), timestamp("2018-03-21T18:30:00"), timestamp("2018-03-23T13:30:00"), timestamp("2018-03-28T12:30:00"), timestamp("2018-03-28T12:30:00"), timestamp("2018-03-29T12:30:00"), timestamp("2018-04-02T14:00:00"), timestamp("2018-04-06T12:30:00"), timestamp("2018-04-06T12:30:00"), timestamp("2018-04-06T17:30:00"), timestamp("2018-04-11T12:30:00"), timestamp("2018-04-11T18:00:00"), timestamp("2018-04-16T12:30:00"), timestamp("2018-04-16T12:30:00"), timestamp("2018-04-26T13:30:00"), timestamp("2018-04-27T12:30:00"), timestamp("2018-04-27T12:30:00"), timestamp("2018-04-30T12:30:00"), timestamp("2018-05-01T14:00:00"), timestamp("2018-05-02T18:00:00"), timestamp("2018-05-02T18:00:00"), timestamp("2018-05-04T12:30:00"), timestamp("2018-05-04T12:30:00"), timestamp("2018-05-08T07:15:00"), timestamp("2018-05-08T18:00:00"), timestamp("2018-05-10T12:30:00"), timestamp("2018-05-15T12:30:00"), timestamp("2018-05-15T12:30:00"), timestamp("2018-05-23T18:00:00"), timestamp("2018-05-25T12:30:00"), timestamp("2018-05-25T13:20:00"), timestamp("2018-05-30T12:30:00"), timestamp("2018-05-30T12:30:00"), timestamp("2018-05-31T12:30:00"), timestamp("2018-06-01T12:30:00"), timestamp("2018-06-01T12:30:00"), timestamp("2018-06-01T14:00:00"), timestamp("2018-06-12T01:00:00"), timestamp("2018-06-12T12:30:00"), timestamp("2018-06-13T18:00:00"), timestamp("2018-06-13T18:00:00"), timestamp("2018-06-13T18:00:00"), timestamp("2018-06-13T18:30:00"), timestamp("2018-06-14T12:30:00"), timestamp("2018-06-14T12:30:00"), timestamp("2018-06-20T13:30:00"), timestamp("2018-06-21T20:30:00"), timestamp("2018-06-26T12:30:00"), timestamp("2018-06-28T12:30:00"), timestamp("2018-06-28T12:30:00"), timestamp("2018-06-29T12:30:00"), timestamp("2018-07-02T14:00:00"), timestamp("2018-07-05T18:00:00"), timestamp("2018-07-06T12:30:00"), timestamp("2018-07-06T12:30:00"), timestamp("2018-07-12T12:30:00"), timestamp("2018-07-12T17:30:00"), timestamp("2018-07-16T10:15:00"), timestamp("2018-07-16T12:30:00"), timestamp("2018-07-16T12:30:00"), timestamp("2018-07-17T14:00:00"), timestamp("2018-07-18T14:00:00"), timestamp("2018-07-25T17:30:00"), timestamp("2018-07-26T12:30:00"), timestamp("2018-07-27T12:30:00"), timestamp("2018-07-27T12:30:00"), timestamp("2018-07-31T12:30:00"), timestamp("2018-08-01T14:00:00"), timestamp("2018-08-01T18:00:00"), timestamp("2018-08-01T18:00:00"), timestamp("2018-08-03T12:30:00"), timestamp("2018-08-03T12:30:00"), timestamp("2018-08-10T12:30:00"), timestamp("2018-08-15T12:30:00"), timestamp("2018-08-15T12:30:00"), timestamp("2018-08-22T18:00:00"), timestamp("2018-08-23T00:00:00"), timestamp("2018-08-24T00:00:00"), timestamp("2018-08-24T12:30:00"), timestamp("2018-08-24T14:00:00"), timestamp("2018-08-25T00:00:00"), timestamp("2018-08-29T12:30:00"), timestamp("2018-08-29T12:30:00"), timestamp("2018-08-30T12:30:00"), timestamp("2018-09-04T14:00:00"), timestamp("2018-09-07T12:30:00"), timestamp("2018-09-07T12:30:00"), timestamp("2018-09-13T12:30:00"), timestamp("2018-09-14T12:30:00"), timestamp("2018-09-14T12:30:00"), timestamp("2018-09-26T18:00:00"), timestamp("2018-09-26T18:00:00"), timestamp("2018-09-26T18:00:00"), timestamp("2018-09-26T18:30:00"), timestamp("2018-09-27T12:30:00"), timestamp("2018-09-27T12:30:00"), timestamp("2018-09-27T12:30:00"), timestamp("2018-09-27T20:30:00"), timestamp("2018-09-28T12:30:00"), timestamp("2018-10-01T14:00:00"), timestamp("2018-10-02T16:45:00"), timestamp("2018-10-03T20:00:00"), timestamp("2018-10-05T12:30:00"), timestamp("2018-10-05T12:30:00"), timestamp("2018-10-11T12:30:00"), timestamp("2018-10-15T12:30:00"), timestamp("2018-10-15T12:30:00"), timestamp("2018-10-17T18:00:00"), timestamp("2018-10-25T12:30:00"), timestamp("2018-10-26T12:30:00"), timestamp("2018-10-26T12:30:00"), timestamp("2018-10-29T12:30:00"), timestamp("2018-11-01T14:00:00"), timestamp("2018-11-02T12:30:00"), timestamp("2018-11-02T12:30:00"), timestamp("2018-11-07T16:30:00"), timestamp("2018-11-08T19:00:00"), timestamp("2018-11-08T19:00:00"), timestamp("2018-11-14T13:30:00"), timestamp("2018-11-14T23:00:00"), timestamp("2018-11-15T13:30:00"), timestamp("2018-11-15T13:30:00"), timestamp("2018-11-15T16:30:00"), timestamp("2018-11-21T13:30:00"), timestamp("2018-11-28T13:30:00"), timestamp("2018-11-28T13:30:00"), timestamp("2018-11-28T17:00:00"), timestamp("2018-11-29T13:30:00"), timestamp("2018-11-29T19:00:00"), timestamp("2018-12-03T15:00:00"), timestamp("2018-12-06T23:45:00"), timestamp("2018-12-07T13:30:00"), timestamp("2018-12-07T13:30:00"), timestamp("2018-12-12T13:30:00"), timestamp("2018-12-14T13:30:00"), timestamp("2018-12-14T13:30:00"), timestamp("2018-12-19T19:00:00"), timestamp("2018-12-19T19:00:00"), timestamp("2018-12-19T19:00:00"), timestamp("2018-12-19T19:30:00"), timestamp("2018-12-21T13:30:00"), timestamp("2018-12-21T13:30:00"), timestamp("2018-12-21T13:30:00"), timestamp("2018-12-21T15:00:00"), timestamp("2019-01-03T15:00:00"), timestamp("2019-01-04T13:30:00"), timestamp("2019-01-04T13:30:00"), timestamp("2019-01-04T15:15:00"), timestamp("2019-01-09T02:00:00"), timestamp("2019-01-09T19:00:00"), timestamp("2019-01-10T17:45:00"), timestamp("2019-01-11T13:30:00"), timestamp("2019-01-30T19:00:00"), timestamp("2019-01-30T19:00:00"), timestamp("2019-01-30T19:30:00"), timestamp("2019-02-01T13:30:00"), timestamp("2019-02-01T13:30:00"), timestamp("2019-02-01T15:00:00"), timestamp("2019-02-04T15:00:00"), timestamp("2019-02-05T15:00:00"), timestamp("2019-02-07T00:00:00"), timestamp("2019-02-12T16:45:00"), timestamp("2019-02-13T13:30:00"), timestamp("2019-02-13T13:30:00"), timestamp("2019-02-14T13:30:00"), timestamp("2019-02-14T13:30:00"), timestamp("2019-02-15T15:00:00"), timestamp("2019-02-15T15:30:00"), timestamp("2019-02-20T19:00:00"), timestamp("2019-02-21T13:30:00"), timestamp("2019-02-26T14:45:00"), timestamp("2019-02-27T14:00:00"), timestamp("2019-02-28T11:30:00"), timestamp("2019-02-28T13:30:00"), timestamp("2019-03-01T01:15:00"), timestamp("2019-03-01T15:00:00"), timestamp("2019-03-05T15:00:00"), timestamp("2019-03-08T13:30:00"), timestamp("2019-03-08T13:30:00"), timestamp("2019-03-09T03:00:00"), timestamp("2019-03-11T12:30:00"), timestamp("2019-03-11T23:00:00"), timestamp("2019-03-12T12:30:00"), timestamp("2019-03-12T12:30:00"), timestamp("2019-03-13T12:30:00"), timestamp("2019-03-15T14:00:00"), timestamp("2019-03-20T18:00:00"), timestamp("2019-03-20T18:00:00"), timestamp("2019-03-20T18:00:00"), timestamp("2019-03-20T18:30:00"), timestamp("2019-03-28T12:30:00"), timestamp("2019-04-01T12:30:00"), timestamp("2019-04-01T14:00:00"), timestamp("2019-04-02T12:30:00"), timestamp("2019-04-03T14:00:00"), timestamp("2019-04-05T12:30:00"), timestamp("2019-04-05T12:30:00"), timestamp("2019-04-10T12:30:00"), timestamp("2019-04-10T12:30:00"), timestamp("2019-04-10T18:00:00"), timestamp("2019-04-12T14:00:00"), timestamp("2019-04-18T12:30:00"), timestamp("2019-04-25T12:30:00"), timestamp("2019-04-26T12:30:00"), timestamp("2019-05-01T14:00:00"), timestamp("2019-05-01T18:00:00"), timestamp("2019-05-01T18:00:00"), timestamp("2019-05-01T18:30:00"), timestamp("2019-05-03T12:30:00"), timestamp("2019-05-03T12:30:00"), timestamp("2019-05-03T14:00:00"), timestamp("2019-05-09T12:30:00"), timestamp("2019-05-10T12:30:00"), timestamp("2019-05-10T12:30:00"), timestamp("2019-05-15T12:30:00"), timestamp("2019-05-17T14:00:00"), timestamp("2019-05-20T23:00:00"), timestamp("2019-05-22T18:00:00"), timestamp("2019-05-24T12:30:00"), timestamp("2019-05-30T12:30:00"), timestamp("2019-06-03T14:00:00"), timestamp("2019-06-04T13:45:00"), timestamp("2019-06-05T14:00:00"), timestamp("2019-06-07T12:30:00"), timestamp("2019-06-07T12:30:00"), timestamp("2019-06-12T12:30:00"), timestamp("2019-06-12T12:30:00"), timestamp("2019-06-14T12:30:00"), timestamp("2019-06-14T14:00:00"), timestamp("2019-06-19T18:00:00"), timestamp("2019-06-19T18:00:00"), timestamp("2019-06-19T18:00:00"), timestamp("2019-06-19T18:30:00"), timestamp("2019-06-25T17:00:00"), timestamp("2019-06-26T12:30:00"), timestamp("2019-06-27T12:30:00"), timestamp("2019-07-01T14:00:00"), timestamp("2019-07-03T14:00:00"), timestamp("2019-07-05T12:30:00"), timestamp("2019-07-05T12:30:00"), timestamp("2019-07-09T12:45:00"), timestamp("2019-07-10T14:00:00"), timestamp("2019-07-10T18:00:00"), timestamp("2019-07-11T12:30:00"), timestamp("2019-07-11T12:30:00"), timestamp("2019-07-11T14:00:00"), timestamp("2019-07-16T12:30:00"), timestamp("2019-07-16T17:00:00"), timestamp("2019-07-19T14:00:00"), timestamp("2019-07-25T12:30:00"), timestamp("2019-07-26T12:30:00"), timestamp("2019-07-31T18:00:00"), timestamp("2019-07-31T18:00:00"), timestamp("2019-07-31T18:30:00"), timestamp("2019-08-01T14:00:00"), timestamp("2019-08-02T12:30:00"), timestamp("2019-08-02T12:30:00"), timestamp("2019-08-05T14:00:00"), timestamp("2019-08-13T12:30:00"), timestamp("2019-08-13T12:30:00"), timestamp("2019-08-15T12:30:00"), timestamp("2019-08-16T14:00:00"), timestamp("2019-08-21T18:00:00"), timestamp("2019-08-22T00:00:00"), timestamp("2019-08-23T00:00:00"), timestamp("2019-08-23T14:00:00"), timestamp("2019-08-24T00:00:00"), timestamp("2019-08-26T12:30:00"), timestamp("2019-08-29T12:30:00"), timestamp("2019-09-03T14:00:00"), timestamp("2019-09-05T14:00:00"), timestamp("2019-09-06T12:30:00"), timestamp("2019-09-06T12:30:00"), timestamp("2019-09-06T16:30:00"), timestamp("2019-09-12T12:30:00"), timestamp("2019-09-12T12:30:00"), timestamp("2019-09-13T12:30:00"), timestamp("2019-09-13T14:00:00"), timestamp("2019-09-18T18:00:00"), timestamp("2019-09-18T18:00:00"), timestamp("2019-09-18T18:00:00"), timestamp("2019-09-18T18:30:00"), timestamp("2019-09-26T12:30:00"), timestamp("2019-09-27T12:30:00"), timestamp("2019-10-01T14:00:00"), timestamp("2019-10-03T14:00:00"), timestamp("2019-10-04T12:30:00"), timestamp("2019-10-04T12:30:00"), timestamp("2019-10-04T18:00:00"), timestamp("2019-10-07T17:00:00"), timestamp("2019-10-08T18:30:00"), timestamp("2019-10-09T15:00:00"), timestamp("2019-10-09T18:00:00"), timestamp("2019-10-10T12:30:00"), timestamp("2019-10-10T12:30:00"), timestamp("2019-10-11T14:00:00"), timestamp("2019-10-16T12:30:00"), timestamp("2019-10-24T12:30:00"), timestamp("2019-10-30T12:30:00"), timestamp("2019-10-30T18:00:00"), timestamp("2019-10-30T18:00:00"), timestamp("2019-10-30T18:30:00"), timestamp("2019-11-01T12:30:00"), timestamp("2019-11-01T12:30:00"), timestamp("2019-11-01T14:00:00"), timestamp("2019-11-05T15:00:00"), timestamp("2019-11-08T15:00:00"), timestamp("2019-11-12T17:00:00"), timestamp("2019-11-13T13:30:00"), timestamp("2019-11-13T13:30:00"), timestamp("2019-11-13T16:00:00"), timestamp("2019-11-14T15:00:00"), timestamp("2019-11-15T13:30:00"), timestamp("2019-11-20T19:00:00"), timestamp("2019-11-26T00:00:00"), timestamp("2019-11-27T13:30:00"), timestamp("2019-11-27T13:30:00"), timestamp("2019-12-02T15:00:00"), timestamp("2019-12-04T15:00:00"), timestamp("2019-12-06T13:30:00"), timestamp("2019-12-06T13:30:00"), timestamp("2019-12-06T15:00:00"), timestamp("2019-12-11T13:30:00"), timestamp("2019-12-11T13:30:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:00:00"), timestamp("2019-12-11T19:30:00"), timestamp("2019-12-13T13:30:00"), timestamp("2019-12-20T13:30:00"), timestamp("2019-12-23T13:30:00") ) // @function USD high imact news date and time from 2020 to 2023 export usdNews2020To2023() => array.from( timestamp("2020-01-03T15:00:00"), timestamp("2020-01-03T19:00:00"), timestamp("2020-01-07T15:00:00"), timestamp("2020-01-10T13:30:00"), timestamp("2020-01-10T13:30:00"), timestamp("2020-01-14T13:30:00"), timestamp("2020-01-14T13:30:00"), timestamp("2020-01-16T13:30:00"), timestamp("2020-01-17T15:00:00"), timestamp("2020-01-28T13:30:00"), timestamp("2020-01-29T19:00:00"), timestamp("2020-01-29T19:30:00"), timestamp("2020-01-30T13:30:00"), timestamp("2020-02-03T15:00:00"), timestamp("2020-02-05T15:00:00"), timestamp("2020-02-07T13:30:00"), timestamp("2020-02-07T13:30:00"), timestamp("2020-02-11T15:00:00"), timestamp("2020-02-12T14:30:00"), timestamp("2020-02-13T13:30:00"), timestamp("2020-02-13T13:30:00"), timestamp("2020-02-14T13:30:00"), timestamp("2020-02-14T15:00:00"), timestamp("2020-02-19T19:00:00"), timestamp("2020-02-26T23:00:00"), timestamp("2020-02-27T13:30:00"), timestamp("2020-02-27T13:30:00"), timestamp("2020-03-02T15:00:00"), timestamp("2020-03-03T05:00:00"), timestamp("2020-03-03T12:00:00"), timestamp("2020-03-03T15:00:00"), timestamp("2020-03-03T16:00:00"), timestamp("2020-03-04T15:00:00"), timestamp("2020-03-06T13:30:00"), timestamp("2020-03-06T13:30:00"), timestamp("2020-03-10T21:30:00"), timestamp("2020-03-11T12:30:00"), timestamp("2020-03-11T12:30:00"), timestamp("2020-03-11T14:00:00"), timestamp("2020-03-12T01:00:00"), timestamp("2020-03-13T14:00:00"), timestamp("2020-03-13T19:00:00"), timestamp("2020-03-15T21:00:00"), timestamp("2020-03-15T21:00:00"), timestamp("2020-03-15T22:30:00"), timestamp("2020-03-16T14:00:00"), timestamp("2020-03-17T12:00:00"), timestamp("2020-03-17T12:30:00"), timestamp("2020-03-19T12:30:00"), timestamp("2020-03-23T16:00:00"), timestamp("2020-03-24T13:45:00"), timestamp("2020-03-24T13:45:00"), timestamp("2020-03-24T13:45:00"), timestamp("2020-03-25T12:30:00"), timestamp("2020-03-26T11:05:00"), timestamp("2020-03-26T12:30:00"), timestamp("2020-03-26T12:30:00"), timestamp("2020-03-27T15:00:00"), timestamp("2020-04-01T12:15:00"), timestamp("2020-04-01T14:00:00"), timestamp("2020-04-02T12:30:00"), timestamp("2020-04-03T12:30:00"), timestamp("2020-04-03T12:30:00"), timestamp("2020-04-03T14:00:00"), timestamp("2020-04-03T14:00:00"), timestamp("2020-04-08T18:00:00"), timestamp("2020-04-09T12:30:00"), timestamp("2020-04-09T14:00:00"), timestamp("2020-04-09T14:00:00"), timestamp("2020-04-09T14:00:00"), timestamp("2020-04-10T12:30:00"), timestamp("2020-04-10T12:30:00"), timestamp("2020-04-15T12:30:00"), timestamp("2020-04-16T12:30:00"), timestamp("2020-04-23T12:30:00"), timestamp("2020-04-24T12:30:00"), timestamp("2020-04-29T12:30:00"), timestamp("2020-04-29T18:00:00"), timestamp("2020-04-29T18:30:00"), timestamp("2020-04-30T12:30:00"), timestamp("2020-05-01T14:00:00"), timestamp("2020-05-05T14:00:00"), timestamp("2020-05-05T14:00:00"), timestamp("2020-05-06T12:15:00"), timestamp("2020-05-07T12:30:00"), timestamp("2020-05-08T12:30:00"), timestamp("2020-05-08T12:30:00"), timestamp("2020-05-12T12:30:00"), timestamp("2020-05-12T12:30:00"), timestamp("2020-05-13T13:00:00"), timestamp("2020-05-14T12:30:00"), timestamp("2020-05-15T12:30:00"), timestamp("2020-05-15T14:00:00"), timestamp("2020-05-19T14:00:00"), timestamp("2020-05-20T18:00:00"), timestamp("2020-05-21T12:30:00"), timestamp("2020-05-21T18:30:00"), timestamp("2020-05-28T12:30:00"), timestamp("2020-05-28T12:30:00"), timestamp("2020-05-28T12:30:00"), timestamp("2020-05-29T15:00:00"), timestamp("2020-06-01T14:00:00"), timestamp("2020-06-03T12:00:00"), timestamp("2020-06-03T12:15:00"), timestamp("2020-06-03T14:00:00"), timestamp("2020-06-03T14:00:00"), timestamp("2020-06-04T12:30:00"), timestamp("2020-06-05T12:30:00"), timestamp("2020-06-05T12:30:00"), timestamp("2020-06-05T14:00:00"), timestamp("2020-06-08T10:00:00"), timestamp("2020-06-10T12:30:00"), timestamp("2020-06-10T12:30:00"), timestamp("2020-06-10T18:00:00"), timestamp("2020-06-10T18:00:00"), timestamp("2020-06-10T18:00:00"), timestamp("2020-06-10T18:00:00"), timestamp("2020-06-10T18:00:00"), timestamp("2020-06-10T18:00:00"), timestamp("2020-06-10T18:00:00"), timestamp("2020-06-10T18:30:00"), timestamp("2020-06-11T12:30:00"), timestamp("2020-06-12T14:00:00"), timestamp("2020-06-16T12:30:00"), timestamp("2020-06-16T14:00:00"), timestamp("2020-06-17T16:00:00"), timestamp("2020-06-18T12:30:00"), timestamp("2020-06-19T17:00:00"), timestamp("2020-06-25T12:30:00"), timestamp("2020-06-25T12:30:00"), timestamp("2020-06-25T12:30:00"), timestamp("2020-06-25T20:30:00"), timestamp("2020-06-30T14:00:00"), timestamp("2020-06-30T16:30:00"), timestamp("2020-07-01T12:15:00"), timestamp("2020-07-01T14:00:00"), timestamp("2020-07-01T18:00:00"), timestamp("2020-07-02T12:30:00"), timestamp("2020-07-02T12:30:00"), timestamp("2020-07-02T13:30:00"), timestamp("2020-07-06T14:00:00"), timestamp("2020-07-14T12:30:00"), timestamp("2020-07-14T12:30:00"), timestamp("2020-07-16T12:30:00"), timestamp("2020-07-17T14:00:00"), timestamp("2020-07-27T12:30:00"), timestamp("2020-07-27T12:30:00"), timestamp("2020-07-29T18:00:00"), timestamp("2020-07-29T18:00:00"), timestamp("2020-07-29T18:30:00"), timestamp("2020-07-30T12:30:00"), timestamp("2020-08-03T14:00:00"), timestamp("2020-08-05T12:15:00"), timestamp("2020-08-05T14:00:00"), timestamp("2020-08-07T12:30:00"), timestamp("2020-08-12T12:30:00"), timestamp("2020-08-12T12:30:00"), timestamp("2020-08-14T12:30:00"), timestamp("2020-08-14T12:30:00"), timestamp("2020-08-14T14:00:00"), timestamp("2020-08-19T18:00:00"), timestamp("2020-08-26T12:30:00"), timestamp("2020-08-26T12:30:00"), timestamp("2020-08-27T00:00:00"), timestamp("2020-08-27T12:30:00"), timestamp("2020-08-27T13:10:00"), timestamp("2020-08-28T00:00:00"), timestamp("2020-09-01T14:00:00"), timestamp("2020-09-02T12:15:00"), timestamp("2020-09-03T14:00:00"), timestamp("2020-09-04T12:30:00"), timestamp("2020-09-11T12:30:00"), timestamp("2020-09-11T12:30:00"), timestamp("2020-09-16T12:30:00"), timestamp("2020-09-16T12:30:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:00:00"), timestamp("2020-09-16T18:30:00"), timestamp("2020-09-18T14:00:00"), timestamp("2020-09-21T14:00:00"), timestamp("2020-09-22T14:30:00"), timestamp("2020-09-23T14:00:00"), timestamp("2020-09-24T14:00:00"), timestamp("2020-09-24T14:00:00"), timestamp("2020-09-25T12:30:00"), timestamp("2020-09-25T12:30:00"), timestamp("2020-09-30T01:00:00"), timestamp("2020-09-30T12:15:00"), timestamp("2020-09-30T12:30:00"), timestamp("2020-10-01T14:00:00"), timestamp("2020-10-02T12:30:00"), timestamp("2020-10-05T14:00:00"), timestamp("2020-10-06T14:40:00"), timestamp("2020-10-07T18:00:00"), timestamp("2020-10-13T12:30:00"), timestamp("2020-10-13T12:30:00"), timestamp("2020-10-16T12:30:00"), timestamp("2020-10-16T12:30:00"), timestamp("2020-10-16T14:00:00"), timestamp("2020-10-19T12:00:00"), timestamp("2020-10-23T01:00:00"), timestamp("2020-10-27T12:30:00"), timestamp("2020-10-27T12:30:00"), timestamp("2020-10-29T12:30:00"), timestamp("2020-11-02T15:00:00"), timestamp("2020-11-03T13:00:00"), timestamp("2020-11-04T13:15:00"), timestamp("2020-11-04T15:00:00"), timestamp("2020-11-05T19:00:00"), timestamp("2020-11-05T19:00:00"), timestamp("2020-11-05T19:30:00"), timestamp("2020-11-06T13:30:00"), timestamp("2020-11-12T13:30:00"), timestamp("2020-11-12T13:30:00"), timestamp("2020-11-12T16:45:00"), timestamp("2020-11-13T15:00:00"), timestamp("2020-11-17T13:30:00"), timestamp("2020-11-17T13:30:00"), timestamp("2020-11-17T18:00:00"), timestamp("2020-11-25T13:30:00"), timestamp("2020-11-25T13:30:00"), timestamp("2020-11-25T13:30:00"), timestamp("2020-11-25T19:00:00"), timestamp("2020-12-01T15:00:00"), timestamp("2020-12-01T15:00:00"), timestamp("2020-12-02T13:15:00"), timestamp("2020-12-03T15:00:00"), timestamp("2020-12-04T13:30:00"), timestamp("2020-12-10T13:30:00"), timestamp("2020-12-10T13:30:00"), timestamp("2020-12-11T15:00:00"), timestamp("2020-12-16T13:30:00"), timestamp("2020-12-16T13:30:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:00:00"), timestamp("2020-12-16T19:30:00"), timestamp("2020-12-18T21:30:00"), timestamp("2020-12-22T13:30:00"), timestamp("2020-12-23T13:30:00"), timestamp("2020-12-23T13:30:00"), timestamp("2021-01-05T15:00:00"), timestamp("2021-01-06T13:15:00"), timestamp("2021-01-06T19:00:00"), timestamp("2021-01-07T15:00:00"), timestamp("2021-01-08T13:30:00"), timestamp("2021-01-13T13:30:00"), timestamp("2021-01-13T13:30:00"), timestamp("2021-01-14T17:30:00"), timestamp("2021-01-15T00:15:00"), timestamp("2021-01-15T13:30:00"), timestamp("2021-01-15T13:30:00"), timestamp("2021-01-15T15:00:00"), timestamp("2021-01-19T15:00:00"), timestamp("2021-01-20T17:00:00"), timestamp("2021-01-22T19:45:00"), timestamp("2021-01-25T20:45:00"), timestamp("2021-01-26T21:45:00"), timestamp("2021-01-27T13:30:00"), timestamp("2021-01-27T13:30:00"), timestamp("2021-01-27T19:00:00"), timestamp("2021-01-27T19:00:00"), timestamp("2021-01-27T19:30:00"), timestamp("2021-01-28T13:30:00"), timestamp("2021-02-01T15:00:00"), timestamp("2021-02-01T22:00:00"), timestamp("2021-02-03T13:15:00"), timestamp("2021-02-03T15:00:00"), timestamp("2021-02-05T13:30:00"), timestamp("2021-02-10T13:30:00"), timestamp("2021-02-10T13:30:00"), timestamp("2021-02-10T19:00:00"), timestamp("2021-02-12T15:00:00"), timestamp("2021-02-17T13:30:00"), timestamp("2021-02-17T13:30:00"), timestamp("2021-02-17T19:00:00"), timestamp("2021-02-23T15:00:00"), timestamp("2021-02-24T15:00:00"), timestamp("2021-02-25T13:30:00"), timestamp("2021-02-25T13:30:00"), timestamp("2021-02-25T13:30:00"), timestamp("2021-03-01T15:00:00"), timestamp("2021-03-03T13:15:00"), timestamp("2021-03-03T15:00:00"), timestamp("2021-03-04T17:05:00"), timestamp("2021-03-05T13:30:00"), timestamp("2021-03-10T13:30:00"), timestamp("2021-03-10T13:30:00"), timestamp("2021-03-10T18:00:00"), timestamp("2021-03-12T15:00:00"), timestamp("2021-03-15T17:45:00"), timestamp("2021-03-16T12:30:00"), timestamp("2021-03-16T12:30:00"), timestamp("2021-03-17T18:00:00"), timestamp("2021-03-17T18:00:00"), timestamp("2021-03-17T18:00:00"), timestamp("2021-03-17T18:00:00"), timestamp("2021-03-17T18:00:00"), timestamp("2021-03-17T18:00:00"), timestamp("2021-03-17T18:30:00"), timestamp("2021-03-17T19:00:00"), timestamp("2021-03-18T15:55:00"), timestamp("2021-03-22T13:00:00"), timestamp("2021-03-23T16:00:00"), timestamp("2021-03-24T12:30:00"), timestamp("2021-03-24T12:30:00"), timestamp("2021-03-24T14:00:00"), timestamp("2021-03-25T12:30:00"), timestamp("2021-03-31T12:15:00"), timestamp("2021-03-31T20:20:00"), timestamp("2021-04-01T14:00:00"), timestamp("2021-04-02T12:30:00"), timestamp("2021-04-05T14:00:00"), timestamp("2021-04-07T17:45:00"), timestamp("2021-04-07T18:00:00"), timestamp("2021-04-08T16:00:00"), timestamp("2021-04-12T17:00:00"), timestamp("2021-04-13T12:30:00"), timestamp("2021-04-13T12:30:00"), timestamp("2021-04-14T16:00:00"), timestamp("2021-04-15T12:30:00"), timestamp("2021-04-15T12:30:00"), timestamp("2021-04-16T14:00:00"), timestamp("2021-04-26T12:30:00"), timestamp("2021-04-26T12:30:00"), timestamp("2021-04-28T18:00:00"), timestamp("2021-04-28T18:00:00"), timestamp("2021-04-28T18:30:00"), timestamp("2021-04-29T12:30:00"), timestamp("2021-05-03T14:00:00"), timestamp("2021-05-03T18:20:00"), timestamp("2021-05-05T12:15:00"), timestamp("2021-05-05T14:00:00"), timestamp("2021-05-07T12:30:00"), timestamp("2021-05-07T15:00:00"), timestamp("2021-05-12T12:30:00"), timestamp("2021-05-12T12:30:00"), timestamp("2021-05-14T12:30:00"), timestamp("2021-05-14T12:30:00"), timestamp("2021-05-14T14:00:00"), timestamp("2021-05-19T18:00:00"), timestamp("2021-05-27T12:30:00"), timestamp("2021-05-27T12:30:00"), timestamp("2021-05-27T12:30:00"), timestamp("2021-06-01T14:00:00"), timestamp("2021-06-03T12:15:00"), timestamp("2021-06-03T14:00:00"), timestamp("2021-06-04T11:00:00"), timestamp("2021-06-04T12:30:00"), timestamp("2021-06-04T14:15:00"), timestamp("2021-06-10T12:30:00"), timestamp("2021-06-10T12:30:00"), timestamp("2021-06-11T14:00:00"), timestamp("2021-06-15T12:30:00"), timestamp("2021-06-15T12:30:00"), timestamp("2021-06-16T18:00:00"), timestamp("2021-06-16T18:00:00"), timestamp("2021-06-16T18:00:00"), timestamp("2021-06-16T18:00:00"), timestamp("2021-06-16T18:00:00"), timestamp("2021-06-16T18:00:00"), timestamp("2021-06-16T18:00:00"), timestamp("2021-06-16T18:30:00"), timestamp("2021-06-22T18:00:00"), timestamp("2021-06-24T12:30:00"), timestamp("2021-06-24T12:30:00"), timestamp("2021-06-24T12:30:00"), timestamp("2021-06-24T20:30:00"), timestamp("2021-06-30T12:15:00"), timestamp("2021-07-01T14:00:00"), timestamp("2021-07-02T12:30:00"), timestamp("2021-07-06T14:00:00"), timestamp("2021-07-07T18:00:00"), timestamp("2021-07-13T12:30:00"), timestamp("2021-07-13T12:30:00"), timestamp("2021-07-14T16:00:00"), timestamp("2021-07-15T13:30:00"), timestamp("2021-07-16T12:30:00"), timestamp("2021-07-16T12:30:00"), timestamp("2021-07-16T14:00:00"), timestamp("2021-07-27T12:30:00"), timestamp("2021-07-27T12:30:00"), timestamp("2021-07-28T18:00:00"), timestamp("2021-07-28T18:00:00"), timestamp("2021-07-28T18:30:00"), timestamp("2021-07-29T12:30:00"), timestamp("2021-08-02T14:00:00"), timestamp("2021-08-04T12:15:00"), timestamp("2021-08-04T14:00:00"), timestamp("2021-08-06T12:30:00"), timestamp("2021-08-11T12:30:00"), timestamp("2021-08-11T12:30:00"), timestamp("2021-08-13T14:00:00"), timestamp("2021-08-17T12:30:00"), timestamp("2021-08-17T12:30:00"), timestamp("2021-08-17T17:30:00"), timestamp("2021-08-18T18:00:00"), timestamp("2021-08-25T12:30:00"), timestamp("2021-08-25T12:30:00"), timestamp("2021-08-26T12:30:00"), timestamp("2021-08-26T14:00:00"), timestamp("2021-08-27T14:00:00"), timestamp("2021-08-27T14:00:00"), timestamp("2021-08-28T14:00:00"), timestamp("2021-09-01T12:15:00"), timestamp("2021-09-01T14:00:00"), timestamp("2021-09-03T12:30:00"), timestamp("2021-09-03T14:00:00"), timestamp("2021-09-14T12:30:00"), timestamp("2021-09-14T12:30:00"), timestamp("2021-09-16T12:30:00"), timestamp("2021-09-16T12:30:00"), timestamp("2021-09-17T14:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:00:00"), timestamp("2021-09-22T18:30:00"), timestamp("2021-09-24T14:00:00"), timestamp("2021-09-27T12:30:00"), timestamp("2021-09-27T12:30:00"), timestamp("2021-09-28T14:00:00"), timestamp("2021-09-29T15:45:00"), timestamp("2021-09-30T12:30:00"), timestamp("2021-09-30T14:00:00"), timestamp("2021-10-01T14:00:00"), timestamp("2021-10-05T14:00:00"), timestamp("2021-10-06T12:15:00"), timestamp("2021-10-08T12:30:00"), timestamp("2021-10-13T12:30:00"), timestamp("2021-10-13T12:30:00"), timestamp("2021-10-13T18:00:00"), timestamp("2021-10-15T12:30:00"), timestamp("2021-10-15T12:30:00"), timestamp("2021-10-15T14:00:00"), timestamp("2021-10-22T15:00:00"), timestamp("2021-10-27T12:30:00"), timestamp("2021-10-27T12:30:00"), timestamp("2021-10-28T12:30:00"), timestamp("2021-11-01T14:00:00"), timestamp("2021-11-03T12:15:00"), timestamp("2021-11-03T14:00:00"), timestamp("2021-11-03T18:00:00"), timestamp("2021-11-03T18:00:00"), timestamp("2021-11-03T18:30:00"), timestamp("2021-11-05T12:30:00"), timestamp("2021-11-08T15:30:00"), timestamp("2021-11-09T14:00:00"), timestamp("2021-11-10T13:30:00"), timestamp("2021-11-10T13:30:00"), timestamp("2021-11-12T15:00:00"), timestamp("2021-11-16T13:30:00"), timestamp("2021-11-16T13:30:00"), timestamp("2021-11-23T20:00:00"), timestamp("2021-11-24T13:30:00"), timestamp("2021-11-24T13:30:00"), timestamp("2021-11-24T13:30:00"), timestamp("2021-11-24T19:00:00"), timestamp("2021-11-29T20:05:00"), timestamp("2021-11-30T15:00:00"), timestamp("2021-12-01T13:15:00"), timestamp("2021-12-01T15:00:00"), timestamp("2021-12-01T15:00:00"), timestamp("2021-12-03T13:30:00"), timestamp("2021-12-03T15:00:00"), timestamp("2021-12-10T13:30:00"), timestamp("2021-12-10T13:30:00"), timestamp("2021-12-10T15:00:00"), timestamp("2021-12-15T13:30:00"), timestamp("2021-12-15T13:30:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:00:00"), timestamp("2021-12-15T19:30:00"), timestamp("2021-12-22T13:30:00"), timestamp("2021-12-23T13:30:00"), timestamp("2021-12-23T13:30:00"), timestamp("2022-01-04T15:00:00"), timestamp("2022-01-05T13:15:00"), timestamp("2022-01-05T19:00:00"), timestamp("2022-01-06T15:00:00"), timestamp("2022-01-07T13:30:00"), timestamp("2022-01-11T15:00:00"), timestamp("2022-01-12T13:30:00"), timestamp("2022-01-12T13:30:00"), timestamp("2022-01-14T13:30:00"), timestamp("2022-01-14T13:30:00"), timestamp("2022-01-14T15:00:00"), timestamp("2022-01-26T19:00:00"), timestamp("2022-01-26T19:00:00"), timestamp("2022-01-26T19:30:00"), timestamp("2022-01-27T13:30:00"), timestamp("2022-01-27T13:30:00"), timestamp("2022-01-27T13:30:00"), timestamp("2022-02-01T15:00:00"), timestamp("2022-02-02T13:15:00"), timestamp("2022-02-03T15:00:00"), timestamp("2022-02-04T13:30:00"), timestamp("2022-02-10T13:30:00"), timestamp("2022-02-10T13:30:00"), timestamp("2022-02-11T15:00:00"), timestamp("2022-02-16T13:30:00"), timestamp("2022-02-16T13:30:00"), timestamp("2022-02-16T19:00:00"), timestamp("2022-02-24T13:30:00"), timestamp("2022-02-25T13:30:00"), timestamp("2022-02-25T13:30:00"), timestamp("2022-03-01T15:00:00"), timestamp("2022-03-02T02:00:00"), timestamp("2022-03-02T13:15:00"), timestamp("2022-03-02T15:00:00"), timestamp("2022-03-03T15:00:00"), timestamp("2022-03-03T15:00:00"), timestamp("2022-03-04T13:30:00"), timestamp("2022-03-10T13:30:00"), timestamp("2022-03-10T13:30:00"), timestamp("2022-03-11T15:00:00"), timestamp("2022-03-11T15:15:00"), timestamp("2022-03-16T12:30:00"), timestamp("2022-03-16T12:30:00"), timestamp("2022-03-16T15:45:00"), timestamp("2022-03-16T18:00:00"), timestamp("2022-03-16T18:00:00"), timestamp("2022-03-16T18:00:00"), timestamp("2022-03-16T18:00:00"), timestamp("2022-03-16T18:00:00"), timestamp("2022-03-16T18:00:00"), timestamp("2022-03-16T18:00:00"), timestamp("2022-03-16T18:30:00"), timestamp("2022-03-21T16:00:00"), timestamp("2022-03-23T12:00:00"), timestamp("2022-03-24T12:30:00"), timestamp("2022-03-24T12:30:00"), timestamp("2022-03-30T12:15:00"), timestamp("2022-03-30T12:30:00"), timestamp("2022-04-01T12:30:00"), timestamp("2022-04-01T14:00:00"), timestamp("2022-04-05T14:00:00"), timestamp("2022-04-06T18:00:00"), timestamp("2022-04-12T12:30:00"), timestamp("2022-04-12T12:30:00"), timestamp("2022-04-14T12:30:00"), timestamp("2022-04-14T12:30:00"), timestamp("2022-04-14T14:00:00"), timestamp("2022-04-21T15:00:00"), timestamp("2022-04-21T17:00:00"), timestamp("2022-04-26T12:30:00"), timestamp("2022-04-26T12:30:00"), timestamp("2022-04-28T12:30:00"), timestamp("2022-05-02T14:00:00"), timestamp("2022-05-04T12:15:00"), timestamp("2022-05-04T14:00:00"), timestamp("2022-05-04T18:00:00"), timestamp("2022-05-04T18:00:00"), timestamp("2022-05-04T18:30:00"), timestamp("2022-05-06T12:30:00"), timestamp("2022-05-10T15:30:00"), timestamp("2022-05-11T12:30:00"), timestamp("2022-05-11T12:30:00"), timestamp("2022-05-11T18:15:00"), timestamp("2022-05-13T14:00:00"), timestamp("2022-05-17T12:30:00"), timestamp("2022-05-17T12:30:00"), timestamp("2022-05-17T18:00:00"), timestamp("2022-05-24T16:20:00"), timestamp("2022-05-25T12:30:00"), timestamp("2022-05-25T12:30:00"), timestamp("2022-05-25T18:00:00"), timestamp("2022-05-26T12:30:00"), timestamp("2022-05-31T13:00:00"), timestamp("2022-06-01T14:00:00"), timestamp("2022-06-02T12:15:00"), timestamp("2022-06-03T12:30:00"), timestamp("2022-06-03T14:00:00"), timestamp("2022-06-03T14:30:00"), timestamp("2022-06-07T14:00:00"), timestamp("2022-06-10T12:30:00"), timestamp("2022-06-10T12:30:00"), timestamp("2022-06-10T14:00:00"), timestamp("2022-06-15T12:30:00"), timestamp("2022-06-15T12:30:00"), timestamp("2022-06-15T18:00:00"), timestamp("2022-06-15T18:00:00"), timestamp("2022-06-15T18:00:00"), timestamp("2022-06-15T18:00:00"), timestamp("2022-06-15T18:00:00"), timestamp("2022-06-15T18:00:00"), timestamp("2022-06-15T18:00:00"), timestamp("2022-06-15T18:30:00"), timestamp("2022-06-17T12:45:00"), timestamp("2022-06-22T13:30:00"), timestamp("2022-06-22T18:00:00"), timestamp("2022-06-23T14:00:00"), timestamp("2022-06-23T20:30:00"), timestamp("2022-06-27T12:30:00"), timestamp("2022-06-27T12:30:00"), timestamp("2022-06-29T12:30:00"), timestamp("2022-06-29T13:00:00"), timestamp("2022-07-01T14:00:00"), timestamp("2022-07-06T14:00:00"), timestamp("2022-07-06T18:00:00"), timestamp("2022-07-08T12:30:00"), timestamp("2022-07-13T12:30:00"), timestamp("2022-07-13T12:30:00"), timestamp("2022-07-15T12:30:00"), timestamp("2022-07-15T12:30:00"), timestamp("2022-07-15T14:00:00"), timestamp("2022-07-27T12:30:00"), timestamp("2022-07-27T12:30:00"), timestamp("2022-07-27T18:00:00"), timestamp("2022-07-27T18:00:00"), timestamp("2022-07-27T18:30:00"), timestamp("2022-07-28T12:30:00"), timestamp("2022-08-01T14:00:00"), timestamp("2022-08-02T23:30:00"), timestamp("2022-08-03T14:00:00"), timestamp("2022-08-05T12:30:00"), timestamp("2022-08-10T12:30:00"), timestamp("2022-08-10T12:30:00"), timestamp("2022-08-12T14:00:00"), timestamp("2022-08-17T12:30:00"), timestamp("2022-08-17T12:30:00"), timestamp("2022-08-17T18:00:00"), timestamp("2022-08-24T12:30:00"), timestamp("2022-08-24T12:30:00"), timestamp("2022-08-25T12:30:00"), timestamp("2022-08-25T14:00:00"), timestamp("2022-08-26T14:00:00"), timestamp("2022-08-26T14:00:00"), timestamp("2022-08-27T14:00:00"), timestamp("2022-08-31T12:15:00"), timestamp("2022-08-31T12:15:05"), timestamp("2022-08-31T12:15:10"), timestamp("2022-09-01T14:00:00"), timestamp("2022-09-02T12:30:00"), timestamp("2022-09-06T14:00:00"), timestamp("2022-09-08T13:10:00"), timestamp("2022-09-13T12:30:00"), timestamp("2022-09-13T12:30:00"), timestamp("2022-09-15T12:30:00"), timestamp("2022-09-15T12:30:00"), timestamp("2022-09-16T14:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:00:00"), timestamp("2022-09-21T18:30:00"), timestamp("2022-09-23T18:00:00"), timestamp("2022-09-27T11:30:00"), timestamp("2022-09-27T12:30:00"), timestamp("2022-09-27T12:30:00"), timestamp("2022-09-28T14:15:00"), timestamp("2022-09-29T12:30:00"), timestamp("2022-10-03T14:00:00"), timestamp("2022-10-05T12:15:00"), timestamp("2022-10-05T14:00:00"), timestamp("2022-10-07T12:30:00"), timestamp("2022-10-12T18:00:00"), timestamp("2022-10-13T12:30:00"), timestamp("2022-10-13T12:30:00"), timestamp("2022-10-14T12:30:00"), timestamp("2022-10-14T12:30:00"), timestamp("2022-10-14T14:00:00"), timestamp("2022-10-27T12:30:00"), timestamp("2022-10-27T12:30:00"), timestamp("2022-10-27T12:30:00"), timestamp("2022-11-01T14:00:00"), timestamp("2022-11-02T12:15:00"), timestamp("2022-11-02T18:00:00"), timestamp("2022-11-02T18:00:00"), timestamp("2022-11-02T18:30:00"), timestamp("2022-11-03T14:00:00"), timestamp("2022-11-04T12:30:00"), timestamp("2022-11-10T13:30:00"), timestamp("2022-11-10T13:30:00"), timestamp("2022-11-11T15:00:00"), timestamp("2022-11-16T13:30:00"), timestamp("2022-11-16T13:30:00"), timestamp("2022-11-23T13:30:00"), timestamp("2022-11-23T13:30:00"), timestamp("2022-11-23T19:00:00"), timestamp("2022-11-30T13:15:00"), timestamp("2022-11-30T13:30:00"), timestamp("2022-11-30T18:30:00"), timestamp("2022-12-01T15:00:00"), timestamp("2022-12-02T13:30:00"), timestamp("2022-12-05T15:00:00"), timestamp("2022-12-09T15:00:00"), timestamp("2022-12-13T13:30:00"), timestamp("2022-12-13T13:30:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:00:00"), timestamp("2022-12-14T19:30:00"), timestamp("2022-12-15T13:30:00"), timestamp("2022-12-15T13:30:00"), timestamp("2022-12-22T13:30:00"), timestamp("2022-12-23T13:30:00"), timestamp("2022-12-23T13:30:00"), timestamp("2023-01-04T15:00:00"), timestamp("2023-01-04T19:00:00"), timestamp("2023-01-05T13:15:00"), timestamp("2023-01-06T13:30:00"), timestamp("2023-01-06T15:00:00"), timestamp("2023-01-10T14:00:00"), timestamp("2023-01-12T13:30:00"), timestamp("2023-01-12T13:30:00"), timestamp("2023-01-12T13:30:00"), timestamp("2023-01-13T15:00:00"), timestamp("2023-01-18T13:30:00"), timestamp("2023-01-18T13:30:00"), timestamp("2023-01-26T13:30:00"), timestamp("2023-01-26T13:30:00"), timestamp("2023-01-26T13:30:00"), timestamp("2023-02-01T13:15:00"), timestamp("2023-02-01T15:00:00"), timestamp("2023-02-01T19:00:00"), timestamp("2023-02-01T19:00:00"), timestamp("2023-02-01T19:30:00"), timestamp("2023-02-03T13:30:00"), timestamp("2023-02-03T15:00:00"), timestamp("2023-02-07T17:40:00"), timestamp("2023-02-08T02:00:00"), timestamp("2023-02-10T15:00:00"), timestamp("2023-02-14T13:30:00"), timestamp("2023-02-14T13:30:00"), timestamp("2023-02-15T13:30:00"), timestamp("2023-02-15T13:30:00"), timestamp("2023-02-22T19:00:00"), timestamp("2023-02-23T13:30:00"), timestamp("2023-02-27T13:30:00"), timestamp("2023-02-27T13:30:00"), timestamp("2023-03-01T15:00:00"), timestamp("2023-03-03T15:00:00"), timestamp("2023-03-07T15:00:00"), timestamp("2023-03-08T13:15:00"), timestamp("2023-03-08T15:00:00"), timestamp("2023-03-10T13:30:00"), timestamp("2023-03-13T13:00:00"), timestamp("2023-03-14T12:30:00"), timestamp("2023-03-14T12:30:00"), timestamp("2023-03-15T12:30:00"), timestamp("2023-03-15T12:30:00"), timestamp("2023-03-17T14:00:00"), timestamp("2023-03-22T18:00:00"), timestamp("2023-03-22T18:00:00"), timestamp("2023-03-22T18:00:00"), timestamp("2023-03-22T18:00:00"), timestamp("2023-03-22T18:00:00"), timestamp("2023-03-22T18:00:00"), timestamp("2023-03-22T18:00:00"), timestamp("2023-03-22T18:30:00"), timestamp("2023-03-24T12:30:00"), timestamp("2023-03-24T12:30:00"), timestamp("2023-03-30T12:30:00"), timestamp("2023-04-03T14:00:00"), timestamp("2023-04-05T12:15:00"), timestamp("2023-04-05T14:00:00"), timestamp("2023-04-07T12:30:00"), timestamp("2023-04-12T12:30:00"), timestamp("2023-04-12T12:30:00"), timestamp("2023-04-12T18:00:00"), timestamp("2023-04-14T12:30:00"), timestamp("2023-04-14T12:30:00"), timestamp("2023-04-14T14:00:00"), timestamp("2023-04-26T12:30:00"), timestamp("2023-04-26T12:30:00"), timestamp("2023-04-27T12:30:00"), timestamp("2023-05-01T14:00:00"), timestamp("2023-05-03T12:15:00"), timestamp("2023-05-03T14:00:00"), timestamp("2023-05-03T18:00:00"), timestamp("2023-05-03T18:00:00"), timestamp("2023-05-03T18:30:00"), timestamp("2023-05-05T12:30:00"), timestamp("2023-05-10T12:30:00"), timestamp("2023-05-10T12:30:00"), timestamp("2023-05-12T14:00:00"), timestamp("2023-05-16T12:30:00"), timestamp("2023-05-16T12:30:00"), timestamp("2023-05-19T15:00:00"), timestamp("2023-05-24T18:00:00"), timestamp("2023-05-25T12:30:00"), timestamp("2023-05-26T12:30:00"), timestamp("2023-05-26T12:30:00"), timestamp("2023-06-01T12:15:00"), timestamp("2023-06-01T14:00:00"), timestamp("2023-06-02T12:30:00"), timestamp("2023-06-05T14:00:00"), timestamp("2023-06-13T12:30:00"), timestamp("2023-06-13T12:30:00"), timestamp("2023-06-14T18:00:00"), timestamp("2023-06-14T18:00:00"), timestamp("2023-06-14T18:00:00"), timestamp("2023-06-14T18:00:00"), timestamp("2023-06-14T18:00:00"), timestamp("2023-06-14T18:00:00"), timestamp("2023-06-14T18:00:00"), timestamp("2023-06-14T18:30:00"), timestamp("2023-06-15T12:30:00"), timestamp("2023-06-15T12:30:00"), timestamp("2023-06-16T14:00:00"), timestamp("2023-06-21T14:00:00"), timestamp("2023-06-22T14:00:00"), timestamp("2023-06-28T13:30:00"), timestamp("2023-06-28T20:30:00"), timestamp("2023-06-29T06:30:00"), timestamp("2023-06-29T12:30:00"), timestamp("2023-06-30T12:30:00"), timestamp("2023-06-30T12:30:00"), timestamp("2023-07-03T14:00:00"), timestamp("2023-07-05T18:00:00"), timestamp("2023-07-06T12:15:00"), timestamp("2023-07-06T14:00:00"), timestamp("2023-07-07T12:30:00"), timestamp("2023-07-07T12:30:00"), timestamp("2023-07-07T12:30:00"), timestamp("2023-07-12T12:30:00"), timestamp("2023-07-12T12:30:00"), timestamp("2023-07-12T12:30:00"), timestamp("2023-07-12T12:30:00"), timestamp("2023-07-13T12:30:00"), timestamp("2023-07-14T14:00:00"), timestamp("2023-07-18T12:30:00"), timestamp("2023-07-18T12:30:00"), timestamp("2023-07-24T13:45:00"), timestamp("2023-07-24T13:45:00"), timestamp("2023-07-26T18:00:00"), timestamp("2023-07-26T18:00:00"), timestamp("2023-07-26T18:30:00"), timestamp("2023-07-27T12:30:00"), timestamp("2023-07-28T12:30:00"), timestamp("2023-07-28T12:30:00"), timestamp("2023-08-01T14:00:00"), timestamp("2023-08-02T12:15:00"), timestamp("2023-08-03T14:00:00"), timestamp("2023-08-04T12:30:00"), timestamp("2023-08-04T12:30:00"), timestamp("2023-08-04T12:30:00"), timestamp("2023-08-10T12:30:00"), timestamp("2023-08-10T12:30:00"), timestamp("2023-08-10T12:30:00"), timestamp("2023-08-10T12:30:00"), timestamp("2023-08-11T12:30:00"), timestamp("2023-08-11T14:00:00"), timestamp("2023-08-15T12:30:00"), timestamp("2023-08-15T12:30:00"), timestamp("2023-08-16T18:00:00"), timestamp("2023-08-23T13:45:00"), timestamp("2023-08-23T13:45:00"), timestamp("2023-08-24T12:30:00"), timestamp("2023-08-31T12:30:00"), timestamp("2023-08-31T12:30:00"), timestamp("2023-09-01T12:30:00"), timestamp("2023-09-01T12:30:00"), timestamp("2023-09-01T12:30:00"), timestamp("2023-09-01T14:00:00"), timestamp("2023-09-04T14:00:00"), timestamp("2023-09-06T12:15:00"), timestamp("2023-09-13T12:30:00"), timestamp("2023-09-13T12:30:00"), timestamp("2023-09-13T12:30:00"), timestamp("2023-09-13T12:30:00"), timestamp("2023-09-14T12:30:00"), timestamp("2023-09-14T12:30:00"), timestamp("2023-09-14T12:30:00"), timestamp("2023-09-15T14:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:00:00"), timestamp("2023-09-20T18:30:00"), timestamp("2023-09-22T13:45:00"), timestamp("2023-09-22T13:45:00"), timestamp("2023-09-28T12:30:00"), timestamp("2023-09-29T12:30:00"), timestamp("2023-09-29T12:30:00"), timestamp("2023-10-02T14:00:00"), timestamp("2023-10-04T12:15:00"), timestamp("2023-10-04T14:00:00"), timestamp("2023-10-06T12:30:00"), timestamp("2023-10-06T12:30:00"), timestamp("2023-10-06T12:30:00"), timestamp("2023-10-11T12:30:00"), timestamp("2023-10-11T18:00:00"), timestamp("2023-10-12T12:30:00"), timestamp("2023-10-12T12:30:00"), timestamp("2023-10-12T12:30:00"), timestamp("2023-10-12T12:30:00"), timestamp("2023-10-13T14:00:00"), timestamp("2023-10-17T12:30:00"), timestamp("2023-10-17T12:30:00"), timestamp("2023-10-24T13:45:00"), timestamp("2023-10-24T13:45:00"), timestamp("2023-10-26T12:30:00"), timestamp("2023-10-27T12:30:00"), timestamp("2023-10-27T12:30:00"), timestamp("2023-11-01T12:15:00"), timestamp("2023-11-01T14:00:00"), timestamp("2023-11-01T18:00:00"), timestamp("2023-11-01T18:00:00"), timestamp("2023-11-01T18:30:00"), timestamp("2023-11-03T12:30:00"), timestamp("2023-11-03T12:30:00"), timestamp("2023-11-03T12:30:00"), timestamp("2023-11-03T15:00:00"), timestamp("2023-11-10T15:00:00"), timestamp("2023-11-14T13:30:00"), timestamp("2023-11-14T13:30:00"), timestamp("2023-11-14T13:30:00"), timestamp("2023-11-14T13:30:00"), timestamp("2023-11-15T13:30:00"), timestamp("2023-11-16T13:30:00"), timestamp("2023-11-16T13:30:00"), timestamp("2023-11-22T19:00:00"), timestamp("2023-11-23T14:45:00"), timestamp("2023-11-23T14:45:00"), timestamp("2023-11-29T13:30:00"), timestamp("2023-11-30T13:30:00"), timestamp("2023-11-30T13:30:00"), timestamp("2023-12-01T13:30:00"), timestamp("2023-12-01T13:30:00"), timestamp("2023-12-01T15:00:00"), timestamp("2023-12-06T13:15:00"), timestamp("2023-12-06T15:00:00"), timestamp("2023-12-08T13:30:00"), timestamp("2023-12-08T15:00:00"), timestamp("2023-12-12T13:30:00"), timestamp("2023-12-12T13:30:00"), timestamp("2023-12-12T13:30:00"), timestamp("2023-12-13T13:30:00"), timestamp("2023-12-13T13:30:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:00:00"), timestamp("2023-12-13T19:30:00"), timestamp("2023-12-14T13:30:00"), timestamp("2023-12-14T13:30:00"), timestamp("2023-12-18T14:45:00"), timestamp("2023-12-18T14:45:00"), timestamp("2023-12-21T13:30:00"), timestamp("2023-12-22T13:30:00"), timestamp("2023-12-22T13:30:00") )
Donchian MA Bands [LuxAlgo]
https://www.tradingview.com/script/XMhy1M9c-Donchian-MA-Bands-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
1,011
study
5
CC-BY-NC-SA-4.0
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © LuxAlgo //@version=5 indicator("Donchian MA Bands [LuxAlgo]", shorttitle="LuxAlgo - Donchian MA Bands", overlay=true) //------------------------------------------------------------------------------ // Settings //-----------------------------------------------------------------------------{ opt = input.string( 'clouds' , 'Style' , options=['clouds', 'Upper band', 'Lower band', 'bands'] , group='Bands' ) typeMA1 = input.string( "VWMA" , 'Type MA', options=["SMA", "EMA", "SMMA (RMA)", "HullMA", "WMA", "VWMA", "DEMA", "TEMA", "NONE"] , group='Bands' ) len1 = input.int ( 50 , 'Length' , group='Bands' ) colU = input.color (#2962ffc0, 'colour bands' , inline='1', group='Bands' ) colD = input.color (#ff5e00c0, '' , inline='1', group='Bands' ) typeMA2 = input.string( "VWMA" , 'Type MA', options=["SMA", "EMA", "SMMA (RMA)", "HullMA", "WMA", "VWMA", "DEMA", "TEMA", "NONE"] , group= 'S/R' ) len2 = input.int ( 50 , 'Length' , group= 'S/R' ) colU2 = input.color (#08998180, 'colour S/R     ' , inline='2', group= 'S/R' ) colD2 = input.color (#f2364580, '' , inline='2', group= 'S/R' ) cMidD = input.color (#B2B5BE , 'Colour Mid Donchian' , inline='2', group= 'Mid Donchian') //-----------------------------------------------------------------------------} // Variables //-----------------------------------------------------------------------------{ var bool inPosition = false int n = bar_index var int trend = 0 var float gU = na var float gD = na var line lU = line.new(na, na, na, na, color=colU2) var line lD = line.new(na, na, na, na, color=colD2) //-----------------------------------------------------------------------------} // Methods //-----------------------------------------------------------------------------{ method ma(string type, int length) => // ema1 = ta.ema(close, length) ema2 = ta.ema(ema1 , length) ema3 = ta.ema(ema2 , length) // switch type "SMA" => ta.sma (close, length) "EMA" => ema1 "SMMA (RMA)" => ta.rma (close, length) "HullMA" => ta.hma (close, length) "WMA" => ta.wma (close, length) "VWMA" => ta.vwma(close, length) "DEMA" => 2 * ema1 - ema2 "TEMA" => (3 * ema1) - (3 * ema2) + ema3 => na method fun(string typeMA, len) => ma = typeMA .ma (len) H = ta.highest(ma, len) L = ta.lowest (ma, len) HH = ta.highest( H, len) HL = ta.lowest ( H, len) LH = ta.highest( L, len) LL = ta.lowest ( L, len) HHH = ta.highest(HH, len) HHL = ta.lowest (HH, len) HLH = ta.highest(HL, len) HLL = ta.lowest (HL, len) LLH = ta.highest(LL, len) LLL = ta.lowest (LL, len) LHH = ta.highest(LH, len) LHL = ta.lowest (LH, len) [HHH, HH, HHL, H, HLH, HL, HLL, ma, LHH, LH, LHL, L, LLH, LL, LLL] //-----------------------------------------------------------------------------} // Calculations //-----------------------------------------------------------------------------{ // Bands bands = opt == 'bands' [HHH1 , HH1 , HHL1, H1 , HLH1, HL1, HLL1, ma1, LHH1, LH1, LHL1, L1, LLH1, LL1, LLL1] = typeMA1.fun(len1) arr1 = bands ? array.from(HHH1, HH1, HHL1, H1, HLH1, HL1, HLL1, ma1, LHH1, LH1, LHL1 , L1, LLH1, LL1, LLL1) : array.from( HH1, H1, HL1, ma1, LH1, L1, LL1), arr1.sort() // S/R [ _ , HH2 , _ , H2 , _ , HL2, _ , ma2, LHH2, LH2, LHL2, L2, LLH2, LL2, LLL2] = typeMA2.fun(len2) arr2 = array.from( HH2, H2, HL2, ma2, LH2, L2, LL2), arr2.sort() //-----------------------------------------------------------------------------} // Execution //-----------------------------------------------------------------------------{ // Bands gt0 = bands ? arr1.get( 0) : na gt1 = arr1.get( 1) gt5 = arr1.get( 5) gt13 = bands ? arr1.get(13) : na gt14 = bands ? arr1.get(14) : na trend := trend < 1 and close > gt14 ? 1 : trend > -1 and close < gt0 ? -1 : trend inPosition := (trend == 1 and trend[1] < 1 ) or (trend == -1 and trend[1] > -1 ) ? true : (trend < 1 and trend[1] == 1 ) or (trend > -1 and trend[1] == -1 ) ? false : inPosition // S/R L_1 = arr2.get(1) L_2 = arr2.get(2) H_4 = arr2.get(4) H_5 = arr2.get(5) gU := L_1 != L_2 ? L_1 : gU gD := H_4 != H_5 ? H_5 : gD if not bands lU.set_xy1(n, gU), lU.set_xy2(n + 10, gU) // Upper S/R line lD.set_xy1(n, gD), lD.set_xy2(n + 10, gD) // lower S/R line //-----------------------------------------------------------------------------} // Plot - Fill //-----------------------------------------------------------------------------{ plot(bands ? math.avg(gt0, gt14) : math.avg(L_1, H_5) , 'Mid Donchian', color=cMidD , style=plot.style_linebr) plot(ma1 , linewidth=2 , title='MA' , color=color.yellow, display=display.none) // Clouds - Upper/Lower Bands _h2 = plot(opt == 'clouds' ? gt5 : na, 'Cloud H' , display=display.none) _l2 = plot(opt == 'clouds' ? gt1 : na, 'Cloud L' , display=display.none) HHs = plot( not bands ? HH1 : na, 'H-H sma' , color=color.red , display=display.none) _Hs = plot( not bands ? H1 : na, 'H sma' , color=color.red , display=display.none) LHs = plot(opt == 'Upper band' ? HL1 : na, 'L-H sma' , color=color.yellow, display=display.none) HLs = plot(opt == 'Lower band' ? LH1 : na, 'H-L sma' , color=color.yellow, display=display.none) _Ls = plot( not bands ? L1 : na, 'L sma' , color=color.lime , display=display.none) LLs = plot( not bands ? LL1 : na, 'L-L sma' , color=color.lime , display=display.none) fill(HHs, _h2, top_value = H1 , bottom_value = HH1 , top_color = color.new(colD, 85) , bottom_color = color.new(colD, 25), title="") fill(LLs, _l2, top_value = L1 , bottom_value = LL1 , top_color = color.new(colU, 85) , bottom_color = color.new(colU, 25), title="") fill(HHs, LHs, top_value = H1 == HH1 ? HH1 : HL1, bottom_value=H1 == HH1 ? HL1 : HH1 , top_color = color.new(H1 == HH1 ? colU : H1 == HL1 ? colD : chart.bg_color, 85) , bottom_color = color.new(H1 == HH1 ? colU : H1 == HL1 ? colD : chart.bg_color, 25), title="") fill(LLs, HLs, top_value = L1 == LL1 ? LL1 : LH1, bottom_value=L1 == LL1 ? LH1 : LL1 , top_color = color.new(L1 == LL1 ? colD : L1 == LH1 ? colU : chart.bg_color, 85) , bottom_color = color.new(L1 == LL1 ? colD : L1 == LH1 ? colU : chart.bg_color, 25), title="") // Bands p1 = plot( bands ? gt0 : na, 'Bands get1' , color=colU ) p2 = plot( bands ? gt1 : na, 'Bands get2' , color=chart.bg_color, display=display.none ) p14 = plot( bands ? gt13 : na, 'Bands get14' , color=chart.bg_color, display=display.none ) p15 = plot( bands ? gt14 : na, 'Bands get15' , color=colD ) fill(p1 , p2 , top_value=gt1 , bottom_value=gt0 , top_color=color.new(colU, 85), bottom_color=color.new(colU, 25), title="") fill(p14, p15, top_value=gt13, bottom_value=gt14, top_color=color.new(colD, 85), bottom_color=color.new(colD, 25), title="") plotshape(trend == 1 and trend[1] < 1 ? low : na, 'Up', style=shape.circle, color=colU, location=location.abovebar, size=size.tiny) plotshape(trend == -1 and trend[1] > -1 ? high : na, 'Dn', style=shape.circle, color=colD, location=location.belowbar, size=size.tiny) // S/R plot (not bands and gU == gU[1] ? gU : na, 'S/R Upper', color=colU2 , style=plot.style_linebr) plot (not bands and gD == gD[1] ? gD : na, 'S/R Lower', color=colD2 , style=plot.style_linebr) g1 = plot(not bands ? L_1 : na, 'S/R get 1', color=color.lime, display=display.none) g2 = plot(not bands ? L_2 : na, 'S/R get 2', color=color.lime, display=display.none) g4 = plot(not bands ? H_4 : na, 'S/R get 4', color=color.red , display=display.none) g5 = plot(not bands ? H_5 : na, 'S/R get 5', color=color.red , display=display.none) fill(g1, g2, color=colU2) fill(g4, g5, color=colD2) //-----------------------------------------------------------------------------}
NewsEventsJpy
https://www.tradingview.com/script/HFrg5Dsc-NewsEventsJpy/
wppqqppq
https://www.tradingview.com/u/wppqqppq/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © wppqqppq //@version=5 // @description This library provides date and time data of the high impact news events on JPY. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script. library("NewsEventsJpy") // @function JPY high impact news date and time from 2015 to 2023 export jpyNews2015To2023() => array.from( timestamp("2015-01-21T06:30:00"), timestamp("2015-01-29T23:30:00"), timestamp("2015-02-15T23:50:00"), timestamp("2015-02-18T06:30:00"), timestamp("2015-02-26T23:30:00"), timestamp("2015-03-08T23:50:00"), timestamp("2015-03-17T06:30:00"), timestamp("2015-03-26T23:30:00"), timestamp("2015-04-08T03:36:00"), timestamp("2015-04-30T04:05:34"), timestamp("2015-04-30T23:30:00"), timestamp("2015-05-15T03:40:00"), timestamp("2015-05-19T23:50:00"), timestamp("2015-05-21T00:00:00"), timestamp("2015-05-22T03:00:00"), timestamp("2015-05-22T03:00:00"), timestamp("2015-05-23T13:30:00"), timestamp("2015-06-04T00:00:00"), timestamp("2015-06-07T23:50:00"), timestamp("2015-06-18T00:00:00"), timestamp("2015-06-19T03:00:00"), timestamp("2015-06-19T06:30:00"), timestamp("2015-07-15T03:00:00"), timestamp("2015-07-15T06:30:00"), timestamp("2015-08-07T03:00:00"), timestamp("2015-08-07T03:00:00"), timestamp("2015-08-07T06:00:00"), timestamp("2015-08-27T23:30:00"), timestamp("2015-09-15T03:00:00"), timestamp("2015-09-15T03:00:00"), timestamp("2015-09-15T03:00:00"), timestamp("2015-09-17T06:35:00"), timestamp("2015-10-01T01:00:00"), timestamp("2015-10-07T03:00:00"), timestamp("2015-10-07T03:02:18"), timestamp("2015-10-07T06:30:00"), timestamp("2015-10-16T06:35:00"), timestamp("2015-10-29T23:30:00"), timestamp("2015-10-30T03:24:00"), timestamp("2015-10-30T03:24:34"), timestamp("2015-10-30T06:30:00"), timestamp("2015-11-06T04:00:00"), timestamp("2015-11-15T23:50:00"), timestamp("2015-11-19T03:00:00"), timestamp("2015-11-19T03:00:00"), timestamp("2015-11-19T06:00:00"), timestamp("2015-11-20T07:00:00"), timestamp("2015-11-30T01:00:00"), timestamp("2015-12-07T03:45:00"), timestamp("2015-12-07T23:50:00"), timestamp("2015-12-07T23:50:00"), timestamp("2015-12-07T23:50:00"), timestamp("2015-12-18T03:00:00"), timestamp("2015-12-18T03:50:00"), timestamp("2015-12-18T05:00:00"), timestamp("2015-12-24T04:00:00"), timestamp("2016-01-12T10:30:00"), timestamp("2016-01-29T03:00:00"), timestamp("2016-01-29T03:00:00"), timestamp("2016-01-29T06:30:00"), timestamp("2016-02-03T02:30:00"), timestamp("2016-03-07T03:40:00"), timestamp("2016-03-15T03:00:00"), timestamp("2016-03-15T03:00:00"), timestamp("2016-03-15T06:30:00"), timestamp("2016-04-07T00:30:00"), timestamp("2016-04-20T00:00:00"), timestamp("2016-04-28T03:00:00"), timestamp("2016-04-28T03:00:00"), timestamp("2016-04-28T05:30:00"), timestamp("2016-05-08T23:50:00"), timestamp("2016-05-13T03:30:00"), timestamp("2016-06-16T02:45:00"), timestamp("2016-06-16T02:45:17"), timestamp("2016-06-16T06:00:00"), timestamp("2016-07-07T00:30:00"), timestamp("2016-07-28T23:30:00"), timestamp("2016-07-29T00:00:00"), timestamp("2016-07-29T01:00:00"), timestamp("2016-07-29T06:30:00"), timestamp("2016-08-23T04:00:00"), timestamp("2016-08-27T04:25:00"), timestamp("2016-09-05T02:30:00"), timestamp("2016-09-21T04:19:05"), timestamp("2016-09-21T04:21:00"), timestamp("2016-09-21T06:00:00"), timestamp("2016-09-29T06:35:00"), timestamp("2016-09-30T04:30:00"), timestamp("2016-10-21T03:00:00"), timestamp("2016-11-01T03:00:00"), timestamp("2016-11-01T03:00:00"), timestamp("2016-11-01T03:00:00"), timestamp("2016-11-06T23:50:00"), timestamp("2016-12-20T03:00:00"), timestamp("2016-12-20T03:00:00"), timestamp("2016-12-20T06:00:00"), timestamp("2016-12-26T04:00:00"), timestamp("2017-01-31T03:00:00"), timestamp("2017-01-31T03:00:00"), timestamp("2017-01-31T06:30:00"), timestamp("2017-02-02T23:50:00"), timestamp("2017-03-16T02:55:00"), timestamp("2017-03-16T02:55:00"), timestamp("2017-03-16T05:30:00"), timestamp("2017-03-21T23:50:00"), timestamp("2017-04-17T06:15:00"), timestamp("2017-04-27T03:15:00"), timestamp("2017-04-27T03:15:00"), timestamp("2017-04-27T06:30:00"), timestamp("2017-05-01T23:50:00"), timestamp("2017-05-02T00:20:00"), timestamp("2017-05-24T00:00:00"), timestamp("2017-06-16T02:00:00"), timestamp("2017-06-16T02:00:00"), timestamp("2017-06-16T06:30:00"), timestamp("2017-06-20T23:50:00"), timestamp("2017-06-21T06:35:00"), timestamp("2017-06-28T13:30:00"), timestamp("2017-07-20T03:12:00"), timestamp("2017-07-20T03:12:00"), timestamp("2017-07-20T06:30:00"), timestamp("2017-07-24T23:50:00"), timestamp("2017-09-21T03:18:00"), timestamp("2017-09-21T03:18:00"), timestamp("2017-09-21T06:30:00"), timestamp("2017-09-25T05:35:00"), timestamp("2017-09-25T23:50:00"), timestamp("2017-09-28T06:35:00"), timestamp("2017-10-22T00:00:00"), timestamp("2017-10-31T03:00:00"), timestamp("2017-10-31T03:07:55"), timestamp("2017-10-31T06:30:00"), timestamp("2017-11-05T23:50:00"), timestamp("2017-11-06T01:00:00"), timestamp("2017-11-13T17:45:00"), timestamp("2017-11-14T10:00:00"), timestamp("2017-12-21T02:00:00"), timestamp("2017-12-21T02:00:00"), timestamp("2017-12-21T06:30:00"), timestamp("2017-12-25T23:50:00"), timestamp("2018-01-23T03:00:00"), timestamp("2018-01-23T03:14:00"), timestamp("2018-01-23T06:30:00"), timestamp("2018-01-25T23:50:00"), timestamp("2018-03-01T23:30:00"), timestamp("2018-03-09T02:00:00"), timestamp("2018-03-09T02:46:00"), timestamp("2018-03-09T06:30:00"), timestamp("2018-03-13T23:50:00"), timestamp("2018-03-29T23:30:00"), timestamp("2018-04-26T23:30:00"), timestamp("2018-04-27T02:00:00"), timestamp("2018-04-27T03:05:14"), timestamp("2018-04-27T06:30:00"), timestamp("2018-05-06T23:50:00"), timestamp("2018-05-24T23:30:00"), timestamp("2018-06-15T04:00:00"), timestamp("2018-06-15T04:00:00"), timestamp("2018-06-15T04:00:00"), timestamp("2018-06-19T23:50:00"), timestamp("2018-06-20T13:30:00"), timestamp("2018-06-28T23:30:00"), timestamp("2018-07-09T00:30:00"), timestamp("2018-07-26T23:30:00"), timestamp("2018-07-31T02:00:00"), timestamp("2018-07-31T02:00:00"), timestamp("2018-07-31T05:00:00"), timestamp("2018-08-02T23:50:00"), timestamp("2018-08-30T23:30:00"), timestamp("2018-09-03T05:40:00"), timestamp("2018-09-19T02:59:00"), timestamp("2018-09-19T02:59:16"), timestamp("2018-09-19T06:00:00"), timestamp("2018-09-24T23:50:00"), timestamp("2018-09-25T05:35:00"), timestamp("2018-09-27T06:35:00"), timestamp("2018-09-27T23:30:00"), timestamp("2018-10-18T00:30:00"), timestamp("2018-10-19T06:35:00"), timestamp("2018-10-25T23:30:00"), timestamp("2018-10-31T02:00:00"), timestamp("2018-10-31T03:09:17"), timestamp("2018-10-31T06:00:00"), timestamp("2018-11-04T23:50:00"), timestamp("2018-11-05T01:00:00"), timestamp("2018-11-19T03:30:00"), timestamp("2018-11-29T23:30:00"), timestamp("2018-12-09T23:50:00"), timestamp("2018-12-20T02:52:00"), timestamp("2018-12-20T02:52:00"), timestamp("2018-12-20T04:00:00"), timestamp("2018-12-25T23:50:00"), timestamp("2018-12-26T04:00:00"), timestamp("2018-12-27T23:30:00"), timestamp("2019-01-17T03:20:00"), timestamp("2019-01-23T03:00:00"), timestamp("2019-01-23T03:00:00"), timestamp("2019-01-23T06:00:00"), timestamp("2019-01-24T23:30:00"), timestamp("2019-01-27T23:50:00"), timestamp("2019-02-13T23:50:00"), timestamp("2019-02-28T23:30:00"), timestamp("2019-03-07T23:50:00"), timestamp("2019-03-15T02:00:00"), timestamp("2019-03-15T02:00:00"), timestamp("2019-03-15T06:00:00"), timestamp("2019-03-15T08:55:00"), timestamp("2019-03-19T23:50:00"), timestamp("2019-03-28T23:30:00"), timestamp("2019-04-10T06:15:00"), timestamp("2019-04-25T03:00:00"), timestamp("2019-04-25T03:00:00"), timestamp("2019-04-25T06:00:00"), timestamp("2019-04-25T23:30:00"), timestamp("2019-05-07T23:50:00"), timestamp("2019-05-19T23:50:00"), timestamp("2019-05-27T03:00:00"), timestamp("2019-05-29T00:00:00"), timestamp("2019-05-30T23:30:00"), timestamp("2019-06-06T03:50:00"), timestamp("2019-06-07T03:50:00"), timestamp("2019-06-08T06:20:00"), timestamp("2019-06-09T23:50:00"), timestamp("2019-06-20T02:00:00"), timestamp("2019-06-20T02:00:00"), timestamp("2019-06-20T06:00:00"), timestamp("2019-06-24T23:50:00"), timestamp("2019-06-27T23:30:00"), timestamp("2019-07-08T00:30:00"), timestamp("2019-07-19T20:30:00"), timestamp("2019-07-22T15:00:00"), timestamp("2019-07-25T23:30:00"), timestamp("2019-07-30T02:00:00"), timestamp("2019-07-30T02:00:00"), timestamp("2019-07-30T06:30:00"), timestamp("2019-08-01T23:50:00"), timestamp("2019-08-08T23:50:00"), timestamp("2019-08-29T23:30:00"), timestamp("2019-09-08T23:50:00"), timestamp("2019-09-19T03:00:00"), timestamp("2019-09-19T03:00:00"), timestamp("2019-09-19T06:30:00"), timestamp("2019-09-24T05:30:00"), timestamp("2019-09-24T23:50:00"), timestamp("2019-09-26T23:30:00"), timestamp("2019-10-15T00:30:00"), timestamp("2019-10-28T23:30:00"), timestamp("2019-10-31T03:00:00"), timestamp("2019-10-31T03:00:00"), timestamp("2019-10-31T06:00:00"), timestamp("2019-11-05T23:50:00"), timestamp("2019-11-13T23:50:00"), timestamp("2019-11-28T23:30:00"), timestamp("2019-12-08T23:50:00"), timestamp("2019-12-19T03:00:00"), timestamp("2019-12-19T03:00:00"), timestamp("2019-12-19T06:00:00"), timestamp("2019-12-23T23:50:00"), timestamp("2019-12-26T00:00:00"), timestamp("2019-12-26T23:30:00"), timestamp("2020-01-15T00:30:00"), timestamp("2020-01-21T03:00:00"), timestamp("2020-01-21T03:00:00"), timestamp("2020-01-21T06:00:00"), timestamp("2020-01-23T23:50:00"), timestamp("2020-01-30T23:30:00"), timestamp("2020-02-16T23:50:00"), timestamp("2020-02-27T23:30:00"), timestamp("2020-03-08T23:50:00"), timestamp("2020-03-16T03:00:00"), timestamp("2020-03-16T03:00:00"), timestamp("2020-03-16T07:00:00"), timestamp("2020-03-18T23:50:00"), timestamp("2020-03-26T23:30:00"), timestamp("2020-04-09T00:30:00"), timestamp("2020-04-27T03:00:00"), timestamp("2020-04-27T03:00:00"), timestamp("2020-04-27T06:30:00"), timestamp("2020-04-29T23:50:00"), timestamp("2020-04-30T23:30:00"), timestamp("2020-04-30T23:50:00"), timestamp("2020-05-17T23:50:00"), timestamp("2020-05-22T03:00:00"), timestamp("2020-05-22T03:00:00"), timestamp("2020-05-28T23:30:00"), timestamp("2020-05-28T23:50:00"), timestamp("2020-06-07T23:50:00"), timestamp("2020-06-16T03:00:00"), timestamp("2020-06-16T03:00:00"), timestamp("2020-06-16T06:00:00"), timestamp("2020-06-18T23:50:00"), timestamp("2020-06-25T23:30:00"), timestamp("2020-07-15T03:00:00"), timestamp("2020-07-15T03:00:00"), timestamp("2020-07-15T06:00:00"), timestamp("2020-07-19T23:50:00"), timestamp("2020-08-02T23:50:00"), timestamp("2020-08-05T12:00:00"), timestamp("2020-08-16T23:50:00"), timestamp("2020-09-07T23:50:00"), timestamp("2020-09-17T03:00:00"), timestamp("2020-09-17T03:00:00"), timestamp("2020-09-17T06:00:00"), timestamp("2020-09-23T05:35:00"), timestamp("2020-09-23T23:50:00"), timestamp("2020-09-30T23:50:00"), timestamp("2020-10-05T06:40:00"), timestamp("2020-10-29T03:00:00"), timestamp("2020-10-29T03:00:00"), timestamp("2020-10-29T06:00:00"), timestamp("2020-11-03T23:50:00"), timestamp("2020-11-15T23:50:00"), timestamp("2020-11-24T12:05:00"), timestamp("2020-12-07T23:50:00"), timestamp("2020-12-13T23:50:00"), timestamp("2020-12-18T03:00:00"), timestamp("2020-12-18T03:00:00"), timestamp("2020-12-18T06:00:00"), timestamp("2020-12-22T23:50:00"), timestamp("2020-12-24T00:00:00"), timestamp("2021-01-21T03:00:00"), timestamp("2021-01-21T03:00:00"), timestamp("2021-01-21T06:00:00"), timestamp("2021-01-25T23:50:00"), timestamp("2021-02-14T23:50:00"), timestamp("2021-03-08T23:50:00"), timestamp("2021-03-16T04:05:00"), timestamp("2021-03-19T03:00:00"), timestamp("2021-03-19T03:00:00"), timestamp("2021-03-19T06:00:00"), timestamp("2021-03-23T23:50:00"), timestamp("2021-03-25T11:20:00"), timestamp("2021-03-31T23:50:00"), timestamp("2021-04-14T06:17:00"), timestamp("2021-04-15T01:00:00"), timestamp("2021-04-27T03:00:00"), timestamp("2021-04-27T03:00:00"), timestamp("2021-04-27T06:00:00"), timestamp("2021-05-05T23:50:00"), timestamp("2021-05-17T23:50:00"), timestamp("2021-05-24T11:05:00"), timestamp("2021-06-07T23:50:00"), timestamp("2021-06-18T03:00:00"), timestamp("2021-06-18T03:00:00"), timestamp("2021-06-18T06:00:00"), timestamp("2021-06-22T23:50:00"), timestamp("2021-06-24T06:45:00"), timestamp("2021-06-30T23:50:00"), timestamp("2021-07-16T03:00:00"), timestamp("2021-07-16T03:00:00"), timestamp("2021-07-16T06:00:00"), timestamp("2021-07-20T23:50:00"), timestamp("2021-07-27T07:30:00"), timestamp("2021-08-15T23:50:00"), timestamp("2021-09-07T23:50:00"), timestamp("2021-09-22T03:00:00"), timestamp("2021-09-22T03:00:00"), timestamp("2021-09-22T06:00:00"), timestamp("2021-09-27T23:50:00"), timestamp("2021-09-30T07:10:00"), timestamp("2021-09-30T23:50:00"), timestamp("2021-10-07T01:00:00"), timestamp("2021-10-28T03:00:00"), timestamp("2021-10-28T03:00:00"), timestamp("2021-10-28T06:00:00"), timestamp("2021-11-01T23:50:00"), timestamp("2021-11-14T23:50:00"), timestamp("2021-11-29T08:30:00"), timestamp("2021-12-07T23:50:00"), timestamp("2021-12-12T23:50:00"), timestamp("2021-12-17T03:00:00"), timestamp("2021-12-17T03:00:00"), timestamp("2021-12-17T06:00:00"), timestamp("2021-12-21T23:50:00"), timestamp("2022-01-12T01:00:00"), timestamp("2022-01-18T03:00:00"), timestamp("2022-01-18T03:00:00"), timestamp("2022-01-18T06:00:00"), timestamp("2022-01-20T23:50:00"), timestamp("2022-02-14T23:50:00"), timestamp("2022-03-08T23:50:00"), timestamp("2022-03-18T03:00:00"), timestamp("2022-03-18T03:00:00"), timestamp("2022-03-18T06:00:00"), timestamp("2022-03-23T23:50:00"), timestamp("2022-03-31T23:50:00"), timestamp("2022-04-11T01:00:00"), timestamp("2022-04-13T06:15:00"), timestamp("2022-04-28T03:00:00"), timestamp("2022-04-28T03:00:00"), timestamp("2022-04-28T06:00:00"), timestamp("2022-05-08T23:50:00"), timestamp("2022-05-17T23:50:00"), timestamp("2022-05-25T11:05:00"), timestamp("2022-06-07T23:50:00"), timestamp("2022-06-17T03:00:00"), timestamp("2022-06-17T03:00:00"), timestamp("2022-06-17T06:00:00"), timestamp("2022-06-21T23:50:00"), timestamp("2022-06-30T23:50:00"), timestamp("2022-07-11T01:00:00"), timestamp("2022-07-21T03:00:00"), timestamp("2022-07-21T03:00:00"), timestamp("2022-07-21T06:30:00"), timestamp("2022-07-25T23:50:00"), timestamp("2022-08-14T23:50:00"), timestamp("2022-09-07T23:50:00"), timestamp("2022-09-22T03:00:00"), timestamp("2022-09-22T03:00:00"), timestamp("2022-09-22T06:00:00"), timestamp("2022-09-26T05:35:00"), timestamp("2022-09-27T23:50:00"), timestamp("2022-10-02T23:50:00"), timestamp("2022-10-28T03:00:00"), timestamp("2022-10-28T03:00:00"), timestamp("2022-10-28T06:00:00"), timestamp("2022-11-01T23:50:00"), timestamp("2022-11-14T23:50:00"), timestamp("2022-12-02T01:30:00"), timestamp("2022-12-07T23:50:00"), timestamp("2022-12-13T23:50:00"), timestamp("2022-12-20T03:00:00"), timestamp("2022-12-20T03:00:00"), timestamp("2022-12-20T06:00:00"), timestamp("2022-12-22T23:50:00"), timestamp("2022-12-26T00:00:00"), timestamp("2023-01-10T10:10:00"), timestamp("2023-01-18T02:30:00"), timestamp("2023-01-18T02:30:00"), timestamp("2023-01-18T06:30:00"), timestamp("2023-01-22T23:50:00"), timestamp("2023-02-13T23:50:00"), timestamp("2023-02-24T05:00:00"), timestamp("2023-02-27T05:00:00"), timestamp("2023-03-08T23:50:00"), timestamp("2023-03-10T02:33:42"), timestamp("2023-03-10T03:00:00"), timestamp("2023-03-10T06:00:00"), timestamp("2023-03-14T23:50:00"), timestamp("2023-03-28T04:00:00"), timestamp("2023-04-02T23:50:00"), timestamp("2023-04-10T10:15:00"), timestamp("2023-04-28T03:00:00"), timestamp("2023-04-28T04:00:31"), timestamp("2023-04-28T06:00:00"), timestamp("2023-05-07T23:50:00"), timestamp("2023-05-16T23:50:00"), timestamp("2023-06-07T23:50:00"), timestamp("2023-06-16T02:45:00"), timestamp("2023-06-16T03:00:00"), timestamp("2023-06-16T06:00:00"), timestamp("2023-06-20T23:50:00"), timestamp("2023-06-28T13:30:00"), timestamp("2023-06-29T23:30:00"), timestamp("2023-06-29T23:30:00"), timestamp("2023-07-02T23:50:00"), timestamp("2023-07-27T23:30:00"), timestamp("2023-07-27T23:30:00"), timestamp("2023-07-28T03:00:00"), timestamp("2023-07-28T03:00:00"), timestamp("2023-07-28T06:00:00"), timestamp("2023-08-10T23:50:00"), timestamp("2023-08-31T23:30:00"), timestamp("2023-08-31T23:30:00"), timestamp("2023-09-06T23:50:00"), timestamp("2023-09-22T03:00:00"), timestamp("2023-09-22T03:00:00"), timestamp("2023-09-22T06:00:00"), timestamp("2023-09-28T23:30:00"), timestamp("2023-09-28T23:30:00"), timestamp("2023-10-01T23:50:00"), timestamp("2023-10-31T03:00:00"), timestamp("2023-10-31T03:00:00"), timestamp("2023-10-31T06:00:00"), timestamp("2023-11-02T23:30:00"), timestamp("2023-11-02T23:30:00"), timestamp("2023-11-14T23:50:00"), timestamp("2023-11-30T23:30:00"), timestamp("2023-11-30T23:30:00"), timestamp("2023-12-07T23:50:00"), timestamp("2023-12-14T23:50:00"), timestamp("2023-12-15T03:00:00"), timestamp("2023-12-15T03:00:00"), timestamp("2023-12-15T06:00:00") )
Overgeared Library Economic Calendar
https://www.tradingview.com/script/6BBnZfbe-Overgeared-Library-Economic-Calendar/
Overgeared
https://www.tradingview.com/u/Overgeared/
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/ // © jdehorty //@version=5 // @description This library is a data provider for important Dates and Times from the Economic Calendar. library(title='OvergearedLibraryEconomicCalendar') // @function Returns the list of dates supported by this library as a string array. // @returns // array<string> : Names of events supported by this library export events () => var array<string> events = array.from( "Special Event", // my add "FOMC Meetings", // Federal Open Market Committee "FOMC Minutes", // FOMC Meeting Minutes "PPI", // Producer Price Index "CPI", // Consumer Price Index "CSI", // Consumer Sentiment Index "CCI", // Consumer Confidence Index "NFP" // Non-Farm Payrolls ) // @function Gets the Special Event Dates // @returns // array<int> : Special Event export specialEvent() => array.from( timestamp("21 June 2023 9:00:00 EST"), //Fed Chair Powell Tesimony ลบไป 12 ชม บ้านเรา timestamp("22 June 2023 7:30:00 EST"), //Jobless ลบไป 12 ชม บ้านเรา timestamp("22 June 2023 9:00:00 EST"), //Fed Chair Powell Tesimony ลบไป 12 ชม บ้านเรา timestamp("23 June 2023 8:45:00 EST"), //S&P PMI timestamp("24 June 2023 12:40:00 EST"), //Fed William Speech timestamp("25 June 2023 8:15:00 EST"), //Fed William Speech timestamp("27 June 2023 7:30:00 EST"), //Durable Goods timestamp("27 June 2023 8:00:00 EST"), //S&P MOM YOY timestamp("27 June 2023 9:00:00 EST"), //CCC timestamp("28 June 2023 8:30:00 EST"), //Fed William Speech timestamp("29 June 2023 1:30:00 EST"), //Fed William Speech timestamp("29 June 2023 7:30:00 EST"), //GDP QoQ Q1 timestamp("29 June 2023 9:00:00 EST"), //Pending Home Sales (MoM) timestamp("30 June 2023 7:30:00 EST"), //Core CPE timestamp("3 July 2023 9:00:00 EST"), //ISM Manufacturing PMI timestamp("5 July 2023 13:00:00 EST"), //FOMC timestamp("6 July 2023 7:15:00 EST"), //ADP Nonfarm timestamp("6 July 2023 7:30:00 EST"), //Initial Jobless Claim timestamp("6 July 2023 8:45:00 EST"), //Services PMI timestamp("6 July 2023 9:00:00 EST"), //ISM Services PMI timestamp("6 July 2023 10:00:00 EST"), //Crude Oil Inventories timestamp("7 July 2023 7:30:00 EST"), //Nonfarm Payroll timestamp("11 July 2023 1:00:00 EST"), //German CPI timestamp("11 July 2023 11:00:00 EST"), //EIA Short Term timestamp("12 July 2023 7:30:00 EST"), //Core CPI timestamp("12 July 2023 9:30:00 EST"), //Crude Oil Inventories timestamp("13 July 2023 1:00:00 EST"), //UK GDP timestamp("13 July 2023 7:30:00 EST"), //Jobless, PPI timestamp("18 July 2023 7:30:00 EST"), //Core Retail Sales timestamp("19 July 2023 1:00:00 EST"), //GBP CPI timestamp("19 July 2023 4:00:00 EST"), //EUR CPI timestamp("19 July 2023 7:30:00 EST"), //Building Permits timestamp("19 July 2023 9:30:00 EST"), //Crude Oil timestamp("20 July 2023 7:30:00 EST"), //Initial Jobless Claims timestamp("20 July 2023 9:00:00 EST"), // timestamp("24 July 2023 2:30:00 EST"), // timestamp("24 July 2023 3:30:00 EST"), // timestamp("24 July 2023 8:45:00 EST"), // timestamp("25 July 2023 9:00:00 EST"), // timestamp("26 July 2023 7:00:00 EST"), // timestamp("26 July 2023 9:00:00 EST"), // timestamp("26 July 2023 9:30:00 EST"), // timestamp("26 July 2023 13:00:00 EST"), // timestamp("26 July 2023 13:30:00 EST"), // timestamp("27 July 2023 7:15:00 EST"), // timestamp("27 July 2023 7:30:00 EST"), // timestamp("27 July 2023 7:45:00 EST"), // timestamp("27 July 2023 9:00:00 EST"), // timestamp("28 July 2023 1:00:00 EST"), // timestamp("28 July 2023 7:00:00 EST"), // timestamp("28 July 2023 7:30:00 EST"), // timestamp("30 July 2023 20:30:00 EST"), // timestamp("31 July 2023 4:00:00 EST"), // timestamp("1 Aug 2023 2:55:00 EST"), // timestamp("1 Aug 2023 9:00:00 EST"), // timestamp("2 Aug 2023 7:15:00 EST"), // timestamp("2 Aug 2023 9:30:00 EST"), // timestamp("3 Aug 2023 6:00:00 EST"), // timestamp("3 Aug 2023 7:30:00 EST"), // timestamp("3 Aug 2023 8:45:00 EST"), // timestamp("3 Aug 2023 9:00:00 EST"), // timestamp("4 Aug 2023 7:30:00 EST") // ) // @function Gets the FOMC Meeting Dates. The FOMC meets eight times a year to determine the course of monetary policy. The FOMC announces its decision on the federal funds rate at the conclusion of each meeting and also issues a statement that provides information on the economic outlook and the Committee's assessment of the risks to the outlook. // @returns // array<int> : FOMC Meeting Dates as timestamps export fomcMeetings() => array.from( timestamp("26 Jan 2022 14:00:00 EST"), // 2022 timestamp("16 March 2022 14:00:00 EDT"), timestamp("4 May 2022 14:00:00 EDT"), timestamp("15 June 2022 14:00:00 EDT"), timestamp("27 July 2022 14:00:00 EDT"), timestamp("21 Sept 2022 14:00:00 EDT"), timestamp("2 Nov 2022 14:00:00 EDT"), timestamp("14 Dec 2022 14:00:00 EST"), timestamp("1 Feb 2023 14:00:00 EST"), // 2023 timestamp("22 March 2023 14:00:00 EDT"), timestamp("3 May 2023 14:00:00 EDT"), timestamp("14 June 2023 14:00:00 EDT"), timestamp("26 July 2023 14:00:00 EDT"), timestamp("20 Sept 2023 14:00:00 EDT"), timestamp("1 Nov 2023 14:00:00 EDT"), timestamp("13 Dec 2023 14:00:00 EST") ) // @function Gets the FOMC Meeting Minutes Dates. The FOMC Minutes are released three weeks after each FOMC meeting. The Minutes provide information on the Committee's deliberations and decisions at the meeting. // @returns // array<int> : FOMC Meeting Minutes Dates as timestamps export fomcMinutes() => array.from( timestamp("16 Feb 2022 14:00:00 EST"), // 2022 timestamp("6 April 2022 14:00:00 EDT"), timestamp("25 May 2022 14:00:00 EDT"), timestamp("6 July 2022 14:00:00 EDT"), timestamp("17 Aug 2022 14:00:00 EDT"), timestamp("12 Oct 2022 14:00:00 EDT"), timestamp("23 Nov 2022 14:00:00 EST"), timestamp("4 Jan 2023 14:00:00 EST"), // 2023 timestamp("22 Feb 2023 14:00:00 EST"), timestamp("12 April 2023 14:00:00 EDT"), timestamp("24 May 2023 14:00:00 EDT"), timestamp("5 July 2023 14:00:00 EDT"), timestamp("16 Aug 2023 14:00:00 EDT"), timestamp("11 Oct 2023 14:00:00 EDT"), timestamp("22 Nov 2023 14:00:00 EST"), timestamp("3 Jan 2024 14:00:00 EST") ) // @function Gets the Producer Price Index (PPI) Dates. The Producer Price Index (PPI) measures the average change over time in the selling prices received by domestic producers for their output. The PPI is a leading indicator of CPI, and CPI is a leading indicator of inflation. // @returns // array<int> : PPI Dates as timestamps export ppiReleases() => array.from( timestamp("9 Nov 2021 8:30:00 EST"), // 2021 timestamp("14 Dec 2021 8:30:00 EST"), timestamp("13 Jan 2022 8:30:00 EST"), // 2022 timestamp("15 Feb 2022 8:30:00 EST"), timestamp("15 Mar 2022 8:30:00 EST"), timestamp("13 Apr 2022 8:30:00 EDT"), timestamp("12 May 2022 8:30:00 EDT"), timestamp("14 Jun 2022 8:30:00 EDT"), timestamp("14 Jul 2022 8:30:00 EDT"), timestamp("11 Aug 2022 8:30:00 EDT"), timestamp("14 Sep 2022 8:30:00 EDT"), timestamp("12 Oct 2022 8:30:00 EDT"), timestamp("15 Nov 2022 8:30:00 EST"), timestamp("9 Dec 2022 8:30:00 EST"), timestamp("18 Jan 2023 8:30:00 EST"), // 2023 timestamp("16 Feb 2023 8:30:00 EST"), timestamp("15 Mar 2023 8:30:00 EST"), timestamp("13 Apr 2023 8:30:00 EDT"), timestamp("11 May 2023 8:30:00 EDT"), timestamp("14 Jun 2023 8:30:00 EDT"), timestamp("13 Jul 2023 8:30:00 EDT"), timestamp("11 Aug 2023 8:30:00 EDT"), timestamp("14 Sep 2023 8:30:00 EDT"), timestamp("11 Oct 2023 8:30:00 EDT"), timestamp("15 Nov 2023 8:30:00 EST"), timestamp("13 Dec 2023 8:30:00 EST") ) // @function Gets the Consumer Price Index (CPI) Rekease Dates. The Consumer Price Index (CPI) measures changes in the price level of a market basket of consumer goods and services purchased by households. The CPI is a leading indicator of inflation. // @returns // array<int> : CPI Dates as timestamps export cpiReleases() => array.from( timestamp("12 Jan 2022 08:30:00 EST"), // 2022 timestamp("10 Feb 2022 08:30:00 EST"), timestamp("10 March 2022 08:30:00 EST"), timestamp("12 April 2022 08:30:00 EDT"), timestamp("11 May 2022 08:30:00 EDT"), timestamp("10 June 2022 08:30:00 EDT"), timestamp("13 July 2022 08:30:00 EDT"), timestamp("10 Aug 2022 08:30:00 EDT"), timestamp("13 Sept 2022 08:30:00 EDT"), timestamp("13 Oct 2022 08:30:00 EDT"), timestamp("10 Nov 2022 08:30:00 EST"), timestamp("13 Dec 2022 08:30:00 EST"), timestamp("12 Jan 2023 08:30:00 EST"), // 2023 timestamp("14 Feb 2023 08:30:00 EST"), timestamp("14 March 2023 08:30:00 EST"), timestamp("12 April 2023 08:30:00 EDT"), timestamp("10 May 2023 08:30:00 EDT"), timestamp("13 June 2023 08:30:00 EDT"), timestamp("12 July 2023 08:30:00 EDT"), timestamp("10 Aug 2023 08:30:00 EDT"), timestamp("13 Sept 2023 08:30:00 EDT"), timestamp("12 Oct 2023 08:30:00 EDT"), timestamp("14 Nov 2023 08:30:00 EST"), timestamp("12 Dec 2023 08:30:00 EST") ) // @function Gets the CSI release dates. The Consumer Sentiment Index (CSI) is a survey of consumer attitudes about the economy and their personal finances. The CSI is a leading indicator of consumer spending. // @returns // array<int> : CSI Dates as timestamps export csiReleases() => array.from( timestamp("14 Jan 2022 10:00:00 EST"), // 2022 timestamp("28 Jan 2022 10:00:00 EST"), timestamp("11 Feb 2022 10:00:00 EST"), timestamp("25 Feb 2022 10:00:00 EST"), timestamp("18 March 2022 10:00:00 EDT"), timestamp("1 April 2022 10:00:00 EDT"), timestamp("15 April 2022 10:00:00 EDT"), timestamp("29 April 2022 10:00:00 EDT"), timestamp("13 May 2022 10:00:00 EDT"), timestamp("27 May 2022 10:00:00 EDT"), timestamp("17 June 2022 10:00:00 EDT"), timestamp("1 July 2022 10:00:00 EDT"), timestamp("15 July 2022 10:00:00 EDT"), timestamp("29 July 2022 10:00:00 EDT"), timestamp("12 Aug 2022 10:00:00 EDT"), timestamp("26 Aug 2022 10:00:00 EDT"), timestamp("16 Sept 2022 10:00:00 EDT"), timestamp("30 Sept 2022 10:00:00 EDT"), timestamp("14 Oct 2022 10:00:00 EDT"), timestamp("28 Oct 2022 10:00:00 EDT"), timestamp("11 Nov 2022 10:00:00 EST"), timestamp("23 Nov 2022 10:00:00 EST"), timestamp("9 Dec 2022 10:00:00 EST"), timestamp("23 Dec 2022 10:00:00 EST"), timestamp("13 Jan 2023 10:00:00 EST"), // 2023 timestamp("27 Jan 2023 10:00:00 EST"), timestamp("10 Feb 2023 10:00:00 EST"), timestamp("24 Feb 2023 10:00:00 EST"), timestamp("17 March 2023 10:00:00 EDT"), timestamp("31 March 2023 10:00:00 EDT"), timestamp("14 April 2023 10:00:00 EDT"), timestamp("28 April 2023 10:00:00 EDT"), timestamp("12 May 2023 10:00:00 EDT"), timestamp("26 May 2023 10:00:00 EDT"), timestamp("16 June 2023 10:00:00 EDT"), timestamp("30 June 2023 10:00:00 EDT"), timestamp("14 July 2023 10:00:00 EDT"), timestamp("28 July 2023 10:00:00 EDT"), timestamp("11 Aug 2023 10:00:00 EDT"), timestamp("25 Aug 2023 10:00:00 EDT"), timestamp("15 Sept 2023 10:00:00 EDT"), timestamp("29 Sept 2023 10:00:00 EDT"), timestamp("13 Oct 2023 10:00:00 EDT"), timestamp("27 Oct 2023 10:00:00 EDT"), timestamp("10 Nov 2023 10:00:00 EST"), timestamp("22 Nov 2023 10:00:00 EST"), timestamp("8 Dec 2023 10:00:00 EST"), timestamp("22 Dec 2023 10:00:00 EST") ) // @function Gets the CCI release dates. The Conference Board's Consumer Confidence Index (CCI) is a survey of consumer attitudes about the economy and their personal finances. The CCI is a leading indicator of consumer spending. // @returns // array<int> : CCI Dates as timestamps export cciReleases() => array.from( timestamp("25 Jan 2022 10:00:00 EST"), // 2022 timestamp("22 Feb 2022 10:00:00 EST"), timestamp("29 March 2022 10:00:00 EDT"), timestamp("26 April 2022 10:00:00 EDT"), timestamp("31 May 2022 10:00:00 EDT"), timestamp("28 June 2022 10:00:00 EDT"), timestamp("26 July 2022 10:00:00 EDT"), timestamp("30 Aug 2022 10:00:00 EDT"), timestamp("27 Sept 2022 10:00:00 EDT"), timestamp("25 Oct 2022 10:00:00 EDT"), timestamp("29 Nov 2022 10:00:00 EST"), timestamp("27 Dec 2022 10:00:00 EST"), timestamp("31 Jan 2023 10:00:00 EST"), // 2023 timestamp("28 Feb 2023 10:00:00 EST"), timestamp("28 March 2023 10:00:00 EDT"), timestamp("25 April 2023 10:00:00 EDT"), timestamp("30 May 2023 10:00:00 EDT"), timestamp("27 June 2023 10:00:00 EDT"), timestamp("25 July 2023 10:00:00 EDT"), timestamp("29 Aug 2023 10:00:00 EDT"), timestamp("26 Sept 2023 10:00:00 EDT"), timestamp("31 Oct 2023 10:00:00 EDT"), timestamp("28 Nov 2023 10:00:00 EST"), timestamp("26 Dec 2023 10:00:00 EST") ) // @function Gets the NFP release dates. Nonfarm payrolls is an employment report released monthly by the Bureau of Labor Statistics (BLS) that measures the change in the number of employed people in the United States. // @returns // array<int> : NFP Dates as timestamps export nfpReleases() => array.from( timestamp("7 Jan 2022 8:30:00 EST"), // 2022 timestamp("4 Feb 2022 8:30:00 EST"), timestamp("4 March 2022 8:30:00 EST"), timestamp("1 April 2022 8:30:00 EDT"), timestamp("6 May 2022 8:30:00 EDT"), timestamp("3 June 2022 8:30:00 EDT"), timestamp("8 July 2022 8:30:00 EDT"), timestamp("5 Aug 2022 8:30:00 EDT"), timestamp("2 Sept 2022 8:30:00 EDT"), timestamp("7 Oct 2022 8:30:00 EDT"), timestamp("4 Nov 2022 8:30:00 EDT"), timestamp("2 Dec 2022 8:30:00 EST"), timestamp("6 Jan 2023 8:30:00 EST"), // 2023 timestamp("3 Feb 2023 8:30:00 EST"), timestamp("3 March 2023 8:30:00 EST"), timestamp("7 April 2023 8:30:00 EDT"), timestamp("5 May 2023 8:30:00 EDT"), timestamp("2 June 2023 8:30:00 EDT"), timestamp("7 July 2023 8:30:00 EDT"), timestamp("4 Aug 2023 8:30:00 EDT"), timestamp("1 Sept 2023 8:30:00 EDT"), timestamp("6 Oct 2023 8:30:00 EDT"), timestamp("3 Nov 2023 8:30:00 EDT"), timestamp("1 Dec 2023 8:30:00 EST") )
Trend Line Xross
https://www.tradingview.com/script/9QnuavYi-Trend-Line-Xross/
SamRecio
https://www.tradingview.com/u/SamRecio/
54
study
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/ // © SamRecio //@version=5 indicator("Trend Line Xross", shorttitle = "TLX", overlay = true) ///_________________________________________ ///Practical Application of y = mx + b - Trendline Intersection Point ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ //Inputs tl1_p1_x = input.time(0,confirm = true, inline = "Trendline 1 - Point 1", title = "Time", group = "Trendline 1") tl1_p1_y = input.price(0,confirm = true, inline = "Trendline 1 - Point 1", title = "Price", group = "Trendline 1") tl1_p2_x = input.time(0,confirm = true, inline = "Trendline 1 - Point 2", title = "Time", group = "Trendline 1") tl1_p2_y = input.price(0,confirm = true, inline = "Trendline 1 - Point 2", title = "Price", group = "Trendline 1") color1 = input.color(color.teal, title = "Trend Line 1 Color", group = "Trendline 1") tl2_p1_x = input.time(0,confirm = true, inline = "Trendline 2 - Point 1", title = "Time", group = "Trendline 2") tl2_p1_y = input.price(0,confirm = true, inline = "Trendline 2 - Point 1", title = "Price", group = "Trendline 2") tl2_p2_x = input.time(0,confirm = true, inline = "Trendline 2 - Point 2", title = "Time", group = "Trendline 2") tl2_p2_y = input.price(0,confirm = true, inline = "Trendline 2 - Point 2", title = "Price", group = "Trendline 2") color2 = input.color(color.aqua, title = "Trend Line 2 Color", group = "Trendline 2") color3 = input.color(color.red, title = "Intersection Point Line", group = "Intersection Point") type point int x float y //Descramble Inputs //Aranging inputs into "Points" in time ascending order, so that the user can input the points for each line in any order. tl1_p1 = tl1_p1_x<tl1_p2_x?point.new(tl1_p1_x,tl1_p1_y):point.new(tl1_p2_x,tl1_p2_y) tl1_p2 = tl1_p1_x<tl1_p2_x?point.new(tl1_p2_x,tl1_p2_y):point.new(tl1_p1_x,tl1_p1_y) tl2_p1 = tl2_p1_x<tl2_p2_x?point.new(tl2_p1_x,tl2_p1_y):point.new(tl2_p2_x,tl2_p2_y) tl2_p2 = tl2_p1_x<tl2_p2_x?point.new(tl2_p2_x,tl2_p2_y):point.new(tl2_p1_x,tl2_p1_y) //Converting Time Values to Bar Index Values //Since interactive mode only allows users to input time, I have to convert the inputs into the useable bar_index values for consistent simple calculations. var int tl1_b1 = na tl1_b1 := time == tl1_p1.x?bar_index:tl1_b1 var int tl1_b2 = na tl1_b2 := time == tl1_p2.x?bar_index:tl1_b2 var int tl2_b1 = na tl2_b1 := time == tl2_p1.x?bar_index:tl2_b1 var int tl2_b2 = na tl2_b2 := time == tl2_p2.x?bar_index:tl2_b2 //Calculating Slopes (Price dif / Bar dif) tl1_slope = (tl1_p2.y - tl1_p1.y)/math.abs(tl1_b1-tl1_b2) tl2_slope = (tl2_p2.y - tl2_p1.y)/math.abs(tl2_b1-tl2_b2) //Determining the bar # difference between the start of both lines //Since both points may not have the same bar_index values, I need to calculate what the (price) value of the longer line is at the place where the shorter line starts. //This is because I need the value of both lines on the same (VERTICAL) axis, so that I can use this as my y-intercept. start_dif = math.max(tl1_b1,tl2_b1) - math.min(tl1_b1,tl2_b1) //Calculating the Starting Point (Price) of each Line accounting for the offset (y - Intercept) tl1_b = tl1_b1<tl2_b1 ? tl1_p1.y + (tl1_slope*start_dif) : tl1_p1.y tl2_b = tl1_b1>tl2_b1 ? tl2_p1.y + (tl2_slope*start_dif) : tl2_p1.y //Slolve for x x = (tl2_b-tl1_b)/(tl1_slope-tl2_slope) // y = mx + b x_point = (tl1_slope * x) + tl1_b //Drawing the Trendlines //Since changing the points re-calculates the script, I only need to draw the lines once. //I am plotting the crossing point so that alerts can be set on it. trend_line_1 = line.new(tl1_b1,tl1_p1.y,tl1_b2,tl1_p2.y, extend = extend.both, color = color1) trend_line_2 = line.new(tl2_b1,tl2_p1.y,tl2_b2,tl2_p2.y, extend = extend.both, color = color2) x_line = line.new(bar_index,x_point,bar_index+1,x_point, extend = extend.both, color = color3) //Not displaying in the pane so that I can impose the Drawn line as the Display, I am using the plot solely for the readouts and alerts. plot(x_point, title = "TrendLine Intersection Price", display = display.all-display.pane, color = color3) //Alerts alertcondition(ta.crossover(close,x_point), "X-Point CrossOver") alertcondition(ta.crossunder(close,x_point), "X-Point CrossUnder") alertcondition(ta.cross(close,x_point), "X-Point Cross") alertcondition(ta.crossover(close,line.get_price(trend_line_1,bar_index)),"Trendline 1 CrossOver") alertcondition(ta.crossunder(close,line.get_price(trend_line_1,bar_index)),"Trendline 1 CrossUnder") alertcondition(ta.cross(close,line.get_price(trend_line_1,bar_index)),"Trendline 1 Cross") alertcondition(ta.crossover(close,line.get_price(trend_line_2,bar_index)),"Trendline 2 CrossOver") alertcondition(ta.crossunder(close,line.get_price(trend_line_2,bar_index)),"Trendline 2 CrossUnder") alertcondition(ta.cross(close,line.get_price(trend_line_2,bar_index)),"Trendline 2 Cross")
SMC Indicator With Webhook
https://www.tradingview.com/script/gqiG3j3a-SMC-Indicator-With-Webhook/
sunwoo101
https://www.tradingview.com/u/sunwoo101/
220
study
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/ // © sunwoo101 //@version=5 indicator("Simple SMC Indicator", overlay = true) // Settings // Price Action onlyDrawInSession = input(false, "Only Draw In Session", group = "Price Action") drawFractals = input(true, "Draw Fractal Highs/Lows", group = "Price Action") fractalPeriod = input.int(title="Fractal Periods", defval=2, minval=1) fractalHighColor = input(color.new(color.white, 50), "Fractal High Color", group = "Price Action") fractalLowColor = input(color.new(color.white, 50), "Fractal Low Color", group = "Price Action") drawLQSweeps = input(true, "Draw Liquidity Sweeps", group = "Price Action") sweepColor = input(color.white, "Sweep Color", group = "Price Action") drawMSS = input(true, "Draw MSS", group = "Price Action") bullishMSSColor = input(color.blue, "Bullish MSS Color", group = "Price Action") bearishMSSColor = input(color.red, "Bearish MSS Color", group = "Price Action") drawFVG = input(true, "Draw FVG", group = "Price Action") bullishFVGColor = input(color.new(color.white, 50), "Bullish FVG Color", group = "Price Action") bearishFVGColor = input(color.new(color.white, 50), "Bearish FVG Color", group = "Price Action") // Alerts alertName = input("1m XAUUSD", "Alert Name") sweepAlerts = input(true, "Sweep Alerts", group = "Alerts") MSSAlerts = input(true, "MSS Alerts", group = "Alerts") FVGAlerts = input(true, "FVG Alerts", group = "Alerts") // Sessions drawSession1 = input(true, "Draw Session 1", group = "Session") session1 = input.session("2100-0100", "Session 1", group = "Session") session1Color = input(color.new(color.purple, 80), "Session 1 Color", group = "Session") drawSession2 = input(true, "Draw Session 2", group = "Session") session2 = input.session("0300-0600", "Session 2", group = "Session") session2Color = input(color.new(color.yellow, 80), "Session 2 Color", group = "Session") drawSession3 = input(true, "Draw Session 3", group = "Session") session3 = input.session("0800-1000", "Session 3", group = "Session") session3Color = input(color.new(color.blue, 80), "Session 3 Color", group = "Session") drawSession4 = input(true, "Draw Session 4", group = "Session") session4 = input.session("1100-1300", "Session 4", group = "Session") session4Color = input(color.new(color.orange, 80), "Session 4 Color", group = "Session") is_session(sess) => not na(time(timeframe.period, sess, "America/New_York")) isSession1 = is_session(session1) isSession2 = is_session(session2) isSession3 = is_session(session3) isSession4 = is_session(session4) backgroundColor = isSession1 ? session1Color : isSession2 ? session2Color : isSession3 ? session3Color : isSession4 ? session4Color : color.new(color.blue, 90) isSession = isSession1 or isSession2 or isSession3 or isSession4 drawSession = isSession1 and drawSession1 or isSession2 and drawSession2 or isSession3 and drawSession3 or isSession4 and drawSession4 bgcolor(isSession and drawSession ? backgroundColor : na) sessionDraw = not onlyDrawInSession or onlyDrawInSession and drawSession // Fractal highs and lows var fractalHighBarIndex = int(na) var fractalLowBarIndex = int(na) n = fractalPeriod // Fractal high bool upflagDownFrontier = true bool upflagUpFrontier0 = true bool upflagUpFrontier1 = true bool upflagUpFrontier2 = true bool upflagUpFrontier3 = true bool upflagUpFrontier4 = true highFound = false lowFound = false if barstate.isconfirmed 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 highFound := (upflagDownFrontier and flagUpFrontier) if highFound fractalHighBarIndex := bar_index[fractalPeriod] // Fractal low 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 lowFound := (downflagDownFrontier and flagDownFrontier) if lowFound fractalLowBarIndex := bar_index[fractalPeriod] // MSS vars var bullishMSSTargetBarIndex = int(na) var bearishMSSTargetBarIndex = int(na) // Sweeps // BSL sweep if fractalHighBarIndex if high > high[bar_index - fractalHighBarIndex] // Draw sweep if drawLQSweeps and sessionDraw line.new(x1 = fractalHighBarIndex, y1 = high[bar_index - fractalHighBarIndex], x2 = bar_index, y2 = high[bar_index - fractalHighBarIndex], color = sweepColor, width = 1) label.new(fractalHighBarIndex, na, "Swept", yloc = yloc.abovebar, style = label.style_none, textcolor = sweepColor, size = size.small) if sweepAlerts and sessionDraw message = '{"content": "@everyone \\n['+alertName+'] Buy side $$$ swept @ '+str.tostring(high[bar_index - fractalHighBarIndex])+'"}' alert(message) // Find MSS target lowestLowOffset = 1 for i = 1 to bar_index - fractalHighBarIndex if low[i] < low[lowestLowOffset] lowestLowOffset := i bearishMSSTargetBarIndex := bar_index[lowestLowOffset] fractalHighBarIndex := int(na) // SSL sweep if fractalLowBarIndex if low < low[bar_index - fractalLowBarIndex] // Draw sweep if drawLQSweeps and sessionDraw line.new(x1 = fractalLowBarIndex, y1 = low[bar_index - fractalLowBarIndex], x2 = bar_index, y2 = low[bar_index - fractalLowBarIndex], color = sweepColor, width = 1) label.new(fractalLowBarIndex, na, "Swept", yloc = yloc.belowbar, style = label.style_none, textcolor = sweepColor, size = size.small) if sweepAlerts and sessionDraw message = '{"content": "@everyone \\n['+alertName+'] Sell side $$$ swept @ '+str.tostring(low[bar_index - fractalLowBarIndex])+'"}' alert(message) // Find MSS target highestHighOffset = 1 for i = 1 to bar_index - fractalLowBarIndex if high[i] > high[highestHighOffset] highestHighOffset := i bullishMSSTargetBarIndex := bar_index[highestHighOffset] fractalLowBarIndex := int(na) // MSS // Bearish MSS if bearishMSSTargetBarIndex if close < low[bar_index - bearishMSSTargetBarIndex] if drawMSS and sessionDraw line.new(x1 = bearishMSSTargetBarIndex, y1 = low[bar_index - bearishMSSTargetBarIndex], x2 = bar_index, y2 = low[bar_index - bearishMSSTargetBarIndex], color = bearishMSSColor, width = 2) label.new(bar_index, na, "MSS", yloc = yloc.abovebar, style = label.style_none, textcolor = bearishMSSColor, size = size.normal) if MSSAlerts and sessionDraw message = '{"content": "@everyone \\n['+alertName+'] Bearish MSS through '+str.tostring(low[bar_index - bearishMSSTargetBarIndex])+'"}' alert(message) bearishMSSTargetBarIndex := int(na) // Bullish MSS if bullishMSSTargetBarIndex if close > high[bar_index - bullishMSSTargetBarIndex] if drawMSS and sessionDraw line.new(x1 = bullishMSSTargetBarIndex, y1 = high[bar_index - bullishMSSTargetBarIndex], x2 = bar_index, y2 = high[bar_index - bullishMSSTargetBarIndex], color = bullishMSSColor, width = 2) label.new(bar_index, na, "MSS", yloc = yloc.belowbar, style = label.style_none, textcolor = bullishMSSColor, size = size.normal) if MSSAlerts and sessionDraw message = '{"content": "@everyone \\n['+alertName+'] Bullish MSS through '+str.tostring(high[bar_index - bullishMSSTargetBarIndex])+'"}' alert(message) bullishMSSTargetBarIndex := int(na) // FVG // Bullish FVG if low > high[2] and close[1] > open[1] and sessionDraw if drawFVG and sessionDraw box.new(left=bar_index[2], top=low, right=bar_index, bottom=high[2], bgcolor=bullishFVGColor, border_color = bullishFVGColor) if FVGAlerts and sessionDraw message = '{"content": "@everyone \\n['+alertName+'] Bullish FVG ('+str.tostring(high[2])+' - '+str.tostring(low)+')"}' alert(message) // Bearish FVG if high < low[2] and close[1] < open[1] and sessionDraw if drawFVG and sessionDraw box.new(left=bar_index[2], top=high, right=bar_index, bottom=low[2], bgcolor=bearishFVGColor, border_color = bearishFVGColor) if FVGAlerts and sessionDraw message = '{"content": "@everyone \\n['+alertName+'] Bearish FVG ('+str.tostring(low[2])+' - '+str.tostring(high)+')"}' alert(message) plotshape(drawFractals and highFound and sessionDraw, style=shape.triangledown, location=location.abovebar, offset=-fractalPeriod, color=fractalHighColor, size = size.tiny) plotshape(drawFractals and lowFound and sessionDraw, style=shape.triangleup, location=location.belowbar, offset=-fractalPeriod, color=fractalLowColor, size = size.tiny)
Spongebob [TFO]
https://www.tradingview.com/script/jF4qg2gK-Spongebob-TFO/
tradeforopp
https://www.tradingview.com/u/tradeforopp/
123
study
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/ // © tradeforopp //@version=5 indicator("Spongebob [TFO]", "Spongebob [TFO]", true) body_color = #eee866 outline_color = #c0bd16 black = #000000 white = color.white red = #d44b2e iris = #37a7dc pants_upper = #b97c33 pants_lower = #855c27 atr = ta.atr(50) * 2.0 // ------------------------------ BODY ------------------------------ left_offset = bar_index + 10 L_x = 2 L_y = atr / 3 B_x = 5 B_y = L_y / 5 L1x = left_offset - 5 L1y = open - (0.5 * L_y) L2x = left_offset + L_x - 4 L2y = L1y - (1 * L_y) L3x = left_offset - 3 L3y = L1y - (2 * L_y) L4x = left_offset + L_x - 3 L4y = L1y - (3 * L_y) L5x = left_offset - 3 L5y = L1y - (4 * L_y) L6x = left_offset + L_x - 2 L6y = L1y - (5 * L_y) L7x = left_offset - 2 L7y = L1y - (6 * L_y) L8x = left_offset + L_x - 1 L8y = L1y - (7 * L_y) L9x = left_offset L9y = L1y - (8 * L_y) L10x = left_offset + L_x L10y = L1y - (9 * L_y) Lx = array.from(L1x, L2x, L3x, L4x, L5x, L6x, L7x, L8x, L9x, L10x) Ly = array.from(L1y, L2y, L3y, L4y, L5y, L6y, L7y, L8y, L9y, L10y) BLx = L10x BLy = L10y B1x = BLx + (1 * B_x) B1y = BLy + B_y B2x = BLx + (2 * B_x) B2y = BLy - B_y B3x = BLx + (3 * B_x) B3y = BLy + B_y B4x = BLx + (4 * B_x) B4y = BLy - B_y B5x = BLx + (5 * B_x) B5y = BLy + B_y B6x = BLx + (6 * B_x) B6y = BLy - B_y B7x = BLx + (7 * B_x) B7y = BLy + B_y B8x = BLx + (8 * B_x) B8y = BLy - B_y B9x = BLx + (9 * B_x) B9y = BLy + B_y B10x = BLx + (10 * B_x) B10y = BLy Bx = array.from(B1x, B2x, B3x, B4x, B5x, B6x, B7x, B8x, B9x, B10x) By = array.from(B1y, B2y, B3y, B4y, B5y, B6y, B7y, B8y, B9y, B10y) RBx = B10x + (1 * L_x) RBy = B10y R1x = RBx R1y = RBy + (1 * L_y) R2x = RBx - L_x + 1 R2y = RBy + (2 * L_y) R3x = RBx + 2 R3y = RBy + (3 * L_y) R4x = RBx - L_x + 2 R4y = RBy + (4 * L_y) R5x = RBx + 3 R5y = RBy + (5 * L_y) R6x = RBx - L_x + 3 R6y = RBy + (6 * L_y) R7x = RBx + 3 R7y = RBy + (7 * L_y) R8x = RBx - L_x + 4 R8y = RBy + (8 * L_y) R9x = RBx + 5 R9y = RBy + (9 * L_y) Rx = array.from(R1x, R2x, R3x, R4x, R5x, R6x, R7x, R8x, R9x) Ry = array.from(R1y, R2y, R3y, R4y, R5y, R6y, R7y, R8y, R9y) RTx = R9x - (1 * L_x) RTy = R9y + (0.5 * L_y) T1x = RTx T1y = RTy + B_y * 0.5 T2x = RTx - (1 * B_x) T2y = RTy - (0.5 * B_y) T3x = RTx - (2 * B_x) T3y = RTy + B_y * 1.2 T4x = RTx - (3 * B_x) T4y = RTy - (0.5 * B_y) T5x = RTx - (4 * B_x) T5y = RTy + B_y * 1.35 T6x = RTx - (5 * B_x) T6y = RTy - (0.5 * B_y) T7x = RTx - (6 * B_x) T7y = RTy + B_y * 1.5 T8x = RTx - (7 * B_x) T8y = RTy - (0.5 * B_y) T9x = RTx - (8 * B_x) T9y = RTy + B_y * 1.35 T10x = RTx - (9 * B_x) T10y = RTy - (0.5 * B_y) T11x = RTx - (10 * B_x) T11y = RTy + B_y * 1.2 T12x = RTx - (11 * B_x) T12y = RTy - (0.5 * B_y) T13x = RTx - (12 * B_x) T13y = RTy + B_y * 0.5 Tx = array.from(T1x, T2x, T3x, T4x, T5x, T6x, T7x, T8x, T9x, T10x, T11x, T12x, T13x) Ty = array.from(T1y, T2y, T3y, T4y, T5y, T6y, T7y, T8y, T9y, T10y, T11y, T12y, T13y) // ------------------------------ BODY ------------------------------ // ------------------------------ LEFT EYE - OUTLINE ------------------------------ Lcenter_x = math.floor((RTx - L1x) / 2.7 + L1x) Lcenter_y = RTy - (RTy - RBy) / 3 E_x = 10 E_y = atr / 1.8 LE1x = Lcenter_x - E_x LE1y = Lcenter_y LE2x = Lcenter_x LE2y = Lcenter_y + E_y LE3x = Lcenter_x + E_x LE3y = Lcenter_y LE4x = Lcenter_x LE4y = Lcenter_y - E_y LEx = array.from(LE1x, LE2x, LE3x, LE4x) LEy = array.from(LE1y, LE2y, LE3y, LE4y) // ------------------------------ LEFT EYE - OUTLINE ------------------------------ // ------------------------------ RIGHT EYE - OUTLINE ------------------------------ Rcenter_x = math.floor(RTx - (RTx - L1x) / 2.9) + 1 Rcenter_y = RTy - (RTy - RBy) / 3 RE1x = Rcenter_x - E_x RE1y = Rcenter_y RE2x = Rcenter_x RE2y = Rcenter_y + E_y RE3x = Rcenter_x + E_x RE3y = Rcenter_y RE4x = Rcenter_x RE4y = Rcenter_y - E_y REx = array.from(RE1x, RE2x, RE3x, RE4x) REy = array.from(RE1y, RE2y, RE3y, RE4y) // ------------------------------ RIGHT EYE - OUTLINE ------------------------------ // ------------------------------ LEFT EYE - IRIS ------------------------------ LIcenter_x = math.floor((RTx - L1x) / 2.5 + L1x) LIcenter_y = RTy - (RTy - RBy) / 3 I_x = 5 I_y = atr / 3.8 LEI1x = LIcenter_x - I_x LEI1y = LIcenter_y LEI2x = LIcenter_x LEI2y = LIcenter_y + I_y LEI3x = LIcenter_x + I_x LEI3y = LIcenter_y LEI4x = LIcenter_x LEI4y = LIcenter_y - I_y LEIx = array.from(LEI1x, LEI2x, LEI3x, LEI4x) LEIy = array.from(LEI1y, LEI2y, LEI3y, LEI4y) // ------------------------------ LEFT EYE - IRIS ------------------------------ // ------------------------------ RIGHT EYE - IRIS ------------------------------ RIcenter_x = math.floor(RTx - (RTx - L1x) / 2.8) RIcenter_y = RTy - (RTy - RBy) / 3 REI1x = RIcenter_x - I_x REI1y = RIcenter_y REI2x = RIcenter_x REI2y = RIcenter_y + I_y REI3x = RIcenter_x + I_x REI3y = RIcenter_y REI4x = RIcenter_x REI4y = RIcenter_y - I_y REIx = array.from(REI1x, REI2x, REI3x, REI4x) REIy = array.from(REI1y, REI2y, REI3y, REI4y) // ------------------------------ RIGHT EYE - IRIS ------------------------------ // ------------------------------ LEFT EYE - PUPIL ------------------------------ P_x = 2 P_y = atr / 9.5 LEP1x = LIcenter_x - P_x LEP1y = LIcenter_y LEP2x = LIcenter_x LEP2y = LIcenter_y + P_y LEP3x = LIcenter_x + P_x LEP3y = LIcenter_y LEP4x = LIcenter_x LEP4y = LIcenter_y - P_y LEPx = array.from(LEP1x, LEP2x, LEP3x, LEP4x) LEPy = array.from(LEP1y, LEP2y, LEP3y, LEP4y) // ------------------------------ LEFT EYE - PUPIL ------------------------------ // ------------------------------ RIGHT EYE - PUPIL ------------------------------ REP1x = RIcenter_x - P_x REP1y = RIcenter_y REP2x = RIcenter_x REP2y = RIcenter_y + P_y REP3x = RIcenter_x + P_x REP3y = RIcenter_y REP4x = RIcenter_x REP4y = RIcenter_y - P_y REPx = array.from(REP1x, REP2x, REP3x, REP4x) REPy = array.from(REP1y, REP2y, REP3y, REP4y) // ------------------------------ RIGHT EYE - PUPIL ------------------------------ // ------------------------------ LEFT EYELASHES ------------------------------ LEL1x = LIcenter_x - 9 LEL1y = LIcenter_y + I_y * 2.8 LEL2x = LIcenter_x - 2 LEL2y = LIcenter_y LEL3x = LIcenter_x - 2 LEL3y = LIcenter_y + I_y * 3.1 LEL4x = LIcenter_x - 2 LEL4y = LIcenter_y LEL5x = LIcenter_x + 4 LEL5y = LIcenter_y + I_y * 2.8 LELx = array.from(LEL1x, LEL2x, LEL3x, LEL4x, LEL5x) LELy = array.from(LEL1y, LEL2y, LEL3y, LEL4y, LEL5y) // ------------------------------ LEFT EYELASHES ------------------------------ // ------------------------------ RIGHT EYELASHES ------------------------------ REL1x = RIcenter_x - 4 REL1y = RIcenter_y + I_y * 2.8 REL2x = RIcenter_x + 2 REL2y = RIcenter_y REL3x = RIcenter_x + 2 REL3y = RIcenter_y + I_y * 3.1 REL4x = RIcenter_x + 2 REL4y = RIcenter_y REL5x = RIcenter_x + 9 REL5y = RIcenter_y + I_y * 2.7 RELx = array.from(REL1x, REL2x, REL3x, REL4x, REL5x) RELy = array.from(REL1y, REL2y, REL3y, REL4y, REL5y) // ------------------------------ RIGHT EYELASHES ------------------------------ // ------------------------------ NOSE ------------------------------ Ncenter_x = math.floor((RTx - L1x) / 2 + L1x) Ncenter_y = RTy - (RTy - RBy) / 2 N_x = 4 N_y = atr / 4.2 N1x = Ncenter_x - N_x N1y = Ncenter_y N2x = Ncenter_x N2y = Ncenter_y + N_y N3x = Ncenter_x + N_x N3y = Ncenter_y N4x = Ncenter_x N4y = Ncenter_y - N_y Nx = array.from(N1x, N2x, N3x, N4x) Ny = array.from(N1y, N2y, N3y, N4y) // ------------------------------ NOSE ------------------------------ // ------------------------------ LEFT CHEEK ------------------------------ LCcenter_x = math.floor((RTx - L1x) / 5 + L1x) LCcenter_y = RTy - (RTy - RBy) / 1.9 LC_x = 4 LC_y = N_y LC1x = LCcenter_x - LC_x LC1y = LCcenter_y - (LC_y / 2) LC2x = LCcenter_x - LC_x LC2y = LCcenter_y + (LC_y) LC3x = LCcenter_x + LC_x LC3y = LCcenter_y + (LC_y) LC4x = LCcenter_x + LC_x LC4y = LCcenter_y - (LC_y / 2) LCx = array.from(LC1x, LC2x, LC3x, LC4x) LCy = array.from(LC1y, LC2y, LC3y, LC4y) // ------------------------------ LEFT CHEEK ------------------------------ // ------------------------------ RIGHT CHEEK ------------------------------ RCcenter_x = math.floor(RTx - (RTx - L1x) / 5) + 1 RCcenter_y = RTy - (RTy - RBy) / 1.9 RC1x = RCcenter_x - LC_x RC1y = RCcenter_y - (LC_y / 2) RC2x = RCcenter_x - LC_x RC2y = RCcenter_y + (LC_y) RC3x = RCcenter_x + LC_x RC3y = RCcenter_y + (LC_y) RC4x = RCcenter_x + LC_x RC4y = RCcenter_y - (LC_y / 2) RCx = array.from(RC1x, RC2x, RC3x, RC4x) RCy = array.from(RC1y, RC2y, RC3y, RC4y) // ------------------------------ RIGHT CHEEK ------------------------------ // ------------------------------ SMILE ------------------------------ S_x = math.floor((RTx - L1x) / 5 + L1x) S_y = (LCcenter_y - RBy) / 1.6 + RBy S1x = LCcenter_x S1y = LCcenter_y S2x = LCcenter_x + (RCcenter_x - LCcenter_x) / 2 S2y = S_y S3x = RCcenter_x S3y = RCcenter_y Sx = array.from(S1x, S2x, S3x) Sy = array.from(S1y, S2y, S3y) // ------------------------------ SMILE ------------------------------ // ------------------------------ LEFT DIMPLE ------------------------------ LD1x = LCcenter_x - (LC_x / 2) LD1y = LCcenter_y - (LC_y / 3) LD2x = LCcenter_x LD2y = LCcenter_y LD3x = LCcenter_x + (LC_x / 2) LD3y = LCcenter_y LDx = array.from(LD1x, LD2x, LD3x) LDy = array.from(LD1y, LD2y, LD3y) // ------------------------------ LEFT DIMPLE ------------------------------ // ------------------------------ RIGHT DIMPLE ------------------------------ RD1x = RCcenter_x - (LC_x / 2) RD1y = RCcenter_y RD2x = RCcenter_x RD2y = RCcenter_y RD3x = RCcenter_x + (LC_x / 2) RD3y = RCcenter_y - (LC_y / 3) RDx = array.from(RD1x, RD2x, RD3x) RDy = array.from(RD1y, RD2y, RD3y) // ------------------------------ RIGHT DIMPLE ------------------------------ // ------------------------------ LEFT TOOTH ------------------------------ LT1x = S2x LT1y = S2y + LC_y / 2 LT2x = S2x - 6 LT2y = S2y + LC_y / 2 LT3x = S2x - 6 LT3y = S2y - LC_y * 1.4 LT4x = S2x LT4y = S2y - LC_y * 1.4 LT5x = S2x LT5y = S2y + LC_y / 2 LTx = array.from(LT1x, LT2x, LT3x, LT4x, LT5x) LTy = array.from(LT1y, LT2y, LT3y, LT4y, LT5y) // ------------------------------ LEFT TOOTH ------------------------------ // ------------------------------ RIGHT TOOTH ------------------------------ RT1x = S2x + 2 RT1y = S2y + LC_y / 2 RT2x = S2x + 8 RT2y = S2y + LC_y / 2 RT3x = S2x + 8 RT3y = S2y - LC_y * 1.4 RT4x = S2x + 2 RT4y = S2y - LC_y * 1.4 RT5x = S2x + 2 RT5y = S2y + LC_y / 2 Rtoothx = array.from(RT1x, RT2x, RT3x, RT4x, RT5x) Rtoothy = array.from(RT1y, RT2y, RT3y, RT4y, RT5y) // ------------------------------ RIGHT TOOTH ------------------------------ // ------------------------------ CHIN ------------------------------ C1x = LT3x - 4 C1y = LT3y C2x = LT3x C2y = LT3y - LC_y / 1.3 C3x = S2x + 1 C3y = LT3y - LC_y / 3 C4x = RT3x C4y = RT3y - LC_y / 1.3 C5x = RT3x + 4 C5y = RT3y Cx = array.from(C1x, C2x, C3x, C4x, C5x) Cy = array.from(C1y, C2y, C3y, C4y, C5y) // ------------------------------ CHIN ------------------------------ // ------------------------------ SHIRT ------------------------------ SH1x = BLx SH1y = BLy + LC_y SH2x = BLx SH2y = BLy - LC_y * 1.3 SH3x = RBx - 2 SH3y = RBy - LC_y * 1.3 SH4x = RBx - 2 SH4y = RBy + LC_y SHx = array.from(SH1x, SH2x, SH3x, SH4x) SHy = array.from(SH1y, SH2y, SH3y, SH4y) // ------------------------------ SHIRT ------------------------------ // ------------------------------ COLLAR ------------------------------ CL1x = LIcenter_x - 4 CL1y = BLy + LC_y / 2 CL2x = LIcenter_x + 1 CL2y = BLy - LC_y CL3x = S2x + 1 CL3y = BLy + LC_y / 2 CL4x = RIcenter_x CL4y = RBy - LC_y CL5x = RIcenter_x + 5 CL5y = BLy + LC_y / 2 CLy = array.from(CL1y, CL2y, CL3y, CL4y, CL5y) CLx = array.from(CL1x, CL2x, CL3x, CL4x, CL5x) // ------------------------------ COLLAR ------------------------------ // ------------------------------ TIE ------------------------------ TI1x = S2x - 2 TI1y = BLy + LC_y / 2 TI2x = S2x TI2y = BLy - LC_y / 2 TI3x = S2x - 3 TI3y = BLy - LC_y * 1.8 TI4x = S2x + 1 TI4y = BLy - LC_y * 2.8 TI5x = S2x + 5 TI5y = BLy - LC_y * 1.8 TI6x = S2x + 2 TI6y = BLy - LC_y / 2 TI7x = S2x TI7y = BLy - LC_y / 2 TI8x = S2x + 2 TI8y = BLy - LC_y / 2 TI9x = S2x + 4 TI9y = BLy + LC_y / 2 TIy = array.from(TI1y, TI2y, TI3y, TI4y, TI5y, TI6y, TI7y, TI8y, TI9y) TIx = array.from(TI1x, TI2x, TI3x, TI4x, TI5x, TI6x, TI7x, TI8x, TI9x) // ------------------------------ TIE ------------------------------ // ------------------------------ PANTS ------------------------------ P1x = BLx P1y = BLy - LC_y * 1.3 P2x = BLx P2y = BLy - LC_y * 3.3 P3x = RBx - 2 P3y = RBy - LC_y * 3.3 P4x = RBx - 2 P4y = RBy + LC_y * 1.3 Px = array.from(P1x, P2x, P3x, P4x) Py = array.from(P1y, P2y, P3y, P4y) // ------------------------------ PANTS ------------------------------ // ------------------------------ LEFT PANT LEG ------------------------------ LP1x = P2x + 8 LP1y = P2y + LC_y / 2 LP2x = P2x + 8 LP2y = P2y - LC_y * 1.3 LP3x = P2x + 18 LP3y = P2y - LC_y * 1.3 LP4x = P2x + 18 LP4y = P2y + LC_y / 2 LPx = array.from(LP1x, LP2x, LP3x, LP4x) LPy = array.from(LP1y, LP2y, LP3y, LP4y) // ------------------------------ LEFT PANT LEG ------------------------------ // ------------------------------ RIGHT PANT LEG ------------------------------ RP1x = P3x - 8 RP1y = P3y + LC_y / 2 RP2x = P3x - 8 RP2y = P3y - LC_y * 1.3 RP3x = P3x - 18 RP3y = P3y - LC_y * 1.3 RP4x = P3x - 18 RP4y = P3y + LC_y / 2 RPx = array.from(RP1x, RP2x, RP3x, RP4x) RPy = array.from(RP1y, RP2y, RP3y, RP4y) // ------------------------------ RIGHT PANT LEG ------------------------------ // ------------------------------ LEFT LEG ------------------------------ LL1x = P2x + 12 LL1y = LP2y LL2x = P2x + 12 LL2y = LP2y - LC_y * 2.0 LL3x = P2x + 15 LL3y = LP2y - LC_y * 2.0 LL4x = P2x + 15 LL4y = LP2y LLx = array.from(LL1x, LL2x, LL3x, LL4x) LLy = array.from(LL1y, LL2y, LL3y, LL4y) // ------------------------------ LEFT LEG ------------------------------ // ------------------------------ RIGHT LEG ------------------------------ RL1x = P3x - 12 RL1y = LP2y RL2x = P3x - 12 RL2y = LP2y - LC_y * 2.0 RL3x = P3x - 15 RL3y = LP2y - LC_y * 2.0 RL4x = P3x - 15 RL4y = LP2y RLx = array.from(RL1x, RL2x, RL3x, RL4x) RLy = array.from(RL1y, RL2y, RL3y, RL4y) // ------------------------------ RIGHT LEG ------------------------------ // ------------------------------ LEFT SOCK ------------------------------ LS1x = P2x + 12 LS1y = LL2y LS2x = P2x + 12 LS2y = LL2y - LC_y * 2.1 LS3x = P2x + 15 LS3y = LL2y - LC_y * 2.1 LS4x = P2x + 15 LS4y = LL2y LSx = array.from(LS1x, LS2x, LS3x, LS4x) LSy = array.from(LS1y, LS2y, LS3y, LS4y) // ------------------------------ LEFT SOCK ------------------------------ // ------------------------------ RIGHT SOCK ------------------------------ RS1x = P3x - 12 RS1y = LL2y RS2x = P3x - 12 RS2y = LL2y - LC_y * 2.1 RS3x = P3x - 15 RS3y = LL2y - LC_y * 2.1 RS4x = P3x - 15 RS4y = LL2y RSx = array.from(RS1x, RS2x, RS3x, RS4x) RSy = array.from(RS1y, RS2y, RS3y, RS4y) // ------------------------------ RIGHT SOCK ------------------------------ // ------------------------------ LEFT SHOE BULB ------------------------------ LSO1x = LS1x - 5 LSO1y = LS2y - LC_y * 0 LSO2x = LS1x - 10 LSO2y = LS2y - LC_y * 1 LSO3x = LS1x - 5 LSO3y = LS2y - LC_y * 2.1 LSO4x = LS1x LSO4y = LS2y - LC_y * 1.1 LSOx = array.from(LSO1x, LSO2x, LSO3x, LSO4x) LSOy = array.from(LSO1y, LSO2y, LSO3y, LSO4y) // ------------------------------ LEFT SHOE BULB ------------------------------ // ------------------------------ RIGHT SHOE BULB ------------------------------ RSO1x = RS1x + 5 RSO1y = RS2y - LC_y * 0 RSO2x = RS1x + 10 RSO2y = RS2y - LC_y * 1 RSO3x = RS1x + 5 RSO3y = RS2y - LC_y * 2.1 RSO4x = RS1x RSO4y = RS2y - LC_y * 1 RSOx = array.from(RSO1x, RSO2x, RSO3x, RSO4x) RSOy = array.from(RSO1y, RSO2y, RSO3y, RSO4y) // ------------------------------ RIGHT SHOE BULB ------------------------------ // ------------------------------ LEFT SHOE BACK ------------------------------ LSB1x = LS1x LSB1y = LS2y - LC_y * 0 LSB2x = LS1x + 3 LSB2y = LS2y - LC_y * 0 LSB3x = LS1x + 3 LSB3y = LS2y - LC_y * 2 LSB4x = LS1x LSB4y = LS2y - LC_y * 2 LSB5x = LS1x LSB5y = LS2y - LC_y * 1 LSB6x = LS1x - 3 LSB6y = LS2y - LC_y * 0.5 LSBx = array.from(LSB1x, LSB2x, LSB3x, LSB4x, LSB5x, LSB6x) LSBy = array.from(LSB1y, LSB2y, LSB3y, LSB4y, LSB5y, LSB6y) // ------------------------------ LEFT SHOE BACK ------------------------------ // ------------------------------ RIGHT SHOE BACK ------------------------------ RSB1x = RS1x RSB1y = LS2y - LC_y * 0 RSB2x = RS1x - 3 RSB2y = LS2y - LC_y * 0 RSB3x = RS1x - 3 RSB3y = LS2y - LC_y * 2 RSB4x = RS1x RSB4y = LS2y - LC_y * 2 RSB5x = RS1x RSB5y = LS2y - LC_y * 1 RSB6x = RS1x + 3 RSB6y = LS2y - LC_y * 0.5 RSBx = array.from(RSB1x, RSB2x, RSB3x, RSB4x, RSB5x, RSB6x) RSBy = array.from(RSB1y, RSB2y, RSB3y, RSB4y, RSB5y, RSB6y) // ------------------------------ RIGHT SHOE BACK ------------------------------ // ------------------------------ LEFT SHOULDER ------------------------------ LSH1x = L7x + 2 LSH1y = S2y LSH2x = L7x - 2 LSH2y = S2y - LC_y * 0.3 LSH3x = L7x - 4 LSH3y = S2y - LC_y * 1.8 LSH4x = L7x - 2 LSH4y = S2y - LC_y * 2.2 LSH5x = L7x + 4 LSH5y = S2y - LC_y * 1.8 LSHx = array.from(LSH1x, LSH2x, LSH3x, LSH4x, LSH5x) LSHy = array.from(LSH1y, LSH2y, LSH3y, LSH4y, LSH5y) // ------------------------------ LEFT SHOULDER ------------------------------ // ------------------------------ RIGHT SHOULDER ------------------------------ RSH1x = R3x - 2 RSH1y = S2y RSH2x = R3x + 2 RSH2y = S2y - LC_y * 0.3 RSH3x = R3x + 4 RSH3y = S2y - LC_y * 1.8 RSH4x = R3x + 2 RSH4y = S2y - LC_y * 2.2 RSH5x = R3x - 4 RSH5y = S2y - LC_y * 1.8 RSHx = array.from(RSH1x, RSH2x, RSH3x, RSH4x, RSH5x) RSHy = array.from(RSH1y, RSH2y, RSH3y, RSH4y, RSH5y) // ------------------------------ RIGHT SHOULDER ------------------------------ // ------------------------------ LEFT ARM ------------------------------ LA1x = L7x - 2 LA1y = S2y - LC_y LA2x = L7x - 5 LA2y = S2y - LC_y * 7 LA3x = L7x - 2 LA3y = S2y - LC_y * 7 LA4x = L7x + 1 LA4y = S2y - LC_y LAx = array.from(LA1x, LA2x, LA3x, LA4x) LAy = array.from(LA1y, LA2y, LA3y, LA4y) // ------------------------------ LEFT ARM ------------------------------ // ------------------------------ RIGHT ARM ------------------------------ RA1x = R3x + 2 RA1y = S2y - LC_y RA2x = R3x + 5 RA2y = S2y - LC_y * 7 RA3x = R3x + 2 RA3y = S2y - LC_y * 7 RA4x = R3x - 1 RA4y = S2y - LC_y RAx = array.from(RA1x, RA2x, RA3x, RA4x) RAy = array.from(RA1y, RA2y, RA3y, RA4y) // ------------------------------ RIGHT ARM ------------------------------ // ------------------------------ LEFT HAND ------------------------------ //palm LH1x = P2x - 7 LH1y = P2y + LC_y * 0.3 LH2x = P2x - 10 LH2y = P2y + LC_y * 0.2 //finger 1 LH3x = P2x - 12 LH3y = P2y - LC_y * 0.8 LH4x = P2x - 15 LH4y = P2y - LC_y * 1.1 LH5x = P2x - 14 LH5y = P2y - LC_y * 1.5 LH6x = P2x - 12 LH6y = P2y - LC_y * 1.3 //finger 2 LH7x = P2x - 12 LH7y = P2y - LC_y * 1.5 LH8x = P2x - 14 LH8y = P2y - LC_y * 1.8 LH9x = P2x - 12 LH9y = P2y - LC_y * 2.1 LH10x = P2x - 10 LH10y = P2y - LC_y * 1.5 //finger 3 LH11x = P2x - 10 LH11y = P2y - LC_y * 2.4 LH12x = P2x - 8 LH12y = P2y - LC_y * 2.4 LH13x = P2x - 7 LH13y = P2y - LC_y * 1.4 //finger 4 LH14x = P2x - 4 LH14y = P2y - LC_y * 1.9 LH15x = P2x - 3 LH15y = P2y - LC_y * 1.5 //palm again LH16x = P2x - 5 LH16y = P2y - LC_y * 1.0 LH17x = P2x - 5 LH17y = P2y - LC_y * 0 LHx = array.from(LH1x, LH2x, LH3x, LH4x, LH5x, LH6x, LH7x, LH8x, LH9x, LH10x, LH11x, LH12x, LH13x, LH14x, LH15x, LH16x, LH17x) LHy = array.from(LH1y, LH2y, LH3y, LH4y, LH5y, LH6y, LH7y, LH8y, LH9y, LH10y, LH11y, LH12y, LH13y, LH14y, LH15y, LH16y, LH17y) // ------------------------------ LEFT HAND ------------------------------ // ------------------------------ RIGHT HAND ------------------------------ //palm RH1x = P3x + 7 RH1y = P2y + LC_y * 0.3 RH2x = P3x + 10 RH2y = P2y + LC_y * 0.2 //finger 1 RH3x = P3x + 12 RH3y = P2y - LC_y * 0.8 RH4x = P3x + 15 RH4y = P2y - LC_y * 1.1 RH5x = P3x + 14 RH5y = P2y - LC_y * 1.5 RH6x = P3x + 12 RH6y = P2y - LC_y * 1.3 //finger 2 RH7x = P3x + 12 RH7y = P2y - LC_y * 1.5 RH8x = P3x + 14 RH8y = P2y - LC_y * 1.8 RH9x = P3x + 12 RH9y = P2y - LC_y * 2.1 RH10x = P3x + 10 RH10y = P2y - LC_y * 1.5 //finger 3 RH11x = P3x + 10 RH11y = P2y - LC_y * 2.4 RH12x = P3x + 8 RH12y = P2y - LC_y * 2.4 RH13x = P3x + 7 RH13y = P2y - LC_y * 1.4 //finger 4 RH14x = P3x + 4 RH14y = P2y - LC_y * 1.9 RH15x = P3x + 3 RH15y = P2y - LC_y * 1.5 //palm again RH16x = P3x + 5 RH16y = P2y - LC_y * 1.0 RH17x = P3x + 5 RH17y = P2y - LC_y * 0 RHx = array.from(RH1x, RH2x, RH3x, RH4x, RH5x, RH6x, RH7x, RH8x, RH9x, RH10x, RH11x, RH12x, RH13x, RH14x, RH15x, RH16x, RH17x) RHy = array.from(RH1y, RH2y, RH3y, RH4y, RH5y, RH6y, RH7y, RH8y, RH9y, RH10y, RH11y, RH12y, RH13y, RH14y, RH15y, RH16y, RH17y) // ------------------------------ RIGHT HAND ------------------------------ // ------------------------------ SPOT 1 ------------------------------ SP11x = BLx + 3 SP11y = BLy + (RTy - BLy) / 5 SP12x = BLx + 5 SP12y = BLy + (RTy - BLy) / 5 SP13x = BLx + 3 SP13y = BLy + (RTy - BLy) / 6.5 SP1x = array.from(SP11x, SP12x, SP13x) SP1y = array.from(SP11y, SP12y, SP13y) // ------------------------------ SPOT 1 ------------------------------ // ------------------------------ SPOT 2 ------------------------------ SP21x = BLx + 4 SP21y = BLy + (RTy - BLy) / 15 SP22x = BLx + 6 SP22y = BLy + (RTy - BLy) / 8 SP23x = BLx + 8 SP23y = BLy + (RTy - BLy) / 15 SP2x = array.from(SP21x, SP22x, SP23x) SP2y = array.from(SP21y, SP22y, SP23y) // ------------------------------ SPOT 2 ------------------------------ // ------------------------------ SPOT 3 ------------------------------ SP31x = RBx - 12 SP31y = BLy + (RTy - BLy) / 8 SP32x = RBx - 11 SP32y = BLy + (RTy - BLy) / 10 SP33x = RBx - 10 SP33y = BLy + (RTy - BLy) / 8 SP3x = array.from(SP31x, SP32x, SP33x) SP3y = array.from(SP31y, SP32y, SP33y) // ------------------------------ SPOT 3 ------------------------------ // ------------------------------ SPOT 4 ------------------------------ SP41x = RBx - 9 SP41y = BLy + (RTy - BLy) / 5.7 SP42x = RBx - 6 SP42y = BLy + (RTy - BLy) / 3.7 SP43x = RBx - 5 SP43y = BLy + (RTy - BLy) / 5.5 SP4x = array.from(SP41x, SP42x, SP43x) SP4y = array.from(SP41y, SP42y, SP43y) // ------------------------------ SPOT 4 ------------------------------ // ------------------------------ SPOT 5 ------------------------------ SP51x = BLx - 2 SP51y = BLy + (RTy - BLy) / 1.35 SP52x = BLx - 1 SP52y = BLy + (RTy - BLy) / 1.42 SP53x = BLx SP53y = BLy + (RTy - BLy) / 1.35 SP5x = array.from(SP51x, SP52x, SP53x) SP5y = array.from(SP51y, SP52y, SP53y) // ------------------------------ SPOT 5 ------------------------------ // ------------------------------ SPOT 6 ------------------------------ SP61x = BLx SP61y = BLy + (RTy - BLy) / 1.15 SP62x = BLx + 2 SP62y = BLy + (RTy - BLy) / 1.25 SP63x = BLx + 4 SP63y = BLy + (RTy - BLy) / 1.15 SP6x = array.from(SP61x, SP62x, SP63x) SP6y = array.from(SP61y, SP62y, SP63y) // ------------------------------ SPOT 6 ------------------------------ // ------------------------------ SPOT 7 ------------------------------ SP71x = RTx - 8 SP71y = BLy + (RTy - BLy) / 1.25 SP72x = RTx - 6 SP72y = BLy + (RTy - BLy) / 1.15 SP73x = RTx - 4 SP73y = BLy + (RTy - BLy) / 1.25 SP7x = array.from(SP71x, SP72x, SP73x) SP7y = array.from(SP71y, SP72y, SP73y) // ------------------------------ SPOT 7 ------------------------------ // ------------------------------ BELT 1 ------------------------------ B11x = P2x + 4 B11y = P3y + (P1y - P2y) / 1.8 B12x = P2x + 11 B12y = P3y + (P1y - P2y) / 1.8 B13x = P2x + 11 B13y = P3y + (P1y - P2y) / 1.4 B14x = P2x + 4 B14y = P3y + (P1y - P2y) / 1.4 BL1x = array.from(B11x, B12x, B13x, B14x) BL1y = array.from(B11y, B12y, B13y, B14y) // ------------------------------ BELT 1 ------------------------------ // ------------------------------ BELT 2 ------------------------------ B21x = P2x + 17 B21y = P3y + (P1y - P2y) / 1.8 B22x = P2x + 23 B22y = P3y + (P1y - P2y) / 1.8 B23x = P2x + 23 B23y = P3y + (P1y - P2y) / 1.4 B24x = P2x + 17 B24y = P3y + (P1y - P2y) / 1.4 BL2x = array.from(B21x, B22x, B23x, B24x) BL2y = array.from(B21y, B22y, B23y, B24y) // ------------------------------ BELT 2 ------------------------------ // ------------------------------ BELT 3 ------------------------------ B31x = P2x + 27 B31y = P3y + (P1y - P2y) / 1.8 B32x = P2x + 33 B32y = P3y + (P1y - P2y) / 1.8 B33x = P2x + 33 B33y = P3y + (P1y - P2y) / 1.4 B34x = P2x + 27 B34y = P3y + (P1y - P2y) / 1.4 BL3x = array.from(B31x, B32x, B33x, B34x) BL3y = array.from(B31y, B32y, B33y, B34y) // ------------------------------ BELT 3 ------------------------------ // ------------------------------ BELT 4 ------------------------------ B41x = P2x + 39 B41y = P3y + (P1y - P2y) / 1.8 B42x = P2x + 46 B42y = P3y + (P1y - P2y) / 1.8 B43x = P2x + 46 B43y = P3y + (P1y - P2y) / 1.4 B44x = P2x + 39 B44y = P3y + (P1y - P2y) / 1.4 BL4x = array.from(B41x, B42x, B43x, B44x) BL4y = array.from(B41y, B42y, B43y, B44y) // ------------------------------ BELT 4 ------------------------------ if barstate.islastconfirmedhistory // ------------------------------ BODY ------------------------------ var body = array.new<chart.point>() for i = 0 to Lx.size() - 1 body.push(chart.point.from_index(Lx.get(i), Ly.get(i))) for i = 0 to Bx.size() - 1 body.push(chart.point.from_index(Bx.get(i), By.get(i))) for i = 0 to Rx.size() - 1 body.push(chart.point.from_index(Rx.get(i), Ry.get(i))) for i = 0 to Tx.size() - 1 body.push(chart.point.from_index(Tx.get(i), Ty.get(i))) // ------------------------------ BODY ------------------------------ // ------------------------------ LEFT EYE - OUTLINE ------------------------------ var Leye = array.new<chart.point>() for i = 0 to LEx.size() - 1 Leye.push(chart.point.from_index(LEx.get(i), LEy.get(i))) // ------------------------------ LEFT EYE - OUTLINE ------------------------------ // ------------------------------ RIGHT EYE - OUTLINE ------------------------------ var Reye = array.new<chart.point>() for i = 0 to REx.size() - 1 Reye.push(chart.point.from_index(REx.get(i), REy.get(i))) // ------------------------------ RIGHT EYE - OUTLINE ------------------------------ // ------------------------------ LEFT EYE - IRIS ------------------------------ var LIeye = array.new<chart.point>() for i = 0 to LEIx.size() - 1 LIeye.push(chart.point.from_index(LEIx.get(i), LEIy.get(i))) // ------------------------------ LEFT EYE - IRIS ------------------------------ // ------------------------------ RIGHT EYE - IRIS ------------------------------ var RIeye = array.new<chart.point>() for i = 0 to REIx.size() - 1 RIeye.push(chart.point.from_index(REIx.get(i), REIy.get(i))) // ------------------------------ RIGHT EYE - IRIS ------------------------------ // ------------------------------ LEFT EYE - PUPIL ------------------------------ var LPeye = array.new<chart.point>() for i = 0 to LEPx.size() - 1 LPeye.push(chart.point.from_index(LEPx.get(i), LEPy.get(i))) // ------------------------------ LEFT EYE - PUPIL ------------------------------ // ------------------------------ RIGHT EYE - PUPIL ------------------------------ var RPeye = array.new<chart.point>() for i = 0 to REPx.size() - 1 RPeye.push(chart.point.from_index(REPx.get(i), REPy.get(i))) // ------------------------------ RIGHT EYE - PUPIL ------------------------------ // ------------------------------ LEFT EYELASHES ------------------------------ var LEL = array.new<chart.point>() for i = 0 to LELx.size() - 1 LEL.push(chart.point.from_index(LELx.get(i), LELy.get(i))) // ------------------------------ LEFT EYELASHES ------------------------------ // ------------------------------ RIGHT EYELASHES ------------------------------ var REL = array.new<chart.point>() for i = 0 to RELx.size() - 1 REL.push(chart.point.from_index(RELx.get(i), RELy.get(i))) // ------------------------------ RIGHT EYELASHES ------------------------------ // ------------------------------ NOSE ------------------------------ var nose = array.new<chart.point>() for i = 0 to Nx.size() - 1 nose.push(chart.point.from_index(Nx.get(i), Ny.get(i))) // ------------------------------ NOSE ------------------------------ // ------------------------------ LEFT CHEEK ------------------------------ var Lcheek = array.new<chart.point>() for i = 0 to LCx.size() - 1 Lcheek.push(chart.point.from_index(LCx.get(i), LCy.get(i))) // ------------------------------ LEFT CHEEK ------------------------------ // ------------------------------ RIGHT CHEEK ------------------------------ var Rcheek = array.new<chart.point>() for i = 0 to RCx.size() - 1 Rcheek.push(chart.point.from_index(RCx.get(i), RCy.get(i))) // ------------------------------ RIGHT CHEEK ------------------------------ // ------------------------------ Smile ------------------------------ var smile = array.new<chart.point>() for i = 0 to Sx.size() - 1 smile.push(chart.point.from_index(Sx.get(i), Sy.get(i))) // ------------------------------ Smile ------------------------------ // ------------------------------ LEFT CHEEK ------------------------------ var LD = array.new<chart.point>() for i = 0 to LDx.size() - 1 LD.push(chart.point.from_index(LDx.get(i), LDy.get(i))) // ------------------------------ LEFT CHEEK ------------------------------ // ------------------------------ RIGHT CHEEK ------------------------------ var RD = array.new<chart.point>() for i = 0 to RDx.size() - 1 RD.push(chart.point.from_index(RDx.get(i), RDy.get(i))) // ------------------------------ RIGHT CHEEK ------------------------------ // ------------------------------ LEFT TOOTH ------------------------------ var LT = array.new<chart.point>() for i = 0 to LTx.size() - 1 LT.push(chart.point.from_index(LTx.get(i), LTy.get(i))) // ------------------------------ LEFT TOOTH ------------------------------ // ------------------------------ LEFT TOOTH ------------------------------ var RT = array.new<chart.point>() for i = 0 to Rtoothx.size() - 1 RT.push(chart.point.from_index(Rtoothx.get(i), Rtoothy.get(i))) // ------------------------------ LEFT TOOTH ------------------------------ // ------------------------------ CHIN ------------------------------ var CH = array.new<chart.point>() for i = 0 to Cx.size() - 1 CH.push(chart.point.from_index(Cx.get(i), Cy.get(i))) // ------------------------------ CHIN ------------------------------ // ------------------------------ SHIRT ------------------------------ var SH = array.new<chart.point>() for i = 0 to SHx.size() - 1 SH.push(chart.point.from_index(SHx.get(i), SHy.get(i))) // ------------------------------ SHIRT ------------------------------ // ------------------------------ COLLAR ------------------------------ var CL = array.new<chart.point>() for i = 0 to CLx.size() - 1 CL.push(chart.point.from_index(CLx.get(i), CLy.get(i))) // ------------------------------ COLLAR ------------------------------ // ------------------------------ TIE ------------------------------ var TI = array.new<chart.point>() for i = 0 to TIx.size() - 1 TI.push(chart.point.from_index(TIx.get(i), TIy.get(i))) // ------------------------------ TIE ------------------------------ // ------------------------------ PANTS ------------------------------ var P = array.new<chart.point>() for i = 0 to Px.size() - 1 P.push(chart.point.from_index(Px.get(i), Py.get(i))) // ------------------------------ PANTS ------------------------------ // ------------------------------ LEFT PANT LEG ------------------------------ var LP = array.new<chart.point>() for i = 0 to LPx.size() - 1 LP.push(chart.point.from_index(LPx.get(i), LPy.get(i))) // ------------------------------ LEFT PANT LEG ------------------------------ // ------------------------------ RIGHT PANT LEG ------------------------------ var RP = array.new<chart.point>() for i = 0 to RPx.size() - 1 RP.push(chart.point.from_index(RPx.get(i), RPy.get(i))) // ------------------------------ RIGHT PANT LEG ------------------------------ // ------------------------------ LEFT LEG ------------------------------ var LL = array.new<chart.point>() for i = 0 to LLx.size() - 1 LL.push(chart.point.from_index(LLx.get(i), LLy.get(i))) // ------------------------------ LEFT LEG ------------------------------ // ------------------------------ RIGHT LEG ------------------------------ var RL = array.new<chart.point>() for i = 0 to RLx.size() - 1 RL.push(chart.point.from_index(RLx.get(i), RLy.get(i))) // ------------------------------ RIGHT LEG ------------------------------ // ------------------------------ LEFT SOCK ------------------------------ var LS = array.new<chart.point>() for i = 0 to LSx.size() - 1 LS.push(chart.point.from_index(LSx.get(i), LSy.get(i))) // ------------------------------ LEFT SOCK ------------------------------ // ------------------------------ RIGHT SOCK ------------------------------ var RS = array.new<chart.point>() for i = 0 to RSx.size() - 1 RS.push(chart.point.from_index(RSx.get(i), RSy.get(i))) // ------------------------------ RIGHT SOCK ------------------------------ // ------------------------------ LEFT SHOULDER ------------------------------ var LSH = array.new<chart.point>() for i = 0 to LSHx.size() - 1 LSH.push(chart.point.from_index(LSHx.get(i), LSHy.get(i))) // ------------------------------ LEFT SHOULDER ------------------------------ // ------------------------------ RIGHT SHOULDER ------------------------------ var RSH = array.new<chart.point>() for i = 0 to RSHx.size() - 1 RSH.push(chart.point.from_index(RSHx.get(i), RSHy.get(i))) // ------------------------------ RIGHT SHOULDER ------------------------------ // ------------------------------ LEFT SHOULDER ------------------------------ var LA = array.new<chart.point>() for i = 0 to LAx.size() - 1 LA.push(chart.point.from_index(LAx.get(i), LAy.get(i))) // ------------------------------ LEFT SHOULDER ------------------------------ // ------------------------------ RIGHT SHOULDER ------------------------------ var RA = array.new<chart.point>() for i = 0 to RAx.size() - 1 RA.push(chart.point.from_index(RAx.get(i), RAy.get(i))) // ------------------------------ RIGHT SHOULDER ------------------------------ // ------------------------------ LEFT SHOE BULB ------------------------------ var LSO = array.new<chart.point>() for i = 0 to LSOx.size() - 1 LSO.push(chart.point.from_index(LSOx.get(i), LSOy.get(i))) // ------------------------------ LEFT SHOE BULB ------------------------------ // ------------------------------ RIGHT SHOE BULB ------------------------------ var RSO = array.new<chart.point>() for i = 0 to RSOx.size() - 1 RSO.push(chart.point.from_index(RSOx.get(i), RSOy.get(i))) // ------------------------------ RIGHT SHOE BULB ------------------------------ // ------------------------------ LEFT SHOE BACK ------------------------------ var LSB = array.new<chart.point>() for i = 0 to LSBx.size() - 1 LSB.push(chart.point.from_index(LSBx.get(i), LSBy.get(i))) // ------------------------------ LEFT SHOE BACK ------------------------------ // ------------------------------ RIGHT SHOE BACK ------------------------------ var RSB = array.new<chart.point>() for i = 0 to RSBx.size() - 1 RSB.push(chart.point.from_index(RSBx.get(i), RSBy.get(i))) // ------------------------------ RIGHT SHOE BACK ------------------------------ // ------------------------------ LEFT HAND ------------------------------ var LH = array.new<chart.point>() for i = 0 to LHx.size() - 1 LH.push(chart.point.from_index(LHx.get(i), LHy.get(i))) // ------------------------------ LEFT HAND ------------------------------ // ------------------------------ RIGHT HAND ------------------------------ var RH = array.new<chart.point>() for i = 0 to RHx.size() - 1 RH.push(chart.point.from_index(RHx.get(i), RHy.get(i))) // ------------------------------ RIGHT HAND ------------------------------ // ------------------------------ SPOT 1 ------------------------------ var SP1 = array.new<chart.point>() for i = 0 to SP1x.size() - 1 SP1.push(chart.point.from_index(SP1x.get(i), SP1y.get(i))) // ------------------------------ SPOT 1 ------------------------------ // ------------------------------ SPOT 2 ------------------------------ var SP2 = array.new<chart.point>() for i = 0 to SP2x.size() - 1 SP2.push(chart.point.from_index(SP2x.get(i), SP2y.get(i))) // ------------------------------ SPOT 2 ------------------------------ // ------------------------------ SPOT 3 ------------------------------ var SP3 = array.new<chart.point>() for i = 0 to SP3x.size() - 1 SP3.push(chart.point.from_index(SP3x.get(i), SP3y.get(i))) // ------------------------------ SPOT 3 ------------------------------ // ------------------------------ SPOT 4 ------------------------------ var SP4 = array.new<chart.point>() for i = 0 to SP4x.size() - 1 SP4.push(chart.point.from_index(SP4x.get(i), SP4y.get(i))) // ------------------------------ SPOT 4 ------------------------------ // ------------------------------ SPOT 5 ------------------------------ var SP5 = array.new<chart.point>() for i = 0 to SP5x.size() - 1 SP5.push(chart.point.from_index(SP5x.get(i), SP5y.get(i))) // ------------------------------ SPOT 5 ------------------------------ // ------------------------------ SPOT 6 ------------------------------ var SP6 = array.new<chart.point>() for i = 0 to SP6x.size() - 1 SP6.push(chart.point.from_index(SP6x.get(i), SP6y.get(i))) // ------------------------------ SPOT 6 ------------------------------ // ------------------------------ SPOT 7 ------------------------------ var SP7 = array.new<chart.point>() for i = 0 to SP2x.size() - 1 SP7.push(chart.point.from_index(SP7x.get(i), SP7y.get(i))) // ------------------------------ SPOT 7 ------------------------------ // ------------------------------ BELT 1 ------------------------------ var BL1 = array.new<chart.point>() for i = 0 to BL1x.size() - 1 BL1.push(chart.point.from_index(BL1x.get(i), BL1y.get(i))) // ------------------------------ BELT 1 ------------------------------ // ------------------------------ BELT 2 ------------------------------ var BL2 = array.new<chart.point>() for i = 0 to BL2x.size() - 1 BL2.push(chart.point.from_index(BL2x.get(i), BL2y.get(i))) // ------------------------------ BELT 2 ------------------------------ // ------------------------------ BELT 3 ------------------------------ var BL3 = array.new<chart.point>() for i = 0 to BL3x.size() - 1 BL3.push(chart.point.from_index(BL3x.get(i), BL3y.get(i))) // ------------------------------ BELT 3 ------------------------------ // ------------------------------ BELT 4 ------------------------------ var BL4 = array.new<chart.point>() for i = 0 to BL4x.size() - 1 BL4.push(chart.point.from_index(BL4x.get(i), BL4y.get(i))) // ------------------------------ BELT 4 ------------------------------ polyline.new(LA, curved = false, closed = true, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RA, curved = false, closed = true, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(LSH, curved = true, closed = true, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RSH, curved = true, closed = true, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(LL, curved = false, closed = true, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RL, curved = false, closed = true, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(LS, curved = false, closed = true, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RS, curved = false, closed = true, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(LP, curved = false, closed = true, fill_color = pants_lower, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RP, curved = false, closed = true, fill_color = pants_lower, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(P, curved = false, closed = true, fill_color = pants_upper, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(BL1, curved = false, closed = true, fill_color = black, line_color = black, line_width = 5, xloc = xloc.bar_index) polyline.new(BL2, curved = false, closed = true, fill_color = black, line_color = black, line_width = 5, xloc = xloc.bar_index) polyline.new(BL3, curved = false, closed = true, fill_color = black, line_color = black, line_width = 5, xloc = xloc.bar_index) polyline.new(BL4, curved = false, closed = true, fill_color = black, line_color = black, line_width = 5, xloc = xloc.bar_index) polyline.new(SH, curved = false, closed = true, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(TI, curved = false, closed = true, fill_color = red, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(CL, curved = false, closed = true, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(body, curved = true, closed = true, fill_color = body_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index) polyline.new(LEL, curved = false, closed = false, fill_color = na, line_color = black, line_width = 6, xloc = xloc.bar_index) polyline.new(REL, curved = false, closed = false, fill_color = na, line_color = black, line_width = 6, xloc = xloc.bar_index) polyline.new(Leye, curved = true, closed = true, fill_color = white, line_color = black, line_width = 2, xloc = xloc.bar_index) polyline.new(Reye, curved = true, closed = true, fill_color = white, line_color = black, line_width = 2, xloc = xloc.bar_index) polyline.new(LIeye, curved = true, closed = true, fill_color = iris, line_color = black, line_width = 2, xloc = xloc.bar_index) polyline.new(RIeye, curved = true, closed = true, fill_color = iris, line_color = black, line_width = 2, xloc = xloc.bar_index) polyline.new(LPeye, curved = true, closed = true, fill_color = black, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RPeye, curved = true, closed = true, fill_color = black, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(Lcheek, curved = true, closed = false, fill_color = body_color, line_color = red, line_width = 3, xloc = xloc.bar_index) polyline.new(Rcheek, curved = true, closed = false, fill_color = body_color, line_color = red, line_width = 3, xloc = xloc.bar_index) polyline.new(LT, curved = false, closed = false, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RT, curved = false, closed = false, fill_color = white, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(smile, curved = true, closed = false, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(nose, curved = true, closed = false, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(LD, curved = true, closed = false, fill_color = na, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RD, curved = true, closed = false, fill_color = na, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(CH, curved = true, closed = false, fill_color = na, line_color = red, line_width = 3, xloc = xloc.bar_index) polyline.new(LSO, curved = true, closed = true, fill_color = black, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RSO, curved = true, closed = true, fill_color = black, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(LSB, curved = false, closed = true, fill_color = black, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RSB, curved = false, closed = true, fill_color = black, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(LH, curved = true, closed = true, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(RH, curved = true, closed = true, fill_color = body_color, line_color = black, line_width = 3, xloc = xloc.bar_index) polyline.new(SP1, curved = true, closed = true, fill_color = outline_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index) polyline.new(SP2, curved = true, closed = true, fill_color = outline_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index) polyline.new(SP3, curved = true, closed = true, fill_color = outline_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index) polyline.new(SP4, curved = true, closed = true, fill_color = outline_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index) polyline.new(SP5, curved = true, closed = true, fill_color = outline_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index) polyline.new(SP6, curved = true, closed = true, fill_color = outline_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index) polyline.new(SP7, curved = true, closed = true, fill_color = outline_color, line_color = outline_color, line_width = 3, xloc = xloc.bar_index)
Consecutive Higher/Lower Closings
https://www.tradingview.com/script/ztAangSn-Consecutive-Higher-Lower-Closings/
rahul_joshi_2
https://www.tradingview.com/u/rahul_joshi_2/
54
study
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/ // © rahul_joshi_2 //@version=5 indicator("Custom Buy/Sell Signal", overlay=true) // Input options consecutiveHigherValues = input(3, title="Consecutive Higher Values for Buy Signal") consecutiveLowerValues = input(3, title="Consecutive Lower Values for Sell Signal") useOpen = input(true, title="Use Open") useHigh = input(false, title="Use High") useLow = input(false, title="Use Low") useClose = input(false, title="Use Close") // Get the selected value type value = close if useOpen value := open else if useHigh value := high else if useLow value := low // Calculate the difference in selected values valueDiff = value - value[1] // Function to check for consecutive higher values consecutiveHigherValuesCheck(count) => higherCount = 0 for i = 0 to count - 1 higherCount := valueDiff[i] > 0 ? higherCount + 1 : higherCount higherCount >= count // Function to check for consecutive lower values consecutiveLowerValuesCheck(count) => lowerCount = 0 for i = 0 to count - 1 lowerCount := valueDiff[i] < 0 ? lowerCount + 1 : lowerCount lowerCount >= count // Generate buy and sell signals buySignal = consecutiveHigherValuesCheck(consecutiveHigherValues) sellSignal = consecutiveLowerValuesCheck(consecutiveLowerValues) // Plot buy and sell signals on the chart plotshape(series=buySignal, location=location.belowbar, color=color.green, style=shape.triangleup, title="Buy Signal") plotshape(series=sellSignal, location=location.abovebar, color=color.red, style=shape.triangledown, title="Sell Signal")
ATH Drawdown Indicator by Atilla Yurtseven
https://www.tradingview.com/script/lIqLjXdt-ATH-Drawdown-Indicator-by-Atilla-Yurtseven/
AtillaYurtseven
https://www.tradingview.com/u/AtillaYurtseven/
62
study
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/ // © AtillaYurtseven //@version=5 indicator("ATH Drawdown // Atilla Yurtseven", shorttitle="ADD") show_as_candles = input.bool(false, title="Show as Candles") show_mean = input.bool(true, title="Show Mean") green = input.color(#27a69a, title="Green", group="Colors") red = input.color(#f05350, title="Red", group="Colors") var float ath = na var bool is_ath_bar = false var float total_dd = 0.0 var int bar = na // functions drawdown(val) => (val / ath - 1) * 100 // reset if na(bar) bar := 0 if na(total_dd) total_dd := 0.0 bar += 1 is_ath_bar := false if na(ath) or high > ath ath := high is_ath_bar := true dd = is_ath_bar?0.0:drawdown(low) total_dd += dd mean = total_dd / bar o = show_as_candles?drawdown(open):na h = show_as_candles?drawdown(high):na l = show_as_candles?drawdown(low):na c = show_as_candles?drawdown(close):na clr = c > o?green:red plot(show_as_candles?na:dd, color=green) plotcandle(o, h, l, c, color=clr, bordercolor=clr) plot(mean, title="Mean") hline(0) hline(-25) hline(-50) hline(-75) hline(-100)
RS for VPA
https://www.tradingview.com/script/7ebucCfu-RS-for-VPA/
karthikmarar
https://www.tradingview.com/u/karthikmarar/
58
study
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/ // © karthikmarar //@version=5 //Relative strength Indicator for use with VPA 5.0 indicator("RS for VPA") i_sym = input.symbol(title='Index for Rel.strength', defval='NSE:cnx500') len = input.int(22, "Period", minval=10, maxval=66, step=1) len1 = input.int(22, "Short MA for Index", minval=10, maxval=32, step=1) len2 = input.int(60, "Mid MA for Index", minval=32, maxval=80, step=1) len3 = input.int(130, "Long MA for Index", minval=80, maxval=150, step=1) a = close bs = request.security(i_sym, 'D', close) zeroline = 0 crs = ((a/a[len])/(bs/bs[len]) - 1) zero_color = (crs >= 0) ? color.green : color.orange plot_color = (crs >= 0) ? color.green : color.red fill_color = (crs >= 0) ? color.new(color.green, 80) : color.new(color.red, 80) hzplot = plot(zeroline, title="Horiz. Axis", color=zero_color, linewidth=1) crs_plot = plot(crs, title="CRS", color=plot_color, linewidth=2) fill(plot1=crs_plot, plot2=hzplot, color=fill_color) x1 = ta.ema(bs,5) x2 = ta.ema(bs,len1) x3 = ta.ema(bs,len2) x4 = ta.ema(bs,len3) xs = x1-x2 > 0 ? 1 : -1 xm = xs == 1 and x2-x3 > 0 ? 1 : -1 xl = xm == 1 and x3-x4 > 0 ? 1 : -1 bgcolor (xl > 0 ? color.new(color.yellow, 40) : (xm > 0 ? color.new(color.yellow, 60) : ( xs >0 ? color.new(color.yellow, 80) : ( xl < 0 ? color.new(color.blue, 80): (xm < 0 and xs > 0? color.new(color.blue,60):color.new(color.blue,40) )))))
Absolute ZigZag Lib
https://www.tradingview.com/script/lRY74dha-Absolute-ZigZag-Lib/
niquedegraaff
https://www.tradingview.com/u/niquedegraaff/
31
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © niquedegraaff // @version=5 library("Absolute_ZigZag_Lib", overlay = true) // @type The source to use // @param high (float) The high value for the pivot lows. // @param low (float) The low value for the pivot highs. // @param priority (bool) Which source has higher priorty ("high" or "low"). Default is "high" export type Source float high = high float low = low string priority = "high" // @type Features to enable // @param closeBreaksClose (bool) Check if current (highest/lowest) pivot close, broke previous pivot close. // @param closeBreaksPivot (bool) Check if current (highest/lowest) pivot close, broke previous pivot (high or low). // @param comulativeVolume (bool) Calculate the comulative volume for each pivot. export type Features bool closeBreaksClose = false bool closeBreaksPivot = false // @type Tooltips to show // @param name (bool) Show the pivot's name in the tooltip? // @param price (bool) Show the pivot's price in the tooltip? // @param closeBreaksClose (bool) Show if current (highest/lowest) pivot close broke previous pivot close (Only effective if feature is enabled). // @param closeBreaksPivot (bool) Show if current (highest/lowest) pivot close broke previous pivot (high/low) (Only effective if feature is enabled). export type Tooltips bool name = true bool price = true bool close = true bool closeBreaksClose = false bool closeBreaksPivot = false // @type Used to create a (color) theme to draw Zigzag // @param enabled (bool) Use this ZigZag indicator library build-in lines and labels? (Set to false if you want to build your own) // @param colorDefault (color) The default color. // @param colorNeutral (color) The neutral color. // @param colorBullish (color) The bullish color. // @param colorBearish (color) The bearish color. // @param coloredLines (bool) Wether the lines should be colored according to bullish/bearish/neutral colors too. export type Theme bool enabled = false color colorDefault = color.gray color colorNeutral = color.yellow color colorBullish = color.green color colorBearish = color.red string labelSize = size.normal int lineWidth = 2 bool coloredLines = false bool showCloseInfo = false bool showTooltips = true Tooltips tooltips = na // @type All settings for the indicator // @param source (Source) The source to be used. // @param features (Features) The features to be used. // @oparam highFirst (bool) In case we have a higher high and a higher low, which comes first? // @param theme (Theme) The theme to be used. // @param tooltips (Tooltips) The tooltips to export type Settings Source source = na Features features = na Theme theme = na // @type Used to determine a coordination on the chart // @param x (int) The time // @param y (float) The price export type Point int x // time float y // price // @type Used to determine pivots on the chart. // @param point (Point) The current coordiation on the chart // @param isHigh (bool) Wether this Pivot is a pivot high or low. // @param isHigher (bool) Wether this Pivot is higher than the previous paired pivot. (not last pivot, but 2 back). // @param isCurrentBar (bool) Wether the pivot is at the current bar // @param name (string) The name of the pivot. // @param abbr (string) The abbr of the name of the pivot. // @param close (float) The highest/lowest close price of the swing to this pivot. // @param closeBreaksClose (bool) Wether the pivot (highest/lowest) close breaks the previous pivot (highest/lowest) close. // @param closeBreaksPivot (bool) Wether the pivot (highest/lowest) close breaks the previous pivot (high/low). // @param ln (line) Line to draw (optional) // @param lb (label) Label to draw (optional) export type Pivot Point point bool isHigh bool isHigher = na string name = na string abbr = na float close = close float comulativeVolume = na bool closeBreaksPivot = na bool closeBreaksClose = na bool isLast = true line ln = na label lb = na // @function Gets the first Pivot // @param this (array<Pivot>) The object to work with. // @return (Pivot) The first Pivot in the array or NA if not available. export method getFirst(array<Pivot> this) => this.size() > 0 ? this.get(0) : na // @function Gets the latest Pivot // @param this (array<Pivot>) The object to work with. // @return (Pivot) The last Pivot in the array or NA if not available. export method getLast(array<Pivot> this) => int size = this.size(), size > 0 ? this.get(size - 1) : na // @function Gets previous Pivot by index number. // @param this (array<Pivot>) The object to work with. // @param index (int) The index number. (optional, default is 1) // @return (Pivot) The previous Pivot or NA if not available. export method getPrev(array<Pivot> this, int index = 1) => int size = this.size(), size > index ? this.get(size - 1 - index) : na // @function Checks if current pivot is Higher than previous one. // @param this (Pivot) The object to work with. // @param pivots (array<Pivot>) The array of pivots. // @return (bool) Weither the pivot is higher or not. Returns (na) if array was too small. method isHigher(Pivot this, Pivot[] pivots) => int size = pivots.size() if size > 2 this.point.y > pivots.get(size - 3).point.y else na // @function Checks if the current pivot is at the current bar // @param this (Pivot) The object to work with. // @return (bool) Wether the current pivot is at the current bar or not. export method isAtCurrentBar(Pivot this) => this.point.x >= last_bar_time // @function Checks if current pivot is a higher high // @param this (Pivot) The object to work with. // @return (bool) True if the pivot is a higher high, false if not. export method isHigherHigh(Pivot this) => bool r = this.isHigh and this.isHigher // @function Checks if current pivot is a lower high // @param this (Pivot) The object to work with. // @return (bool) True if the pivot is a lower high, false if not. export method isLowerHigh(Pivot this) => bool r = this.isHigh and not this.isHigher // @function Checks if current pivot is a higher low // @param this (Pivot) The object to work with. // @return (bool) True if the pivot is a higher low, false if not. export method isHigherLow(Pivot this) => bool r = not this.isHigh and this.isHigher // @function Checks if current pivot is a lower low // @param this (Pivot) The object to work with. // @return (bool) True if the pivot is a lower low, false if not. export method isLowerLow(Pivot this) => bool r = not this.isHigh and not this.isHigher // @function Gets the latest Pivot High based on prev number Pivot high back. Default the latest // @param this (array<Pivot>) The object to work with. // @param prev (int) Number of prev pivot highs back. (1 = latest, 1 < is previous ones). // @return (Pivot) The latest Pivot High or NA if not available. export method getHigh(array<Pivot> this, int prev = 1) => int size = this.size() int n = math.max(1, prev) Pivot lastPivot = this.getLast() Pivot returnPivot = na if not na(lastPivot) if n == 1 and lastPivot.isHigh returnPivot := lastPivot else n := n * (lastPivot.isHigh ? 2 : 1) if size > n returnPivot := this.get(size - 1 - n) returnPivot // @function Gets the latest pivot high // @param this (array<Pivot>) The object to work with. // @return (Pivot) The latest Pivot high in the array export method getLastHigh(array<Pivot> this) => this.getHigh(1) // @function Gets the previous pivot high // @param this (array<Pivot>) The object to work with. // @return (Pivot) The previous Pivot high in the array or NA if not available export method getPrevHigh(array<Pivot> this) => this.getHigh(2) // @function Gets the Pivot Low // @param this (array<Pivot>) The object to work with. // @param n (int) Number of pivot lows back. (1 = latest, 1 < is previous ones) // @return (Pivot) The latest Pivot Low or NA if not available export method getLow(array<Pivot> this, int prev = 1) => int size = this.size() int n = math.max(1, prev) Pivot lastPivot = this.getLast() Pivot returnPivot = na if not na(lastPivot) if n == 1 and not lastPivot.isHigh returnPivot := lastPivot else n := n * (lastPivot.isHigh ? 1 : 2) if size > n returnPivot := this.get(size - 1 - n) returnPivot // @function Gets the latest pivot low // @param this (array<Pivot>) The object to work with. // @return (Pivot) The latest Pivot low in the array or NA if not available export method getLastLow(array<Pivot> this) => this.getLow(1) // @function Gets the previous pivot low // @param this (array<Pivot>) The object to work with. // @return (Pivot) The previous Pivot low in the array or NA if not available export method getPrevLow(array<Pivot> this) => this.getLow(2) // @function Builds name (and abbreviation) string for current pivot // @param this (Pivot) The Object to work with. // @return (string) The name for this pivot. // @return (string) Abbreviation of the name for this pivot. method buildNameString(Pivot this) => string highLowAbbr = this.isHigh ? "H" : "L" string highLow = highLowAbbr + (this.isHigh ? "igh" : "ow") string higherLowerAbbr = "" string higherLower = "" if not na(this.isHigher) higherLowerAbbr := this.isHigher ? "H" : "L" higherLower := higherLowerAbbr + (this.isHigher ? "igher " : "ower ") string name = str.format("{0}{1}", higherLower, highLow) string abbr = str.format("{0}{1}", higherLowerAbbr, highLowAbbr) [name, abbr] // @function Builds the string for the CloseBreaksClose feature // @param this (Pivot) The Object to work with. // @return (string) The string. method buildCloseBreaksCloseString(Pivot this) => string str = this.closeBreaksClose ? (this.isHigh ? "꜀" : "ᶜ") : "" // @function Builds the string for the CloseBreaksPivot feature // @param this (Pivot) The Object to work with. // @return (string) The string. method buildCloseBreaksPivotString(Pivot this) => string str = this.closeBreaksClose ? (this.isHigh ? "ₚ" : "ᵖ") : "" // @function Generates the text for the label of the Pivot // @param this (Pivot) The object to work with. // @param settings (Settings) The global settings for the indicator. // @return (string) Text: HH for higher high, LH for lower high, HL for higher low, LL for lower low method buildLabelTextString(Pivot this, Settings settings) => string str = "" string highInfo = "" string lowInfo = "" if settings.theme.showCloseInfo str := settings.features.closeBreaksClose ? this.closeBreaksClose ? this.buildCloseBreaksCloseString() : "" : str str += settings.features.closeBreaksPivot ? this.closeBreaksPivot ? this.buildCloseBreaksPivotString() : "" : "" if na(this.isHigher) str := this.abbr else str := this.isHigh ? str + "\n" + this.abbr : this.abbr + "\n" + str // @function Creates a color based on current pivot conditions. // @param this (Pivot) The object to work with. // @param last (Pivot) The previous pivot // @returns (color) The color for this pivot method generateColor(Pivot this, Pivot prev, Theme theme) => color c = theme.colorDefault if this.isHigherLow() c := not prev.isHigher ? theme.colorNeutral : theme.colorBullish if this.isLowerLow() c := theme.colorBearish if this.isHigherHigh() c := theme.colorBullish if this.isLowerHigh() c := prev.isHigher ? theme.colorNeutral : theme.colorBearish c // @function Checks if current close broke previous pivot value // @param this (Pivot) The Object to work with. // @return (bool) Wether the current close broke the previous pivot value method closeBrokePrevPivot(Pivot this) => this.isHigh ? this.closeBreaksPivot : not this.closeBreaksPivot // @function Checks if current close broke previous pivot close // @param this (Pivot) The Object to work with. // @return (bool) Wether the current close broke the previous pivot close method closeBrokePrevPivotClose(Pivot this) => this.isHigh ? this.closeBreaksClose : not this.closeBreaksClose // @function Calculates the comulative volume from previous pivot to current pivot method calculateComulativeVolume(Pivot this) => this.comulativeVolume + volume // @function Builds a tooltip string // @param this (Pivot) The object to work with. // @param settings (Settings) The global settings. // @return (string) The tooltip method buildTooltipString(Pivot this, Settings settings) => array<string> tooltips = array.new<string>() string strName = this.name string strHighOrLow = this.isHigh ? "high" : "low" string strAboveOrBelow = this.isHigh ? "above" : "below" string strHighestOrLowest = this.isHigh ? "highest" : "lowest" // tooltips.push("X:\t" + str.tostring(this.point.x)) if settings.theme.tooltips.name tooltips.push("name\t\t\t: " + strName) if settings.theme.tooltips.price tooltips.push("price\t\t\t: " + str.tostring(this.point.y)) if settings.theme.tooltips.close tooltips.push(strHighestOrLowest + " close\t\t: " + str.tostring(this.close)) if settings.theme.tooltips.closeBreaksPivot tooltips.push(str.format("close {0} pivot\t: {1}", this.isAtCurrentBar() or this.isLast ? "breaks" : "broke", this.isHigh ? this.closeBreaksPivot : not this.closeBreaksPivot)) if settings.theme.tooltips.closeBreaksClose tooltips.push(str.format("close {0} close\t: {1}", this.isAtCurrentBar() or this.isLast ? "breaks" : "broke", this.isHigh ? this.closeBreaksClose : not this.closeBreaksClose)) // Return the joined string string str = array.join(tooltips, "\n") // @function Adds a new pivot to the pivots array. // @param this (array<Pivot>) The object to work with. // @param point (Point) The point coordinates of the new pivot. // @param isHigh (bool) Wether the pivot is a high or not (then it is a low). // @param settings (Settings) The global settings. // @return (Pivot) The latest Pivot. method add(array<Pivot> this, Point point, bool isHigh, Settings settings) => Theme theme = settings.theme Pivot lastPivot = this.getLast() Pivot prevPivot = this.getPrev() Pivot pivot = Pivot.new(point, isHigh) pivot.close := (isHigh ? math.max(close, close[1]) : math.min(close, close[1])) pivot.close := (isHigh and close > pivot.close) or (not isHigh and close < pivot.close) ? close : pivot.close if not na(lastPivot) color pivotColor = pivot.generateColor(lastPivot, theme) // If we have a previous Pivot... if not na(prevPivot) pivot.closeBreaksPivot := pivot.isHigh ? close > prevPivot.point.y : close < prevPivot.point.y pivot.closeBreaksClose := pivot.isHigh ? close > prevPivot.close : close < prevPivot.close pivot.isHigher := point.y > prevPivot.point.y [name, abbr] = pivot.buildNameString() pivot.name := name pivot.abbr := abbr pivotColor := pivot.generateColor(lastPivot, theme) // Create the line for the new Pivot if theme.enabled pivot.ln := line.new( x1 = lastPivot.point.x, y1 = lastPivot.point.y, x2 = pivot.point.x, y2 = pivot.point.y, xloc = xloc.bar_time, extend = extend.none, color = theme.coloredLines ? pivotColor : theme.colorDefault, style = line.style_solid, width = theme.lineWidth) // Create label for the new Pivot if theme.enabled pivot.lb := label.new( x = pivot.point.x, y = pivot.point.y, text = pivot.buildLabelTextString(settings), xloc = xloc.bar_time, yloc = isHigh ? yloc.abovebar : yloc.belowbar, color = color.rgb(0, 0, 0, 100), style = label.style_none, textcolor = pivotColor, size = theme.labelSize, textalign = text.align_center, text_font_family = font.family_default, tooltip = theme.showTooltips ? pivot.buildTooltipString(settings) : na) // Last pivot is no longer the last pivot lastPivot.isLast := false this.set(this.size() - 1, lastPivot) // Remove old pivot when max amount of pivot is reached if this.size() > 1000 this.shift() // Push the new pivot to the end of the array this.push(pivot) // Return the new Pivot pivot // @function Update pivot in array // @param this (array<Pivot>) The object to work with. // @return (Pivot) The latest Pivot Low method update(array<Pivot> this, Pivot pivot, Point point, Settings settings) => Theme theme = settings.theme Pivot prevPivot = na pivot.point.x := point.x pivot.point.y := point.y pivot.ln.set_xy2(point.x, point.y) pivot.lb.set_xy(point.x, point.y) pivot.close := (pivot.isHigh ? math.max(close, close[1]) : math.min(close, close[1])) if not na(this) prevPivot := this.getPrev(2) pivot.close := (pivot.isHigh and close > pivot.close) or (not pivot.isHigh and close < pivot.close) ? close : pivot.close if not na(prevPivot) Pivot lastPivot = this.getLast() pivot.isHigher := point.y > prevPivot.point.y // Check if close is higher than previous pivot and pivot's bar close value. pivot.closeBreaksPivot := pivot.isHigh ? close > prevPivot.point.y : close < prevPivot.point.y pivot.closeBreaksClose := pivot.isHigh ? close > prevPivot.close : close < prevPivot.close // Rebuild name string [name, abbr] = pivot.buildNameString() pivot.name := name pivot.abbr := abbr if theme.enabled color pivotColor = pivot.generateColor(lastPivot, theme) pivot.lb.set_text(pivot.buildLabelTextString(settings)) pivot.lb.set_textcolor(pivotColor) if theme.showTooltips pivot.lb.set_tooltip(lastPivot.buildTooltipString(settings)) pivot.ln.set_color(theme.coloredLines ? pivotColor : theme.colorDefault) // DEBUG // if not pivot.isHigh // line debug = line.new(prevPivot.point.x, prevPivot.point.y, point.x, point.y, xloc.bar_time, extend.none, pivot.isHigh ? color.new(color.lime, 70) : color.new(color.yellow, 70), line.style_solid, 1) this.set(this.size() - 1, pivot) pivot // @function Scans for new pivot // @param this (array<Pivot>) The object to work with. // @param isHigh (bool) Wether we look for a pivot high or not. // @param settings (Settings) The settings. method scan(array<Pivot> this, float source, bool isHigh, Settings settings) => Point point = Point.new(time, source) Pivot lastPivot = this.getLast() if not na(lastPivot) if lastPivot.isHigh if point.y > lastPivot.point.y this.update(lastPivot, point, settings) if not isHigh this.add(point, isHigh, settings) else if point.y < lastPivot.point.y this.update(lastPivot, point, settings) if isHigh this.add(point, isHigh, settings) else this.add(point, isHigh, settings) // @function Creates a new ZigZag Instance // @param customSettings (Settings) The settings for this instance. // @param return (array<Pivot>) The array of pivots. export new(Settings customSettings = na) => Settings settings = customSettings // If no settings were given, create default settings if na(settings) settings := Settings.new() if na(settings.source) settings.source := Source.new() if na(settings.theme) settings.theme := Theme.new() if na(settings.features) settings.features := Features.new() // Change settings based on enabled/disabled features if not na(settings.theme.tooltips) if settings.features.closeBreaksClose == false settings.theme.tooltips.closeBreaksClose := false if settings.features.closeBreaksPivot == false settings.theme.tooltips.closeBreaksPivot := false // Create pivots var Pivot[] pivots = array.new<Pivot>() float srcLow = settings.source.low float srcHigh = settings.source.high if srcHigh != srcLow and srcLow < srcLow[1] and srcHigh > srcHigh[1] if settings.source.priority == "high" // IF HIGH CAME FIRST pivots.scan(srcHigh, 1, settings) // HIGH pivots.scan(srcLow, 0, settings) // LOW else pivots.scan(srcLow, 0, settings) // LOW pivots.scan(srcHigh, 1, settings) // HIGH else if srcHigh > srcHigh[1] if srcLow >= srcLow[1] pivots.scan(srcHigh, 1, settings) // HIGH if srcLow < srcLow[1] if srcHigh <= srcHigh[1] pivots.scan(srcLow, 0, settings) // LOW // Return the pivots array pivots export method barIsPivot(array<Pivot> pivots) => var lastPivot = pivots.getLast() // @function Helper function to generate a lower timeframe period (string) for current timeframe period. // You can use this on conjuction with request.security_lower_tf() to figure out if current high of // of this bar was created before the low of this bar. // @return (string) Timeframe period for lower timeframe. export getLowerTimeframePeriod() => int tf = timeframe.in_seconds(timeframe.period) string ltf = switch true tf <= 60 => '10S' tf <= 300 => '1' // 5 minutes => 1 minute tf <= 600 => '2' // 10 minutes => 2 minutes tf <= 1800 => '3' // 30 minutes => 3 minutes tf <= 3600 => '5' // 1 hour => 5 minutes tf <= 14400 => '15' // 4 hour => 15 minutes tf <= 86400 => '30' // 1 day => 30 minutes tf <= 172800 => '60' // 2 days => 1 hour tf <= 259200 => '240' // 3 days => 4 hours tf <= 432000 => '360' // 5 days => 6 hours tf <= 604800 => '720' // 1 week => 12 hours tf <= 1209600 => 'D' // 2 weeks => 1 day tf <= 2628000 => '2D' // 1 month => 2 days tf <= 5256000 => '5D' // 2 months => 5 days tf <= 7884000 => 'W' // 3 months => 1 week tf <= 15768000 => '2W' // 6 months => 2 weeks tf <= 31536000 => '1M' // 1 year => 1 month => timeframe.period // --------------------------------------------------------------------------------------------------------------------- // USAGE EXAMPLE AREA // --------------------------------------------------------------------------------------------------------------------- // Input: General options string iSource = input.string( title = "Source", defval = "high/low", options = ["high/low", "custom"], group = "S O U R C E") float iSourceHigh = input.source( title = "Custom High", defval = close, group = "S O U R C E") float iSourceLow = input.source( title = "Custom Low", defval = close, group = "S O U R C E") string iSourcePriority = input.string( title = "Prioritize", defval = "auto", options = ["auto", "high", "low"], tooltip = "In the case if we have both a higher high and a lower low, which is prioritized? If set to automatic, the indicator will look at lower timeframe.", group = "S O U R C E") // Input: Features bool iFeatureCloseBreaksClose = input.bool( title = "Close Breaks Close", defval = true, tooltip = "Check if current pivot (highest/lowest) close broke previous paired pivot (highest/lowest) close.", group = "F E A T U R E S") bool iFeatureCloseBreaksPivot = input.bool( title = "Close Breaks Pivot", defval = true, tooltip = "Check if current pivot (highest/lowest) close broke previous paired pivot (high/low).", group = "F E A T U R E S") // Input: Set theming options bool iThemeHide = input.bool( title = "Hide", defval = false, tooltip = "You can hide or show everything at once with this setting.", group = "T H E M I N G") bool iThemeShowCloseInfo = input.bool( title = "Show close info", defval = true, tooltip = "Show extra close info above and below pivot labels?\nC = Close is higher than previous paired pivot close. \nCP = Close is higher than previous paired pivot.", group = "T H E M I N G") color iThemeColorDefault = input.color( title = "Default", defval = color.rgb(120, 123, 134, 0), group = "T H E M I N G") color iThemeColorNeutral = input.color( title = "Neutral", defval = color.rgb(200, 200, 000, 0), group = "T H E M I N G") color iThemeColorBullish = input.color( title = "Bullish", defval = color.rgb(000, 200, 000, 0), group = "T H E M I N G") color iThemeColorBearish = input.color( title = "Bearish", defval = color.rgb(200, 000, 000, 0), group = "T H E M I N G") string iThemeStyle = input.string( title = "Style", defval = "labels & lines", options = ["labels & lines", "labels", "none"], tooltip = "If \"none\" is selected, the default color will be used for all drawings.", group = "T H E M I N G") string iThemeLabelSize = input.string( title = "Label size", defval = "normal", options = ["huge", "large", "normal", "small", "tiny"], group = "T H E M I N G") int iThemeLineWidth = input.int( title = "Line width", defval = 2, minval = 1, maxval = 50, tooltip = "Width in pixels", group = "T H E M I N G") // Input: Set Tooltip Options bool iTooltipDisable = input.bool( title = "Disable", defval = false, tooltip = "This setting overrides all below tooltip settings.", group = "T O O L T I P S") bool iTooltipName = input.bool( title = "Show name", defval = true, group = "T O O L T I P S") bool iTooltipPrice = input.bool( title = "Show price", defval = true, group = "T O O L T I P S") bool iTooltipClose = input.bool( title = "Show close", defval = true, group = "T O O L T I P S") bool iTooltipCloseBreaksClose = input.bool( title = "Show close breaks close", defval = true, group = "T O O L T I P S") bool iTooltipCloseBreaksPivot = input.bool( title = "Show close breaks pivot", defval = true, group = "T O O L T I P S") // Setup the highFirst value for the ZigZag indicator // This is an example to find out how you can find the value that came first, the high or the low? // We can also just set highFirst to 1. But for accuracy, using the below setup is recommended. // So, in this example we use the ZigZag build-in helper function to generate a lower timeframe period string! ltf = getLowerTimeframePeriod() [ltf_high, ltf_low] = request.security_lower_tf(syminfo.tickerid, ltf, [iSourceHigh, iSourceLow]) string sourcePriorityAuto = (ltf == timeframe.period ? false : ltf_high.lastindexof(ltf_high.max()) <= ltf_low.lastindexof(ltf_low.min())) ? "high" : "low" // Setup the source for the ZigZag indicator Source sourceSettings = Source.new( high = iSource == "high/low" ? high : iSourceHigh, low = iSource == "high/low" ? low : iSourceLow, priority = iSourcePriority == "auto" ? sourcePriorityAuto : iSourcePriority) // Setup to be used features for the ZigZag indicator Features featuresSettings = Features.new( closeBreaksClose = iFeatureCloseBreaksClose, closeBreaksPivot = iFeatureCloseBreaksPivot) // Setup the theme for the ZigZag indicator Theme themeSettings = Theme.new( enabled = not iThemeHide, colorDefault = iThemeColorDefault, colorNeutral = iThemeStyle == "none" ? iThemeColorDefault : iThemeColorNeutral, colorBullish = iThemeStyle == "none" ? iThemeColorDefault : iThemeColorBullish, colorBearish = iThemeStyle == "none" ? iThemeColorDefault : iThemeColorBearish, coloredLines = iThemeStyle == "labels & lines" ? true : false, labelSize = iThemeLabelSize, lineWidth = iThemeLineWidth, showCloseInfo = iThemeShowCloseInfo, showTooltips = not iTooltipDisable, tooltips = Tooltips.new(iTooltipName, iTooltipPrice, iTooltipClose, iTooltipCloseBreaksClose, iTooltipCloseBreaksPivot)) // All settings for the ZigZag indicator settings = Settings.new(sourceSettings, featuresSettings, themeSettings) // Create the ZigZag indicator array<Pivot> pivots = new(settings)
GeneratorBeta
https://www.tradingview.com/script/spDdHM7H-GeneratorBeta/
Mutik159
https://www.tradingview.com/u/Mutik159/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Mutik159 //@version=5 // @description [SNG_BETA] Levels Generating Library library("GeneratorBeta") import Mutik159/TypesBeta/1 // ****************************************************** // // ******************** FUNCTIONS *********************** // ****************************************************** // // @function Generating daily / weekly / monthly levels export horizontals(array<TypesBeta.Level> levelsArray, float _open, float _close, float _extendLow, float _extendHigh, int _confluenceScore, string _name) => // Candle two ticks away is red, next is green - bottom formed | candle two ticks away is green, next is red - top formed if (((_close[2] < _open[2]) and _close[1] > _open[1]) or ((_close[2] > _open[2]) and _close[1] < _open[1])) array.push(levelsArray, TypesBeta.Level.new(_open[1] - _extendLow, _open[1] + _extendHigh, _confluenceScore, _name)) // @function Generating previous low levels export previous_low(array<TypesBeta.Level> levelsArray, series float _low, float _extendLow, float _extendHigh, int _confluenceScore, string _name, int _barIndex = 0, int _barExpiration = 0, string _timeframe = "") => array.push(levelsArray, TypesBeta.Level.new(_low[0] - _extendLow, _low[0] + _extendHigh, _confluenceScore, _name, _barIndex, _barExpiration, _timeframe)) // @function Generating previous high levels export previous_high(array<TypesBeta.Level> levelsArray, series float _high, float _extendLow, float _extendHigh, int _confluenceScore, string _name, int _barIndex = 0, int _barExpiration = 0, string _timeframe = "") => array.push(levelsArray, TypesBeta.Level.new(_high[0] - _extendLow, _high[0] + _extendHigh, _confluenceScore, _name, _barIndex, _barExpiration, _timeframe)) // @function Generating previous open levels export previous_open(array<TypesBeta.Level> levelsArray, series float _open, float _extendLow, float _extendHigh, int _confluenceScore, string _name, int _barIndex = 0, int _barExpiration = 0, string _timeframe = "") => array.push(levelsArray, TypesBeta.Level.new(_open[0] - _extendLow, _open[0] + _extendHigh, _confluenceScore, _name, _barIndex, _barExpiration, _timeframe)) // @function Generating previous eq levels export previous_eq(array<TypesBeta.Level> levelsArray, series float _low, float _high, float _extendLow, float _extendHigh, int _confluenceScore, string _name, int _barIndex = 0, int _barExpiration = 0, string _timeframe = "") => array.push(levelsArray, TypesBeta.Level.new((_high[0] + _low[0]) / 2 - _extendLow, (_high[0] + _low[0]) / 2 + _extendHigh, _confluenceScore, _name, _barIndex, _barExpiration, _timeframe)) // @function Generating VWAP close levels export vwap_close(array<TypesBeta.Level> levelsArray, float _vwapPrice, float _extendLow, float _extendHigh, int _confluenceScore, string _name) => array.push(levelsArray, TypesBeta.Level.new(_vwapPrice - _extendLow, _vwapPrice + _extendHigh, _confluenceScore, _name))
MyVolatilityBands
https://www.tradingview.com/script/QPnYTaX0-MyVolatilityBands/
ClassicScott
https://www.tradingview.com/u/ClassicScott/
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/ // © ClassicScott //@version=5 // @description Just a lil' library of volatility bands that I use in some scripts library("MyVolatilityBands") // @function Bollinger Bands // @param src float // @param lkbk int // @param mult float // @param basis float // @param band_width float // @returns Bollinger Bands with an outer band of varying thickness adjustable by the band_width input export bollingerbands(float src, int lkbk, float mult, float basis, float band_width) => dev = mult * ta.stdev(src, lkbk) upper = basis + dev lower = basis - dev width = (upper - lower) / band_width inner_upper = upper - width inner_lower = lower + width [basis, upper, lower, inner_upper, inner_lower] // @function Donchian Channels // @param src float // @param lkbk int // @param band_width float // @returns Donchian Channels with an outer band of varying thickness adjustable by the band_width input export donchianchannels(float src, int lkbk, float band_width) => upper = ta.highest(src, lkbk) lower = ta.lowest(src, lkbk) width = (upper - lower) / band_width inner_upper = upper - width inner_lower = lower + width basis = math.avg(upper, lower) [basis, upper, lower, inner_upper, inner_lower] // @function Double Half Donchian Channels // @param src float // @param lkbk int // @param divisor float // @returns two adjustable bases calculated using Donchian Channels calculation that can act as a measure of volatility for below chart indicators export doublehalfdonchianchannels(float src, int lkbk, float divisor) => _high = ta.highest(src, lkbk) _low = ta.lowest(src, lkbk) high_vol = _high / divisor low_vol = _low / divisor [high_vol, low_vol] // @function Keltner Channels // @param src float // @param lkbk int // @param mult float // @param atr_lkbk int // @param basis float // @param band_width float // @returns Keltner Channels with an outer band of varying thickness adjustable by the band_width input export keltnerchannels(int atr_lkbk, float mult, float basis, float band_width) => upper = basis + ta.atr(atr_lkbk) * mult lower = basis - ta.atr(atr_lkbk) * mult width = (upper - lower) / band_width inner_upper = upper - width inner_lower = lower + width [basis, upper, lower, inner_upper, inner_lower]
LYGLibrary
https://www.tradingview.com/script/ujM2JW4W-LYGLibrary/
liyugen
https://www.tradingview.com/u/liyugen/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © liyugen // Last Updated: 16 June, 2023 // @version=5 // @description A collection of custom tools & utility functions commonly used with my scripts library("LYGLibrary") // --- 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 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 barInSession2(simple string sess, bool useFilter = true) => na(time(timeframe.period, sess + ":1234567", "Asia/Shanghai")) == 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
JavaScript-style Debug Console
https://www.tradingview.com/script/bnbjXk0D-JavaScript-style-Debug-Console/
algotraderdev
https://www.tradingview.com/u/algotraderdev/
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/ // © algotraderdev // @version=5 // @description JavaScript-style Debug Console for Pine Coders library("Console", overlay = true) // Enum for log levels. int LOG_LEVEL_DEBUG = 0 int LOG_LEVEL_INFO = 1 int LOG_LEVEL_WARN = 2 int LOG_LEVEL_ERROR = 3 // @variable The index of the column containing timestamps in the console table. int COLUMN_TIMESTAMP = 0 // @variable The index of the column containing log messages in the console table. int COLUMN_MSG = 1 // @function Returns a human-readable timestamp. // @returns The formatted timestamp. timestamp() => switch timeframe.isdwm => str.format_time(time, 'yyyy-MM-dd', syminfo.timezone) timeframe.isseconds => str.format_time(time, 'yyyy-MM-dd HH:mm:ss', syminfo.timezone) => str.format_time(time, 'yyyy-MM-dd HH:mm', syminfo.timezone) // @type A formatted log message to display in the console, including a timestamp. // @field timestamp The formatted timestamp for the log message. // @field level The log level. // @field msg The message to display. export type Log string timestamp int level string msg // @type A class representing a simple counter for a label. // @field label The label to track. // @field count The count for the label. export type Counter string label int count // @type A debug console to display logs to the user. // @field table The underlying table object to display the logs. // @field logs An array of `Log` objects containing timestamped log messages to display. // @field max_rows An integer specifying the maximum number of rows to display in the console. // @field width int The width of the message column as a % of the indicator's visual space. // @field text_size The size of the text in the console. Same as what the `table.cell` function accepts at // https://www.tradingview.com/pine-script-reference/v5/#fun_table%7Bdot%7Dcell // @field timestamp_color The color of the timestamp column. // @field info_text_color The color of the `INFO` log messages. // @field debug_text_color The color of the `DEBUG` log messages. // @field warn_text_color The color of the `WARN` log messages. // @field error_text_color The color of the `ERROR` log messages. // @field indent A string representing the current indentation to use when displaying new logs. // @field isHidden Whether the console is hidden. export type Console table table Log[] logs Counter[] counters int max_rows int width string text_size color timestamp_color color info_text_color color debug_text_color color warn_text_color color error_text_color string indent = '' bool isHidden = false // Gets the appropriate color for a log message based on its severity level. // @param log The Log object containing the severity level of the message. // @returns color The color code to apply to the message when displayed in the console. method _get_text_color(Console this, Log log) => switch log.level LOG_LEVEL_DEBUG => this.debug_text_color LOG_LEVEL_WARN => this.warn_text_color LOG_LEVEL_ERROR => this.error_text_color => this.info_text_color // @function Writes a `Log` object at a specified row index. // @param row_index The index of the row in which to write the log. // @param log The `Log` object to be written to the specified row. method _write(Console this, int row_index, Log log) => if not this.isHidden this.table.cell(COLUMN_TIMESTAMP, row_index, log.timestamp, text_color = this.timestamp_color, text_size = this.text_size, text_halign = text.align_left, text_valign = text.align_top, text_font_family = font.family_monospace) this.table.cell(COLUMN_MSG, row_index, log.msg, width = this.width, text_color = this._get_text_color(log), text_size = this.text_size, text_halign = text.align_left, text_valign = text.align_top, text_font_family = font.family_monospace) // @function Flushes all the stored logs to the underlying table. method _flush(Console this) => for [i, l] in this.logs this._write(i, l) // @function Writes a message with the specified level to the console. // @param level The log level. // @param msg The message to write to the console. method _log(Console this, int level, string msg) => // If the number of existing logs in the console exceeds the 'max_rows' limit, the oldest // log is removed to make room for the new log. if this.logs.size() == this.max_rows this.logs.shift() this._flush() Log l = Log.new(timestamp(), level, this.indent + msg) this._write(this.logs.size(), l) this.logs.push(l) // @function Writes a message to the console at the `DEBUG` log level. // @param msg The message to write to the console. export method debug(Console this, string msg) => this._log(LOG_LEVEL_DEBUG, msg) // @function Writes a message to the console at the `INFO` log level. // @param msg The message to write to the console. export method info(Console this, string msg) => this._log(LOG_LEVEL_INFO, msg) // @function Writes a message to the console at the `INFO` log level. // @param msg The message to write to the console. export method log(Console this, string msg) => this.info(msg) // @function Writes a message to the console at the `WARN` log level. // @param msg The message to write to the console. export method warn(Console this, string msg) => this._log(LOG_LEVEL_WARN, msg) // @function Writes a message to the console at the `ERROR` log level. // @param msg The message to write to the console. export method error(Console this, string msg) => this._log(LOG_LEVEL_ERROR, msg) // @function Clears the underlying table, without impacting the logs. method _clearTable(Console this) => this.table.clear(0, 0, 1, this.logs.size() - 1) // @function Clears all content from the console. export method clear(Console this) => this._clearTable() this.logs.clear() // @function Hides the console. export method hide(Console this) => this._clearTable() this.isHidden := true // @function Shows the console. export method show(Console this) => this.isHidden := false this._flush() // @function Creates a new inline group in the console, causing any subsequent console messages // to be indented by an additional level, until `groupEnd()` is called. export method group(Console this) => this.indent += ' ' // @function Exits the current inline group in the console. export method groupEnd(Console this) => if str.length(this.indent) > 0 this.indent := str.substring(this.indent, 4) // @function Gets the counter for the specified label. // @param label The label to get the counter for. // @returns The counter for the specified label, or a newly created counter if one does not already exist. method _getCounter(Console this, string label) => Counter counter = for counter in this.counters if counter.label == label counter if na(counter) counter := Counter.new(label, 0) this.counters.push(counter) counter // @function Logs the number of times that this particular call to `count()` has been called. // @param label If supplied, `count()` outputs the number of times it has been called with that label. export method count(Console this, string label = 'default') => Counter counter = this._getCounter(label) counter.count += 1 this.info(str.format('{0}: {1}', counter.label, counter.count)) // @function Resets counter used with `count()`. // @param label The label for which the count will be reset to 0. export method countReset(Console this, string label = 'default') => Counter counter = this._getCounter(label) counter.count := 0 // @function Writes an error message to the console if the assertion is false. // If the assertion is true, nothing happens. // @param assertion A boolean assertion. // @param msg The message to write to the console if the assertion is false. export method assert(Console this, bool assertion, string msg) => if not assertion this.error('Assertion failed: ' + msg) // @function Creates a new `Console` instance. // @param position The position of the console. Same as what the `table.new` function accepts at // https://www.tradingview.com/pine-script-reference/v5/#fun_table{dot}new // @param max_rows The maximum number of rows to display. // @param width The width of the message column as a % of the indicator's visual space. // @param text_size The size of the text in the console. Same as what the `table.cell` function accepts at // https://www.tradingview.com/pine-script-reference/v5/#fun_table%7Bdot%7Dcell // @param background_color The background color of the console. // @param timestamp_color The color of the timestamp column. // @param info_text_color The color of the `INFO` log messages. // @param debug_text_color The color of the `DEBUG` log messages. // @param warn_text_color The color of the `WARN` log messages. // @param error_text_color The color of the `ERROR` log messages. export new( string position = position.bottom_right, int max_rows = 50, int width = 0, string text_size = size.normal, color background_color = #000000CC, color timestamp_color = #AAAAAA, color info_text_color = #DDDDDD, color debug_text_color = #AAAAAA, color warn_text_color = #FFEB3B, color error_text_color = #ff3c00) => table t = table.new( position = position, columns = 2, rows = max_rows, bgcolor = background_color, frame_width = 0, border_width = 0) Console.new( table = t, logs = array.new<Log>(), counters = array.new<Counter>(), max_rows = max_rows, width = width, text_size = text_size, timestamp_color = timestamp_color, info_text_color = info_text_color, debug_text_color = debug_text_color, warn_text_color = warn_text_color, error_text_color = error_text_color) // ====================================================================== // Example // ====================================================================== var console = new() if barstate.islast console.debug('This is a DEBUG message') console.log('This is an INFO message') console.warn('This is a WARN message') console.error('This is an ERROR message')
toString
https://www.tradingview.com/script/2vqK0lGM-toString/
moebius1977
https://www.tradingview.com/u/moebius1977/
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/ // © moebius1977 //@version=5 // @description Contains toString/toS conversion methods for int/float/bool/string/line/label/box and arrays and matrices thereof. Also contains a string wraping function. library("toString", overlay = true) // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // HELPER FUNCTIONS //{ // --------- getXloc( label/line/box ) ---------{ // true if line or box have xloc.bar_time (by 1 Jan 1971 UNIX time was already 31,528,800) // overloaded for box and line // @function returns xloc xloc.bar_index or xloc.bar_time true if line/box/label have xloc.bar_time (by 1 Jan 1971 UNIX time was already 31,528,800) export method getXloc(line _d) => na(line.get_x1(_d)) ? na : line.get_x1(_d) > 1000000 ? xloc.bar_time : xloc.bar_index // @function true if line/box/label have xloc.bar_time (by 1 Jan 1971 UNIX time was already 31,528,800) export method getXloc(box _d) => na(box.get_left(_d)) ? na : box.get_left(_d) > 1000000 ? xloc.bar_time : xloc.bar_index // @function true if line/box/label have xloc.bar_time (by 1 Jan 1971 UNIX time was already 31,528,800) export method getXloc(label _d) => na(label.get_x(_d)) ? na : label.get_x(_d) > 1000000 ? xloc.bar_time : xloc.bar_index // END OF f_getXloc() } // --------- xlocFormat()--------- { // @function for str.format("bar/time = {0" + xlocFormat(xloc)", _x1), where _x1 is either bar index or time // @param _xloc (series string) xloc.bar_index or xloc.bar_time xlocFormat(string _xloc) => _xloc == xloc.bar_index ? "}" : ", time, dd.MM.yy HH:mm:ss}" // END OF xlocFormat } //----------- _type_item () -----------{ // @function Returns type of variable or the element for array/matrix. // ``` // int n = 0 // n._type_item() // returns "int" // arr = array.new<int>() // arr._type_item() // returns "int" // ``` method _type_item(int _temp)=> na(_temp) ? 'int' : 'int' method _type_item(float _temp)=> na(_temp) ? 'float' : 'float' method _type_item(bool _temp)=> na(_temp) ? 'bool' : 'bool' method _type_item(string _temp)=> na(_temp) ? 'string' : 'string' method _type_item(color _temp)=> na(_temp) ? 'color' : 'color' method _type_item(line _temp)=> na(_temp) ? 'line' : 'line' method _type_item(label _temp)=> na(_temp) ? 'label' : 'label' method _type_item(box _temp)=> na(_temp) ? 'box' : 'box' method _type_item(table _temp)=> na(_temp) ? 'table' : 'table' method _type_item(linefill _temp)=> na(_temp) ? 'linefill' : 'linefill' method _type_item(int [] _temp)=> na(_temp) ? 'int' : 'int' method _type_item(float [] _temp)=> na(_temp) ? 'float' : 'float' method _type_item(bool [] _temp)=> na(_temp) ? 'bool' : 'bool' method _type_item(string [] _temp)=> na(_temp) ? 'string' : 'string' method _type_item(color [] _temp)=> na(_temp) ? 'color' : 'color' method _type_item(line [] _temp)=> na(_temp) ? 'line' : 'line' method _type_item(label [] _temp)=> na(_temp) ? 'label' : 'label' method _type_item(box [] _temp)=> na(_temp) ? 'box' : 'box' method _type_item(table [] _temp)=> na(_temp) ? 'table' : 'table' method _type_item(linefill [] _temp)=> na(_temp) ? 'linefill' : 'linefill' method _type_item(matrix <int> _temp)=> na(_temp) ? 'int' : 'int' method _type_item(matrix <float> _temp)=> na(_temp) ? 'float' : 'float' method _type_item(matrix <bool> _temp)=> na(_temp) ? 'bool' : 'bool' method _type_item(matrix <string> _temp)=> na(_temp) ? 'string' : 'string' method _type_item(matrix <color> _temp)=> na(_temp) ? 'color' : 'color' method _type_item(matrix <line> _temp)=> na(_temp) ? 'line' : 'line' method _type_item(matrix <label> _temp)=> na(_temp) ? 'label' : 'label' method _type_item(matrix <box> _temp)=> na(_temp) ? 'box' : 'box' method _type_item(matrix <table> _temp)=> na(_temp) ? 'table' : 'table' method _type_item(matrix <linefill>_temp)=> na(_temp) ? 'linefill' : 'linefill' // END OF _type_item } // --------- nzs()--------- { // @function Analogue of nz but for strings. Returns "" is _s is na. export nzs(string _s) => na(_s) ? "" : _s // END OF nzs() } // --------- method wrap()--------- { // @function Wraps the string to wrap_width adding breaker_prefix to the end of each line (before "\n") and breaker_postfix to the beginning of each line (after "\n")". // @param wrap_width (series int) Width of each line (chars). // @param breaker_prefix (series string) (Optional) Text to add at the end of each line. (Default = "") export method wrap(string this, int wrap_width, string breaker_prefix = "", string breaker_postfix = "") => l = str.length(this) breaker = breaker_prefix + "\n" + breaker_postfix breaksN = int(l / wrap_width) // adding breakers may lead to overflow. Truncate and add [...] in this case resultL = l + breaksN * (str.length(breaker_prefix)+1) adjBreaksN = resultL > 4096 ? int ( (4096 - 5) / (wrap_width +str.length(breaker_prefix)+1) )-1 : breaksN // adjBreaksN = breaksN s = "" for i = 0 to adjBreaksN s += str.substring(this, (wrap_width) * i, math.min(wrap_width * (i+1), l)) + (i == adjBreaksN ? "" : breaker) s += resultL > 4096 ? "[...]" : "" // END OF wrap() } // END OF HELPER FUNCTIONS //} // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // -------------------- ++++++++++++++++++++++ ---- ---- ---- ---- // ---- ---- ---- ---- ===== TO STRING ==== -------------------- // ---- ---- ---- ---- ++++++++++++++++++++++ ---- ---- ---- ---- // ====== ======== ====== ======== ======== // ----- toS(bool/int/.../line/label/...) ------ { // --- parse_format() helper --- { // @function Helper function fo toS, toStringAr, toStringMx parse_format(string format= "", string _type = "number") => switch format // --- number --- "" => "{0}" "number" => "{0}" "0" => "{0, number, 0 }" "0.0" => "{0, number, 0.0 }" "0.00" => "{0, number, 0.00 }" "0.000" => "{0, number, 0.000 }" "0.0000" => "{0, number, 0.0000 }" "0.00000" => "{0, number, 0.00000 }" "0.000000" => "{0, number, 0.000000 }" "0.0000000" => "{0, number, 0.0000000}" // --- date --- "date" => "{0, date, dd.MM.YY}" "date : time" => "{0, date, dd.MM.YY} : {0, time, HH.mm.ss}" "dd.MM" => "{0, date, dd:MM}" "dd" => "{0, date, dd}" // --- time --- "time" => "{0, time, HH:mm:ss}" "HH:mm" => "{0, time, HH:mm}" "mm:ss" => "{0, time, mm:ss}" "date time" => "{0, date, dd.MM.YY} {0, time, HH.mm.ss}" "date, time" => "{0, date, dd.MM.YY}, {0, time, HH.mm.ss}" "date,time" => "{0, date, dd.MM.YY},{0, time, HH.mm.ss}" "date\ntime" => "{0, date, dd.MM.YY}\n{0, time, HH.mm.ss}" => if na(format) "{0}" // else if str.contains(format, "date") or str.contains(format, "time") // s1 = str.replace(format, "date", "{0, date, dd.MM.YY}") // s1 := str.replace(s1, "time", "{0, time, HH.mm.ss}") else format // END OF parse_format() helper } // "toString()"" method name did not work due to some naming bug in PineScript (reported) // ------------ toS( int, format ) ------------ { // @function Same as str.format() with additional "format" options: // - --- Number formats --- // - "number" // - "0" // - "0.0" // - "0.00" // - "0.000" // - "0.0000" // - "0.00000" // - "0.000000" // - "0.0000000" // - --- Date formats --- // - "date" // - "date : time" // - "dd.MM" // - "dd" // - --- Time formats --- // - "time" // - "HH:mm" // - "mm:ss" // - "date time" // - "date, time" // - "date,time" export method toS(int val, string format = "") => str.format(nzs(format)=="" ? "{0}" : parse_format(format), val) // END OF toS( int, _format ) ------------ } // ------------ toS( float, format ) ------------ { // @function Same as str.format() with additional "format" options: // - --- Number formats --- // - "number" // - "0" // - "0.0" // - "0.00" // - "0.000" // - "0.0000" // - "0.00000" // - "0.000000" // - "0.0000000" // - --- Date formats --- // - "date" // - "date : time" // - "dd.MM" // - "dd" // - --- Time formats --- // - "time" // - "HH:mm" // - "mm:ss" // - "date time" // - "date, time" // - "date,time" export method toS(float val, string format = "") => str.format(nzs(format)=="" ? "{0}" : parse_format(format), val) // END OF toS( float, _format ) ------------ } // ------------ toS( bool, format ) ------------ { // @function Same as str.format() for int/float/bool/string export method toS(bool val, string dummy_format_not_used = "") => dummy_format_not_used == dummy_format_not_used ? str.tostring(val) : "" // export method toS(bool val, string format = "") => str.format(nzs(format)=="" ? "{0}" : parse_format(format), val) // END OF toS( bool, _format ) ------------ } // ------------ toS( string, format ) ------------ { // @function Same as str.format() for int/float/bool/string export method toS(string val, string format = "") => str.format(nzs(format)=="" ? "{0}" : parse_format(format), val) // END OF toS(string, _format ) ------------ } // ------------ toS( line, format ) ------------ { // --- parse_format_line() helper --- { parse_format_line(string format = "") => switch format "" => "({0}, {1}) - ({2}, {3})" // x1, y1, x2, y2 => s = format s := str.replace_all(s, "x1", "{0}") s := str.replace_all(s, "y1", "{1}") s := str.replace_all(s, "x2", "{2}") s := str.replace_all(s, "y2", "{3}") // END OF parse parse_format_line } // @function Returns line's main data as a string. // @param format (string) If empty returns coordinates as "(x1, y1) - (x2, y2)". Otherwise replaces "x1", "x2", "y1", "y2" in `format` string by values. export method toS(line ln, string format = "") => _sXy = "line is na" if not na(ln) _format = parse_format_line(format) _xloc = ln.getXloc() _sXFormat = xlocFormat(_xloc) _format := str.replace_all(_format, "{0}", "{0" +_sXFormat) _format := str.replace_all(_format, "{2}", "{2" +_sXFormat) // line below is highlighted as error by editor but still compiles fine _sXy := str.format(_format , ln.get_x1() , ln.get_y1() , ln.get_x2() , ln.get_y2() ) _sXy // END OF toS() } // ------------ toS( label, format ) ------------ { // --- parse_format_label() helper --- { parse_format_label(string format = "") => switch format "" => "({0}, {1}): text = {2}" // x1, y1, text => s = format s := str.replace_all(s, "x1", "{0}") s := str.replace_all(s, "y1", "{1}") s := str.replace_all(s, "txt", "{2}") // END OF parse_format_label parse_format_line } // @function Returns label's main data as a string. // @param format (string) If empty returns coordinates and text (if _printText) as "(x, y): text = text". Otherwise replaces "x1", "x2", "txt" in `format` string by values. export method toS(label lbl, string format = "") => // , bool printText = false) => // had to remove this arg because of internal server error _sXy = "lbl is na" if not na(lbl) // _format = format == "" ? (printText == false ? "(x1, y1)" : "(x1, y1): text = txt") : format _format = format // BUG!: THIS CAUSES INTERNAL SERVER ERROR // if printText and _format == "" // _format := "(x1, y1): txt" // else // _format := "(x1, y1)" _format := parse_format_label(format) _xloc = lbl.getXloc() _sXFormat = xlocFormat(_xloc) _format := str.replace_all(_format, "{0}", "{0" +_sXFormat) // line below is highlighted as error by editor but still compiles fine _sXy := str.format(_format , lbl.get_x() , lbl.get_y() , lbl.get_text() ) _sXy // END OF toS } // ------------ toS( box, format ) ------------ { // --- parse_format_box() helper --- { parse_format_box(string format = "") => switch format "" => "({0}, {1}) - ({2}, {3})" // x1, y1, x2, y2 => s = format s := str.replace_all(s, "x1", "{0}") s := str.replace_all(s, "y1", "{1}") s := str.replace_all(s, "x2", "{2}") s := str.replace_all(s, "y2", "{3}") // s := str.replace_all(s, "txt", "{4}") // END OF parse_format_box } // @function Returns box's main data as a string. // @param format (string) If empty returns coordinates as "(x1, y1) - (x2, y2)". Otherwise replaces "x1", "x2", "y1", "y2" in `format` string by values. export method toS(box bx, string format = "") => _sXy = "line is na" if not na(bx) _format = parse_format_box(format) _xloc = bx.getXloc() _sXFormat = xlocFormat(_xloc) _format := str.replace_all(_format, "{0}", "{0" +_sXFormat) _format := str.replace_all(_format, "{2}", "{2" +_sXFormat) // line below is highlighted as error by editor but still compiles fine _sXy := str.format(_format , bx.get_left() , bx.get_top() , bx.get_right() , bx.get_bottom() // , bx.get_text() ) _sXy // END OF toS() } // END OF toS(bool/int/....) } // ====== ======== ====== ======== ======== // ====== ======== ====== ======== ======== // ----- toS(array) ------ { //----------- toS(<string>[] this, _from, _to, _separator, _format, _truncate) -----------{ // @function Like join() but with string length limit. Joins elements into readable string (length capped at 4000, truncating the end or beg) export method toS(string[] this, int _from = na , int _to = na, string _separator = ", ", bool _showIDs = false, string _format = na, bool _truncate_left = false, int _size_limit = 4000) => string _s = "" if this.size() > 0 _to1 = na(_to) ? array.size(this)-1 : math.min(_to,array.size(this)-1) _from1 = na(_from) ? 0 : math.max(_from, 0) __format = na(_format) ? _showIDs ? "{0}: {1}" : "{1}" : _format __size_limit = math.min(4095, _size_limit) if _truncate_left for _i = _to1 to _from1 _p = array.get(this, _i) _sp = str.format(__format, _i, _p) if str.length(_s) + str.length(_sp) < __size_limit _s := _sp + (_i == _to1 ? "" : _separator) + _s else break else for _i = _from1 to _to1 _p = array.get(this, _i) _sp = str.format(__format, _i, _p) if str.length(_s) + str.length(_sp) < __size_limit _s := _s + (_i == _from1 ? "" : _separator) + _sp else break _s // END OF toS (string []) } // ^^^ END OF toStringAr / toStringMx (array) ^^^ } // ====== ======== ====== ======== ======== // ====== ======== ====== ======== ======== // ----- toStringAr() group ------ { // --- _toStringAr() helper--- { // @function Applies toS to each of the elements (int/float/bool/string) _toStringAr(arr, string format = na) => if na(arr) runtime.error("toStringAr: array is na") sz = arr.size() if sz > 0 arS = array.new<string>(sz,na) for i = 0 to sz-1 arS.set(i, arr.get(i).toS(format)) arS // END OF _toStringAr() helper} // ------------ toStringAr( bool, format ) ------------ { // @function Returns a string array made of original array items converted to string using toS() using `format` string. // @param format (string) Not used. export method toStringAr(bool [] arr, string dummy_format_not_used = na) => _toStringAr(arr, dummy_format_not_used) // END OF toStringAr( bool, _format ) ------------ } // ------------ toStringAr( int, format ) ------------ { // @function Returns a string array made of original array items converted to string using toS() using `format` string. // - --- Number formats --- // - "number" // - "0" // - "0.0" // - "0.00" // - "0.000" // - "0.0000" // - "0.00000" // - "0.000000" // - "0.0000000" // - --- Date formats --- // - "date" // - "date : time" // - "dd.MM" // - "dd" // - --- Time formats --- // - "time" // - "HH:mm" // - "mm:ss" // - "date time" // - "date, time" // - "date,time" export method toStringAr(int [] arr, string format = na) => _toStringAr(arr, format) // END OF toStringAr( int, _format ) ------------ } // ------------ toStringAr( float, format ) ------------ { // @function Returns a string array made of original array items converted to string using toS() using `format` string. // - --- Number formats --- // - "number" // - "0" // - "0.0" // - "0.00" // - "0.000" // - "0.0000" // - "0.00000" // - "0.000000" // - "0.0000000" // - --- Date formats --- // - "date" // - "date : time" // - "dd.MM" // - "dd" // - --- Time formats --- // - "time" // - "HH:mm" // - "mm:ss" // - "date time" // - "date, time" // - "date,time" export method toStringAr(float [] arr, string format = na) => _toStringAr(arr, format) // END OF toStringAr( float, _format ) ------------ } // ------------ toStringAr( string, format ) ------------ { // @function Returns a string array made of original array items converted to string using toS() using `format` string. export method toStringAr(string [] arr, string format = na) => _toStringAr(arr, format) // END OF toStringAr( string, _format ) ------------ } // ------------ toStringAr( line, format ) ------------ { // @function Returns a string array made of original array items converted to string with toS(). // @param format (string) If empty returns coordinates as "(x1, y1) - (x2, y2)". Otherwise replaces "x1", "x2", "y1", "y2" in `format` string by values. export method toStringAr(line [] arr, string format = na) => _toStringAr(arr, format) // END OF toStringAr( bolineol, _format ) ------------ } // ------------ toStringAr( label, format ) ------------ { // @function Returns a string array made of original array items converted to string with toS(). // @param format (string) If empty returns coordinates and text (if _printText) as "(x, y): text = text". Otherwise replaces "x1", "x2", "txt" in `format` string by values. export method toStringAr(label [] arr, string format = na) => _toStringAr(arr, format) // END OF toStringAr( label, _format ) ------------ } // ------------ toStringAr( box, format ) ------------ { // @function Returns a string array made of original array items converted to string with toS(). // @param format (string) If empty returns coordinates as "(x1, y1) - (x2, y2)". Otherwise replaces "x1", "x2", "y1", "y2" in `format` string by values. export method toStringAr(box [] arr, string format = na) => _toStringAr(arr, format) // END OF toStringAr( box, _format ) ------------ } // ^^^ END OF toStringAr group ^^^ } // ====== ======== ====== ======== ======== // ====== ======== ====== ======== ======== // ----- toStringMx() group ------ { // --- _toStringMx() helper --- { // @function Applies toS to each of the elements _toStringMx(mx, string format = "") => if na(mx) runtime.error("toStringMx: matrix is na") rs = mx.rows() cs = mx.columns() if rs > 0 mxS = matrix.new<string>(rs, cs ,na) while rs > 0 rs-=1 cs1 = cs while cs1 >0 cs1-=1 mxS.set( rs, cs1, mx.get(rs, cs1).toS(format) ) mxS // END OF _toStringMx() } // --- method _toStringMx() --- { // @function Returns a string array made of original array items converted to string using `str.format()` using `format` string. [] // - --- Number formats --- // - "number" // - "0" // - "0.0" // - "0.00" // - "0.000" // - "0.0000" // - "0.00000" // - "0.000000" // - "0.0000000" // - --- Date formats --- // - "date" // - "date : time" // - "dd.MM" // - "dd" // - --- Time formats --- // - "time" // - "HH:mm" // - "mm:ss" // - "date time" // - "date, time" // - "date,time" // @function Returns a string matrix made of original matrix items converted to string using toS() using `format` string. (see format options in toS description) export method toStringMx(matrix<bool> mx, string format = "") => _toStringMx(mx, format) // @function Returns a string matrix made of original matrix items converted to string using toS() using `format` string. (see format options in toS description) export method toStringMx(matrix<int> mx, string format = "") => _toStringMx(mx, format) // @function Returns a string matrix made of original matrix items converted to string using toS() using `format` string. (see format options in toS description) export method toStringMx(matrix<float> mx, string format = "") => _toStringMx(mx, format) // @function Returns a string matrix made of original matrix items converted to string using toS() using `format` string. (see format options in toS description) export method toStringMx(matrix<string> mx, string format = "") => _toStringMx(mx, format) // @function Returns a string matrix made of original matrix items converted to string with toS(). // @param format (string) If empty returns coordinates as "(x1, y1) - (x2, y2)". Otherwise replaces "x1", "x2", "y1", "y2" in `format` string by values. export method toStringMx(matrix<line> mx, string format = "") => _toStringMx(mx, format) // @function Returns a string matrix made of original matrix items converted to string with toS(). // @param format (string) If empty returns coordinates and text (if _printText) as "(x, y): text = text". Otherwise replaces "x1", "x2", "txt" in `format` string by values. export method toStringMx(matrix<label> mx, string format = "") => _toStringMx(mx, format) // @function Returns a string matrix made of original matrix items converted to string with toS(). // @param format (string) If empty returns coordinates as "(x1, y1) - (x2, y2)". Otherwise replaces "x1", "x2", "y1", "y2" in `format` string by values. export method toStringMx(matrix<box> mx, string format = "") => _toStringMx(mx, format) // END OF method _toStringMx() } // ^^^ END OF toStringAr / toStringMx () ^^^ } // ====== ======== ====== ======== ======== // ++++++++++++++ ++++++++++++++ ---- ++++++++++++++ ++++++++++++++ // || || || || || || || DEMO || || || || || || || { if bar_index == last_bar_index - 1 b = true i = 1 f = 1. s = "aaa" lnB = line.new(bar_index - 3, low[3], bar_index, low, color = color.yellow) lnT = line.new(time[6], low[6], time[3], low[3], color = color.rgb(255, 148, 134), xloc = xloc.bar_time) lblB = label.new(bar_index,high, "test", color = color.yellow) lblT = label.new(time[6],high[6], "test", color = color.yellow, xloc = xloc.bar_time) bxB = box.new(bar_index - 3, low[3], bar_index,low, text = "box", bgcolor = color.rgb(170, 237, 246, 57)) bxT = box.new(time[6], low[6], time[3], low[3], text = "box", bgcolor = color.rgb(243, 213, 169, 59), xloc = xloc.bar_time) arB = array.from(true,false) arI = array.from(10,20) arF = array.from(30,40.) arS = array.from("AAA","BBB") arLn = array.from(lnB,lnT) arLbl = array.from(lblB,lblT) arBx = array.from(bxB,bxT) arT = array.from(time,time[1]) mxF = matrix.new<float>() mxF.add_row(0, arI) mxF.add_row(0, arF) mxFS = mxF.toStringMx("0.000") arMxFS1 = mxFS.row(1).join(", ") txt = "bool[]: toStringAr(): " + arB.toStringAr() .join(", ") txt += "\n" + "int[] toStringAr(): " + arI.toStringAr() .join(", ") txt += "\n" + "float[] toStringAr(): " + arF.toStringAr("0.00") .join(", ") txt += "\n" + "string[] toStringAr(): " + arS.toStringAr() .join(", ") txt += "\n" + "int[] time toStringAr(\"date\\ntime\")\n: " + arT.toStringAr("date\ntime") .join(", ") txt += "\n" + "int[] time toStringAr(\"{0, date, dd} {0, time, HH:mm:ss}\"):\n " + arT.toStringAr("{0, date, dd} {0, time, HH:mm:ss}") .join(", ") txt += "\n --------------------------------- " txt += "\n" + "line[] toStringAr():\n" + arLn.toStringAr() .join(",\n ") txt += "\n --------------------------------- " txt += "\n" + "line[] toStringAr(<x1/x2>-<y1/y2>):\n" + arLn.toStringAr("<x1/x2>-<y1/y2>") .join(",\n ") txt += "\n --------------------------------- " txt += "\n" + "label[] toStringAr():\n" + arLbl.toStringAr() .join(",\n ") txt += "\n --------------------------------- " txt += "\n" + "label[] toStringAr(<x1,y1>:txt):\n" + arLbl.toStringAr("<x1,y1>:txt") .join(",\n ") txt += "\n --------------------------------- " txt += "\n" + "box[] toStringAr() wrapped:\n" + arBx.toStringAr() .join(", ").wrap(24, "", "> ") txt += "\n --------------------------------- " txt += "\n" + "box[] toStringAr(<x1/x2><y1/y2>):\n" + arBx.toStringAr("<x1/x2><y1/y2>") .join(",\n ") txt += "\n" + "matrix<int> toStringMx():\n" + arMxFS1 t = table.new(position.bottom_center, 1, 1, bgcolor = color.rgb(209, 251, 159)) table.cell(t,0,0, text_halign = text.align_left) table.cell_set_text(t, 0, 0, txt) plotchar(bar_index, "bar_index", "", location = location.bottom) plotchar(array.size(table.all), "table.all size", "", location = location.bottom) plotchar(array.size(line.all), "line.all size", "", location = location.bottom) plotchar(array.size(label.all), "label.all size", "", location = location.bottom) // END OF DEMO } // ++++++++++++++ ++++++++++++++ ---- ++++++++++++++ ++++++++++++++
Mad_MATH
https://www.tradingview.com/script/5kms7jpa-Mad-MATH/
djmad
https://www.tradingview.com/u/djmad/
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/ // © djmad // included and modified code from HPotter // included code from peacefulLizard50262 // Mathematics from Pafnuti Lwowitsch Tschebyschow (1821–1894) // Mathematics from John F. Ehlers // Mathematics from alexgrover (arma/a2rma) //@version=5 // @description this is a mathematics library where i store useful kernels, filters and selectors library("MAD_MATH") // Ehlers Army Knife { //SWISS ARMY KNIFE INDICATOR by John F. Ehlers //exported to single functions, digged for hours to find most of them, still missing the fourier :-( // @function Calculates the Ehlers Exponential Moving Average (Ehlers_EMA) // @param _src The source series for calculation // @param _length The length for the Ehlers EMA // @returns The Ehlers EMA value export Ehlers_EMA(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, a1 = 0.0, alpha = 0.0 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length alpha := (math.cos(cycle) + math.sin(cycle) - 1) / math.cos(cycle) b0 := alpha a1 := 1 - alpha _Input = _src _Output = 0.0 _Output := (c0 * (b0 * _Input)) + (a1 * nz(_Output[1])) // @function Calculates the Ehlers Gaussian Filter // @param _src The source series for calculation // @param _length The length for the Ehlers Gaussian Filter // @returns The Ehlers Gaussian Filter value export Ehlers_Gaussian(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, a1 = 0.0, a2 = 0.0, alpha = 0.0, beta = 0.0 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length beta := 2.415 * (1 - math.cos(cycle)) alpha := -beta + math.sqrt((beta * beta) + (2 * beta)) c0 := alpha * alpha a1 := 2 * (1 - alpha) a2 := -(1 - alpha) * (1 - alpha) _Input = _src _Output = 0.0 _Output := (c0 * (b0 * _Input)) + (a1 * nz(_Output[1])) + (a2 * nz(_Output[2])) // @function Calculates the Ehlers Supersmoother // @param _src The source series for calculation // @param _length The length for the Ehlers Supersmoother // @returns The Ehlers Supersmoother value export Ehlers_Supersmoother(float _src = close, simple int _length = 20) => float _Output = na a1 = math.exp(-math.sqrt(2) * math.pi / _length) b1 = 2 * a1 * math.cos(math.sqrt(2) * math.pi / _length) c3 = -math.pow(a1, 2) c2 = b1 c1 = 1 - c2 - c3 _Output := c1 * _src + c2 * nz(_Output[1], _src[1]) + c3 * nz(_Output[2], _src[2]) // @function Calculates the Ehlers Simple Moving Average (SMA) Fast // @param _src The source series for calculation // @param _length The length for the Ehlers SMA Fast // @returns The Ehlers SMA Fast value export Ehlers_SMA_fast(float _src = close, simple int _length = 20) => c0 = 1.0, c1 = 0.0, b0 = 1.0, a1 = 0.0 c1 := 1 / _length b0 := 1 / _length a1 := 1 _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input))) + (a1 * nz(_Output[1])) - (c1 * nz(_Input[_length])) // @function Calculates the Ehlers Exponential Moving Average (EMA) Fast // @param _src The source series for calculation // @param _length The length for the Ehlers EMA Fast // @returns The Ehlers EMA Fast value export Ehlers_EMA_fast(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, a1 = 0.0, alpha = 0.0 alpha := 2/(_length+1) b0 := alpha a1 := 1 - alpha _Input = _src _Output = 0.0 _Output := (c0 * (b0 * _Input)) + (a1 * nz(_Output[1])) // @function Calculates the Ehlers Relative Strength Index (RSI) Fast // @param _src The source series for calculation // @param _length The length for the Ehlers RSI Fast // @returns The Ehlers RSI Fast value export Ehlers_RSI_fast(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, a1 = 0.0, alpha = 0.0 alpha := 1 / _length b0 := alpha a1 := 1 - alpha _Input = _src _Output = 0.0 _Output := (c0 * (b0 * _Input)) + (a1 * nz(_Output[1])) // @function Calculates the Ehlers BandPass Filter // @param _src The source series for calculation // @param _length The length for the Ehlers BandPass Filter // @returns The Ehlers BandPass Filter value export Ehlers_Band_Pass_Filter(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, b2 = 0.0, a1 = 0.0, a2 = 0.0 alpha = 0.0, beta = 0.0, gamma = 0.0, delta = 0.1 // delta default to 0.1. Acceptable delta -- 0.05<d<0.5 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length beta := math.cos(2*pi / _length) gamma := 1 / math.cos(4*pi*delta / _length) // delta ^^ alpha := gamma - math.sqrt(gamma*gamma - 1) c0 := (1 - alpha) / 2 b2 := -1 a1 := beta*(1 + alpha) a2 := -alpha _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) + (b2 * nz(_Input[2])))) + (a1 * nz(_Output[1])) + (a2 * nz(_Output[2])) // @function Calculates the Ehlers Butterworth Filter // @param _src The source series for calculation // @param _length The length for the Ehlers Butterworth Filter // @returns The Ehlers Butterworth Filter value export Ehlers_Butterworth(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, b1 = 0.0, b2 = 0.0 a1 = 0.0, a2 = 0.0, alpha = 0.0, beta = 0.0 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length beta := 2.415 * (1 - math.cos(cycle)) alpha := -beta + math.sqrt((beta * beta) + (2 * beta)) c0 := alpha * alpha / 4 b1 := 2 b2 := 1 a1 := 2 * (1 - alpha) a2 := -(1 - alpha) * (1 - alpha) _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) + (b1 * nz(_Input[1])) + (b2 * nz(_Input[2])))) + (a1 * nz(_Output[1])) + (a2 * nz(_Output[2])) // @function Calculates the Ehlers Two-Pole Gaussian Filter // @param _src The source series for calculation // @param _length The length for the Ehlers Two-Pole Gaussian Filter // @returns The Ehlers Two-Pole Gaussian Filter value export Ehlers_Two_Pole_Gaussian_Filter(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, a1 = 0.0, a2 = 0.0 alpha = 0.0, beta = 0.0 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length beta := 2.415 * (1 - math.cos(cycle)) alpha := -beta + math.sqrt((beta * beta) + (2 * beta)) c0 := alpha * alpha a1 := 2 * (1 - alpha) a2 := -(1 - alpha) * (1 - alpha) _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) )) + (a1 * nz(_Output[1])) + (a2 * nz(_Output[2])) // @function Calculates the Ehlers Two-Pole Butterworth Filter // @param _src The source series for calculation // @param _length The length for the Ehlers Two-Pole Butterworth Filter // @returns The Ehlers Two-Pole Butterworth Filter value export Ehlers_Two_Pole_Butterworth_Filter(float _src = close, simple int _length = 20) => c0 = 1.0,b0 = 1.0,b1 = 0.0,b2 = 0.0,a1 = 0.0,a2 = 0.0 alpha = 0.0, beta = 0.0, gamma = 0.0 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length beta := 2.415 * (1 - math.cos(cycle)) alpha := -beta + math.sqrt((beta * beta) + (2 * beta)) c0 := alpha * alpha / 4 b1 := 2 b2 := 1 a1 := 2 * (1 - alpha) a2 := -(1 - alpha) * (1 - alpha) _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) + (b1 * nz(_Input[1])) + (b2 * nz(_Input[2])))) + (a1 * nz(_Output[1])) + (a2 * nz(_Output[2])) // @function Calculates the Ehlers Band Stop Filter // @param _src The source series for calculation // @param _length The length for the Ehlers Band Stop Filter // @returns The Ehlers Band Stop Filter value export Ehlers_Band_Stop_Filter(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, b1 = 0.0, b2 = 0.0, a1 = 0.0, a2 = 0.0, alpha = 0.0, beta = 0.0, gamma = 0.0, delta = 0.1 // delta default to 0.1. Acceptable delta -- 0.05<d<0.5 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length beta := math.cos(cycle) gamma := 1 / math.cos(cycle*2*delta) // delta ^^ alpha := gamma - math.sqrt((gamma * gamma) - 1) c0 := (1 + alpha) / 2 b1 := -2 * beta b2 := 1 a1 := beta * (1 + alpha) a2 := -alpha _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) + (b1 * nz(_Input[1])) + (b2 * nz(_Input[2])))) + (a1 * nz(_Output[1])) + (a2 * nz(_Output[2])) // @function Calculates the Ehlers Smoother // @param _src The source series for calculation // @returns The Ehlers Smoother value export Ehlers_Smoother(float _src = close) => c0 = 0.25, b0 = 1.0, b1 = 2, b2 = 1 _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) + (b1 * nz(_Input[1])) + (b2 * nz(_Input[2])))) // @function Calculates the Ehlers High Pass Filter // @param _src The source series for calculation // @param _length The length for the Ehlers High Pass Filter // @returns The Ehlers High Pass Filter value export Ehlers_High_Pass_Filter(float _src = close, simple int _length = 20) => c0 = 1.0, c1 = 0.0, b0 = 1.0, b1 = 0.0, b2 = 0.0 a1 = 0.0, a2 = 0.0, alpha = 0.0 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length alpha := (math.cos(2*pi/_length) + math.sin(2*pi/_length) - 1) / math.cos(2*pi/_length) c0 := 1 - alpha / 2 b1 := -1 a1 := 1 - alpha _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) + (b1 * nz(_Input[1])) )) + (a1 * nz(_Output[1])) // @function Calculates the Ehlers Two-Pole High Pass Filter // @param _src The source series for calculation // @param _length The length for the Ehlers Two-Pole High Pass Filter // @returns The Ehlers Two-Pole High Pass Filter value export Ehlers_Two_Pole_High_Pass_Filter(float _src = close, simple int _length = 20) => c0 = 1.0, b0 = 1.0, b1 = 0.0, b2 = 0.0 a1 = 0.0, a2 = 0.0, alpha = 0.0, beta = 0.0 pi = 2 * math.asin(1) cycle = 2 * math.pi / _length beta := 2.415*(1 - math.cos(2*pi / _length)) alpha := -beta + math.sqrt(beta*beta + 2*beta) c0 := (1 - alpha / 2)*(1 - alpha / 2) b1 := -2 b2 := 1 a1 := 2*(1 - alpha) a2 := -(1 - alpha)*(1 - alpha) _Input = _src _Output = 0.0 _Output := (c0 * ((b0 * _Input) + (b1 * nz(_Input[1])) + (b2 * nz(_Input[2])))) + (a1 * nz(_Output[1])) + (a2 * nz(_Output[2])) //SWISS ARMY KNIFE INDICATOR by John F. Ehlers //exported to single functions } // Moving Averages { // @function PR Calculates the percentage rank (PR) of a value within a range. // @param _src The source value for which the percentage rank is calculated. It rePResents the value to be ranked within the range. // @param _length The _length of the range over which the percentage rank is calculated. It determines the number of bars considered for the calculation. // @returns The percentage rank (PR) of the source value within the range, adjusted by adding 50 to the result. export PR(float _src = close, simple int _length = 20) => float _max = na float _min = na float _PR = na _max := ta.highest(_src, _length) _min := ta.lowest(_src, _length) _PR := (100 * (_src - _max) / (_max - _min)) + 50 _PR // @function Calculates the SMMA (Smoothed Moving Average) // @param _src The source series for calculation // @param len The _length of the SMMA // @returns The SMMA value export SMMA(float _src = close, simple int _length = 20) => SMMA = 0.0 temp_sma = ta.sma(_src, _length) SMMA := na(SMMA[1]) ? temp_sma : (SMMA[1] * (_length - 1) + _src) / _length SMMA // @function Calculates the Hull Moving Average (HULLMA) // @param _src The source series for calculation // @param _length The _length of the HULLMA // @returns The HULLMA value export HULLMA(float _src = close, simple int _length = 20) => ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length))) // @function Calculates the Triple Moving Average (TMA) // @param _src The source series for calculation // @param _length The _length of the TMA // @returns The TMA value export TMA(float _src = close, simple int _length = 20) => ta.sma(ta.sma(_src, _length), _length) // @function Calculates the Double Exponential Moving Average (DEMA) // @param _src The source series for calculation // @param _length The _length of the DEMA // @returns The DEMA value export DEMA(float _src = close, simple int _length = 20) => emaValue = ta.ema(_src, _length) 2 * emaValue - ta.ema(emaValue, _length) // @function Calculates the Triple Exponential Moving Average (TEMA) // @param _src The source series for calculation // @param _length The _length of the TEMA // @returns The TEMA value export TEMA(float _src = close, simple int _length = 20) => ema1 = ta.ema(_src, _length) ema2 = ta.ema(ema1, _length) ema3 = ta.ema(ema2, _length) 3 * ema1 - 3 * ema2 + ema3 // @function Calculates the Normalized Double Moving Average (N2MA) // @param _src The source series for calculation // @param _length The _length of the N2MA // @returns The N2MA value export W2MA(float _src = close, simple int _length = 20) => 2 * ta.wma(_src, math.round(_length / 2)) // @function Calculates the Normalized Moving Average (NMA) // @param _src The source series for calculation // @param _length The _length of the NMA // @returns The NMA value export wma(float _src = close, simple int _length = 20) => ta.wma(_src, _length) // @function Calculates the Normalized Moving Average (NMA) // @param _open The open PRice series // @param _close The close PRice series // @param _length The _length for finding the highest and lowest values // @returns The NMA value export nma(float _open = open, float _close = close, simple int _length = 20) => highestValue = ta.highest(math.max(_open, _close), _length) lowestValue = ta.lowest(math.min(_open, _close), _length) nmaValue = math.avg(highestValue, lowestValue) nmaValue export lma(float _src = close, simple int _length = 20) => norm = 0.0, sum = 0.0, alpha = 0.0, d1 = 0.0 for i = 0 to _length - 1 alpha := math.log(_length + 1 - i) norm += alpha sum += _src[i] * alpha d1 := sum/norm d1 // Helperfunction for A2RMA - Adaptive Autonomous Recursive Moving Average // @function ama (not Exported) // @param _x Input value for the ama function // @param _er Efficiency ratio to be used for calculation // @returns a float value calculated based on the efficiency ratio and input value ama(float _x, float _src, simple int _length) => //Helper for A2RMA // The AMA is a type of moving average that adjusts its sensitivity based on market conditions, //rePResented by the efficiency ratio. It is commonly used in technical analysis to smooth out PRice data and identify trends var float a = 0.0 _er = math.abs(ta.change(_src, _length)) / math.sum(math.abs(ta.change(_src)), _length) a := _er * _x + (1 - _er) * nz(a[1], _x) a // @function A2RMA - Adaptive Autonomous Recursive Moving Average // @param _src Source float input used for the calculation // @param _length Integer value rePResenting the length of the period // @param _gamma Integer value rePResenting a factor for the calculation // @returns the value of the adaptive moving average export A2RMA(float _src = close, simple int _length = 14, simple float _gamma = 3) => //Thanks alexgrover for the permission to add the a2rma here //https://www.tradingview.com/script/4bI1zjc6-Adaptive-Autonomous-Recursive-Moving-Average/ ma = 0.0 d = ta.cum(math.abs(_src - nz(ma[1], _src))) / bar_index * _gamma ma := ama(ama(_src > nz(ma[1], _src) + d ? _src + d : _src < nz(ma[1], _src) - d ? _src - d : nz(ma[1], _src),_src, _length),_src, _length) ma // @function Calculates the Autonomous Recursive Moving Average (ARMA) // @param _src The source series for calculation // @param _length The length for the ARMA // @param _gamma The parameter for ARMA calculation // @param _zerolag Boolean flag indicating whether to use zero lag // @returns An array containing the ARMA value and a flag indicating flatness export ARMA(float _src = close, simple int _length = 14, simple float _gamma = 3, simple bool _zerolag = false) => //Thanks alexgrover for the permission to add the arma here //https://www.tradingview.com/script/AnmTY0Q3-Autonomous-Recursive-Moving-Average/ ma = 0.0 mad = 0.0 change_1 = ta.change(_src, _length / 2) _src_ = _zerolag ? _src + change_1 : _src ma := nz(mad[1], _src_) d = ta.cum(math.abs(_src_[_length] - ma)) / bar_index * _gamma mad := ta.sma( ta.sma( _src_ > nz(mad[1], _src_) + d ? _src_ + d : _src_ < nz(mad[1], _src_) - d ? _src_ - d : nz(mad[1], _src_), _length ), _length ) mad // Trigonometrics for Chebyshev // Pafnuti Lwowitsch Tschebyschow (1821–1894) // Thanks peacefulLizard50262 for the find and translation cosh(float x) => (math.exp(x) + math.exp(-x)) / 2 acosh(float x) => x < 1 ? na : math.log(x + math.sqrt(x * x - 1)) sinh(float x) => (math.exp(x) - math.exp(-x)) / 2 asinh(float x) => math.log(x + math.sqrt(x * x + 1)) atan(float x) => math.pi / 2 - math.atan(1 / x) // @function Calculates the Chebyshev Type I Filter // @param src The source series for calculation // @param len The length of the filter // @param ripple The ripple factor for the filter // @returns The output of the Chebyshev Type I Filter // math from Pafnuti Lwowitsch Tschebyschow (1821–1894) // Thanks peacefulLizard50262 for the find and translation export ChebyshevI(float _src = close, int _length = 20, float _ripple = 0.05) => a = 0. b = 0. g = 0. chebyshev = 0. a := cosh(1 / _length * acosh(1 / (1 - _ripple))) b := sinh(1 / _length * asinh(1 / _ripple)) g := (a - b) / (a + b) chebyshev := (1 - g) * _src + g * nz(chebyshev[1]) chebyshev // @function Calculates the Chebyshev Type II Filter // @param src The source series for calculation // @param len The length of the filter // @param ripple The ripple factor for the filter // @returns The output of the Chebyshev Type II Filter // math from Pafnuti Lwowitsch Tschebyschow (1821–1894) // Thanks peacefulLizard50262 for the find export ChebyshevII(float _src = close, int _length = 20, float _ripple = 0.05) => a = 0. b = 0. g = 0. chebyshev = 0. a := cosh(1 / _length * acosh(1 / _ripple)) b := sinh(1 / _length * asinh(_ripple)) g := (a - b) / (a + b) chebyshev := (1 - g) * _src + g * nz(chebyshev[1], _src) chebyshev //} // Others { // @function Calculates the WaveTrend indicator // @param _src The source series for calculation // @param _n1 The period for the first EMA calculation // @param _n2 The period for the second EMA calculation // @returns The WaveTrend value export wavetrend(float _src = close, simple int _n1 = 10, simple int _n2 = 21) => esa = ta.ema(_src, _n1) d = ta.ema(math.abs(_src - esa), _n1) ci = (_src - esa) / (0.015 * d) wt = ta.ema(ci, _n2) wt // } // Selectors { // @function Calculates various types of moving averages // @param _type The type of indicator to calculate // @param _src The source series for calculation // @param _length The length for the moving average or indicator // @returns The calculated moving average or indicator value export f_getma(simple string _type = "OFF", float _src = close, simple int _length = 20, simple float _gamma = 3, simple float _ripple = 0.05, simple bool _zerolag = false) => float ma = switch _type "OFF" => _src "ARMA" => ARMA(_src, _length, _gamma, _zerolag) "A2RMA" => A2RMA(_src, _length, _gamma) "ChebyshevI" => ChebyshevI(_src, _length, _ripple) "ChebyshevII" => ChebyshevII(_src, _length, _ripple) "DEMA" => DEMA(_src, _length) "EMA" => Ehlers_EMA_fast(_src, _length) "Ehlers Band Stop Filter" => Ehlers_Band_Stop_Filter(_src, _length) "Ehlers Butterworth" => Ehlers_Butterworth(_src, _length) "Ehlers EMA" => Ehlers_EMA(_src, _length) "Ehlers Gaussian" => Ehlers_Gaussian(_src, _length) "Ehlers Smoother" => Ehlers_Smoother(_src) "Ehlers Supersmoother" => Ehlers_Supersmoother(_src, _length) "Ehlers Two Pole Butterworth Filter" => Ehlers_Two_Pole_Butterworth_Filter(_src, _length) "Ehlers Two Pole Gaussian Filter" => Ehlers_Two_Pole_Gaussian_Filter(_src, _length) "Ehlers Relative Strength Index" => Ehlers_RSI_fast(_src, _length) "HMA" => ta.hma(_src, _length) "LMA" => lma(_src, _length) "RMA" => ta.rma(_src, _length) "SMA" => Ehlers_SMA_fast(_src, _length) "SMMA" => SMMA(_src, _length) "TEMA" => TEMA(_src, _length) "TMA" => TMA(_src, _length) "VWMA" => ta.vwma(_src,_length) "WMA" => ta.wma(_src, _length) "W2MA" => W2MA(_src, _length) => _src // @function Calculates various types of Deviations and other indicators // @param _type The type of indicator to calculate // @param _src The source series for calculation // @param _length The length for the moving average or indicator // @returns The calculated moving average or indicator value export f_getoszillator(simple string _type = "OFF", float _src = close, simple int _length = 20) => float oszii = switch _type "OFF" => _src "Average True Range" => ta.atr(_length) "Ehlers Band Pass Filter" => Ehlers_Band_Pass_Filter(_src, _length) "Ehlers High Pass Filter" => Ehlers_High_Pass_Filter(_src, _length) "Ehlers Two Pole High Pass Filter" => Ehlers_Two_Pole_High_Pass_Filter(_src, _length) "Percent Range" => PR(_src, _length) "Rate of Change" => ta.roc(_src, _length) "Standard Deviation" => ta.stdev(_src, _length) "True Range" => ta.tr(false) => _src // @function Calculates various types of Deviations and other indicators // @param _type The type of indicator to calculate // @param _src The source series for calculation // @param _length The length for the moving average or indicator // @returns The calculated moving average or indicator value export f_getall(simple string _type = "OFF", float _src = close, simple int _length = 20, simple float _gamma = 3, simple float _ripple = 0.05, simple bool _zerolag = false) => float oszii = switch _type "OFF" => _src "ARMA" => ARMA(_src, _length, _gamma, _zerolag) "A2RMA" => A2RMA(_src, _length, _gamma) "Average True Range" => ta.atr(_length) "ChebyshevI" => ChebyshevI(_src, _length, _ripple) "ChebyshevII" => ChebyshevII(_src, _length, _ripple) "DEMA" => DEMA(_src, _length) "EMA" => Ehlers_EMA_fast(_src, _length) "Ehlers Band Pass Filter" => Ehlers_Band_Pass_Filter(_src, _length) "Ehlers Band Stop Filter" => Ehlers_Band_Stop_Filter(_src, _length) "Ehlers Butterworth" => Ehlers_Butterworth(_src, _length) "Ehlers EMA" => Ehlers_EMA(_src, _length) "Ehlers Gaussian" => Ehlers_Gaussian(_src, _length) "Ehlers High Pass Filter" => Ehlers_High_Pass_Filter(_src, _length) "Ehlers Relative Strength Index" => Ehlers_RSI_fast(_src, _length) "Ehlers Smoother" => Ehlers_Smoother(_src) "Ehlers Supersmoother" => Ehlers_Supersmoother(_src, _length) "Ehlers Two Pole Butterworth Filter" => Ehlers_Two_Pole_Butterworth_Filter(_src, _length) "Ehlers Two Pole Gaussian Filter" => Ehlers_Two_Pole_Gaussian_Filter(_src, _length) "Ehlers Two Pole High Pass Filter" => Ehlers_Two_Pole_High_Pass_Filter(_src, _length) "HMA" => ta.hma(_src, _length) "LMA" => lma(_src, _length) "Percentage rank" => PR(_src, _length) "Rate of Change" => ta.roc(_src, _length) "RMA" => ta.rma(_src, _length) "SMA" => Ehlers_SMA_fast(_src, _length) "SMMA" => SMMA(_src, _length) "Standard Deviation" => ta.stdev(_src, _length) "TEMA" => TEMA(_src, _length) "TMA" => TMA(_src, _length) "True Range" => ta.tr(false) "VWMA" => ta.vwma(_src,_length) "WMA" => ta.wma(_src, _length) "W2MA" => W2MA(_src, _length) => _src //} // ALL THE NAMES: //input.string("OFF", options=["OFF","ARMA","A2RMA","Average True Range","ChebyshevI","ChebyshevII","DEMA","EMA","Ehlers Band Pass Filter","Ehlers Band Stop Filter","Ehlers Butterworth","Ehlers EMA","Ehlers Gaussian","Ehlers High Pass Filter","Ehlers Smoother","Ehlers Supersmoother","Ehlers Two Pole Butterworth Filter","Ehlers Two Pole Gaussian Filter","Ehlers Two Pole High Pass Filter","Ehlers Relative Strength Index","HMA","LMA","Percentage rank","Rate of Change","RMA","SMA","SMMA","Standard Deviation","TEMA","TMA","True Range","VWMA","WMA","W2MA",])
arraybrowser
https://www.tradingview.com/script/VXY9LAys-arraybrowser/
moebius1977
https://www.tradingview.com/u/moebius1977/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © moebius1977 // Using © kaigouthro's beautiful matrixautotable library. Many thanks! //@version=5 // ---- VERSIONS ----- { // v49 published as import moebius1977/arraybrowser/5, added varip arrays support (previous version disrupted varip arrays functioning) // // ^^^ END OF versions ^^^ } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // DESCRIPTION //{ // @description Array browser. // Copy the "ARRAY BROWSER" commented code section below to your script and uncomment. // Use - see DEMO section below. Basically: // ------- // import moebius1977/arraybrowser/1 as arDbgLib // this alias is used in the copied section, so better keep it // arDbg.clear() // clears all rows and deletes the table // arDbg.add(arrayFloat, format = "0.00") // adds an array with title // arDbg.add(arrayInt) // adds an array without title // arDbg.add(arrayTimes, "array of times 1", "date\ntime") // format date and time so as to fit in the cell. // arDbg.add(arrayTimes, "array of times 2", "{0, time, HH:mm}") // format date and time so as to fit in the cell. // arDbg.add(arrayString) // adds an array // arDbg.add(arrayLine, "arrayLines", "(x1, y1)\n(x2,y2)") // adds an array // arDbg.add(arrayLabel, "arrayLabel", "txt") // adds an array // arDbg.add(arrayBox, showIds = true) // adds an array Ids can be shown only for selected arrays (see respective input option) // arDbg.draw() // shows the table with arrays // ------- // Change offset in the input settings to scroll left/right. // // Formatting options // // For float/int] you can always use format string like "{0, time, HH:mm:ss}" or "{0.00}". // Additional options are // - --- Number formats --- // - "number" // - "0" // - "0.0" // - "0.00" // - "0.000" // - "0.0000" // - "0.00000" // - "0.000000" // - "0.0000000" // - --- Date formats --- // - "date" // - "date : time" // - "dd.MM" // - "dd" // - --- Time formats --- // - "time" // - "HH:mm" // - "mm:ss" // - "date time" // - "date, time" // - "date,time" // // For line and box: Empty `format` returns coordinates as "(x1, y1) - (x2, y2)". Otherwise "x1", "x2", "y1", "y2" in `format` string are replaced by values. (e.g. toS(line, "x1, x2") will only return x1 and x2 separated by comma). // // For label: Empty `format` returns coordinates and text as "(x, y): text = text". Otherwise "x1", "y1", "txt" in `format` string are replaced by values. (e.g. toS(label, "txt") will only return text of the label)// // END OF DESCRIPTION } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ library("arraybrowser", overlay = true) // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // ARRAY BROWSER // // // <<COPY THIS PART TO YOUR SCRIPT >> //{ // // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // INPUTS - ARRAY BROWSER //{ // var ARDBGT = "Array Browser Window" // var NAVIGATION = "Navigation" // var BGCOLOR = "Format" // i_maxCols = input.int (group=NAVIGATION , inline = "IdOrOffset" , title="Show" , defval = 6) // i_bIdOrOffset = input.string (group=NAVIGATION , inline = "IdOrOffset" , title="items", defval = "up to offset", options = ["up to offset", "starting from id"], tooltip="") // i_n = input.int (group=NAVIGATION , inline = "IdOrOffset" , title="" , defval = 0, tooltip="The window will show array starting from this item (id) or up to this item (offset). Change this value to scroll the array(s) left or right. Arrays are aligned to the left if \"starting from id\" is selected and to the right if \"up to offset\" is selected.") // i_showIds = input.string (group=BGCOLOR , inline = "" , title="Show id's" , defval = "always", options = ["always", "never", "individually"], tooltip="Disabling overrides individual showID settings of each array.") // i_defaultxt = input.color (group=BGCOLOR , inline = 'text color' , title = "Text color" , defval = #000000f5) // i_bgClrNormal = input.color (group=BGCOLOR , inline = "BgColor" , title="Background: Normal" , defval = #fff7d3) // i_bgClrNa = input.color (group=BGCOLOR , inline = "BgColor" , title="NA" , defval = #000000bd) // var string group_table = 'ARRAY BROWSER WINDOW' // i_maxRows = input.int (group = group_table, inline = "", defval = 10, title="Max rows") // i_tblShrink = input.int (group = group_table, inline = 'size', defval = 50, title = "Shrink, %" ) // i_textSize = input.int (group = group_table, inline = 'size', defval = 2 , title = 'Table Text Size' ) // i_cellsizeW = input.int (group = group_table, inline = 'size', defval = 100 , title = 'Scale W, % ' ) // i_cellsizeH = input.int (group = group_table, inline = 'size', defval = 100 , title = 'scale H, %' ) // i_fit = input.bool (group = group_table, inline = 'place', defval = false, title = "Fit") // i_tableYpos = input.string (group = group_table, inline = 'place', defval = 'bottom' , title = '↕' , options=['top', 'middle', 'bottom']) // i_tableXpos = input.string (group = group_table, inline = 'place', defval = 'left' , title = '↔' , options=['left', 'center', 'right'], tooltip='Position on the chart.') // // END OF INPUTS } // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // INIT ARRAY DEBUG TABLE //{ // varip arbr = arraybrowser.arrayBrowser.new().init( // i_bIdOrOffset = i_bIdOrOffset // , i_n = i_n // , i_maxRows = i_maxRows // , i_showIds = i_showIds // , i_maxCols = i_maxCols // , i_bgClrNormal = i_bgClrNormal // , i_bgClrNa = i_bgClrNa // , i_tblShrink = i_tblShrink // , i_textSize = i_textSize // , i_cellsizeW = i_cellsizeW // , i_cellsizeH = i_cellsizeH // , i_fit = i_fit // , i_tableYpos = i_tableYpos // , i_tableXpos = i_tableXpos // , i_defaultxt = i_defaultxt // ) // // END OF INIT } // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // // END OF THE PART TO BE INSERTED } // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ import moebius1977/toString/4 import kaigouthro/matrixautotable/14 as mtt // import moebius1977/matrixautotable/2 as mtt // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // HELPER FUNCTIONS //{ // import moebius1977/arraymethods/2 // ----- array_new() ------ { // @function Creates a new array of size `n` filled with `val`. array_new(int n, bool val) => array.new<bool >(n, val) array_new(int n, box val) => array.new<box >(n, val) array_new(int n, color val) => array.new<color >(n, val) array_new(int n, float val) => array.new<float >(n, val) array_new(int n, int val) => array.new<int >(n, val) array_new(int n, label val) => array.new<label >(n, val) array_new(int n, line val) => array.new<line >(n, val) array_new(int n, linefill val) => array.new<linefill>(n, val) array_new(int n, string val) => array.new<string >(n, val) array_new(int n, table val) => array.new<table >(n, val) // END OF array_new() } // ----------- growR() ----------- { //@function Grows array up to size szTo (if it is smaller) by adding val to the end _agrowR(a,szTo, val) => //naItem = a.tona() growBy = szTo-a.size() if growBy > 0 a.concat(array_new(growBy, val)) else a //@function Grows array up to size szTo (if it is smaller) by adding val to the end method growR(int [] arr, int sizeTo,int val=na)=>_agrowR(arr, sizeTo, val) method growR(float [] arr, int sizeTo,float val=na)=>_agrowR(arr, sizeTo, val) method growR(bool [] arr, int sizeTo,bool val=na)=>_agrowR(arr, sizeTo, val) method growR(string [] arr, int sizeTo,string val=na)=>_agrowR(arr, sizeTo, val) method growR(color [] arr, int sizeTo,color val=na)=>_agrowR(arr, sizeTo, val) method growR(line [] arr, int sizeTo,line val=na)=>_agrowR(arr, sizeTo, val) method growR(label [] arr, int sizeTo,label val=na)=>_agrowR(arr, sizeTo, val) method growR(box [] arr, int sizeTo,box val=na)=>_agrowR(arr, sizeTo, val) method growR(table [] arr, int sizeTo,table val=na)=>_agrowR(arr, sizeTo, val) method growR(linefill [] arr, int sizeTo,linefill val=na)=>_agrowR(arr, sizeTo, val) // END OF growR() } // ----------- growL() ----------- { //@function Grows array up to size szTo (if it is smaller) by adding val to the beginning _agrowL(a,szTo, val) => growBy = szTo-a.size() if growBy > 0 (array_new(growBy, val)).concat(a) else a //@function Grows array up to size szTo (if it is smaller) by adding val to the beginning method growL(int [] arr, int sizeTo,int val=na)=>_agrowL(arr, sizeTo, val) method growL(float [] arr, int sizeTo,float val=na)=>_agrowL(arr, sizeTo, val) method growL(bool [] arr, int sizeTo,bool val=na)=>_agrowL(arr, sizeTo, val) method growL(string [] arr, int sizeTo,string val=na)=>_agrowL(arr, sizeTo, val) method growL(color [] arr, int sizeTo,color val=na)=>_agrowL(arr, sizeTo, val) method growL(line [] arr, int sizeTo,line val=na)=>_agrowL(arr, sizeTo, val) method growL(label [] arr, int sizeTo,label val=na)=>_agrowL(arr, sizeTo, val) method growL(box [] arr, int sizeTo,box val=na)=>_agrowL(arr, sizeTo, val) method growL(table [] arr, int sizeTo,table val=na)=>_agrowL(arr, sizeTo, val) method growL(linefill [] arr, int sizeTo,linefill val=na)=>_agrowL(arr, sizeTo, val) // END OF growL() } // import moebius1977/typeandcast/5 //----------- _type_item () -----------{ // @function Returns type of variable or the element for array/matrix. // ``` // int n = 0 // n._type_item() // returns "int" // arr = array.new<int>() // arr._type_item() // returns "int" // ``` method _type_item(int _temp)=> na(_temp) ? 'int' : 'int' method _type_item(float _temp)=> na(_temp) ? 'float' : 'float' method _type_item(bool _temp)=> na(_temp) ? 'bool' : 'bool' method _type_item(string _temp)=> na(_temp) ? 'string' : 'string' method _type_item(color _temp)=> na(_temp) ? 'color' : 'color' method _type_item(line _temp)=> na(_temp) ? 'line' : 'line' method _type_item(label _temp)=> na(_temp) ? 'label' : 'label' method _type_item(box _temp)=> na(_temp) ? 'box' : 'box' method _type_item(table _temp)=> na(_temp) ? 'table' : 'table' method _type_item(linefill _temp)=> na(_temp) ? 'linefill' : 'linefill' method _type_item(int [] _temp)=> na(_temp) ? 'int' : 'int' method _type_item(float [] _temp)=> na(_temp) ? 'float' : 'float' method _type_item(bool [] _temp)=> na(_temp) ? 'bool' : 'bool' method _type_item(string [] _temp)=> na(_temp) ? 'string' : 'string' method _type_item(color [] _temp)=> na(_temp) ? 'color' : 'color' method _type_item(line [] _temp)=> na(_temp) ? 'line' : 'line' method _type_item(label [] _temp)=> na(_temp) ? 'label' : 'label' method _type_item(box [] _temp)=> na(_temp) ? 'box' : 'box' method _type_item(table [] _temp)=> na(_temp) ? 'table' : 'table' method _type_item(linefill [] _temp)=> na(_temp) ? 'linefill' : 'linefill' method _type_item(matrix <int> _temp)=> na(_temp) ? 'int' : 'int' method _type_item(matrix <float> _temp)=> na(_temp) ? 'float' : 'float' method _type_item(matrix <bool> _temp)=> na(_temp) ? 'bool' : 'bool' method _type_item(matrix <string> _temp)=> na(_temp) ? 'string' : 'string' method _type_item(matrix <color> _temp)=> na(_temp) ? 'color' : 'color' method _type_item(matrix <line> _temp)=> na(_temp) ? 'line' : 'line' method _type_item(matrix <label> _temp)=> na(_temp) ? 'label' : 'label' method _type_item(matrix <box> _temp)=> na(_temp) ? 'box' : 'box' method _type_item(matrix <table> _temp)=> na(_temp) ? 'table' : 'table' method _type_item(matrix <linefill>_temp)=> na(_temp) ? 'linefill' : 'linefill' // END OF _type_item } // END OF HELPER FUNCTIONS //} // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // TYPE AND METHODS - ARRAY BROWSER //{ //----------- tblRow TYPE -----------{ export type tblRow varip string title varip string arType varip int arId varip bool showId varip string format varip string[] arDataS varip string[] arTitleS varip string[] arStrBgColor // `varip color[] arrayColors` is not supported as at 29 May 2023 varip int dataArSize // END OF type tblRow } //----------- +++++++++++++++++++++ ----------- //----------- ARRAY CONTAINERS TYPE GROUP ----------- { //----------- array containers arsF, arsS,... TYPE -----------{ export type arsB varip bool[] ar0 = na varip bool[] ar1 = na varip bool[] ar2 = na varip bool[] ar3 = na varip bool[] ar4 = na varip bool[] ar5 = na varip bool[] ar6 = na varip bool[] ar7 = na varip bool[] ar8 = na varip bool[] ar9 = na export type arsF varip float[] ar0 = na varip float[] ar1 = na varip float[] ar2 = na varip float[] ar3 = na varip float[] ar4 = na varip float[] ar5 = na varip float[] ar6 = na varip float[] ar7 = na varip float[] ar8 = na varip float[] ar9 = na export type arsS varip string[] ar0 = na varip string[] ar1 = na varip string[] ar2 = na varip string[] ar3 = na varip string[] ar4 = na varip string[] ar5 = na varip string[] ar6 = na varip string[] ar7 = na varip string[] ar8 = na varip string[] ar9 = na export type arsBx box[] ar0 = na box[] ar1 = na box[] ar2 = na box[] ar3 = na box[] ar4 = na box[] ar5 = na box[] ar6 = na box[] ar7 = na box[] ar8 = na box[] ar9 = na export type arsLn line[] ar0 = na line[] ar1 = na line[] ar2 = na line[] ar3 = na line[] ar4 = na line[] ar5 = na line[] ar6 = na line[] ar7 = na line[] ar8 = na line[] ar9 = na export type arsLb label[] ar0 = na label[] ar1 = na label[] ar2 = na label[] ar3 = na label[] ar4 = na label[] ar5 = na label[] ar6 = na label[] ar7 = na label[] ar8 = na label[] ar9 = na // END OF array containers type } //----------- array container functions -----------{ // --- _clear(arCont) --- { // @funcction Frees all array slots of the container (deletes all references to arrays) _clear(arCont) => arCont.ar0 := na arCont.ar1 := na arCont.ar2 := na arCont.ar3 := na arCont.ar4 := na arCont.ar5 := na arCont.ar6 := na arCont.ar7 := na arCont.ar8 := na arCont.ar9 := na // END OF clear(azrCont) } // --- _clear(arCont, slotId) --- { // @function Frees a particular slot in the container _clear(arCont, int slotId) => switch slotId 0 => arCont.ar0 := na, 1 1 => arCont.ar1 := na, 1 2 => arCont.ar2 := na, 1 3 => arCont.ar3 := na, 1 4 => arCont.ar4 := na, 1 5 => arCont.ar5 := na, 1 6 => arCont.ar6 := na, 1 7 => arCont.ar7 := na, 1 8 => arCont.ar8 := na, 1 9 => arCont.ar9 := na, 1 => runtime.error(str.format("_clear(array of {0}): n = {1} out of range (0 to 9)", arCont.ar1._type_item(), slotId)) 1 // dummy return // END OF _clear(arCont, slotId) } // --- _get(arCont, slotId) --- { // @function Returns a reference to array in slot slotId _get(arCont, int slotId) => switch slotId 0 => arCont.ar0 1 => arCont.ar1 2 => arCont.ar2 3 => arCont.ar3 4 => arCont.ar4 5 => arCont.ar5 6 => arCont.ar6 7 => arCont.ar7 8 => arCont.ar8 9 => arCont.ar9 => runtime.error(str.format("_get(array of {0}): n = {1} out of range (0 to 9)", arCont.ar1._type_item(), slotId)) arCont.ar1 // dummy return // END OF _get(arCont, slotId) } // --- _set(arCont, slotId, ar) --- { // @function Returns a reference to array in slot slotId _set(arCont, slotId, ar) => switch slotId 0 => arCont.ar0 := ar, 1 1 => arCont.ar1 := ar, 1 2 => arCont.ar2 := ar, 1 3 => arCont.ar3 := ar, 1 4 => arCont.ar4 := ar, 1 5 => arCont.ar5 := ar, 1 6 => arCont.ar6 := ar, 1 7 => arCont.ar7 := ar, 1 8 => arCont.ar8 := ar, 1 9 => arCont.ar9 := ar, 1 => runtime.error(str.format("_set(array of {0}): n = {1} out of range (0 to 9)", arCont.ar1._type_item(), slotId)) 1 // dummy return // END OF _set(arCont, slotId) } // --- _get_free_slot (arCont) --- { // @function Returns a reference to array in slot slotId _get_free_slot (arCont) => i = 0 while i <= 9 if na(_get(arCont,i)) break i+=1 i > 9 ? na : i // END OF _set(arCont, slotId) } // --- _get_free_slot (arCont) --- { // @function Returns a reference to array in slot slotId _count_free_slots (arCont) => c = 0 for i = 0 to 9 if na(_get(arCont,i)) c+=1 c // END OF _set(arCont, slotId) } // END OF array container functions} // END OF ARRAY CONTAINERS TYPE GROUP ----------- } //----------- +++++++++++++++++++++ ----------- //----------- arrayBrowser TYPE -----------{ // @type Array browser object, declare as `var`. export type arrayBrowser varip tblRow[] arRows // rows index // matrix<string> mxDataS // matrix of cell text strings for the table // matrix<string> mxTitlesS // matrix of cell text strings for the table // matrix<color> mxBgColor // matrix of bgcolor for the table table tbl varip int cols // actual number of columns varip string message = "" // --- navigation --- // string masterArType // int masterArId bool bIdOrOffset // true - id, false - offset int n bool windowDirection // true - normal (to the right of Id and to the left of offset, false - reverse) string syncAlign // align other arrays to the master array string showIds //--- params --- int maxRows int maxCols // color bgClrMaster = #fbff26b0 color bgClrNormal = #fff7d3 color bgClrNa = #000000bd int tblShrink int textSize int cellsizeW int cellsizeH bool fit string tableYpos string tableXpos color defaultxt // --- array references --- varip arsB b varip arsF f varip arsS s arsBx bx arsLn ln arsLb lb // END OF type arrayBrowser } //----------- init() export -----------{ export method init(arrayBrowser this , string i_bIdOrOffset // true - id, false - offset , int i_n // , string i_windowDirection // true - normal (to the right of Id and to the left of offset, false - reverse) , int i_maxRows , string i_showIds , int i_maxCols // , color i_bgClrMaster = #fbff26b0 , color i_bgClrNormal = #fff7d3 , color i_bgClrNa = #000000bd , int i_tblShrink = 50 , int i_textSize = 2 , int i_cellsizeW = 1 , int i_cellsizeH = 1 , bool i_fit = false , string i_tableYpos = "bottom" , string i_tableXpos = "left" , color i_defaultxt = #000000f5 ) => this.arRows := array.new<tblRow>() this.b := arsB .new() this.f := arsF .new() this.s := arsS .new() this.bx := arsBx .new() this.ln := arsLn .new() this.lb := arsLb .new() this.bIdOrOffset := (i_bIdOrOffset == "starting from id") ? true : false this.n := i_n // this.windowDirection := (i_windowDirection == "normal") ? true : false this.maxRows := i_maxRows this.showIds := i_showIds this.maxCols := i_maxCols // this.bgClrMaster := i_bgClrMaster this.bgClrNormal := i_bgClrNormal this.bgClrNa := i_bgClrNa this.tblShrink := i_tblShrink this.textSize := i_textSize this.cellsizeW := i_cellsizeW / 100 this.cellsizeH := i_cellsizeH / 100 this.fit := i_fit this.tableYpos := i_tableYpos this.tableXpos := i_tableXpos this.defaultxt := i_defaultxt this.message := "" this // END OF init() } //----------- deleteRow() -----------{ method deleteRow(arrayBrowser t, int i) => _arRows = t.arRows if i < 0 or i > _arRows.size()-1 runtime.error(str.format("deleteRow: i out of bounds = {0}, t.arRows.size()= {1}", i, t.arRows.size())) r = t.arRows.get(i) switch r.arType "bool" => _clear(t.b, r.arId) "float" => _clear(t.f, r.arId) "string" => _clear(t.s, r.arId) "box" => _clear(t.bx, r.arId) "line" => _clear(t.ln, r.arId) "label" => _clear(t.lb, r.arId) _arRows.remove(i) // END OF deleteRow } //----------- pushRow() -----------{ method pushRow(arrayBrowser t, string arType, int arId, string title = "", string format = "", bool showId = false) => newRow = tblRow.new( title = title , arType = arType , arId = arId , showId = showId , format = format ) t.arRows.push(newRow) // if over masxRows delete top row if not master array, otherwise delete the second row if t.arRows.size() > t.maxRows t.deleteRow(0) 1 // END OF setAr } //----------- _add(arCont, ar) -----------{ _add(arCont, ar, arrayBrowser t, string title = "", string format = "", bool showId = false) => if na(ar) runtime.error("_add: ar is na") i = _get_free_slot(arCont) if t.arRows.size() < t.maxRows if not na(i) // if slot found // plug array into the slot _set(arCont, i, ar) // register the new array in the catalogue t.pushRow(ar._type_item(), i, title, format, showId) else t.message += (t.message == "" ? "" : "\n") + "No free slot for the array " + title + " found.", 1 if str.length(t.message) > 3096 t.message := str.substring(t.message, 100) 1 else t.message += (t.message == "" ? "" : "\n") + str.format("No free rows for array {0}, maxRows = {1}", title, t.maxRows), 1 if str.length(t.message) > 3096 t.message := str.substring(t.message, 100) // runtime.error(str.format("arraybrowser._add(): t.arRows.size() {0} is over t.maxRows {1}, ar._type_item() = {2}", t.arRows.size(), t.maxRows, ar._type_item())) 1 // END OF _add(arCont, ar) } //----------- add(bool[]) export -----------{ export method add(arrayBrowser t, bool[] arr, string title = "", string format = "", bool showId = false) => _add(t.b, arr, t, title, format, showId) // END OF add() } //----------- add(float[]) export -----------{ export method add(arrayBrowser t, float[] arr, string title = "", string format = "", bool showId = false) => _add(t.f, arr, t, title, format, showId) // END OF add() } //----------- add(string[]) export -----------{ export method add(arrayBrowser t, string[] arr, string title = "", string format = "", bool showId = false) => _add(t.s, arr, t, title, format, showId) // END OF add() } //----------- add(line[]) export -----------{ export method add(arrayBrowser t, line[] arr, string title = "", string format = "", bool showId = false) => _add(t.ln, arr, t, title, format, showId) // END OF add() } //----------- add(label[]) export -----------{ export method add(arrayBrowser t, label[] arr, string title = "", string format = "", bool showId = false) => _add(t.lb, arr, t, title, format, showId) // END OF add() } //----------- add(box[]) export -----------{ export method add(arrayBrowser t, box[] arr, string title = "", string format = "", bool showId = false) => _add(t.bx, arr, t, title, format, showId) // END OF add() } //----------- _sliceToString() -----------{ // slices the required part (as defined by navigation input settings) out of array, and converts to string array (does nothing to size). // @returns <void>> _sliceToString(ar, arrayBrowser t, tblRow r) => startId = 100 endId = -100 if na(ar) r.arDataS := array.new<string>() r.arTitleS := array.new<string>() r.arStrBgColor := array.new<string>() int(na) else if t.n >= 0 and t.n < ar.size() // if t.windowDirection // window to the right of id and to the left of offset if t.bIdOrOffset // if t.n is Id startId := t.n endId := math.min(ar.size()-1, startId+(t.maxCols-1)) else // if t.n is offset endId := ar.size()-1-t.n startId := math.max(0, endId-(t.maxCols-1)) // else // window to the left of id an // if t.bIdOrOffset // if t.n is Id // endId := t.n // startId := math.max(0, endId-(t.maxCols-1)) // else // if t.n is offset // startId := ar.size()-1-t.n // endId := math.min(ar.size()-1, startId+(t.maxCols-1)) if startId <= endId r.arDataS := ar.slice(startId, endId+1).toStringAr(r.format) // populate titles (id's) and bgcolors r.arTitleS := array.new<string>() for i = startId to endId r.arTitleS.push(((r.showId and t.showIds == "individually") or t.showIds == "always" )? "id=" + str.tostring(i) : "") r.arStrBgColor := array.new<string>(r.arDataS.size(), "bgClrNormal") r.dataArSize := ar.size() else r.arDataS := array.new<string>() r.arTitleS := array.new<string>() r.arStrBgColor := array.new<string>() int(na) // END OF _sliceToString1 } //----------- populateRows() -----------{ // populate row string arrays method populateRows(arrayBrowser t) => i = 0 cols = 0 while i < t.arRows.size() r = t.arRows.get(i) // populate row's string arrays with data from its data array switch r.arType "bool" => a = _sliceToString(_get(t.b , r.arId), t, r) "float" => a = _sliceToString(_get(t.f , r.arId), t, r) "string" => a = _sliceToString(_get(t.s , r.arId), t, r) "line" => a = _sliceToString(_get(t.ln , r.arId), t, r) "label" => a = _sliceToString(_get(t.lb , r.arId), t, r) "box" => a = _sliceToString(_get(t.bx , r.arId), t, r) cols := math.max(nz(cols), r.arDataS.size()) i+=1 // expand rows and add title and size for r in t.arRows // expan arrays to match the longest or maxCols if t.bIdOrOffset == true // to the right r.arDataS := r.arDataS .growR(cols) r.arTitleS := r.arTitleS .growR(cols) r.arStrBgColor := r.arStrBgColor .growR(cols, "bgClrNa") else // or to the left r.arDataS := r.arDataS .growL(cols) r.arTitleS := r.arTitleS .growL(cols) r.arStrBgColor := r.arStrBgColor .growL(cols, "bgClrNa") // add array size r.arDataS.unshift(str.tostring(r.dataArSize)) r.arTitleS.unshift("size") r.arStrBgColor.unshift("clrHeaderColumns") // add title r.arDataS.unshift(r.title) // array titles r.arTitleS.unshift("") r.arStrBgColor.unshift("clrHeaderColumns") // dbgPrintf(r.title + " // , r.arDataS.size() = {0 // , r.arTitleS.size() = {1 // , r.arBgColor.size() = {2 // , cols = {3 // " // , r.arDataS.size() // , r.arTitleS.size() // , r.arBgColor.size() // , cols // ) t.cols := cols+2 // set max array length (table width capped with maxCols input ) // END OF populateRows } //----------- clear() -----------{ // @function Clears the array browser window/table (deletes all rows / removes all arrays) export method clear(arrayBrowser t) => while t.arRows.size() > 0 tp = t.arRows.get(0).arType i = t.arRows.get(0).arId t.deleteRow(0) t.tbl.delete() // END OF populateRows } method toColor(arrayBrowser t, string strColor) => switch strColor "clrHeaderColumns" => #ffce8a "bgClrNormal" =>t.bgClrNormal "bgClrNa" => t.bgClrNa //----------- draw() export -----------{ // @function Displays array browser table. Should be called on barstate.islast export method draw(arrayBrowser t) => // --- populate rows with slices from data arrays--- t.populateRows() // --- init table and its matrices --- messageRows = t.message == "" ? 0 : 1 // prepare a row for the message if any rows = t.arRows.size() + messageRows if rows > 0 t.tbl.delete() matrix<string> mxTitleS = matrix.new<string> (rows, t.cols, "") matrix<string> mxDataS = matrix.new<string> (rows, t.cols, "") matrix<color> mxBgColor = matrix.new<color> (rows, t.cols, t.bgClrNormal) matrix<color> mxTextColor = matrix.new<color> (rows, t.cols, t.defaultxt ) // // // matrix<string> _tooltipmatrix = matrix.new<string> (rows, t.cols, string(na) ) // --- print rows to the table aligning and expanding as necessary --- i = 0 while i < t.arRows.size() r = t.arRows.get(i) for j = 0 to t.cols-1 mxDataS .set(i+ messageRows,j, r.arDataS.get(j)) mxTitleS .set(i+ messageRows,j, r.arTitleS.get(j)) mxBgColor .set(i+ messageRows,j, t.toColor(r.arStrBgColor.get(j))) i+=1 t.tbl := mtt.matrixtable(mxDataS, mxTitleS, mxBgColor // t.tbl := mtt.matrixtable(mxDataS, mxTitleS, mxBgColor, mxTextColor // no such signature in kaigouthro/matrixautotable/14 unfortunately , _textSize = t.textSize , tableYpos = t.tableYpos , tableXpos = t.tableXpos , _fit = t.fit , _shrink = t.tblShrink , _w = t.cellsizeW , _h = t.cellsizeH , _defaultbg = t.bgClrNormal , _defaultxt = color.black ) // print message if t.message !="" t.tbl.merge_cells(0, 0, t.cols-1, 0) table.cell_set_text(t.tbl,0,0,t.message) table.cell_set_bgcolor(t.tbl,0,0,color.rgb(255, 163, 151)) // END OF draw() } // END OF TYPE AND METHODS } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // INPUTS - ARRAY BROWSER //{ var ARDBGT = "Array Browser Window" var NAVIGATION = "Navigation" var BGCOLOR = "Format" i_maxCols = input.int (group=NAVIGATION , inline = "IdOrOffset" , title="Show" , defval = 6) i_bIdOrOffset = input.string (group=NAVIGATION , inline = "IdOrOffset" , title="items", defval = "up to offset", options = ["up to offset", "starting from id"], tooltip="") i_n = input.int (group=NAVIGATION , inline = "IdOrOffset" , title="" , defval = 0, tooltip="The window will show array starting from this item (id) or up to this item (offset). Change this value to scroll the array(s) left or right. Arrays are aligned to the left if \"starting from id\" is selected and to the right if \"up to offset\" is selected.") i_showIds = input.string (group=BGCOLOR , inline = "" , title="Show id's" , defval = "always", options = ["always", "never", "individually"], tooltip="Disabling overrides individual showID settings of each array.") i_defaultxt = input.color (group=BGCOLOR , inline = 'text color' , title = "Text color" , defval = #000000f5) i_bgClrNormal = input.color (group=BGCOLOR , inline = "BgColor" , title="Background: Normal" , defval = #fff7d3) i_bgClrNa = input.color (group=BGCOLOR , inline = "BgColor" , title="NA" , defval = #000000bd) // // demo var string group_table = 'ARRAY BROWSER WINDOW' i_maxRows = input.int (group = group_table, inline = "", defval = 10, title="Max rows") i_tblShrink = input.int (group = group_table, inline = 'size', defval = 50, title = "Shrink, %" ) i_textSize = input.int (group = group_table, inline = 'size', defval = 2 , title = 'Table Text Size' ) i_cellsizeW = input.int (group = group_table, inline = 'size', defval = 100 , title = 'Scale W, % ' ) i_cellsizeH = input.int (group = group_table, inline = 'size', defval = 100 , title = 'scale H, %' ) i_fit = input.bool (group = group_table, inline = 'place', defval = false, title = "Fit") i_tableYpos = input.string (group = group_table, inline = 'place', defval = 'bottom' , title = '↕' , options=['top', 'middle', 'bottom']) i_tableXpos = input.string (group = group_table, inline = 'place', defval = 'left' , title = '↔' , options=['left', 'center', 'right'], tooltip='Position on the chart.') // END OF INPUTS } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // INIT ARRAY BROWSER TABLE //{ var t = arrayBrowser.new().init( i_bIdOrOffset = i_bIdOrOffset , i_n = i_n // , i_windowDirection = i_windowDirection , i_maxRows = i_maxRows , i_showIds = i_showIds , i_maxCols = i_maxCols // , i_bgClrMaster = i_bgClrMaster , i_bgClrNormal = i_bgClrNormal , i_bgClrNa = i_bgClrNa , i_tblShrink = i_tblShrink , i_textSize = i_textSize , i_cellsizeW = i_cellsizeW , i_cellsizeH = i_cellsizeH , i_fit = i_fit , i_tableYpos = i_tableYpos , i_tableXpos = i_tableXpos , i_defaultxt = i_defaultxt ) // END OF INIT } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // @function Helper for converting series to array. // @param source float, data series. // @param length int, size. // @returns float array. series_to_array (float source, int length) => float[] _data = array.new_float(length, float(na)) for _i = (length-1) to 0 if bar_index[_i] >= 0 array.set(_data, _i, source[_i]) _data // ++++++++++++++ ++++++++++++++ ---- ++++++++++++++ ++++++++++++++ // || || || || || || || DEMO || || || || || || || { ar1 = array.from(100, 200, 300 ) ar2 = array.from(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) arTDS = series_to_array(time, 5).toStringAr("date\ntime") arTS = series_to_array(time, 5).toStringAr("time") arT = series_to_array(time, 5) arB = array.from(true, false, false, true, false) // array of times of 500000 last calculations varip arCalcTimes = array.new<int>() varip arCalcBarIndices = array.new<int>() arCalcTimes.push(timenow) arCalcBarIndices.push(bar_index) while arCalcTimes.size() > 50000 arCalcTimes.shift() while arCalcBarIndices.size() > 50000 arCalcBarIndices.shift() if bar_index < 1 t.add(ar1.toStringAr(), title = "!!! WILL NOT SHOW") if barstate.islast lnB = line.new(bar_index - 3, low[3], bar_index, low, color = color.yellow) lnT = line.new(time[6], low[6], time[3], low[3], color = color.rgb(255, 148, 134), xloc = xloc.bar_time) lblB = label.new(bar_index,high, "test", color = color.yellow) lblT = label.new(time[6],high[6], "test", color = color.yellow, xloc = xloc.bar_time) bxB = box.new(bar_index - 3, low[3], bar_index,low, text = "box", bgcolor = color.rgb(170, 237, 246, 57)) bxT = box.new(time[6], low[6], time[3], low[3], text = "box", bgcolor = color.rgb(243, 213, 169, 59), xloc = xloc.bar_time) arI = array.from(10,20) arF = array.from(30,40.) arS = array.from("AAA","BBB") arLn = array.from(lnB,lnT) arLb = array.from(lblB,lblT) arBx = array.from(bxB,bxT) t.clear() // t.add(ar2, title = "ar2") // t.add(arTDS, title = "arTDS") // t.add(arTS, title = "arTS") t.add(arT, title = "arT\n\"date\\ntime\"", format = "date\ntime") t.add(arT, title = "arT\n\"date: {0, date, dd MMM}\\ntime: {0, time, HH:mm:ss}\"", format = "date: {0, date, dd MMM}\ntime: {0, time, HH:mm:ss}") t.add(arCalcTimes, title = "arCalcTimes", format = "{0, time, HH:mm:ss:SSS}") t.add(arCalcBarIndices, title = "arCalcBarIndices") // t.add(ar1, title = "ar1 no id", showId = false) t.add(ar1, title = "ar1 show id", showId = true) t.add(arLn, "arLn\n\"(x1, y1)\\n(x2, y2)\"", format = "(x1, y1)\n(x2, y2)") t.add(arLb, "arLb\n\"text: txt\"", "text: txt", showId = true) t.add(arBx, "arBx \n\"bottomright:\\n(x2,y2)\"", "bottomright:\n(x2,y2)") t.add(ar2, title = "ar2") // t.add(ar1, title = "ar1-2") t.add(arB, title = "arB") // this is 11'th array whereas default input is 10 rows, so, this will produce an error message over the browser table t.add(array.from("aaa", "bbb"), title = "aaa-2") // t.add(array.from("aaa", "bbb"), title = "aaa-3") t.draw() plotchar(ar1.size(), "ar1.size()", "", location = location.bottom) plotchar(t.arRows.size(), "t.arRows.size()", "", location = location.bottom) // END OF DEMO } // ++++++++++++++ ++++++++++++++ ---- ++++++++++++++ ++++++++++++++ //====================================================================================== // DEBUG PRINTS //{ plotchar(false, "--- BAR INDEX ---", "", location = location.bottom) plotchar(bar_index, "bar_index", "", location = location.bottom) plotchar(false, "--- PINE's ARRAY SIZES ---", "", location = location.bottom) plotchar(array.size(label.all), "label.all size", "", location = location.bottom) plotchar(array.size(line.all), "line.all size", "", location = location.bottom) plotchar(array.size(box.all), "box.all size", "", location = location.bottom) plotchar(array.size(table.all), "table.all size", "", location = location.bottom) // ^^^^^^ END OF DEBUG PRINTS ^^^^^^} //======================================================================================
3x MTF MACD v3.0
https://www.tradingview.com/script/TlzO43LY-3x-MTF-MACD-v3-0/
thebearfib
https://www.tradingview.com/u/thebearfib/
39
study
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/ // Idea by © thebearfib - Made By @kioseffTrading // //MACD on 3time frames //@version=5 // indicator("3x MTF MACD v5.150", overlay = true, max_labels_count = 500) import RicardoSantos/MathOperator/2 import HeWhoMustNotBeNamed/arraymethods/1 color _Bullish = input.color(color.rgb(34, 255, 0), 'Bullish', inline = '1x', group = '390 min in a Trading Day') color _Bearish = input.color(color.rgb(255, 0, 0), 'Bearish', inline = '1x', group = '390 min in a Trading Day') _time = input.timeframe("D","TimeFrame" , group = 'Simple Moving Avg Line', inline='1x' ) showSMA = input.bool (true, '', group = 'Simple Moving Avg Line', inline='3x' ) _smaLen = input.int (defval = 13, title=' ', group = 'Simple Moving Avg Line', inline='3x' ) _smaWt = input.int (defval = 2, title=' ', group = 'Simple Moving Avg Line', inline='3x', minval = 1, maxval = 20) showMin = input.bool(defval = true, title = "sʜᴏᴡ ᴍᴀᴄᴅ ᴛɪᴍᴇ ғʀᴀᴍᴇ ɪɴ ᴍɪɴᴜᴛᴇs [ɪɴ ᴛᴀʙʟᴇ]", group = "MACD Input Settings", inline = "0") one = input.float(defval = 30, title = "ᴛɪᴍᴇ", minval = 1, maxval = 1444, group = "MACD Input Settings", inline = "1") fast1 = input.int(defval = 12, minval = 2, title = "ғᴀsᴛ", group = "MACD Input Settings", inline = "2") slow1 = input.int(defval = 26, minval = 2, title = "sʟᴏᴡ", group = "MACD Input Settings", inline = "3") smooth1 = input.int(defval = 9 , minval = 2, title = "sᴍᴏᴏ", group = "MACD Input Settings", inline = "4") two = input.float(defval = 45, title = " ", minval = 1, maxval = 1444, group = "MACD Input Settings", inline = "1") fast2 = input.int(defval = 18, minval = 2, title = " ", group = "MACD Input Settings", inline = "2") slow2 = input.int(defval = 32, minval = 2, title = " ", group = "MACD Input Settings", inline = "3") smooth2 = input.int(defval = 15, minval = 2, title = " ", group = "MACD Input Settings", inline = "4") three = input.float(defval = 60, title = " ", minval = 1, maxval = 1444, group = "MACD Input Settings", inline = "1") fast3 = input.int(defval = 24, minval = 2, title = " ", group = "MACD Input Settings", inline = "2") slow3 = input.int(defval = 38, minval = 2, title = " ", group = "MACD Input Settings", inline = "3") smooth3 = input.int(defval = 21, minval = 2, title = " ", group = "MACD Input Settings", inline = "4") method Float(int id) => float(id) type lowerTFvals array<label> upLabels array<label> dnLabels int counterUp int counterDn [dayOpen, dayHigh, dayLow, dayClose] = request.security(syminfo.tickerid, _time, [open, high, low, close], lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_on ) _sma13 = ta.sma(dayClose, _smaLen) _trend = switch _sma13 > _sma13[3] => color.rgb(0, 255, 8) _sma13 < _sma13[3] => color.rgb(255, 0, 0) _sma13 > _sma13[1] => color.rgb(109, 111, 120,50) _sma13 < _sma13[1] => color.rgb(108, 110, 117,50) => color.rgb(113, 116, 125,50) rs(fast, slow, smooth) => _rs1 = ta.ema(close, fast), _rs2 = ta.ema(close, slow) rs = _rs1.subtract(_rs2) rsMA = ta.sma(rs, smooth) crossUp = ta.crossover (rs, rsMA) crossDn = ta.crossunder(rs, rsMA) [n, tim] = switch crossUp => [1 , time] crossDn => [-1, time] => [0 , 0 ] [n, tim] req(timeframe, fast, slow, smooth) => [higher, highert] = request.security (syminfo.tickerid, timeframe = str.tostring(timeframe), expression = rs(fast, slow, smooth)) [lower , lowert ] = request.security_lower_tf(syminfo.tickerid, timeframe = str.tostring(timeframe), expression = rs(fast, slow, smooth), ignore_invalid_timeframe = true) [higher, highert, lower, lowert] [rs1, t1, rs1ltf, tltf1] = req(one, fast1, slow1, smooth1), [rs2, t2, rs2ltf, tltf2] = req(two, fast2, slow2, smooth2), [rs3, t3, rs3ltf, tltf3] = req(three, fast3, slow3, smooth3) determine(rs) => switch rs 1 => _Bullish -1 => _Bearish => color.black atrFunction( float ) => atr = ta.atr(30) x = float * atr + close y = float * -atr + close [x, y] [_atrH1, _atrL1] = atrFunction(2), [_atrH2, _atrL2] = atrFunction(8), [_atrH3, _atrL3] = atrFunction(12) method appendLabel(array<label> id, cond, txtu, txtd) => [upText, col, location, styl] = switch cond true => ["▲" + txtu, _Bullish, yloc.belowbar, label.style_label_up ] => [txtd + "▼", _Bearish, yloc.abovebar, label.style_label_down] id.push(label.new(time, close, upText, size = size.tiny, color = #00000000, textcolor = col, xloc = xloc.bar_time, yloc = location, style = styl )) method levelDetection (array<float> id, timefram, rsint, t1, upstr, dnstr) => if timeframe.in_seconds(timeframe.period).Float().under_equal(timeframe.in_seconds(str.tostring(timefram))) if rsint.Float().not_equal(0) [str, col, location, styl] = switch rsint.Float().equal(1) => [upstr, _Bullish, yloc.belowbar, label.style_label_up ] => [dnstr, _Bearish, yloc.abovebar, label.style_label_down] label.new(t1, close, str, size=size.large, color = #00000000, textcolor = col,xloc = xloc.bar_time, yloc = location, style = styl) else if id.size().Float().over(0) labsu = array.new_label(), labsd = array.new_label(), counteru = 0 , counterd = 0 for i = 0 to id.size().Float().subtract(1) cond = id.get(i).equal(1) if id.get(i).not_equal(0) switch id.get(i).equal(1) => counteru += 1 => counterd += 1 extraCondition = counteru.Float().over(1) [txtu, txtd] = switch extraCondition true => ["\n" + str.tostring(counteru), str.tostring(counterd) + "\n"] => ["",""] if id.get(i).equal(1) if labsu.size().Float().over(0) labsu.flush() labsu.appendLabel(cond, txtu, txtd) if id.get(i).equal(-1) if labsd.size().Float().over(0) labsd.flush() labsd.appendLabel(cond, txtu, txtd) id rs1ltf.levelDetection(one , rs1, t1, "\n▲\n①" , "\n①\n▼" ) rs2ltf.levelDetection(two , rs2, t2, "\n\n\n▲\n②" ,"\n\n②\n▼" ) rs3ltf.levelDetection(three, rs3, t3, "\n \n \n \n \n▲\n③" , "\n\n\n\n③\n▼") if barstate.islastconfirmedhistory _xo1 = determine(rs1), _xo2 = determine(rs2), _xo3 = determine(rs3) showTable = input.bool(defval = true, title = "Show Table", inline = '1', group = 'Table') positionGo = input.string("Top Right", " ", options = ["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"], inline = '1', group = 'Table') tableposGo = switch positionGo "Top Right" => position.top_right "Top Center" => position.top_center "Top Left" => position.top_left "Middle Right" => position.middle_right "Middle Center" => position.middle_center "Middle Left" => position.middle_left "Bottom Right" => position.bottom_right "Bottom Center" => position.bottom_center "Bottom Left" => position.bottom_left var table Display3 = table.new(tableposGo, 99, 99, bgcolor = color.rgb(54, 58, 69, 100), frame_width = 1, frame_color = color.rgb(255, 255, 255, 100)) if showTable table.cell(Display3, 1, 1,"①", bgcolor= color.rgb(0, 187, 212, 100), text_halign=text.align_center, text_color=_xo1, text_size=size.huge, text_font_family = font.family_monospace) table.cell(Display3, 2, 1,"②", bgcolor= color.rgb(0, 187, 212, 100), text_halign=text.align_center, text_color=_xo2, text_size=size.huge, text_font_family = font.family_monospace) table.cell(Display3, 3, 1,"③", bgcolor= color.rgb(0, 187, 212, 100), text_halign=text.align_center, text_color=_xo3, text_size=size.huge, text_font_family = font.family_monospace) if showMin table.cell(Display3, 1, 2,str.tostring(one)+" min", bgcolor= color.rgb(0, 187, 212, 100), text_halign=text.align_center, text_color=_xo1, text_size=size.normal, text_font_family = font.family_monospace) table.cell(Display3, 2, 2,str.tostring(two)+" min", bgcolor= color.rgb(0, 187, 212, 100), text_halign=text.align_center, text_color=_xo2, text_size=size.normal, text_font_family = font.family_monospace) table.cell(Display3, 3, 2,str.tostring(three)+" min", bgcolor= color.rgb(0, 187, 212, 100), text_halign=text.align_center, text_color=_xo3, text_size=size.normal, text_font_family = font.family_monospace) if showSMA table.cell(Display3, 1, 3,"══════════",bgcolor= color.rgb(0, 187, 212, 100),text_halign=text.align_center, text_color=_xo1, text_size=size.normal, text_font_family = font.family_monospace) table.cell(Display3, 2, 3,"══════════",bgcolor= color.rgb(0, 187, 212, 100),text_halign=text.align_center, text_color=_xo1, text_size=size.normal, text_font_family = font.family_monospace) table.cell(Display3, 3, 3,"══════════",bgcolor= color.rgb(0, 187, 212, 100),text_halign=text.align_center, text_color=_xo1, text_size=size.normal, text_font_family = font.family_monospace) table.cell(Display3, 1, 4,"SMA ",bgcolor= color.rgb(0, 187, 212, 100),text_halign=text.align_center, text_color=_trend, text_size=size.normal, text_font_family = font.family_monospace) table.cell(Display3, 2, 4,str.tostring(_smaLen),bgcolor= color.rgb(0, 187, 212, 100),text_halign=text.align_center, text_color=_trend, text_size=size.normal, text_font_family = font.family_monospace) table.cell(Display3, 3, 4, _time,bgcolor= color.rgb(0, 187, 212, 100),text_halign=text.align_center, text_color=_trend, text_size=size.normal, text_font_family = font.family_monospace) plot(showSMA ? _sma13 : na, 'SMA 13', color= _trend, linewidth = _smaWt, display = display.all) plot(_atrL1,'ATR Low', color=color.rgb(255, 0, 0), style = plot.style_line, linewidth = 2, display = display.all, show_last = 1) plot(_atrH1,'ATR Low', color=color.rgb(255, 0, 0), style = plot.style_line, linewidth = 2, display = display.all, show_last = 1) plot(_atrL2,'ATR Low', color=color.rgb(166, 0, 0), style = plot.style_line, linewidth = 2, display = display.all, show_last = 1) plot(_atrH2,'ATR Low', color=color.rgb(166, 0, 0), style = plot.style_line, linewidth = 2, display = display.all, show_last = 1) plot(_atrL3,'ATR Low', color=color.rgb(79, 1, 1), style = plot.style_line, linewidth = 2, display = display.all, show_last = 1) plot(_atrH3,'ATR Low', color=color.rgb(79, 1, 1), style = plot.style_line, linewidth = 2, display = display.all, show_last = 1)
HelperTA
https://www.tradingview.com/script/3yk4SvI6-HelperTA/
leap-forward
https://www.tradingview.com/u/leap-forward/
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/ // © leap-forward //@version=5 // @description TODO: add library description here library("HelperTA", true) // @function stockRSI // @returns <[k, d]> export stockRSI(series float src, int K, int D, int rsiPeriod, int stochPeriod) => rsi1 = ta.rsi(src, rsiPeriod) k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, stochPeriod), K) d = ta.sma(k, D) [k, d] // @function DCO // @returns <[DCO, s]> export DCO(series float price, int donchianPeriod, int smaPeriod) => lower = ta.lowest(price, donchianPeriod) upper = ta.highest(price, donchianPeriod) DCO = (price-lower)/(upper-lower)*100 s = ta.sma(DCO, smaPeriod) [DCO, s] // @function MarketCycle // @returns <aggr> export MarketCycle(series float donchianPrice, series float rsiPrice, series float srsiPrice, simple int donchianPeriod, simple int donchianSmoothing, simple int rsiPeriod, int rsiSmoothing, simple int srsiPeriod, simple int srsiSmoothing, simple int srsiK, simple int srsiD, simple float rsiWeight, simple float srsiWeight, simple float dcoWeight) => // DCO [DCO, DCOs] = DCO(donchianPrice, donchianPeriod, donchianSmoothing) // RSI rsiValue = ta.rsi(rsiPrice, rsiPeriod) rsiK = ta.sma(rsiValue, rsiSmoothing) // StochRSI [k, d] = stockRSI(srsiPrice, srsiK, srsiD, srsiPeriod, srsiSmoothing) // Weighted aggregate tw = rsiWeight + srsiWeight + dcoWeight aggr = ((DCO + DCOs)*dcoWeight + (rsiValue + rsiK)*rsiWeight + (k + d)*srsiWeight) / (2*(dcoWeight+rsiWeight+srsiWeight)) aggr
Vector3
https://www.tradingview.com/script/Wximy5Sk-Vector3/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
45
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 Representation of 3D vectors and points. // This structure is used to pass 3D positions and directions around. It also contains functions for doing common vector operations. // Besides the functions listed below, other classes can be used to manipulate vectors and points as well. // For example the Quaternion and the Matrix4x4 classes are useful for rotating or transforming vectors and points. // ___ // **Reference:** // - https://github.com/phoboslab/q1k3/blob/master/source/math_utils.js // - https://github.com/lauripiispanen/vectorz/blob/master/3d.js // - https://github.com/thormeier/vanilla-vectors-3d/blob/master/src/Vector.js // - http://www.movable-type.co.uk/scripts/geodesy/docs/vector3d.js.html // - https://docs.unity3d.com/ScriptReference/Vector3.html // - https://referencesource.microsoft.com/#System.Numerics/System/Numerics/Vector3.cs // - https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector3.cs // \ library(title = 'Vector3') // <-- 101 Character spaces. -->| // 3456789 123456789 123456789 123456789 123456789|123456789 123456789 123456789 123456789 123456789| // | | | | | | | | | | | | | | //#region 0: Pre loading and module dependencies. //#region 0.0: Imports: import RicardoSantos/CommonTypesMath/1 as TMath import RicardoSantos/Vector2/1 as V2 import RicardoSantos/Vector2DrawLine/1 as DrawLine import RicardoSantos/DebugConsole/12 as console //#endregion 0.0 //#region 0.1: Constants: console.Console logger = console.new() //#endregion 0.1 //#region 0.2: Helpers: //#endregion 0.2 //#endregion 0 //#region 1: Constructor. // > - Methods to Initialize the structure of a `Vector3` //#region 1.1: Basic Constructor: //#region 1.1.1: new () // @function Create a new `Vector3`. // @param x `float` Property `x` value, (optional, default=na). // @param y `float` Property `y` value, (optional, default=na). // @param z `float` Property `z` value, (optional, default=na). // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .new(1.1, 1, 1) // ``` export new (float x = na, float y = na, float z = na) => TMath.Vector3.new(x, y, z) //#endregion 1.1.1 //#region 1.1.2: from () // @function Create a new `Vector3` from a single value. // @param value `float` Properties positional value, (optional, default=na). // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .from(1.1) // ``` export from (float value = na) => TMath.Vector3.new(value, value, value) //#endregion 1.1.2 //#region 1.1.3: from_Array () // @function Create a new `Vector3` from a list of values, only reads up to the third item. // @param values `array<float>` Vector property values. // @param fill_na `float` Parameter value to replace missing indexes, (optional, defualt=na). // @returns `Vector3` Generated new vector. // ___ // **Notes:** // - Supports any size of array, fills non available fields with `na`. // ___ // **Usage:** // ``` // .from_Array(array.from(1.1, fill_na=33)) // .from_Array(array.from(1.1, 2, 3)) // ``` export from_Array (array<float> values, float fill_na=na) => switch values.size() 00 => TMath.Vector3.new(fill_na , fill_na , fill_na ) 01 => TMath.Vector3.new(values.get(0), fill_na , fill_na ) 02 => TMath.Vector3.new(values.get(0), values.get(1), fill_na ) => TMath.Vector3.new(values.get(0), values.get(1), values.get(2)) // TEST 20230512 OK RS // if barstate.islast // _tmp0 = from_Array(array.new<float>(), 123) // _tmp1 = from_Array(array.from(1.0)) // _tmp2 = from_Array(array.from(1.0, 2.0)) // _tmp3 = from_Array(array.from(1.0, 2.0, 3.0)) // logger.queue_one('x: ' + str.tostring(_tmp0.x) + ' y: ' + str.tostring(_tmp0.y) + ' z: ' + str.tostring(_tmp0.z)) // logger.queue_one('x: ' + str.tostring(_tmp1.x) + ' y: ' + str.tostring(_tmp1.y) + ' z: ' + str.tostring(_tmp1.z)) // logger.queue_one('x: ' + str.tostring(_tmp2.x) + ' y: ' + str.tostring(_tmp2.y) + ' z: ' + str.tostring(_tmp2.z)) // logger.queue_one('x: ' + str.tostring(_tmp3.x) + ' y: ' + str.tostring(_tmp3.y) + ' z: ' + str.tostring(_tmp3.z)) //#endregion 1.1.3 //#region 1.1.4: from_Vector2 () // @function Create a new `Vector3` from a `Vector2`. // @param values `Vector2` Vector property values. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .from:Vector2(.Vector2.new(1, 2.0)) // ``` // ___ // **Notes:** // - Type `Vector2` from CommonTypesMath library. export from_Vector2 (TMath.Vector2 values) => TMath.Vector3.new(values.x, values.y, float(na)) //#endregion 1.1.4 //#region 1.1.5: from_Quaternion () // @function Create a new `Vector3` from a `Quaternion`'s `x, y, z` properties. // @param values `Quaternion` Vector property values. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .from_Quaternion(.Quaternion.new(1, 2, 3, 4)) // ``` // ___ // **Notes:** // - Type `Quaternion` from CommonTypesMath library. export from_Quaternion (TMath.Quaternion values) => TMath.Vector3.new(values.x, values.y, values.z) //#endregion 1.1.5 //#region 1.1.6: from_String () // @function Create a new `Vector3` from a list of values in a formated string. // @param expression `array<float>` String with the list of vector properties. // @param separator `string` Separator between entries, (optional, default=`","`). // @param fill_na `float` Parameter value to replace missing indexes, (optional, defualt=na). // @returns `Vector3` Generated new vector. // ___ // **Notes:** // - Supports any size of array, fills non available fields with `na`. // - `",,"` Empty fields will be ignored. // ___ // **Usage:** // ``` // .from_String("1.1", fill_na=33)) // .from_String("(1.1,, 3)") // 1.1 , 3.0, NaN // empty field will be ignored!! // ``` export from_String (string expression, string separator=',', float fill_na=na) => array<string> _values = str.split(expression, separator) switch _values.size() 00 => TMath.Vector3.new(fill_na , fill_na , fill_na) 01 => TMath.Vector3.new(str.tonumber(_values.get(0)), fill_na , fill_na) 02 => TMath.Vector3.new(str.tonumber(_values.get(0)), str.tonumber(_values.get(1)), fill_na) => TMath.Vector3.new(str.tonumber(_values.get(0)), str.tonumber(_values.get(1)), str.tonumber(_values.get(2))) // if barstate.islast // _v = from_String('1.0, , 3') // logger.queue(str.format('x: {0}, y: {1}, z: {2}', _v.x, _v.y, _v.z)) //#endregion 1.1.6 //#endregion 1.1 //#region 1.2: Static Properties: //#region 1.2.01: back () // @function Create a new `Vector3` object in the form `(0, 0, -1)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .back() // ``` export back () => TMath.Vector3.new(0.0, 0.0, -1.0) //#endregion 1.2.1 //#region 1.2.02: front () // @function Create a new `Vector3` object in the form `(0, 0, 1)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .front() // ``` export front () => TMath.Vector3.new(0.0, 0.0, 1.0) //#endregion 1.2.2 //#region 1.2.03: up () // @function Create a new `Vector3` object in the form `(0, 1, 0)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .up() // ``` export up () => TMath.Vector3.new(0.0, 1.0, 0.0) //#endregion 1.2.3 //#region 1.2.04: down () // @function Create a new `Vector3` object in the form `(0, -1, 0)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .down() // ``` export down () => TMath.Vector3.new(0.0, -1.0, 0.0) //#endregion 1.2.4 //#region 1.2.05: left () // @function Create a new `Vector3` object in the form `(-1, 0, 0)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .left() // ``` export left () => TMath.Vector3.new(-1.0, 0.0, 0.0) //#endregion 1.2.5 //#region 1.2.06: right () // @function Create a new `Vector3` object in the form `(1, 0, 0)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .right() // ``` export right () => TMath.Vector3.new(1.0, 0.0, 0.0) //#endregion 1.2.6 //#region 1.2.07: zero () // @function Create a new `Vector3` object in the form `(0, 0, 0)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .zero() // ``` export zero () => TMath.Vector3.new(0.0, 0.0, 0.0) //#endregion 1.2.7 //#region 1.2.08: one () // @function Create a new `Vector3` object in the form `(1, 1, 1)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .one() // ``` export one () => TMath.Vector3.new(1.0, 1.0, 1.0) //#endregion 1.2.8 //#region 1.2.09: minus_one () // @function Create a new `Vector3` object in the form `(-1, -1, -1)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .minus_one() // ``` export minus_one () => TMath.Vector3.new(-1.0, -1.0, -1.0) //#endregion 1.2.9 //#region 1.2.10: unit_x () // @function Create a new `Vector3` object in the form `(1, 0, 0)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .unit_x() // ``` export unit_x () => TMath.Vector3.new(1.0, 0.0, 0.0) //#endregion 1.2.10 //#region 1.2.11: unit_y () // @function Create a new `Vector3` object in the form `(0, 1, 0)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .unit_y() // ``` export unit_y () => TMath.Vector3.new(0.0, 1.0, 0.0) //#endregion 1.2.11 //#region 1.2.12: unit_z () // @function Create a new `Vector3` object in the form `(0, 0, 1)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .unit_z() // ``` export unit_z () => TMath.Vector3.new(0.0, 0.0, 1.0) //#endregion 1.2.12 //#region 1.2.13: nan () // @function Create a new `Vector3` object in the form `(na, na, na)`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .nan() // ``` export nan () => TMath.Vector3.new(float(na), float(na), float(na)) //#endregion 1.2.13 //#endregion 1.2 //#region 1.3: Random Generation: //#region 1.3.1: random () min, max // @function Generate a vector with random properties. // @param max `Vector3` Maximum defined range of the vector properties. // @param min `Vector3` Minimum defined range of the vector properties. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .random(.from(math.pi), .from(-math.pi)) // ``` export random (TMath.Vector3 max, TMath.Vector3 min) => TMath.Vector3.new(math.random(min.x, max.x), math.random(min.y, max.y), math.random(min.z, max.z)) //#endregion 1.3.1 //#region 1.3.2: random () max // @function Generate a vector with random properties (min set to 0.0). // @param max `Vector3` Maximum defined range of the vector properties. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // .random(.from(math.pi)) // ``` export random (TMath.Vector3 max) => TMath.Vector3.new(math.random(0.0, max.x), math.random(0.0, max.y), math.random(0.0, max.z)) //#endregion 1.3.2 //#region 1.3.3: random () min, max, seed *NI* // *NI*: Not Implemented // // @function Generate a vector with random properties with a specified seed. // // @param max `Vector3` Maximum defined range of the vector properties. // // @param min `Vector3` Minimum defined range of the vector properties. // // @param seed `int` Seed parameter for reproduction of values. // // @returns `Vector3`. // export random (TMath.Vector3 max, TMath.Vector3 min, int seed) => // TMath.Vector3.new(math.random(min.x, max.x, seed), math.random(min.y, max.y, seed), math.random(min.z, max.z, seed)) //#endregion 1.3.3 //#region 1.3.4: random () max, seed *NI* // *NI*: Not Implemented // // @function Generate a vector with random properties (min set to 0.0) with a specified seed. // // @param max `Vector3` Maximum defined range of the vector properties. // // @param seed `int` Seed parameter for reproduction of values. // // @returns `Vector3`. // export random (TMath.Vector3 max, simple int seed) => // TMath.Vector3.new(math.random(0.0, max.x, seed), math.random(0.0, max.y, seed), math.random(0.0, max.z, seed)) //#endregion 1.3.4 //#endregion 1.3 //#endregion 1 //#region 2: Class Methods. // > - Methods that pass its class in the first argument (not exactly the same as other languages), // and are callable from the namespace of its class. // ex:. `method fun(vector3 this) => this.x` , `a = vector3.new()` , `a.fun()` //#region 2.1: Instance: //#region 2.1.1: copy () // @function Copy a existing `Vector3` // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .one().copy() // ``` export method copy (TMath.Vector3 this) => TMath.Vector3.copy(this) //#endregion 2.1.1 //#region 2.1.2: Inplace Operators: // > - A set of operators that manipulate the source vector. //#region 2.1.2.1: i_add () //#region 2.1.2.1.1: Vector3 + Vector3 // @function Modify a instance of a vector by adding a vector to it. // @param this `Vector3` Source vector. // @param other `Vector3` Other Vector. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_add(.up()) // ``` export method i_add (TMath.Vector3 this, TMath.Vector3 other) => this.x += other.x this.y += other.y this.z += other.z this // TEST 20230515 RS // if barstate.islast // _v = from(1), logger.queue_one('origin: ' + str.tostring(_v.x) + ' ' + str.tostring(_v.y) + ' ' + str.tostring(_v.z)) // _v.i_add(_v), logger.queue_one('added : ' + str.tostring(_v.x) + ' ' + str.tostring(_v.y) + ' ' + str.tostring(_v.z)) //#endregion 2.1.2.1.1 //#region 2.1.2.1.2: Vector3 + float // @function Modify a instance of a vector by adding a vector to it. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_add(3.2) // ``` export method i_add (TMath.Vector3 this, float value) => this.x += value this.y += value this.z += value this //#endregion 2.1.2.1.2 //#endregion 2.1.2.1 //#region 2.1.2.2: i_subtract () //#region 2.1.2.2.1: Vector3 - Vector3 // @function Modify a instance of a vector by subtracting a vector to it. // @param this `Vector3` Source vector. // @param other `Vector3` Other Vector. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_subtract(.down()) // ``` export method i_subtract (TMath.Vector3 this, TMath.Vector3 other) => this.x -= other.x this.y -= other.y this.z -= other.z this //#endregion 2.1.2.2.1 //#region 2.1.2.2.2: Vector3 - float // @function Modify a instance of a vector by subtracting a vector to it. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_subtract(3) // ``` export method i_subtract (TMath.Vector3 this, float value) => this.x -= value this.y -= value this.z -= value this //#endregion 2.1.2.2.2 //#endregion 2.1.2.2 //#region 2.1.2.3: i_multiply () //#region 2.1.2.3.1: Vector3 * Vector3 // @function Modify a instance of a vector by multiplying a vector with it. // @param this `Vector3` Source vector. // @param other `Vector3` Other Vector. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_multiply(.left()) // ``` export method i_multiply (TMath.Vector3 this, TMath.Vector3 other) => this.x *= other.x this.y *= other.y this.z *= other.z this //#endregion 2.1.2.3.1 //#region 2.1.2.3.2: Vector3 * float // @function Modify a instance of a vector by multiplying a vector with it. // @param this `Vector3` Source vector. // @param value `float` value. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_multiply(3) // ``` export method i_multiply (TMath.Vector3 this, float value) => this.x *= value this.y *= value this.z *= value this //#endregion 2.1.2.3.2 //#endregion 2.1.2.3 //#region 2.1.2.4: i_divide () //#region 2.1.2.4.1: Vector3 / Vector3 // @function Modify a instance of a vector by dividing it by another vector. // @param this `Vector3` Source vector. // @param other `Vector3` Other Vector. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_divide(.forward()) // ``` export method i_divide (TMath.Vector3 this, TMath.Vector3 other) => this.x /= other.x this.y /= other.y this.z /= other.z this //#endregion 2.1.2.4.1 //#region 2.1.2.4.2: Vector3 / float // @function Modify a instance of a vector by dividing it by another vector. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_divide(3) // ``` export method i_divide (TMath.Vector3 this, float value) => this.x /= value this.y /= value this.z /= value this //#endregion 2.1.2.4.2 //#endregion 2.1.2.4 //#region 2.1.2.5: i_mod () //#region 2.1.2.5.1: Vector3 % Vector3 // @function Modify a instance of a vector by modulo assignment with another vector. // @param this `Vector3` Source vector. // @param other `Vector3` Other Vector. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_mod(.back()) // ``` export method i_mod (TMath.Vector3 this, TMath.Vector3 other) => this.x %= other.x this.y %= other.y this.z %= other.z this // TEST 20230515 RS // if barstate.islast // _v = from(12) , logger.queue_one('origin: ' + str.tostring(_v.x) + ' ' + str.tostring(_v.y) + ' ' + str.tostring(_v.z)) // //_v.i_mod(from(3)) , logger.queue_one('mod3 : ' + str.tostring(_v.x) + ' ' + str.tostring(_v.y) + ' ' + str.tostring(_v.z)) // _v.i_mod(from(5)) , logger.queue_one('mod5 : ' + str.tostring(_v.x) + ' ' + str.tostring(_v.y) + ' ' + str.tostring(_v.z)) //#endregion 2.1.2.5.1 //#region 2.1.2.5.2: Vector3 % float // @function Modify a instance of a vector by modulo assignment with another vector. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_mod(3) // ``` export method i_mod (TMath.Vector3 this, float value) => this.x %= value this.y %= value this.z %= value this //#endregion 2.1.2.5.2 //#endregion 2.1.2.5 //#region 2.1.2.6: i_pow () //#region 2.1.2.6.1: Vector3 ^ Vector3 // @function Modify a instance of a vector by modulo assignment with another vector. // @param this `Vector3` Source vector. // @param exponent `Vector3` Exponent Vector. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_pow(.up()) // ``` export method i_pow (TMath.Vector3 this, TMath.Vector3 exponent) => this.x := math.pow(this.x, exponent.x) this.y := math.pow(this.y, exponent.y) this.z := math.pow(this.z, exponent.z) this //#endregion 2.1.2.6.1 //#region 2.1.2.6.2: Vector3 ^ float // @function Modify a instance of a vector by modulo assignment with another vector. // @param this `Vector3` Source vector. // @param exponent `float` Exponent Value. // @returns `Vector3` Updated source vector. // ___ // **Usage:** // ``` // a = .from(1) , a.i_pow(2) // ``` export method i_pow (TMath.Vector3 this, float exponent) => this.x := math.pow(this.x, exponent) this.y := math.pow(this.y, exponent) this.z := math.pow(this.z, exponent) this //#endregion 2.1.2.6.2 //#endregion 2.1.2.6 //#endregion 2.1.2 //#endregion 2.1 //#region 2.2: Properties: //#region 2.2.1: length_squared () // @function Squared length of the vector. // @param a `Vector3` Source vector. // @returns `float` The squared length of this vector. // ___ // **Usage:** // ``` // a = .one().length_squared() // ``` export method length_squared (TMath.Vector3 this) => (this.x * this.x) + (this.y * this.y) + (this.z * this.z) //#endregion 2.2.1 //#region 2.2.2: magnitude_squared () // @function Squared magnitude of the vector. // @param this `Vector3` Source vector. // @returns `float` The length squared of this vector. // ___ // **Usage:** // ``` // a = .one().magnitude_squared() // ``` export method magnitude_squared (TMath.Vector3 this) => (this.x * this.x) + (this.y * this.y) + (this.z * this.z) //#endregion 2.2.2 //#region 2.2.3: length () // @function Length of the vector. // @param this `Vector3` Source vector. // @returns `float` The length of this vector. // ___ // **Usage:** // ``` // a = .one().length() // ``` export method length (TMath.Vector3 this) => math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z)) //#endregion 2.2.3 //#region 2.2.4: magnitude () // @function Magnitude of the vector. // @param this `Vector3` Source vector. // @returns `float` The Length of this vector. // ___ // **Usage:** // ``` // a = .one().magnitude() // ``` export method magnitude (TMath.Vector3 this) => math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z)) //#endregion 2.2.4 //#region 2.2.5: normalize () // @function Normalize a vector with a magnitude of 1(optional). // @param this `Vector3` Source vector. // @param magnitude `float` Value to manipulate the magnitude of normalization, (optional, default=1.0). // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .new(33, 50, 100).normalize() // (x=0.283, y=0.429, z=0.858) // a = .new(33, 50, 100).normalize(2) // (x=0.142, y=0.214, z=0.429) // ``` export method normalize (TMath.Vector3 this, float magnitude = 1.0, float eps = 0.000001) => float _magnitude = this.length() * magnitude if _magnitude > eps float _m = 1.0 / _magnitude TMath.Vector3.new(this.x * _m, this.y * _m, this.z * _m) else zero() // if barstate.islast // a = new(33, 50, 100).normalize() // b = new(33, 50, 100).normalize(2) // logger.queue(str.format('a: {0}, {1}, {2}', a.x, a.y, a.z)) // logger.queue(str.format('b: {0}, {1}, {2}', b.x, b.y, b.z)) //#endregion 2.2.1 //#endregion 2.2 //#region 2.3: Type Conversion: //#region 2.3.1: to_String () // @function Converts source vector to a string format, in the form `"(x, y, z)"`. // @param this `Vector3` Source vector. // @param precision `string` Precision format to apply to values (optional, default=''). // @returns `string` Formated string in a `"(x, y, z)"` format. // ___ // **Usage:** // ``` // a = .one().to_String("#.###") // ``` export method to_String (TMath.Vector3 this, string precision = '') => switch precision '' => str.format('({0}, {1}, {2})', this.x, this.y, this.z) => str.format( '({0,number,' + precision + '}, {0,number,' + precision + '}, {0,number,' + precision + '})', this.x, this.y, this.z ) //#endregion 2.3.1 //#region 2.3.2: to_Array () // @function Converts source vector to a array format. // @param this `Vector3` Source vector. // @returns `array<float>` List of the vector properties. // ___ // **Usage:** // ``` // a = .new(1, 2, 3).to_Array() // ``` export method to_Array (TMath.Vector3 this) => array<float> _return = array.from(float(this.x), float(this.y), float(this.z)) //#endregion 2.3.2 //#region 2.3.3: to_Vector2 () // @function Converts source vector to a Vector2 in the form `x, y`. // @param this `Vector3` Source vector. // @returns `Vector2` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).to_Vector2() // ``` export method to_Vector2 (TMath.Vector3 this) => TMath.Vector2.new(this.x, this.y) //#endregion 2.3.3 //#region 2.3.4: to_Quaternion () // @function Converts source vector to a Quaternion in the form `x, y, z, w`. // @param this `Vector3` Sorce vector. // @param w `float` Property of `w` new value. // @returns `Quaternion` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).to_Quaternion(w=1) // ``` export method to_Quaternion (TMath.Vector3 this, float w = na) => TMath.Quaternion.new(this.x, this.y, this.z, w) //#endregion 2.3.4 //#endregion 2.3 //#region 2.4: Operators: //#region 2.4.01: add () //#region 2.4.01.1: Vector3 + Vector3 // @function Add a vector to source vector. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).add(.unit_z()) // ``` export method add (TMath.Vector3 this, TMath.Vector3 other) => TMath.Vector3.new(this.x + other.x, this.y + other.y, this.z + other.z) //#endregion 2.4.01.1 //#region 2.4.01.2: Vector3 + float // @function Add a value to each property of the vector. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).add(2.0) // ``` export method add (TMath.Vector3 this, float value) => TMath.Vector3.new(this.x + value, this.y + value, this.z + value) //#endregion 2.4.01.2 //#region 2.4.01.3: float + Vector3 // @function Add each property of a vector to a base value as a new vector. // @param value `float` Value. // @param other `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(2) , b = .add(1.0, a) // ``` export add (float value, TMath.Vector3 other) => TMath.Vector3.new(value + other.x, value + other.y, value + other.z) //#endregion 2.4.01.3 //#endregion 2.4.01 //#region 2.4.02: subtract () //#region 2.4.02.1: Vector3 - Vector3 // @function Subtract vector from source vector. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).subtract(.left()) // ``` export method subtract (TMath.Vector3 this, TMath.Vector3 other) => TMath.Vector3.new(this.x - other.x, this.y - other.y, this.z - other.z) //#endregion 2.4.02.1 //#region 2.4.02.2: Vector3 - float // @function Subtract a value from each property in source vector. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).subtract(2.0) // ``` export method subtract (TMath.Vector3 this, float value) => TMath.Vector3.new(this.x - value, this.y - value, this.z - value) //#endregion 2.4.02.2 //#region 2.4.02.3: float - Vector3 // @function Subtract each property in a vector from a base value and create a new vector. // @param value `float` Value. // @param other `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .subtract(1.0, .right()) // ``` export subtract (float value, TMath.Vector3 other) => TMath.Vector3.new(value - other.x, value - other.y, value - other.z) //#endregion 2.4.02.3 //#endregion 2.4.02 //#region 2.4.03: multiply () //#region 2.4.03.1: Vector3 * Vector3 // @function Multiply a vector by another. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).multiply(.up()) // ``` export method multiply (TMath.Vector3 this, TMath.Vector3 other) => TMath.Vector3.new(this.x * other.x, this.y * other.y, this.z * other.z) //#endregion 2.4.03.1 //#region 2.4.03.2: Vector3 * float // @function Multiply each element in source vector with a value. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).multiply(2.0) // ``` export method multiply (TMath.Vector3 this, float value) => TMath.Vector3.new(this.x * value, this.y * value, this.z * value) //#endregion 2.4.03.2 //#region 2.4.03.3: float * Vector3 // @function Multiply a value with each property in a vector and create a new vector. // @param value `float` Value. // @param other `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .multiply(1.0, .new(1, 2, 1)) // ``` export multiply (float value, TMath.Vector3 other) => TMath.Vector3.new(value * other.x, value * other.y, value * other.z) //#endregion 2.4.03.3 //#endregion 2.4.03 //#region 2.4.04: divide () //#region 2.4.04.1: Vector3 / Vector3 // @function Divide a vector by another. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).divide(.from(2)) // ``` export method divide (TMath.Vector3 this, TMath.Vector3 other) => TMath.Vector3.new(this.x / other.x, this.y / other.y, this.z / other.z) //#endregion 2.4.04.1 //#region 2.4.04.2: Vector3 / float // @function Divide each property in a vector by a value. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).divide(2.0) // ``` export method divide (TMath.Vector3 this, float value) => TMath.Vector3.new(this.x / value, this.y / value, this.z / value) //#endregion 2.4.04.2 //#region 2.4.04.3: float / Vector3 // @function Divide a base value by each property in a vector and create a new vector. // @param value `float` Value. // @param other `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .divide(1.0, .from(2)) // ``` export divide (float value, TMath.Vector3 other) => TMath.Vector3.new(value / other.x, value / other.y, value / other.z) //#endregion 2.4.04.3 //#endregion 2.4.04 //#region 2.4.05: mod () //#region 2.4.05.1: Vector3 / Vector3 // @function Modulo a vector by another. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).mod(.from(2)) // ``` export method mod (TMath.Vector3 this, TMath.Vector3 other) => TMath.Vector3.new(this.x % other.x, this.y % other.y, this.z % other.z) //#endregion 2.4.05.1 //#region 2.4.05.2: Vector3 / float // @function Modulo each property in a vector by a value. // @param this `Vector3` Source vector. // @param value `float` Value. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).mod(2.0) // ``` export method mod (TMath.Vector3 this, float value) => TMath.Vector3.new(this.x % value, this.y % value, this.z % value) //#endregion 2.4.05.2 //#region 2.4.05.3: float / Vector3 // @function Modulo a base value by each property in a vector and create a new vector. // @param value `float` Value. // @param other `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .mod(1.0, .from(2)) // ``` export mod (float value, TMath.Vector3 other) => TMath.Vector3.new(value % other.x, value % other.y, value % other.z) //#endregion 2.4.05.3 //#endregion 2.4.05 //#region 2.4.06: negate () // @function Negate a vector in the form `(zero - this)`. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .one().negate() // ``` export method negate (TMath.Vector3 this) => TMath.Vector3.new(0.0 - this.x, 0.0 - this.y, 0.0 - this.z) //#endregion 2.4.6 //#region 2.4.07: pow () //#region 2.4.07.1: Vector3 ^ Vector3 // @function Modulo a vector by another. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(2).pow(.from(3)) // ``` export method pow (TMath.Vector3 this, TMath.Vector3 other) => TMath.Vector3.new(math.pow(this.x, other.x), math.pow(this.y, other.y), math.pow(this.z, other.z)) //#endregion 2.4.07.1 //#region 2.4.07.2: Vector3 ^ float // @function Raise the vector elements by a exponent. // @param this `Vector3` Source vector. // @param exponent `float` The exponent to raise the vector by. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).pow(2.0) // ``` export method pow (TMath.Vector3 this, float exponent) => TMath.Vector3.new(math.pow(this.x, exponent), math.pow(this.y, exponent), math.pow(this.z, exponent)) //#endregion 2.4.07.2 //#region 2.4.07.3: float ^ Vector3 // @function Raise value into a vector raised by the elements in exponent vector. // @param value `float` Base value. // @param exponent `Vector3` The exponent to raise the vector of base value by. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .pow(1.0, .from(2)) // ``` export pow (float value, TMath.Vector3 exponent) => TMath.Vector3.new(math.pow(value, exponent.x), math.pow(value, exponent.y), math.pow(value, exponent.z)) //#endregion 2.4.07.3 //#endregion 2.4.07 //#region 2.4.08: sqrt () // @function Square root of the elements in a vector. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).sqrt() // ``` export method sqrt (TMath.Vector3 this) => TMath.Vector3.new(math.sqrt(this.x), math.sqrt(this.y), math.sqrt(this.z)) //#endregion 2.4.08 //#region 2.4.09: abs () // @function Absolute properties of the vector. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).abs() // ``` export method abs (TMath.Vector3 this) => TMath.Vector3.new(math.abs(this.x), math.abs(this.y), math.abs(this.z)) //#endregion 2.4.09 //#region 2.4.10: max () // @function Highest property of the vector. // @param this `Vector3` Source vector. // @returns `float` Highest value amongst the vector properties. // ___ // **Usage:** // ``` // a = .new(1, 2, 3).max() // ``` export method max (TMath.Vector3 this) => math.max(this.x, this.y, this.z) //#endregion 2.4.10 //#region 2.4.11: min () // @function Lowest element of the vector. // @param this `Vector3` Source vector. // @returns `float` Lowest values amongst the vector properties. // ___ // **Usage:** // ``` // a = .new(1, 2, 3).min() // ``` export method min (TMath.Vector3 this) => math.min(this.x, this.y, this.z) //#endregion 2.4.11 //#region 2.4.12: floor () // @function Floor of vector a. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .new(1.33, 1.66, 1.99).floor() // ``` export method floor (TMath.Vector3 this) => TMath.Vector3.new(math.floor(this.x), math.floor(this.y), math.floor(this.z)) //#endregion 2.4.12 //#region 2.4.13: ceil () // @function Ceil of vector a. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .new(1.33, 1.66, 1.99).ceil() // ``` export method ceil (TMath.Vector3 this) => TMath.Vector3.new(math.ceil(this.x), math.ceil(this.y), math.ceil(this.z)) //#endregion 2.4.13 //#region 2.4.14: round () //#region 2.4.14.1: with out precision. // @function Round of vector elements. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .new(1.33, 1.66, 1.99).round() // ``` export method round (TMath.Vector3 this) => TMath.Vector3.new(math.round(this.x), math.round(this.y), math.round(this.z)) //#endregion 2.4.14.1 //#region 2.4.14.2: with precision. // @function Round of vector elements to n digits. // @param this `Vector3` Source vector. // @param precision `int` Number of digits to round the vector elements. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .new(1.33, 1.66, 1.99).round(1) // 1.3, 1.7, 2 // ``` export method round (TMath.Vector3 this, int precision) => int _d = math.max(0, precision) TMath.Vector3.new(math.round(this.x, _d), math.round(this.y, _d), math.round(this.z, _d)) //#endregion 2.4.14.2 //#endregion 2.4.14 //#region 2.4.15: fractional () // @function Fractional parts of vector. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1.337).fractional() // 0.337 // ``` export method fractional (TMath.Vector3 this) => TMath.Vector3.new(this.x - math.floor(this.x), this.y - math.floor(this.y), this.z - math.floor(this.z)) //#endregion 2.4.15 //#region 2.4.16: dot_product () // @function Dot product of two vectors. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `float` Dot product. // ___ // **Usage:** // ``` // a = .from(2).dot_product(.left()) // ``` export method dot_product (TMath.Vector3 this, TMath.Vector3 other) => this.x * other.x + this.y * other.y + this.z * other.z //#endregion 2.4.16 //#region 2.4.17: cross_product () // @function Cross product of two vectors. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).cross_produc(.right()) // ``` export method cross_product (TMath.Vector3 this, TMath.Vector3 other) => TMath.Vector3.new( this.y * other.z - this.z * other.y, this.z * other.x - this.x * other.z, this.x * other.y - this.y * other.x ) //#endregion 2.4.17 //#region 2.4.18: scale () // @function Scale vector by a scalar value. // @param this `Vector3` Source vector. // @param scalar `float` Value to scale the the vector by. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).scale(2) // ``` export method scale (TMath.Vector3 this, float scalar) => TMath.Vector3.new(this.x * scalar, this.y * scalar, this.z * scalar) //#endregion 2.4.18 //#region 2.4.19: rescale () // @function Rescale a vector to a new magnitude. // @param this `Vector3` Source vector. // @param magnitude `float` Value to manipulate the magnitude of normalization. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(20).rescale(1) // ``` export method rescale (TMath.Vector3 this, float magnitude) => float _scalar = magnitude / this.length() multiply(this, _scalar) //#endregion 2.4.19 //#region 2.4.20: equals () // @function Compares two vectors. // @param this `Vector3` Source vector. // @param other `Vector3` Other vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).equals(.one()) // ``` export method equals (TMath.Vector3 this, TMath.Vector3 other) => this.x == other.x and this.y == other.y and this.z == other.z //#endregion 2.4.20 //#endregion 2.4 //#region 2.5: Trigonometry: //#region 2.5.1: sin () // @function Sine of vector. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).sin() // ``` export method sin (TMath.Vector3 this) => TMath.Vector3.new(math.sin(this.x), math.sin(this.y), math.sin(this.z)) //#endregion 2.5.1 //#region 2.5.2: cos () // @function Cosine of vector. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).cos() // ``` export method cos (TMath.Vector3 this) => TMath.Vector3.new(math.cos(this.x), math.cos(this.y), math.cos(this.z)) //#endregion 2.5.2 //#region 2.5.3: tan () // @function Tangent of vector. // @param this `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .from(1).tan() // ``` export method tan (TMath.Vector3 this) => TMath.Vector3.new(math.tan(this.x), math.tan(this.y), math.tan(this.z)) //#endregion 2.5.3 //#endregion 2.5 //#endregion 2 //#region 3: Static Methods. //#region 3.01: vmax () //#region 3.01.1: 2 vectors: // @function Highest elements of the properties from two vectors. // @param a `Vector3` Vector. // @param b `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .vmax(.one(), .from(2)) // ``` export vmax (TMath.Vector3 a, TMath.Vector3 b) => TMath.Vector3.new( math.max(a.x, b.x), math.max(a.y, b.y), math.max(a.z, b.z)) //#endregion 3.01.1 //#region 3.01.2: 3 vectors: // @function Highest elements of the properties from three vectors. // @param a `Vector3` Vector. // @param b `Vector3` Vector. // @param c `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .vmax(.new(0.1, 2.5, 3.4), .from(2), .from(3)) // ``` export vmax (TMath.Vector3 a, TMath.Vector3 b, TMath.Vector3 c) => TMath.Vector3.new( math.max(a.x, b.x, c.x), math.max(a.y, b.y, c.y), math.max(a.z, b.z, c.z)) //#endregion 3.01.2 //#endregion 3.01 //#region 3.02: vmin () //#region 3.02.1: 2 vectors: // @function Lowest elements of the properties from two vectors. // @param a `Vector3` Vector. // @param b `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .vmin(.one(), .from(2)) // ``` export vmin (TMath.Vector3 a, TMath.Vector3 b) => TMath.Vector3.new( math.min(a.x, b.x), math.min(a.y, b.y), math.min(a.z, b.z)) //#endregion 3.02.1 //#region 3.02.2: 3 vectors: // @function Lowest elements of the properties from three vectors. // @param a `Vector3` Vector. // @param b `Vector3` Vector. // @param c `Vector3` Vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .vmin(.one(), .from(2), .new(3.3, 2.2, 0.5)) // ``` export vmin (TMath.Vector3 a, TMath.Vector3 b, TMath.Vector3 c) => TMath.Vector3.new( math.min(a.x, b.x, c.x), math.min(a.y, b.y, c.y), math.min(a.z, b.z, c.z)) //#endregion 3.02.2 //#endregion 3.02 //#region 3.03: distance () // @function Distance between vector `a` and `b`. // @param a `Vector3` Source vector. // @param b `Vector3` Target vector. // @returns `float`. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = distance(.from(3), .unit_z()) // ``` export distance (TMath.Vector3 a, TMath.Vector3 b) => length(TMath.Vector3.new(a.x - b.x, a.y - b.y, a.z - b.z)) //#endregion 3.03 //#region 3.04: clamp () // @function Restrict a vector between a min and max vector. // @param a `Vector3` Source vector. // @param min `Vector3` Minimum boundary vector. // @param max `Vector3` Maximum boundary vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .clamp(a=.new(2.9, 1.5, 3.9), min=.from(2), max=.new(2.5, 3.0, 3.5)) // ``` export clamp (TMath.Vector3 a, TMath.Vector3 min, TMath.Vector3 max) => TMath.Vector3.new( a.x > min.x ? (a.x < max.x ? a.x : max.x) : min.x, a.y > min.y ? (a.y < max.y ? a.y : max.y) : min.y, a.z > min.z ? (a.z < max.z ? a.z : max.z) : min.z) //#endregion 3.04 //#region 3.05: clamp_magnitude () // @function Vector with its magnitude clamped to a radius. // @param a `Vector3` Source vector.object, vector with properties that should be restricted to a radius. // @param radius `float` Maximum radius to restrict magnitude of vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .clamp_magnitude(.from(21), 7) // ``` export clamp_magnitude (TMath.Vector3 a, float radius) => float _sqrmag = magnitude_squared(a) if _sqrmag > radius * radius float _mag = math.sqrt(_sqrmag) //these intermediate variables force the intermediate result to be //of float precision. without this, the intermediate result can be of higher //precision, which changes behavior. float _normalized_x = a.x / _mag float _normalized_y = a.y / _mag float _normalized_z = a.z / _mag TMath.Vector3.new( _normalized_x * radius, _normalized_y * radius, _normalized_z * radius) else TMath.Vector3.copy(a) //#endregion 3.05 //#region 3.06: lerp_unclamped () // @function `Unclamped` linearly interpolates between provided vectors by a rate. // @param a `Vector3` Source vector. // @param b `Vector3` Target vector. // @param rate `float` Rate of interpolation, range(0 > 1) where 0 == source vector and 1 == target vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .lerp_unclamped(.from(1), .from(2), 1.2) // ``` export lerp_unclamped (TMath.Vector3 a, TMath.Vector3 b, float rate) => TMath.Vector3.new( x = a.x + (b.x - a.x) * rate , y = a.y + (b.y - a.y) * rate , z = a.z + (b.z - a.z) * rate ) //#endregion 3.06 //#region 3.07: lerp () // @function Linearly interpolates between provided vectors by a rate. // @param a `Vector3` Source vector. // @param b `Vector3` Target vector. // @param rate `float` Rate of interpolation, range(0 > 1) where 0 == source vector and 1 == target vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = lerp(.one(), .from(2), 0.2) // ``` export lerp (TMath.Vector3 a, TMath.Vector3 b, float rate) => float _t = rate > 0.0 ? (rate < 1.0 ? rate : 1.0) : 0.0 TMath.Vector3.new( x = a.x + (b.x - a.x) * _t , y = a.y + (b.y - a.y) * _t , z = a.z + (b.z - a.z) * _t ) //#endregion 3.07 //#region 3.08: herp () // @function Hermite curve interpolation between provided vectors. // @param start `Vector3` Start vector. // @param start_tangent `Vector3` Start vector tangent. // @param end `Vector3` End vector. // @param end_tangent `Vector3` End vector tangent. // @param rate `float` Rate of the movement from `start` to `end` to get position, should be range(0 > 1). // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // s = .new(0, 0, 0) , st = .new(0, 1, 1) // e = .new(1, 2, 2) , et = .new(-1, -1, 3) // h = .herp(s, st, e, et, 0.3) // ``` // ___ // **Reference:** https://en.m.wikibooks.org/wiki/Cg_Programming/Unity/Hermite_Curves export herp ( TMath.Vector3 start , TMath.Vector3 start_tangent , TMath.Vector3 end , TMath.Vector3 end_tangent , int rate ) => // float _m0x = start_tangent.x - start.x , float _m1x = end_tangent.x - end.x float _m0y = start_tangent.y - start.y , float _m1y = end_tangent.y - end.y float _m0z = start_tangent.z - start.z , float _m1z = end_tangent.z - end.z float _t2 = rate * rate , float _t3 = rate * _t2 float _2t2 = 2.0 * _t2 , float _2t3 = 2.0 * _t3 , float _3t2 = 3.0 * _t2 float _a = _2t3 - _3t2 + 1.0 , float _b = _t3 - _2t2 + rate float _c = -_2t3 + _3t2 , float _d = (_t3 - _t2) TMath.Vector3.new( x = (_a * start.x) + (_b * _m0x) + (_c * end.x) + (_d * _m1x) , y = (_a * start.y) + (_b * _m0y) + (_c * end.y) + (_d * _m1y) , z = (_a * start.z) + (_b * _m0z) + (_c * end.z) + (_d * _m1z) ) //#endregion 3.08 //#region 3.09: herp_2 () // @function Hermite curve interpolation between provided vectors. // @param a `Vector3` Source vector. // @param b `Vector3` Target vector. // @param rate `Vector3` Rate of the movement per component from `start` to `end` to get position, should be range(0 > 1). // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // h = .herp_2(.one(), .new(0.1, 3, 2), 0.6) // ``` export herp_2 (TMath.Vector3 a, TMath.Vector3 b, TMath.Vector3 rate) => // used on noise() function float _tx = math.max(math.min((rate.x - a.x) / (b.x - a.x), 1.0), 0.0) float _ty = math.max(math.min((rate.y - a.y) / (b.y - a.y), 1.0), 0.0) float _tz = math.max(math.min((rate.z - a.z) / (b.z - a.z), 1.0), 0.0) TMath.Vector3.new( x = _tx * _tx * (3.0 - 2.0 * _tx) , y = _ty * _ty * (3.0 - 2.0 * _ty) , z = _tz * _tz * (3.0 - 2.0 * _tz) ) //#endregion 3.09 //#region 3.10: noise () // @function 3D Noise based on Morgan McGuire @morgan3d // @param a `Vector3` Source vector. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = noise(.one()) // ``` // ___ // **Reference:** // - https://thebookofshaders.com/11/ // - https://www.shadertoy.com/view/4dS3Wd export noise (TMath.Vector3 a) => TMath.Vector3 _step = TMath.Vector3.new(110.0, 241.0, 271.0) TMath.Vector3 _i = floor(a) TMath.Vector3 _f = fractional(a) // For performance, compute the base input to a 1D hash from the integer part of the argument and the // incremental change to the 1D based on the 3D -> 1D wrapping float _n = dot_product(_i, _step) TMath.Vector3 _u = herp_2(zero(), one(), _f)// multiply(multiply(_f, _f), subtract(from(3.0), multiply(from(2.0), _f))) // _f * _f * (3.0 - 2.0 * _f) TMath.Vector3 _mix00 = lerp( random(from(_n + dot_product(_step, zero()))), random(from(_n + dot_product(_step, right()))), _u.x) TMath.Vector3 _mix01 = lerp( random(from(_n + dot_product(_step, up()))), random(from(_n + dot_product(_step, TMath.Vector3.new(1, 1, 0)))), _u.x) TMath.Vector3 _mix10 = lerp( random(from(_n + dot_product(_step, front()))), random(from(_n + dot_product(_step, TMath.Vector3.new(1, 0, 1)))), _u.x) TMath.Vector3 _mix11 = lerp( random(from(_n + dot_product(_step, new(0, 1, 1)))), random(from(_n + dot_product(_step, TMath.Vector3.new(1, 1, 1)))), _u.x) TMath.Vector3 _mix0 = lerp(_mix00, _mix01, _u.y) TMath.Vector3 _mix1 = lerp(_mix10, _mix11, _u.y) lerp(_mix0, _mix1, _u.z) //#endregion 3.10 //#region 3.11: Rotation. //#region 3.11.1: rotate () // @function Rotate a vector around a axis. // @param a `Vector3` Source vector. // @param axis `string` The plane to rotate around, `option="x", "y", "z"`. // @param angle `float` Angle in radians. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .rotate(.from(3), 'y', math.toradians(45.0)) // ``` // ___ // **Reference:** // - https://nikhilrao.blog/rotation-of-a-vector-in-python export rotate (TMath.Vector3 a, string axis, float angle) => float _sin = math.sin(angle) float _cos = math.cos(angle) switch axis 'x' => float _m00 = 1.0, float _m10 = 0.0, float _m20 = 0.0 float _m01 = 0.0, float _m11 = _cos, float _m21 = -_sin float _m02 = 0.0, float _m12 = _sin, float _m22 = _cos // dot product of M.a TMath.Vector3.new( x = ((_m00 * a.x) + (_m10 * a.y) + (_m20 * a.z)) , y = ((_m01 * a.x) + (_m11 * a.y) + (_m21 * a.z)) , z = ((_m02 * a.x) + (_m12 * a.y) + (_m22 * a.z)) ) 'y' => float _m00 = _cos, float _m10 = 0.0, float _m20 = _sin float _m01 = 0.0, float _m11 = 1.0, float _m21 = 0.0 float _m02 = 0.0, float _m12 = 0.0, float _m22 = _cos // dot product of M.a TMath.Vector3.new( x = ((_m00 * a.x) + (_m10 * a.y) + (_m20 * a.z)) , y = ((_m01 * a.x) + (_m11 * a.y) + (_m21 * a.z)) , z = ((_m02 * a.x) + (_m12 * a.y) + (_m22 * a.z)) ) 'z' => float _m00 = _cos, float _m10 = -_sin, float _m20 = 0.0 float _m01 = _sin, float _m11 = _cos, float _m21 = 0.0 float _m02 = 0.0, float _m12 = 0.0, float _m22 = 1.0 // dot product of M.a TMath.Vector3.new( x = ((_m00 * a.x) + (_m10 * a.y) + (_m20 * a.z)) , y = ((_m01 * a.x) + (_m11 * a.y) + (_m21 * a.z)) , z = ((_m02 * a.x) + (_m12 * a.y) + (_m22 * a.z)) ) => TMath.Vector3.copy(a) //#endregion 3.11.1 //#region 3.11.2: rotate_x () // @function Rotate a vector on a fixed `x`. // @param a `Vector3` Source vector. // @param angle `float` Angle in radians. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .rotate_x(.from(3), math.toradians(90.0)) // ``` export rotate_x (TMath.Vector3 a, float angle) => float _rcos = math.cos(angle), float _rsin = math.sin(angle) TMath.Vector3.new(a.x, a.y * _rcos - a.z * _rsin, a.y * _rsin + a.z * _rcos) //#endregion 3.11.2 //#region 3.11.3: rotate_y () // @function Rotate a vector on a fixed `y`. // @param a `Vector3` Source vector. // @param angle `float` Angle in radians. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .rotate_y(.from(3), math.toradians(90.0)) // ``` export rotate_y (TMath.Vector3 a, float angle) => float _rcos = math.cos(angle), float _rsin = math.sin(angle) TMath.Vector3.new(a.z * _rsin + a.x * _rcos, a.y, a.z * _rcos - a.x * _rsin) //#endregion 3.11.3 //#region 3.11.3: rotate_z () // @function Rotate a vector on a fixed `z`. // @param a `Vector3` Source vector. // @param angle `float` Angle in radians. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .rotate_z(.from(3), math.toradians(90.0)) // ``` export rotate_z (TMath.Vector3 a, float angle) => float _rcos = math.cos(angle), float _rsin = math.sin(angle) TMath.Vector3.new(a.x * _rcos - a.y * _rsin, a.x * _rsin + a.y * _rcos, a.z) //#endregion 3.11.3 //#region 3.11.4: rotate_yaw_pitch () // @function Rotate a vector by yaw and pitch values. // @param a `Vector3` Source vector. // @param yaw `float` Angle in radians. // @param pitch `float` Angle in radians. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .rotate_yaw_pitch(.from(3), math.toradians(90.0), math.toradians(45.0)) // ``` export rotate_yaw_pitch (TMath.Vector3 a, float yaw, float pitch) => rotate_y(rotate_x(a, pitch), yaw) //#endregion 3.11.4 //#endregion 3.11 //#region 3.12: Projection. //#region 3.12.1: project () // @function Project a vector off a plane defined by a normal. // @param a `Vector3` Source vector. // @param normal `Vector3` The normal of the surface being reflected off. // @param eps `float` Minimum resolution to void division by zero (default=0.000001). // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .project(.one(), .down()) // ``` export project (TMath.Vector3 a, TMath.Vector3 normal, float eps = 0.000001) => float _sqr_mag = normal.x * normal.x + normal.y * normal.y + normal.z * normal.z if _sqr_mag < eps zero() else float _dot = a.x * normal.x + a.y * normal.y + a.z * normal.z TMath.Vector3.new(normal.x * _dot / _sqr_mag, normal.y * _dot / _sqr_mag, normal.z * _dot / _sqr_mag) //#endregion 3.12.1 //#region 3.12.2: project_on_plane () // @function Projects a vector onto a plane defined by a normal orthogonal to the plane. // @param a `Vector3` Source vector. // @param normal `Vector3` The normal of the surface being reflected off. // @param eps `float` Minimum resolution to void division by zero (default=0.000001). // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .project_on_plane(.one(), .left()) // ``` export project_on_plane (TMath.Vector3 a, TMath.Vector3 normal, float eps = 0.000001) => float _sqr_mag = normal.x * normal.x + normal.y * normal.y + normal.z * normal.z if _sqr_mag < eps TMath.Vector3.copy(a) else float _dot = a.x * normal.x + a.y * normal.y + a.z * normal.z TMath.Vector3.new(a.x - normal.x * _dot / _sqr_mag, a.y - normal.y * _dot / _sqr_mag, a.z - normal.z * _dot / _sqr_mag) //#endregion 3.12.2 //#region 3.12.3: project_to_2d () // @function Project a vector onto a two dimensions plane. // @param a `Vector3` Source vector. // @param camera_position `Vector3` Camera position. // @param camera_target `Vector3` Camera target plane position. // @returns `Vector2` Generated new vector. // ___ // **Usage:** // ``` // a = .project_to_2d(.one(), .new(2, 2, 3), .zero()) // ``` export project_to_2d (TMath.Vector3 a, TMath.Vector3 camera_position, TMath.Vector3 camera_target) => _d_to_source = subtract(a, camera_position) _d_to_target = subtract(camera_target, camera_position) _r = divide(_d_to_target, _d_to_source) V2.new(a.x - _d_to_source.x * _r.x, a.y - _d_to_source.y * _r.y) //#endregion 3.12.3 //#endregion 3.12 //#region 3.13: reflect () // @function Reflects a vector off a plane defined by a normal. // @param a `Vector3` Source vector. // @param normal `Vector3` The normal of the surface being reflected off. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .reflect(.one(), .right()) // ``` export reflect (TMath.Vector3 a, TMath.Vector3 normal) => float _dot = a.x * normal.x + a.y * normal.y + a.z * normal.z float _factor = 2.0 * _dot float _tx = normal.x * _factor float _ty = normal.y * _factor float _tz = normal.z * _factor TMath.Vector3.new(a.x - _tx, a.y - _ty, a.z - _tz) //#endregion 3.13 //#region 3.14: Angle. //#region 3.14.1: angle () // @function Angle in degrees between two vectors. // @param a `Vector3` Source vector. // @param b `Vector3` Target vector. // @param eps `float` Minimum resolution to void division by zero (default=1.0e-15). // @returns `float` Angle value in degrees. // ___ // **Usage:** // ``` // a = .angle(.one(), .up()) // ``` export angle (TMath.Vector3 a, TMath.Vector3 b, float eps = 1.0e-15) => // allways the smallest // sqrt(a) * sqrt(b) = sqrt(a * b) -- valid for real numbers float _denominator = math.sqrt(magnitude_squared(a) * magnitude_squared(b)) if _denominator < eps 0.0 else float _dot = math.max(math.min(dot_product(a, b) / _denominator, 1.0), -1.0) math.todegrees(math.acos(_dot)) //#endregion 3.14.1 //#region 3.14.2: angle_signed () // @function Signed angle in degrees between two vectors. // @param a `Vector3` Source vector. // @param b `Vector3` Target vector. // @param axis `Vector3` Axis vector. // @returns `float` Angle value in degrees. // ___ // **Usage:** // ``` // a = .angle_signed(.one(), .left(), .down()) // ``` // ___ // **Notes:** // - The smaller of the two possible angles between the two vectors is returned, therefore the result will never // be greater than 180 degrees or smaller than -180 degrees. // - If you imagine the from and to vectors as lines on a piece of paper, both originating from the same point, // then the /axis/ vector would point up out of the paper. // - The measured angle between the two vectors would be positive in a clockwise direction and negative in an // anti-clockwise direction. // ___ // **Reference:** // - https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector3.cs#L335 export angle_signed (TMath.Vector3 a, TMath.Vector3 b, TMath.Vector3 axis) => float _unsigned_angle = angle(a, b) // float _cross_x = a.y * b.z - a.z * b.y float _cross_y = a.z * b.x - a.x * b.z float _cross_z = a.x * b.y - a.y * b.x float _sign = math.sign(axis.x * _cross_x + axis.y * _cross_y + axis.z * _cross_z) _unsigned_angle * _sign //#endregion 3.14.2 //#region 3.14.3: angle_2d () // @function 2D angle between two vectors. // @param a `Vector3` Source vector. // @param b `Vector3` Target vector. // @returns `float` Angle value in degrees. // ___ // **Usage:** // ``` // a = .angle2d(.one(), .left()) // ``` export angle2d (TMath.Vector3 a, TMath.Vector3 b) => V2.atan2(V2.new(b.x - a.x, b.z - a.z)) //#endregion 3.14.3 //#endregion 3.14 //#region 3.15: Transforms. //#region 3.15.1: transform_Matrix () // @function Transforms a vector by the given matrix. // @param a `Vector3` Source vector. // @param M `matrix<float>` A 4x4 matrix. The transformation matrix. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // mat = matrix.new<float>(4, 0) // mat.add_row(0, array.from(0.0, 0.0, 0.0, 1.0)) // mat.add_row(1, array.from(0.0, 0.0, 1.0, 0.0)) // mat.add_row(2, array.from(0.0, 1.0, 0.0, 0.0)) // mat.add_row(3, array.from(1.0, 0.0, 0.0, 0.0)) // b = .transform_Matrix(.one(), mat) // ``` export transform_Matrix (TMath.Vector3 a, matrix<float> M) => if matrix.rows(M) == 4 and matrix.columns(M) == 4 TMath.Vector3.new( a.x * M.get(0, 0) + a.y * M.get(0, 1) + a.z * M.get(0, 2) + M.get(0, 3) , a.x * M.get(1, 0) + a.y * M.get(1, 1) + a.z * M.get(1, 2) + M.get(1, 3) , a.x * M.get(2, 0) + a.y * M.get(2, 1) + a.z * M.get(2, 2) + M.get(2, 3) ) else TMath.Vector3.copy(a) //#endregion 3.15.1 //#region 3.15.2: transform_M44 () // @function Transforms a vector by the given matrix. // @param a `Vector3` Source vector. // @param M `M44` A 4x4 matrix. The transformation matrix. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .transform_M44(.one(), .M44.new(0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0)) // ``` // ___ // **Notes:** // - Type `M44` from `CommonTypesMath` library. export transform_M44 (TMath.Vector3 a, TMath.M44 M) => TMath.Vector3.new( x = a.x * M.m11 + a.y * M.m12 + a.z * M.m13 + M.m14 , y = a.x * M.m21 + a.y * M.m22 + a.z * M.m23 + M.m24 , z = a.x * M.m31 + a.y * M.m32 + a.z * M.m33 + M.m34 ) //#endregion 3.15.2 //#region 3.15.3: transform_normal_Matrix () // @function Transforms a vector by the given matrix. // @param a `Vector3` Source vector. // @param M `matrix<float>` A 4x4 matrix. The transformation matrix. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // mat = matrix.new<float>(4, 0) // mat.add_row(0, array.from(0.0, 0.0, 0.0, 1.0)) // mat.add_row(1, array.from(0.0, 0.0, 1.0, 0.0)) // mat.add_row(2, array.from(0.0, 1.0, 0.0, 0.0)) // mat.add_row(3, array.from(1.0, 0.0, 0.0, 0.0)) // b = .transform_normal_Matrix(.one(), mat) // ``` export transform_normal_Matrix (TMath.Vector3 a, matrix<float> M) => if matrix.rows(M) == 4 and matrix.columns(M) == 4 TMath.Vector3.new( a.x * M.get(0, 0) + a.y * M.get(1, 0) + a.z * M.get(2, 0) , a.x * M.get(0, 1) + a.y * M.get(1, 1) + a.z * M.get(2, 1) , a.x * M.get(0, 2) + a.y * M.get(1, 2) + a.z * M.get(2, 2) ) else TMath.Vector3.copy(a) //#endregion 3.15.3 //#region 3.15.4: transform_normal_M44 () // @function Transforms a vector by the given matrix. // @param a `Vector3` Source vector. // @param M `M44` A 4x4 matrix. The transformation matrix. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .transform_normal_M44(.one(), .M44.new(0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0)) // ``` // ___ // **Notes:** // - Type `M44` from `CommonTypesMath` library. export transform_normal_M44 (TMath.Vector3 a, TMath.M44 M) => TMath.Vector3.new( x = a.x * M.m11 + a.y * M.m21 + a.z * M.m31 , y = a.x * M.m12 + a.y * M.m22 + a.z * M.m32 , z = a.x * M.m13 + a.y * M.m23 + a.z * M.m33 ) //#endregion 3.15.3 //#region 3.15.4: transform_Array () // @function Transforms a vector by the given Quaternion rotation value. // @param a `Vector3` Source vector. The source vector to be rotated. // @param rotation `array<float>` A 4 element array. Quaternion. The rotation to apply. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .transform_Array(.one(), array.from(0.2, 0.2, 0.2, 1.0)) // ``` // ___ // **Reference:** // - https://referencesource.microsoft.com/#System.Numerics/System/Numerics/Vector3.cs,340 export transform_Array (TMath.Vector3 a, array<float> rotation) => if array.size(rotation) >= 4 float _rx = array.get(rotation, 0), float _ry = array.get(rotation, 1), float _rz = array.get(rotation, 2), float _rw = array.get(rotation, 3) float _x2 = _rx + _rx, float _y2 = _ry + _ry, float _z2 = _rz + _rz float _wx2 = _rw * _x2 float _wy2 = _rw * _y2 float _wz2 = _rw * _z2 float _xx2 = _rx * _x2 float _xy2 = _rx * _y2 float _xz2 = _rx * _z2 float _yy2 = _ry * _y2 float _yz2 = _ry * _z2 float _zz2 = _rz * _z2 TMath.Vector3.new( a.x * (1.0 - _yy2 - _zz2) + a.y * (_xy2 - _wz2) + a.z * (_xz2 + _wy2), a.x * (_xy2 + _wz2) + a.y * (1.0 - _xx2 - _zz2) + a.z * (_yz2 - _wx2), a.x * (_xz2 - _wy2) + a.y * (_yz2 + _wx2) + a.z * (1.0 - _xx2 - _yy2)) else TMath.Vector3.copy(a) //#endregion 3.15.4 //#region 3.15.4: transform_Quaternion () // @function Transforms a vector by the given Quaternion rotation value. // @param a `Vector3` Source vector. The source vector to be rotated. // @param rotation `array<float>` A 4 element array. Quaternion. The rotation to apply. // @returns `Vector3` Generated new vector. // ___ // **Usage:** // ``` // a = .transform_Quaternion(.one(), .Quaternion.new(0.2, 0.2, 0.2, 1.0)) // ``` // ___ // **Notes:** // - Type `Quaternion` from `CommonTypesMath` library. // ___ // **Reference:** // - https://github.com/microsoft/referencesource/blob/master/System.Numerics/System/Numerics/Vector3.cs export transform_Quaternion (TMath.Vector3 a, TMath.Quaternion rotation) => float _rx = rotation.x, float _ry = rotation.y, float _rz = rotation.z, float _rw = rotation.w float _x2 = _rx + _rx, float _y2 = _ry + _ry, float _z2 = _rz + _rz float _wx2 = _rw * _x2 float _wy2 = _rw * _y2 float _wz2 = _rw * _z2 float _xx2 = _rx * _x2 float _xy2 = _rx * _y2 float _xz2 = _rx * _z2 float _yy2 = _ry * _y2 float _yz2 = _ry * _z2 float _zz2 = _rz * _z2 TMath.Vector3.new( x = a.x * (1.0 - _yy2 - _zz2) + a.y * (_xy2 - _wz2) + a.z * (_xz2 + _wy2) , y = a.x * (_xy2 + _wz2) + a.y * (1.0 - _xx2 - _zz2) + a.z * (_yz2 - _wx2) , z = a.x * (_xz2 - _wy2) + a.y * (_yz2 + _wx2) + a.z * (1.0 - _xx2 - _yy2) ) //#endregion 3.15.4 //#endregion 3.15 //#endregion 3 logger.update()
ka66: lib/MovingAverages
https://www.tradingview.com/script/sSlwVjuI-ka66-lib-MovingAverages/
ka66
https://www.tradingview.com/u/ka66/
4
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © ka66 //@version=5 // @description Exotic or Interesting Moving Averages Lib. library("MovingAverages", overlay = true) emaAlpha(src, alpha) => // https://nullbeans.com/how-to-calculate-the-exponential-moving-average-ema/ // alpha value must be between 0 and 1 ema = 0.0 // update happens on demand at each iteration/bar, calculate current EMA based // on prior bar thus we don't use any looping constructs. ema := na(ema[1]) ? src : alpha * src + (1 - alpha) * nz(ema[1]) ema emaAlphaSmoothing(src, alpha, nSmooth) => if nSmooth <= 0 src else _ema = src for i = 1 to nSmooth // warning shown, but seems to work okay. _ema := emaAlpha(_ema, alpha) _ema // @function Calculates a variation of the EMA by specifying a custom alpha value. // @param src a float series to get the EMA for, e.g. close, hlc3, etc. // @param alpha a value between 0 (ideally greater, to get any MA!) and 1. Closer // to one makes it more responsive, and choppier. // @param nSmooth Just applies the same alpha and EMA to the last Alpha-EMA output. // A value between 0 and 10 (just keeping a a reasonable bound). The idea is // you can first use a reasonably high alpha, then smooth it out. Default 0, // no further smoothing. // @returns MA series. export alphaConfigurableEma(float src, float alpha = 0.5, int nSmooth = 0) => if alpha < 0 or alpha > 1 runtime.error("Alpha must be 0 and 1, more than zero to get a non-zero series!") if nSmooth < 0 or nSmooth > 10 runtime.error("nSmooth must be between 0 and 10, inclusive") ma = emaAlpha(src = src, alpha = alpha) ma := emaAlphaSmoothing(src = ma, alpha = alpha, nSmooth = nSmooth) ma // @function Calculates fixed bands around a series, can be any series, though the intent // here is for MA series. // @param src a float series. // @param multiplier a value greater than or equal to 0 (ideally greater, to get any MA!), // determines the width of the bands. Start with small float values, or it may go // beyond the scale, e.g. 0.005. // @returns a 2-tuple of (upBand, downBand) export bands(float src, float multiplier) => if multiplier < 0 runtime.error("Band Multiplier must be 0 or more, e.g. 0.003. 0, is valid, but would produce zero series!") offset = src * multiplier upBand = src + offset downBand = src - offset [upBand, downBand] // sample code ema = alphaConfigurableEma(src = close, alpha = 0.3, nSmooth = 2) [upBand, downBand] = bands(ema, multiplier = 0.006) plot(ema, linewidth = 2, color = color.maroon) plot(upBand, linewidth = 1, color = color.gray) plot(downBand, linewidth = 1, color = color.gray)
libhs_td5
https://www.tradingview.com/script/6EqyduOa-libhs-td5/
GETpacman
https://www.tradingview.com/u/GETpacman/
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/ // © GETpacman //@version=5 // @description td5 Test Data Library for Logx Testing library("libhs_td5") export fill(matrix<string> dbus, bool fillData=true) => string gm1='' string gm2='' string gm3='' string gm4='' string gm5='' string gm6='' string gm='' string gl='' string gs='' string gc='' string tab2='  ' string tab4='    ' var string o_skiplog = '^skip^' var string[] alphabet=array.from('     Alpha','      Beta','   Charlie','     Delta','      Echo','   Foxtrot','      Golf','     Hotel','     India','    Juliet','      Kilo','      Lima','      Mike','  November','     Oscar','      Papa','    Quebec','     Romeo','     Sugar','     Tango','   Uniform','    Victor','    Whisky','      Xray','    Yankee','      Zulu') var string[] alphabetc=array.from('Alpha','Beta','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sugar','Tango','Uniform','Victor','Whisky','Xray','Yankee','Zulu') int devcolmsg=2, int devcollevelC=3, int devcolstatusC=4, int prodcolmsg=5, int prodcollevelC=6, int prodcolstatusC=7 int devcolm1=8, int devcolm2=9, int devcolm3=10, int devcolm4=11, int devcolm5=12, int devcolm6=13, int devcollevelL=14, int devcolstatusL=15 int prodcolm1=16, int prodcolm2=17, int prodcolm3=18, int prodcolm4=19, int prodcolm5=20, int prodcolm6=21, int prodcollevelL=22, int prodcolstatusL=23 int c=1 var logxBus=array.new_string() var _filled=false if fillData and not _filled logxBus.push('') //zidx=1 logxBus.push('Commencing Logx Testing') //zidx=1 logxBus.push('You will need to slowly go through about 450 bars 600 bars (300 each for Logx and Console) to see full suite of possibilities with this library') logxBus.push('Multiple tests will be conducted to show how each feature works of this library') logxBus.push('All tests will do one main action at each bar and some supplementary to show the best use of that test case') logxBus.push('Logx started with 5 rows and is filled up now') logxBus.push('Test 1 = Resize (add 5 rows)') //zidx=6 logxBus.push('@q2=● on next bar call => logx.resize(10) ▼') logxBus.push(o_skiplog) logxBus.push('@q2=More space added to queue') logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Test 1 completed ▲') //13 logxBus.push('Test 2 = Resize (remove 3 rows)') //zidx=14 logxBus.push('@q2=● on next bar call => logx.resize(7) ▼') logxBus.push(o_skiplog) logxBus.push('@q2=Space removed from the queue'+' (Frame will be removed at end of this test)') logxBus.push('Test 2 completed ▲') logxBus.push('Test 3 = set text color (to blue)') //zidx=19 logxBus.push('@q2=● on next bar call => logx.textColor:=color.blue ▼') logxBus.push('@q2=Text color is now blue') logxBus.push('Test 3 completed ▲') logxBus.push('Test 4 = set background color (to orange)') //zidx=23 logxBus.push('@q2=● on next bar call => logx.textColorBG:=color.orange ▼') logxBus.push('@q2=Background color is now orange') logxBus.push('Test 4 completed ▲') logxBus.push('Test 5 = reset background color to library default') //zidx=27 logxBus.push('@q2=● on next bar call => logx.resetTextColorBG() ▼') logxBus.push('@q2=Background color is same as chart background color') logxBus.push('Test 5 completed ▲') logxBus.push('Test 6 = reset text color to library default') //zidx=31 logxBus.push('@q2=● on next bar call => logx.resetTextColor() ▼') logxBus.push('@q2=Text color is now library default') logxBus.push('Test 6 completed ▲') logxBus.push('Test 7 = Set Status color to green') //zidx=35 logxBus.push('@q2=● on next bar call => logx.statusColor:=color.green ▼') logxBus.push('@q2=Status color is green now') logxBus.push('Test 7 completed ▲') logxBus.push('Test 8 = Set Status background color to white') //zidx=39 logxBus.push('@q2=● on next bar call => logx.statusColorBG:=color.white ▼') logxBus.push('@q2=Status background color is white now') logxBus.push('Test 8 completed ▲') logxBus.push('Test 9 = Reset Status background color to library default') //zidx=43 logxBus.push('@q2=● on next bar call => logx.resetStatusColorBG() ▼') logxBus.push('@q2=Status background color is now library default') logxBus.push('Test 9 completed ▲') logxBus.push('Test 10 = Reset Status color to library default') //zidx=47 logxBus.push('@q2=● on next bar call => logx.resetStatusColor() ▼') logxBus.push('@q2=Status color is now library default') logxBus.push('Test 10 completed ▲') logxBus.push('Test 11 = Show a frame around Logx (green colored)') //zidx=51 logxBus.push('@q2=● on next bar call => logx.frameColor:=color.green ▼') logxBus.push('@q2=A green frame around Logx is visible') logxBus.push('Test 11 completed ▲') logxBus.push('Test 12 = Remove the colored frame around Logx') //zidx=55 logxBus.push('@q2=● on next bar call => logx.resetFrameColor() ▼') logxBus.push('@q2=There is no frame around Logx anymore') logxBus.push('Test 12 completed ▲') logxBus.push('Test 13 = Color Logx as per error codes, with user supplied colors') //zidx=59 logxBus.push('@q2=● on next bar call => logx.setErrorColors(customFG) ▼ (fuschia/olive/maroon/navy @ 100%/65%)') logxBus.push('@q2=● on next bar call => logx.ColorText:=true ▼') c:=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Test 13 completed ▲') logxBus.push('Test 14 = Highlight Logx as per error codes, with user supplied colors') //zidx=71 logxBus.push('@q2=● on next bar call => logx.setErrorHCcolors(customHC) ▼ (fuschia/olive/maroon/navy @ 100%/65%)') logxBus.push('@q2=● on next bar call => logx.HighlightText:=true ▼') c:=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Test 14 completed ▲') logxBus.push('Test 15 = Color Logx as per default error codes') //zidx=83 logxBus.push('@q2=● on next bar call => logx.resetErrorColors() ▼') logxBus.push('@q2=● on next bar call => logx.ColorText:=true ▼') c:=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Test 15 completed ▲') logxBus.push('Test 16 = Highlight Logx as per default error codes') //zidx=94 logxBus.push('@q2=● on next bar call => logx.resetErrorHCcolors() ▼') logxBus.push('@q2=● on next bar call => logx.HighlightText:=true ▼') c:=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Test 16 completed ▲') logxBus.push('Test 17 = ShowColors + setColor/HC/BG + setLevelName') //idzx=105 logxBus.push('@q2=You can see the color of error codes on a sepatate table, to see how they look') logxBus.push('@q2=● on next bar call and remainder of this test call => logx.showColors(position=position.bottom_left,showColors=(idzc>=108 and idzc<=123)) ▼') logxBus.push('@q2=A table with colors corresponding to error codes can be see on bottom left. It shows how they look with and without highlighting, and what the log level names are.') logxBus.push('@q2=At the moment there are 36 error codes. Error Code 36 (in range),40,41 will be set to new colors') logxBus.push('@q2=Some codes are out of range, hence the color array codes will be expanded.') logxBus.push("@q2=Log Level names do not get expanded when color array gets expanded. ") logxBus.push("@q2=To auto expand Log Level names, Log Level for Code 40 will be set to 'Custom Code 40' (36 codes at moment)") logxBus.push("@q2=● on next bar call => logx.setLevelName(40,'Custom Code 40') ▼") logxBus.push('@q2=Log Level Name has been expanded, but is not visible as Color Table only goes upto max colors code, which is 36 at the moment. Wait for color expansion') logxBus.push('@q2=● on next bar call => logx.setColor(36,color.red) ▼') logxBus.push('@q2=Error Code 36 has Red Color as foreground.') logxBus.push('@q2=● on next bar call => logx.setColorHC(40,color.black) ▼ logx.setColor(40,color.orange) ▼') logxBus.push('@q2=Error Code 40 is now visible with orange foreground and black as highlight color. Background color is taken from TextColorBG') logxBus.push('@q2=Log Level for Code 40 is now visible as well, with custom log level name visible') logxBus.push('@q2=● on next bar call => logx.setColorBG(41,color.yellow) ▼') logxBus.push('@q2=Error Code 41 is now visible with Yellow Color as background. Foreground/Highlight has been taken from TexColor/color.white') logxBus.push('Color table will be deleted at end of this test') logxBus.push('Test 17 completed ▲') logxBus.push('Test 18 = Move Status to top') //zidx=105 +19 logxBus.push('@q2=● on next bar call => logx.StatusBarAtBottom:=false ▼') logxBus.push(o_skiplog) logxBus.push('@q2=Status has moved to the top (will be moved back to bottom at end of this test)') logxBus.push('Test 18 completed ▲') logxBus.push('Test 19 = Move Headers to bottom') //zidx=110 +19 logxBus.push('@q2=● on next bar call => logx.HeaderAtTop:=false ▼') logxBus.push( o_skiplog) logxBus.push('@q2=Header is now at the bottom (will be moved back to top at end of this test)') logxBus.push('Test 19 completed ▲') logxBus.push('Test 20 = Hide Headers') //zidx=115 +19 logxBus.push('@q2=● on next bar call => logx.ShowHeader:=false ▼') logxBus.push( o_skiplog) logxBus.push('@q2=Header is no longer visible now') logxBus.push('Test 20 completed ▲') if fillData and not _filled logxBus.push('Test 21 = Change the scroll direction') //zidx=120 +19 logxBus.push('@q2=This can get confusing so Logx will be cleared first, status moved to top and then') logxBus.push('@q2=● on next bar call => logx.MoveLogUp:=false ▼') logxBus.push('@q2=Commencing scrolling test. messages pile on top and older messages are pushed down') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('Test 21 completed ▼') //zidx=130 +19 logxBus.push('') logxBus.push('') logxBus.push('') logxBus.push('') //zidx=134 +19 logxBus.push('Test 22 = Show Bar Index') //zidx=135 +19 logxBus.push('@q2=● on next bar call => logx.ShowBarIndex:=true ▼') logxBus.push('@q2=Bar Index is visible now') logxBus.push('Test 22 completed ▲') logxBus.push('Test 23 = Show/Format Date/Time') //zidx=139 +19 logxBus.push('@q2=● on next bar call => logx.ShowDateTime:=true ▼') logxBus.push('@q2=Date/Time is visible now. Format will be changed next') logxBus.push("@q2=● on next bar call => logx.dateTimeFormat('dd.MMM.yy') ▼") logxBus.push('@q2=Only date is visible now') logxBus.push('@q2=to reset back to default format ● on next bar call => logx.dateTimeFormat() ▼') logxBus.push('Test 23 completed ▲') logxBus.push('Test 24 = Paging! Only messages from current/active bar will be kept') //zidx=146 +19 logxBus.push('@q2=● on next bar call => logx.PageOnEveryBar:=true ▼') //zidx=147 +19 logxBus.push('Paging Test 24. Only messages from active bar will be recorded.') //zidx=148 +19 zx=148 +19 logxBus.push('@q2=All messages from previous bars have been cleared. When paging is on you should see this => ● in status bar') logxBus.push('@q2=These messages are not getting cleared as they are on the same bar (even if running on historical bars, its still on same bar).') c:=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Paging Test 24. This is the 2nd bar with paging setting still on ') //zidx=149 +19 zx=154 +19 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Paging Test 24. This is the 3rd bar with paging setting still on.') //zidx=150 +19 zx=159 +19 c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('@q2=on next bar paging history will be increased by calling logx.PageHistory:=1') logxBus.push('Paging Test 24. This is the 4th bar with paging setting still on. we should now see 2 bars of data only (as remembering 1 page history)') //zidx=151 +19 zx=164 +19 c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Paging Test 24. This is the 5th bar with paging setting still on. we should now see 2 bars of data only (as remembering 1 page history)') //zidx=152 +19 zx=169 +19 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Paging Test 24. This is the 6th bar with paging setting still on.') //zidx=153 +19 zx=174 +19 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Test 24 completed ▲') //zidx=154 +19 zx=179 +19 logxBus.push('With Paging turned off, the messages from previous bars were not erased') //zidx=155 +19 zx=180 +19 logxBus.push('This happaned as,from that bar Paging was turned off, it stopped clearing old messages') logxBus.push('Test 25 = adhoc paging without changing the Paging config') //zidx=157 +19 zx=182 +19 logxBus.push('@q2=● on next few bars call => logx.page ▼') for x=1 to 3 //zidx=159 +19, 160 +19, 161 +19 logxBus.push('Adhoc paging Test 25. Paging is not on as there is no ● in the status bar.') logxBus.push('Adhoc paged messages will have no history from previous bars, viz it will only show messages from current bar.') logxBus.push('@q2=Following messages are logged on same bar via logx.page') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('Test 25 completed ▲') //zidx=181 zx=221 logxBus.push('Test 26 = Show/Hide Selected Message Q') //zidx=182 zx=222 logxBus.push("At the moment all 6 queues are visible. Let's hide Q2 and Q6 (with auto merge disabled)") logxBus.push('<This is a message for Q1>@q2=<This is a message for Q2>@q3=<This is a message for Q3>@q4=<This is a message for Q4>@q5=<This is a message for Q5>@q6=<This is a message for Q6>') logxBus.push('   ● on next bar call => logx.ShowQ2:=false, logx.ShowQ6:=false ▼') logxBus.push('Q2 and Q6 are hidden now') logxBus.push('Lets hide Q3 and Q5 instead and bring back Q2 and Q6') logxBus.push('   ● on next bar call => logx.ShowQ2:=true, logx.ShowQ6:=true ▼') logxBus.push('   ● on next bar call => logx.ShowQ3:=false, logx.ShowQ5:=false ▼') logxBus.push('Q3 and Q5 are hidden now') logxBus.push('Test 26 completed ▲') logxBus.push('Test 27 = Automerge') //zidx=192 zx=232 logxBus.push('Automerge has been on since start of the testing') logxBus.push('Automerge has been disabled during previous test and the effect should be visible now, with the messages from different queues separating') logxBus.push('all it does is merge the cell queues towards the right. (if right side queues are empty all becomes one big cell)') logxBus.push('(if only Q3 empty Q2/Q3 become one big cell, excluding Q1)') logxBus.push('@q2=Clearing the queues should make the effect more prominent') logxBus.push('<This is a longer message for Q1, to make it spill over into Q2>') logxBus.push('@q2=<This is a message for Q2, does it create the indent effect due to automerge?>') logxBus.push('@q3=<This is a message for Q3>') logxBus.push('Test 27 completed ▲') logxBus.push('Test 28 = Auto Indent') //zidx=202 zx=242 logxBus.push('@q2=● on next bar call => logx.tabSizeQ1:=1, logx.tabSizeQ2:=2, logx.tabSizeQ3:=3 ▼') c:=1 for x=1 to 7 //zidx=204 to 210 logxBus.push('Level '+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+'@q2=Message for Q2@q3=Message for Q3') c+=1 logxBus.push('Auto Indenting works on error codes 1 to 7 only. To disable auto indenting set respective tabsize to 0') logxBus.push('Test 28 completed ▲') //zidx=212 zx=252 logxBus.push('Test 29 = Update / Hide Status Meta Info / Hide Status') //zidx=213 zx=253 logxBus.push('Test 29a = Update Status') logxBus.push('@q2=Status Bar has Test Number at the moment, this will be replaced with a custom status message') logxBus.push('@q2=● on next bar call => logx.Status:="Look we have a status message now, that will persist across updates" ▼') logxBus.push('@q2=Not all of the status message may get updated, as table may expand as per length of logged message.') logxBus.push('@q2=Some part of the status is also taken by bar number and other message, hence not full status will be used') logxBus.push('@q2=Reset the status using logx.Status property') logxBus.push('Test 29b = Hide Status Meta Info') logxBus.push('@q2=Notice lower left corner has current bar info (as well as paging status if set)') logxBus.push('@q2=● on next bar call => logx.ShowMetaStatus:=false ▼') logxBus.push('@q2=Meta info no longer visible in status bar and full bar is available for custom status messages') logxBus.push('Test 29b = Hide Status') logxBus.push('@q2=● on next bar call => logx.ShowStatusBar:=false ▼') logxBus.push('@q2=Status bar is hidden now') logxBus.push('Test 29 completed ▲') logxBus.push('Test 30 = Mark New Bars') //idzx=228 zx=268 logxBus.push('@q2=This option adds a marker at start of each new bar') logxBus.push('@q2=● on next bar call => logx.MarkNewBar:=true ▼') for x=1 to 12 //idzc=231, 232, 233 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('Test 30 completed ▲') logxBus.push('Test 31 = Change mininum Logx width') //idzx=235 zx=275 logxBus.push('@q2=Current minimum Logx width is 80. We will be increasing this to 200 minimum') logxBus.push('@q2=● on next bar call => logx.MinWidth:=200 ▼') logxBus.push('@q2=Logx Width is now changed to atlest 200 characters wide') logxBus.push('@q2=Reset back to 80 at end of this test') logxBus.push('Test 31 completed ▲') logxBus.push('Test 32 = Show Error Code/Debug Level Q') //zidx=241 zx=262 logxBus.push('@q2=Some messages with 10 log levels will be shown') logxBus.push('@q2=● on next bar call => logx.ShowLogLevels:=true ▼') c:=1 logxBus.push('@q2=Sample TRACE message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample DEBUG message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample INFO message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample WARNING message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample ERROR message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample CRITICAL message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample FATAL message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('To only see Log Levels for key 7 levels (INFO to Critical), then @q2=● call => logx.RestrictToKey7:=true ▼') //zidx=245 zx=275 +19 logxBus.push('If you wish to track error codes, then @q2=● on next bar call => logx.ReplaceWithErrorCodes:=true ▼') c:=1 logxBus.push('@q2=Sample TRACE message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample DEBUG message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample INFO message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample WARNING message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample ERROR message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample CRITICAL message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample FATAL message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('To not see Log Levels or Error Codes, ● on next bar call => logx.showLogLevels:=false') logxBus.push('Test 32 completed ▲') //zidx=249 zx=307 logxBus.push('Test 33 = Convert Logx to Console') //zidx=250 zx=308 logxBus.push('@q2=Now Logx will be converted into a console. There is no need to create a new variable') c:=0 for x=1 to 3 //zidx=252 to 254 c+=1 tm='<Q1 message = '+alphabetc.get((c-1)%26)+'>' for y=2 to 6 c+=1 tm+='@q'+str.tostring(y)+'=<Q'+str.tostring(y)+' message = '+alphabetc.get((c-1)%26)+'>' logxBus.push(tm) logxBus.push('@q2=● on next bar call => logx.IsConsole:=true ▼') logxBus.push('Look this is a console now') logxBus.push('@q2=Converting to a console will make you lose data in Q6,') logxBus.push('@q2=while the data in Q2-5 will not be shown') logxBus.push('@q2=However when you convert console back to Logx, Q1-5 data will still be available.') logxBus.push('@q2=Now lets convert this Console back to Logx') logxBus.push('@q2=● on next bar call => logx.IsConsole:=false ▼') logxBus.push('Test 33 completed ▲') //zidx=262 zx=320 logxBus.push('Test 34 = Turning a page') //idzx=263 zx=321 logxBus.push('@q2=All messages are logged on a "page", which could be turned at any point of time.') logxBus.push('@q2=This is different from console.page which will flush all messages from previous bars') logxBus.push('@q2=This is also different from PageOnEveryBar which will flush all messages from previous bars, based on Page History') logxBus.push('@q2=turnPage will clear all older messages at the point turnPage is called, and is independent from above') c:=1 c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) c+=1 logxBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3=   Sample message = '+alphabetc.get((c-1)%26)) logxBus.push('@q2=● on next bar call => logx.turnPage() ▼') logxBus.push('@q2=All older messages have been cleared and we are on a new page (not dependent on PageOnEveryBar or console.page)') logxBus.push('@q2=So, effectively, there are 3 ways to page messages') logxBus.push('Test 34 completed ▲') logxBus.push('Test 35 = Asynchronous Logging') //zidx=275 zx=343 logxBus.push('@q2=Another way to log messages is to log them to each queue individually') logxBus.push('@q2=This may be needed when you need to log messages at different times') logxBus.push('@q2=Logging four sample messages to Q1 at one go, using logx.alog(0,msg,1). These will be followed by logging to Q2 and Q3 separately, using logx.alog(0,msg,2) and logx.alog(0,msg,3) ') c:=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') //zidx=279 zx=347 c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') //zidx=280 zx=352 c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') //zidx=287 zx=359 c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') //zidx=291 zx=363 c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') logxBus.push('@q2=As soon as normal log method is used all queues are logged in sync') logxBus.push('Test 35 completed ▲') //zidx=298+3 zx=370 logxBus.push('Test 36 = Show Specific Log Level messages/Independent Coloring') //idzx=299+3 zc= logxBus.push('Logging some sample messages with the Log Level 0 to 7') c:=1 logxBus.push(tab4+'Level 0'+tab4+'No Level'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) c+=1 logxBus.push(tab4+'Level 1'+tab4+'TRACE'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) c+=1 logxBus.push(tab4+'Level 2'+tab4+'DEBUG'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) c+=1 logxBus.push(tab4+'Level 3'+tab4+'INFO'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) c+=1 logxBus.push(tab4+'Level 4'+tab4+'WARNING'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) c+=1 logxBus.push(tab4+'Level 5'+tab4+'ERROR'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) c+=1 logxBus.push(tab4+'Level 6'+tab4+'CRITICAL'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) c+=1 logxBus.push(tab4+'Level 7'+tab4+'FATAL'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) logxBus.push('Setting sit.ShowMinimumLvel := 3 to display INFO or higher messages') logxBus.push('Setting sit.ShowMinimumLvel := 4 to display WARNING or higher messages') logxBus.push('Test 36 completed ▲') //idzc=307 zx= logxBus.push('Test 37 = Undo logged messages') //idzx=308 zx= logxBus.push('@q2=Pushing some sample messages') logxBus.push('@q2=First message #15 will be removed, followed by removal of #14, #13, #12 and finally all sample messages') c:=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼') logxBus.push('@q2=All messages were removed') logxBus.push('@q2=Undo will remove messages logged via logx.log and stop as soon as it finds asynchronously logged messages') logxBus.push('Test 37 completed ▲') //idzx=317 zx= logxBus.push('Test 38 = Undo asynchronously logged messages') //idzx=318 zx= logxBus.push('@q2=Pushing some sample messages') logxBus.push('@q2=First messages from Q1 will be removed, followed by removal of Q2, while Q3 will be left alone.') c:=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') //idzx=321 zx= c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') //idzx=321 zx= c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') //idzx=321 zx= c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q3=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') c+=1 logxBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼') logxBus.push('@q2=All messages from Q1 and Q2 were removed') //idzx=325 logxBus.push('Test 38 completed ▲') //idzx=326 zx= logxBus.push('All Logx Tests completed') //idzx=327 zx= // _________________________________________________________________________Logx Testing ends on zidx=299 if fillData and not _filled //______ == ______________________________ Attachment Testing starts on za=1 logxBus.push('Attachment Test 1 = Attaching a Console to Logx') //idza=1 logxBus.push('While a lLogx can be converted into Console and vice versa, sometimes there may be a need to see both') logxBus.push('In this test a new and separate Console will be created and attached to this Logx') logxBus.push('Console is created. Now lets attach it') logxBus.push('@q2=● on next bar call => logx.attachConsole(console) ▼') logxBus.push('@q2=Console attached !') //idza=6 logxBus.push(o_skiplog) logxBus.push(o_skiplog) logxBus.push(o_skiplog) logxBus.push(o_skiplog) logxBus.push('Console will be moved around Logx (Left, Top, and Right)') logxBus.push('@q2=● on next bar call => logx.moveConsole(console,"left") ▼') //idza=12 logxBus.push('Console is now on left of Logx') logxBus.push("Let's move Console's Status Bar to the top, while it is attached on the left .@q2=● on next bar call => console.StatusBarAtBottom:=false") logxBus.push('Moving Console to top of Logx @q2=● on next bar call => logx.moveConsole(console,"top") ▼') //idza=15 logxBus.push('Console is now on top of Logx') logxBus.push('Console Status Bar will be kept at the top for now') logxBus.push('Moving Console to the right of Logx @q2=● on next bar call => logx.moveConsole(console,"right") ▼') //idza=18 logxBus.push('Console is now at right of Logx') logxBus.push("Let's move Status Bar of both Logx and Console to top") logxBus.push('@q2=● on next bar call => logx.StatusBarAtBottom:=false ▼') //idza=21 logxBus.push('Moving Console to default location, viz "anywhere" of Logx @q2=● on next bar call => logx.moveConsole(console,"anywhere") ▼') //idza=22 logxBus.push('Console is now at bottom of Logx (default is bottom, if location specified is not one of these -> top, right, bottom, left)') logxBus.push('Console will now be detached') logxBus.push('@q2=● on next bar call => logx.detachConsole(console) ▼') //idza=25 logxBus.push('Console detached') logxBus.push('Attachment Test 1 completed ▲') logxBus.push('Attachment testing is completed now !!') //za=28 //______ xx ______________________________ Attachment Testing ends on za=28 for zx=0 to logxBus.size()-1 gl:=logxBus.get(zx) dbus.set(zx,1,gl) q2pos=str.pos(gl,'@q2=') q3pos=str.pos(gl,'@q3=') q4pos=str.pos(gl,'@q4=') q5pos=str.pos(gl,'@q5=') q6pos=str.pos(gl,'@q6=') end=str.length(gl) gm1:= str.substring(gl,0,na(q2pos)?na(q3pos)?na(q4pos)?na(q5pos)?na(q6pos)?end:q6pos:q5pos:q4pos:q3pos:q2pos) gm2:= na(q2pos) ? '' : str.substring(gl,q2pos+4,na(q3pos)?na(q4pos)?na(q5pos)?na(q6pos)?end:q6pos:q5pos:q4pos:q3pos) gm3:= na(q3pos) ? '' : str.substring(gl,q3pos+4,na(q4pos)?na(q5pos)?na(q6pos)?end:q6pos:q5pos:q4pos) gm4:= na(q4pos) ? '' : str.substring(gl,q4pos+4,na(q5pos)?na(q6pos)?end:q6pos:q5pos) gm5:= na(q5pos) ? '' : str.substring(gl,q5pos+4,na(q6pos)?end:q6pos) gm6:= na(q6pos) ? '' : str.substring(gl,q6pos+4,end) if (zx>=323 and zx<=327) gm:=gm1+(gm2==''?'':(tab4+gm2))+(gm3==''?'':(tab4+gm3))+(gm4==''?'':(tab4+gm4))+(gm5==''?'':(tab4+gm5))+(gm6==''?'':(tab4+gm6)) dbus.set(zx, devcolmsg, str.replace_all(gm,'logx.','sit.')) dbus.set(zx, prodcolmsg, str.replace_all(gm,'logx.','demo.')) dbus.set(zx, devcollevelC,'zx='+ str.tostring(zx)) dbus.set(zx, prodcollevelC,'zx='+ str.tostring(zx)) dbus.set(zx, devcolm1, str.replace_all(gm1,'logx.','sit.')) dbus.set(zx, devcolm2, str.replace_all(gm2,'logx.','sit.')) dbus.set(zx, devcolm3, str.replace_all(gm3,'logx.','sit.')) dbus.set(zx, devcolm4, str.replace_all(gm4,'logx.','sit.')) dbus.set(zx, devcolm5, str.replace_all(gm5,'logx.','sit.')) dbus.set(zx, devcolm6, str.replace_all(gm6,'logx.','sit.')) dbus.set(zx, prodcolm1, str.replace_all(gm1,'logx.','demo.')) dbus.set(zx, prodcolm2, str.replace_all(gm2,'logx.','demo.')) dbus.set(zx, prodcolm3, str.replace_all(gm3,'logx.','demo.')) dbus.set(zx, prodcolm4, str.replace_all(gm4,'logx.','demo.')) dbus.set(zx, prodcolm5, str.replace_all(gm5,'logx.','demo.')) dbus.set(zx, prodcolm6, str.replace_all(gm6,'logx.','demo.')) if str.contains(gl,'Test') and str.contains(gl,'=') and not str.contains(gl,'@q') gs:=gl if str.contains(gl,'Test') and str.contains(gl,'completed') gs:='' dbus.set(zx, devcolstatusL, '<SIT zx = ' + str.tostring(zx)+' ▶ '+gs+'>') dbus.set(zx, prodcolstatusL, gs) dbus.set(zx, devcollevelL,'zx='+ str.tostring(zx)) dbus.set(zx, prodcollevelL,'zx='+ str.tostring(zx)) for x=logxBus.size() to dbus.rows()-1 dbus.set(x, devcolm1,'Logx testing has been completed #'+str.tostring(x)) dbus.set(x, prodcolm1,'Logx testing has been completed #'+str.tostring(x)) _filled:=true logxBus.clear() // td5 dev.111
Uptrend Downtrend Loopback Candle Identification Lib
https://www.tradingview.com/script/7XVVW2CK-Uptrend-Downtrend-Loopback-Candle-Identification-Lib/
AugustoErni
https://www.tradingview.com/u/AugustoErni/
4
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © AugustoErni //@version=5 library("uptrend_downtrend_loopback_candle_identification_lib", overlay=true) export uptrendLoopbackCandleIdentification(int lookbackPeriod) => var bool isUptrend = false for i = 1 to lookbackPeriod if low > low[i] isUptrend := true else isUptrend := false break isUptrend export downtrendLoopbackCandleIdentification(int lookbackPeriod) => var bool isDowntrend = false for i = 1 to lookbackPeriod if low < low[i] isDowntrend := true else isDowntrend := false break isDowntrend
Strategy Utilities
https://www.tradingview.com/script/kzwONNw9/
TheSocialCryptoClub
https://www.tradingview.com/u/TheSocialCryptoClub/
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/ // © TheSocialCryptoClub //@version=5 // @description: Utilities for Strategies, library("strategy_utilities") // @function monthly_table prints the Monthly Returns table, modified from QuantNomad. Please put calc_on_every_tick = true to plot it. // @param results_prec for the precision for decimals // @param results_dark true or false to print the table in dark mode // @returns nothing (void), but prints the monthly equity table export monthly_table(int results_prec, bool results_dark) => new_month = month(time) != month(time[1]) new_year = year(time) != year(time[1]) eq = strategy.equity bar_pnl = eq / eq[1] - 1 cur_month_pnl = 0.0 cur_year_pnl = 0.0 // Current Monthly P&L cur_month_pnl := new_month ? 0.0 : (1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1 // Current Yearly P&L cur_year_pnl := new_year ? 0.0 : (1 + cur_year_pnl[1]) * (1 + bar_pnl) - 1 // Arrays to store Yearly and Monthly P&Ls var month_pnl = array.new_float(0) var month_time = array.new_int(0) var year_pnl = array.new_float(0) var year_time = array.new_int(0) last_computed = false if (not na(cur_month_pnl[1]) and (new_month or barstate.islast)) if (last_computed[1]) array.pop(month_pnl) array.pop(month_time) array.push(month_pnl , cur_month_pnl[1]) array.push(month_time, time[1]) if (not na(cur_year_pnl[1]) and (new_year or barstate.islast)) if (last_computed[1]) array.pop(year_pnl) array.pop(year_time) array.push(year_pnl , cur_year_pnl[1]) array.push(year_time, time[1]) last_computed := barstate.islast ? true : nz(last_computed[1]) // Monthly P&L Table var monthly_table = table(na) cell_hr_bg_color = results_dark ? #0F0F0F : #F5F5F5 cell_hr_text_color = results_dark ? #D3D3D3 : #555555 cell_border_color = results_dark ? #000000 : #FFFFFF // ell_hr_bg_color = results_dark ? #0F0F0F : #F5F5F5 // cell_hr_text_color = results_dark ? #D3D3D3 : #555555 // cell_border_color = results_dark ? #000000 : #FFFFFF if (barstate.islast) monthly_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_pnl) + 1, bgcolor=cell_hr_bg_color,border_width=1,border_color=cell_border_color) table.cell(monthly_table, 0, 0, syminfo.tickerid + " " + timeframe.period, text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 1, 0, "Jan", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 2, 0, "Feb", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 3, 0, "Mar", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 4, 0, "Apr", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 5, 0, "May", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 6, 0, "Jun", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 7, 0, "Jul", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 8, 0, "Aug", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 9, 0, "Sep", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 10, 0, "Oct", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 11, 0, "Nov", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 12, 0, "Dec", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) table.cell(monthly_table, 13, 0, "Year", text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) for yi = 0 to array.size(year_pnl) - 1 table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), text_color=cell_hr_text_color, bgcolor=cell_hr_bg_color) y_color = array.get(year_pnl, yi) > 0 ? color.lime : array.get(year_pnl, yi) < 0 ? color.red : color.gray table.cell(monthly_table, 13, yi + 1, str.tostring(math.round(array.get(year_pnl, yi) * 100, results_prec)), bgcolor = y_color) for mi = 0 to array.size(month_time) - 1 m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1 m_col = month(array.get(month_time, mi)) m_color = array.get(month_pnl, mi) > 0 ? color.lime : array.get(month_pnl, mi) < 0 ? color.red : color.gray table.cell(monthly_table, m_col, m_row, str.tostring(math.round(array.get(month_pnl, mi) * 100, results_prec)), bgcolor = m_color)
BankNifty_CSM
https://www.tradingview.com/script/E0EShlA5-BankNifty-CSM/
chhagansinghmeena
https://www.tradingview.com/u/chhagansinghmeena/
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/ // © chhagansinghmeena //@version=5 // @description TODO: add library description here library("BankNifty_CSM", overlay = true) // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns cell_upColor()=> UPcolor =#4caf50 cell_DWNColor()=> UPcolor =#FF5252 cell_transp()=> cell_transp = 10 cell_neturalColor()=> cell_netural = color.gray getAllPrices()=> prevClose = nz(close[1]) prevOpen = nz(open[1]) prevHigh = nz(high[1]) prevLow = nz(low[1]) currClose = close currOpen = open currHigh = high currLow = low [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] //Thanks to LUXALGO for the gradient idea // This gradient idea i took from '[LUX] Adjustable MA & Alternating Extremities' export getGradientColor(bool isFirstbar = false, float src = close, simple int length = 50, float beta = 0.5, bool isSmoothed = true)=> var os = 0 var b = array.new_float(0) var css = array.new_color(0) if isFirstbar for i = 0 to length - 1 by 1 x = i / (length - 1) w = math.avg(math.atan(2 * math.pi * (1 - math.pow(x, beta))) , math.sin(2 * math.pi * (1 - math.pow(x, beta)))) array.push(b, w) array.push(css, #FF1100),array.push(css, #FF1200),array.push(css, #FF1400),array.push(css, #FF1500),array.push(css, #FF1700),array.push(css, #FF1800),array.push(css, #FF1A00),array.push(css, #FF1B00),array.push(css, #FF1D00),array.push(css, #FF1F00),array.push(css, #FF2000),array.push(css, #FF2200),array.push(css, #FF2300),array.push(css, #FF2500),array.push(css, #FF2600),array.push(css, #FF2800),array.push(css, #FF2900),array.push(css, #FF2B00),array.push(css, #FF2D00),array.push(css, #FF2E00),array.push(css, #FF3000),array.push(css, #FF3100),array.push(css, #FF3300),array.push(css, #FF3400),array.push(css, #FF3600),array.push(css, #FF3700),array.push(css, #FF3900),array.push(css, #FF3B00),array.push(css, #FF3C00),array.push(css, #FF3E00),array.push(css, #FF3F00),array.push(css, #FF4100),array.push(css, #FF4200),array.push(css, #FF4400),array.push(css, #FF4500),array.push(css, #FF4700),array.push(css, #FF4900),array.push(css, #FF4A00),array.push(css, #FF4C00),array.push(css, #FF4D00),array.push(css, #FF4F00),array.push(css, #FF5000),array.push(css, #FF5200),array.push(css, #FF5300),array.push(css, #FF5500),array.push(css, #FF5700),array.push(css, #FF5800),array.push(css, #FF5A00),array.push(css, #FF5B00),array.push(css, #FF5D00),array.push(css, #FF5E00),array.push(css, #FF6000),array.push(css, #FF6200),array.push(css, #FF6300),array.push(css, #FF6500),array.push(css, #FF6600),array.push(css, #FF6800),array.push(css, #FF6900),array.push(css, #FF6B00),array.push(css, #FF6C00),array.push(css, #FF6E00),array.push(css, #FF7000),array.push(css, #FF7100),array.push(css, #FF7300),array.push(css, #FF7400),array.push(css, #FF7600),array.push(css, #FF7700),array.push(css, #FF7900),array.push(css, #FF7A00),array.push(css, #FF7C00),array.push(css, #FF7E00),array.push(css, #FF7F00),array.push(css, #FF8100),array.push(css, #FF8200),array.push(css, #FF8400),array.push(css, #FF8500),array.push(css, #FF8700),array.push(css, #FF8800),array.push(css, #FF8A00),array.push(css, #FF8C00),array.push(css, #FF8D00),array.push(css, #FF8F00),array.push(css, #FF9000),array.push(css, #FF9200),array.push(css, #FF9300),array.push(css, #FF9500),array.push(css, #FF9600),array.push(css, #FF9800),array.push(css, #FF9A00),array.push(css, #FF9B00),array.push(css, #FF9D00),array.push(css, #FF9E00),array.push(css, #FFA000),array.push(css, #FFA100),array.push(css, #FFA300),array.push(css, #FFA400),array.push(css, #FFA600),array.push(css, #FFA800),array.push(css, #FFA900),array.push(css, #FFAB00),array.push(css, #FDAC00),array.push(css, #FBAD02),array.push(css, #F9AE03),array.push(css, #F7AE04),array.push(css, #F5AF06),array.push(css, #F3B007),array.push(css, #F1B108),array.push(css, #EFB20A),array.push(css, #EDB30B),array.push(css, #EBB30C),array.push(css, #E9B40E),array.push(css, #E7B50F),array.push(css, #E4B610),array.push(css, #E2B712),array.push(css, #E0B813),array.push(css, #DEB814),array.push(css, #DCB916),array.push(css, #DABA17),array.push(css, #D8BB18),array.push(css, #D6BC1A),array.push(css, #D4BD1B),array.push(css, #D2BD1C),array.push(css, #D0BE1E),array.push(css, #CEBF1F),array.push(css, #CCC020),array.push(css, #C9C122),array.push(css, #C7C223),array.push(css, #C5C224),array.push(css, #C3C326),array.push(css, #C1C427),array.push(css, #BFC528),array.push(css, #BDC62A),array.push(css, #BBC72B),array.push(css, #B9C72C),array.push(css, #B7C82E),array.push(css, #B5C92F),array.push(css, #B3CA30),array.push(css, #B0CB32),array.push(css, #AECC33),array.push(css, #ACCC34),array.push(css, #AACD36),array.push(css, #A8CE37),array.push(css, #A6CF38),array.push(css, #A4D03A),array.push(css, #A2D13B),array.push(css, #A0D13C),array.push(css, #9ED23E),array.push(css, #9CD33F),array.push(css, #9AD440),array.push(css, #98D542),array.push(css, #95D643),array.push(css, #93D644),array.push(css, #91D746),array.push(css, #8FD847),array.push(css, #8DD948),array.push(css, #8BDA4A),array.push(css, #89DB4B),array.push(css, #87DB4C),array.push(css, #85DC4E),array.push(css, #83DD4F),array.push(css, #81DE50),array.push(css, #7FDF52),array.push(css, #7CE053),array.push(css, #7AE054),array.push(css, #78E156),array.push(css, #76E257),array.push(css, #74E358),array.push(css, #72E45A),array.push(css, #70E55B),array.push(css, #6EE55C),array.push(css, #6CE65E),array.push(css, #6AE75F),array.push(css, #68E860),array.push(css, #66E962),array.push(css, #64EA63),array.push(css, #61EA64),array.push(css, #5FEB66),array.push(css, #5DEC67),array.push(css, #5BED68),array.push(css, #59EE6A),array.push(css, #57EF6B),array.push(css, #55EF6C),array.push(css, #53F06E),array.push(css, #51F16F),array.push(css, #4FF270),array.push(css, #4DF372),array.push(css, #4BF473),array.push(css, #48F474),array.push(css, #46F576),array.push(css, #44F677),array.push(css, #42F778),array.push(css, #40F87A),array.push(css, #3EF97B),array.push(css, #3CF97C),array.push(css, #3AFA7E),array.push(css, #38FB7F),array.push(css, #36FC80),array.push(css, #34FD82),array.push(css, #32FE83),array.push(css, #30FF85), src_sum = 0.0 for i = 0 to length - 1 by 1 src_sum += src[i] * array.get(b, i) src_sum src_sum := src_sum / array.sum(b) os_css = math.avg(ta.mfi(src_sum, length)/100, ta.rsi(src_sum, length)/100) scale_color = array.get(css, math.round(os_css * 199)) src_sum := isSmoothed ? src_sum : src [src_sum, scale_color] //========== Indicators Logic getVwapPrediction(openPrice, closePrice, bnfprice, Ex_RS)=> //VWAP VWAP = ta.vwap(openPrice) trend = closePrice > VWAP ? true : false BuySell = trend ? "Buy" : "Sell" VWAP_Color = trend ? color.new( cell_upColor() ,cell_transp()) : color.new( cell_DWNColor() ,cell_transp()) bank_rs = ta.vwap(ta.change(closePrice), 14) / ta.vwap(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1 bank_rs := bank_rs + Ex_RS [VWAP_Color, BuySell, bank_rs] getEMA_20_Prediction(closePrice,bnfprice, Ex_RS)=> //EMA EMA = ta.ema(closePrice, 20) trend = closePrice > EMA ? true : false BuySell = trend ? "Buy" : "Sell" bank_rs = ta.ema(ta.change(closePrice), 14) / ta.ema(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1 bank_rs := bank_rs + Ex_RS [trend, BuySell, bank_rs] export getADX_Prediction(float highPrice = high, float lowPrice = low)=> tr = ta.rma(ta.tr(true), 14) dmplus = ta.rma(math.max(highPrice - highPrice[1], 0), 17) dmminus = ta.rma(math.max(lowPrice[1] - lowPrice, 0), 17) dip = 100 * dmplus / tr din = 100 * dmminus / tr dx = 100 * math.abs(dip - din) / (dip + din) adx = ta.ema(dx, 14) var ADXColor = color.white var ADXText = '' if adx >= 35 and dmplus > dmminus ADXColor:= color.new( cell_upColor() ,cell_transp()) ADXText:= 'Buy+++' else if adx >= 35 and dmplus < dmminus ADXColor:= color.new( cell_DWNColor() ,cell_transp()) ADXText:= 'Sell---' else if adx >= 30 and dmplus > dmminus ADXColor:= color.new( cell_upColor() ,cell_transp()) ADXText:= 'Buy ++' else if adx >= 30 and dmplus < dmminus ADXColor:= color.new( cell_DWNColor() ,cell_transp()) ADXText:= 'Sell--' if adx >= 25 and dmplus > dmminus ADXColor:= color.new( cell_upColor() ,cell_transp()) ADXText:= 'Buy+' else if adx >= 25 and dmplus < dmminus ADXColor:= color.new( cell_DWNColor() ,cell_transp()) ADXText:= 'Sell-' else if adx < 25 and adx >= 20 and dmplus > dmminus ADXColor:= color.new( color.orange ,cell_transp()) ADXText:= 'Buy' else if adx < 25 and adx >= 20 and dmplus < dmminus ADXColor:= color.new( color.orange ,cell_transp()) ADXText:= 'Sell' else if adx < 20 and adx > 15 ADXColor:= color.new( cell_neturalColor() ,cell_transp()) ADXText:= '-' else if adx <= 15 ADXColor:= color.new( cell_neturalColor() ,cell_transp()) ADXText:= '-' [ADXColor, ADXText] export get_RSI_Prediction(float closePrice=close, float bnfprice = close, int Ex_RS = 0)=> //RSI RSI = ta.rsi(closePrice,14) // Generate buy and sell signals buy_signal = RSI > 50 and RSI < 70 //RSI < 70 and RSI > 30 and RSI > 50 sell_signal = RSI < 50 and RSI > 30 //and RSI < 30 and RSI < 50 BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-' RSi_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) switch RSI > 25 and RSI < 50 => BuySell := 'Oversold' RSi_Color := color.new( color.red , 0) RSI > 15 and RSI < 25=> BuySell := 'Oversold+' RSi_Color := color.new(#650808, cell_transp()) RSI < 15=> BuySell := 'Ex-Oversold' RSi_Color := color.new(#650808, 0) RSI < 75 and RSI > 50 => BuySell := 'Overbought' RSi_Color := color.new( color.green , 0) RSI < 85 and RSI > 75 => BuySell := 'Overbought++' RSi_Color := color.new(#2f59c5, cell_transp()) RSI > 85 => BuySell := 'Ex-Overbought' RSi_Color := color.new(#6b2fc5, 0) BuySell := str.tostring(RSI,'#') bank_rs = ta.rsi(ta.change(closePrice), 14) / ta.rsi(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1 bank_rs := bank_rs + Ex_RS [RSi_Color, BuySell, bank_rs] export get_MFI_Prediction(float hlc3Price = hlc3, float bnfprice = close,int Ex_RS = 0)=> //MFI MFI = ta.mfi(hlc3Price, 14) // Generate buy and sell signals buy_signal = MFI > 50 and MFI < 75 sell_signal = MFI < 50 and MFI > 25 BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-' MFi_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) switch MFI > 20 and MFI < 50 => BuySell := 'Oversold' MFi_Color := color.new( color.red , 0) MFI > 10 and MFI < 20=> BuySell := 'Oversold+' MFi_Color := color.new(#650808, cell_transp()) MFI < 10=> BuySell := 'Ex-Oversold' MFi_Color := color.new(#650808, 0) MFI < 80 and MFI > 50=> BuySell := 'Overbought' MFi_Color := color.new( color.green , 0) MFI > 80 and MFI < 90=> BuySell := 'Overbought+' MFi_Color := color.new(#2f59c5, cell_transp()) MFI > 90 => BuySell := 'Ex-Overbought' MFi_Color := color.new(#6b2fc5, 0) BuySell := str.tostring(MFI,'#') bank_rs = ta.mfi(ta.change(hlc3Price), 14) / ta.mfi(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1 bank_rs := bank_rs + Ex_RS [MFi_Color, BuySell, bank_rs] get_Alligator_Prediction(hl2Alligs, closePrice)=> // Alligator jawLen = 13 teethLen = 8 lipsLen = 5 jaw = ta.sma(hl2Alligs, jawLen) teeth = ta.sma(hl2Alligs, teethLen) lips = ta.sma(hl2Alligs, lipsLen) buyAlligator = lips > teeth and teeth > jaw and closePrice > lips sellAlligator = lips < teeth and teeth < jaw and closePrice < lips BuySell = buyAlligator ? "Buy" : sellAlligator ? "Sell" : 'Sleep' Alligator_Color = buyAlligator ? color.new( cell_upColor() ,cell_transp()) : sellAlligator ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) [Alligator_Color, BuySell] get_MACD_Prediction(closePrice)=> // Calculate the MACD and signal line [macdLine, signalLine, histLine] = ta.macd(closePrice, 12, 26, 9) // Generate buy and sell signals buy_signal = macdLine > signalLine // ta.crossover(macdLine, signalLine) sell_signal = macdLine < signalLine // ta.crossunder(macdLine, signalLine) BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-' MACD_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) [MACD_Color, BuySell] export frama_Calculation(float src = close,int length = 21, float mult = 1.0) => // Define the FRAMA function using a loop alpha = 2 / (length + 1) sum_wt = 0.0 sum_wt_src = 0.0 for i = 0 to length - 1 by 1 weight = math.exp(math.log(mult) * i * i / (length * length)) sum_wt += weight sum_wt_src += weight * src[length - 1 - i] sum_wt_src frama_value = sum_wt_src / sum_wt frama_value export CSM_CPMA(simple int length=21, float price = close, float HL2 = hl2,float Open = open , float High = high, float Low = low, float OHLC4 = ohlc4, float HLC3 = hlc3, float HLCC4 = hlcc4)=> // Calculate the average of the last 21 candles for each price type price_avg = ta.ema(price, length) HL2_avg = ta.sma(HL2, length) Open_avg = ta.ema(Open, length) High_avg = ta.sma(High, length) Low_avg = ta.ema(Low, length) OHLC4_avg = ta.sma(OHLC4, length) HLC3_avg = ta.ema(HLC3, length) HLCC4_avg = ta.sma(HLCC4, length) // Calculate the average of the price types price_average = (price_avg + HL2_avg + Open_avg + High_avg + Low_avg + OHLC4_avg + HLC3_avg + HLCC4_avg) / 8 price_average := na(price_average[1]) ? price_average : price_average[1] + (price - price_average[1]) / (length * math.pow(price/price_average[1], 4)) price_average get_FARMA_Prediction(closePrice, bnfprice, Ex_RS)=> // Calculate the FRAMA frama_value = frama_Calculation(closePrice, 16, 1) // Generate buy and sell signals buy_signal = closePrice > frama_value //ta.crossover(closePrice, frama_value) sell_signal = closePrice < frama_value //ta.crossunder(closePrice, frama_value) BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-' FARMA_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) bank_rs = frama_Calculation(ta.change(closePrice),16,1) / frama_Calculation(ta.change(bnfprice), 16, 1) * 100 > 0 ? 1 : -1 bank_rs := bank_rs + Ex_RS [FARMA_Color, BuySell, bank_rs] // Thanks For TradingView // The same on Pine Script™ pine_supertrend(factor, atrPeriod, hl2Price, closePrice) => src = hl2Price atr = ta.atr(atrPeriod) upperBand = src + factor * atr lowerBand = src - factor * atr prevLowerBand = nz(lowerBand[1]) prevUpperBand = nz(upperBand[1]) lowerBand := lowerBand > prevLowerBand or closePrice[1] < prevLowerBand ? lowerBand : prevLowerBand upperBand := upperBand < prevUpperBand or closePrice[1] > prevUpperBand ? upperBand : prevUpperBand int direction = na float superTrend = na prevSuperTrend = superTrend[1] if na(atr[1]) direction := 1 else if prevSuperTrend == prevUpperBand direction := closePrice > upperBand ? -1 : 1 else direction := closePrice < lowerBand ? 1 : -1 superTrend := direction == -1 ? lowerBand : upperBand [superTrend, direction] get_SuperTrend_Prediction(factor, atrPeriod, hl2Price, closePrice)=> //Supertrend [superTrend, dir] = pine_supertrend(factor, atrPeriod, hl2Price, closePrice) buySignal = dir < 0 sellSignal = dir > 0 BuySell = buySignal ? "Buy" : sellSignal ? "Sell" : '-' ST_Color = buySignal ? color.new( cell_upColor() ,cell_transp()) : sellSignal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) [ST_Color, BuySell] // For first symbol export getLtp_N_Chang(float openPrice = open, float closePrice = close, float highPrice = high, float hl2Price = hl2, float lowPrice = low, float hlc3Price = hlc3,float stockLastClosePrice = close,float bankNiftyClose = close)=> ts1 = closePrice ts1C = stockLastClosePrice ts1Chng = (ts1-ts1C) ts1p = (ts1-ts1C)*100/ts1C [VWAPColor, VWAPText, Vwap_bnf] = getVwapPrediction(openPrice = openPrice, closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = 0) [trend, BuySell, EMA_bnf] = getEMA_20_Prediction(closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = Vwap_bnf ) [ADXColor, ADXText] = getADX_Prediction(highPrice = highPrice, lowPrice = lowPrice) [RSIColor, RSIText, RSI_bnf] = get_RSI_Prediction(closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = EMA_bnf) [MFIColor, MFIText, MFI_bnf] = get_MFI_Prediction(hlc3Price = hlc3Price, bnfprice = bankNiftyClose, Ex_RS = RSI_bnf) [AllG_Color, AllG_Text] = get_Alligator_Prediction(hl2Alligs = hl2Price, closePrice = closePrice) [MACD_Color, MACDText] = get_MACD_Prediction(closePrice = closePrice) [FARMA_Color, FARMAText, FARMA_bnf] = get_FARMA_Prediction(closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = MFI_bnf) [ST_Color_21, ST_Text_21] = get_SuperTrend_Prediction(factor=1, atrPeriod=21, hl2Price=hl2Price, closePrice=closePrice) [ST_Color_14, ST_Text_14] = get_SuperTrend_Prediction(factor=2, atrPeriod=14, hl2Price=hl2Price, closePrice=closePrice) [ST_Color_10, ST_Text_10] = get_SuperTrend_Prediction(factor=3, atrPeriod=10, hl2Price=hl2Price, closePrice=closePrice) // FARMA_bnf := ADXText == 'Buy' or ADXText == 'Buy+' or ADXText == 'Buy++' or ADXText == 'Buy+++' ? FARMA_bnf + 1 : ADXText == 'Sell' or ADXText == 'Sell-' or ADXText == 'Sell--' or ADXText == 'Sell---' ? FARMA_bnf - 1 : FARMA_bnf // FARMA_bnf := AllG_Text == 'Buy' ? FARMA_bnf + 1 : AllG_Text == 'Sell' ? FARMA_bnf - 1 : FARMA_bnf // FARMA_bnf := MACDText == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1 // FARMA_bnf := ST_Text_21 == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1 // FARMA_bnf := ST_Text_14 == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1 // FARMA_bnf := ST_Text_10 == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1 // Calculate the RS ratio rs_ratio = closePrice / bankNiftyClose // Calculate the moving average of the RS ratio over 20 periods rs_ma = ta.sma(rs_ratio, 20) // Plot buy/sell signals based on the RS comparison buy = rs_ratio > rs_ma sell = rs_ratio < rs_ma RS_Text = buy ? "Buy" : sell ? "Sell" : '-' RS_Color = buy ? color.new( cell_upColor() ,cell_transp()) : sell ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) [ts1, ts1Chng, ts1p, VWAPColor, VWAPText, trend, BuySell, ADXColor, ADXText, RSIColor, RSIText, MFIColor, MFIText, AllG_Color, AllG_Text, MACD_Color, MACDText, FARMA_Color, FARMAText, ST_Color_21, ST_Text_21, ST_Color_14, ST_Text_14, ST_Color_10, ST_Text_10, RS_Text, RS_Color] //Thanks For Trading For Candlistick Pattern ditection script //This is totaly depend on inbuilt candlistic patters script by TRADINGVIEW, i am adding few modification. //Thanks for tradingview for candlestick pattern script, funcGetCandlebaseConfiguration(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5,int C_Factor = 2)=> [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices() C_BodyHi = math.max(currClose, currOpen) C_BodyLo = math.min(currClose, currOpen) C_Body = C_BodyHi - C_BodyLo C_BodyAvg = ta.ema(C_Body, C_Len) C_SmallBody = C_Body < C_BodyAvg C_LongBody = C_Body > C_BodyAvg C_UpShadow = currHigh - C_BodyHi C_DnShadow = C_BodyLo - currLow C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body C_WhiteBody = currOpen < currClose C_BlackBody = currOpen > currClose C_Range = currHigh - currLow C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo C_BodyMiddle = C_Body / 2 + C_BodyLo C_ShadowEquals = C_UpShadow == C_DnShadow or math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100 < C_ShadowEqualsPercent and math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100 < C_ShadowEqualsPercent C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100 C_Doji = C_IsDojiBody and C_ShadowEquals [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody, C_Doji] // Define a function to detect bullish engulfing patterns export candlepatternbullish(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5)=> [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody, C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = 2) [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices() IsBullish = prevClose < prevOpen and currClose > currOpen and currClose > prevOpen and currOpen < prevClose and currHigh > prevHigh and currLow < prevLow //1 IsAlternativeBullish = prevOpen > prevClose ? currClose > currOpen ? currLow >=prevLow[1] ? currOpen <= prevClose[1] ? prevOpen - currOpen > prevOpen[1] - prevClose[1] ? true : false : false : false : false : false //2 engulfing = C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and currClose >= prevOpen[1] and currOpen <= prevClose[1] and (currClose > prevOpen[1] or currOpen < prevClose[1]) //3. Rising Window risingWindow = C_Range != 0 and C_Range[1] != 0 and currLow > prevHigh //4. Rising 3 methods risingMethods = C_LongBody[4] and C_WhiteBody[4] and C_SmallBody[3] and C_BlackBody[3] and open[3] < high[4] and close[3] > low[4] and C_SmallBody[2] and C_BlackBody[2] and open[2] < high[4] and close[2] > low[4] and C_SmallBody[1] and C_BlackBody[1] and prevOpen < high[4] and prevClose > low[4] and C_LongBody and C_WhiteBody and currClose > close[4] //5. Up Side Tuski up_Tuski = C_LongBody[2] and C_SmallBody[1] and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_WhiteBody[1] and C_BlackBody and C_BodyLo >= C_BodyHi[2] and C_BodyLo <= C_BodyLo[1] //6. MarooBhuju C_MarubozuShadowPercentWhite = 5.0 marubozuWhiteBullish = C_WhiteBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentWhite / 100 * C_Body and C_DnShadow <= C_MarubozuShadowPercentWhite / 100 * C_Body and C_WhiteBody //7 Dragon Fly Doji dragonflyDojiBullish = C_IsDojiBody and C_UpShadow <= C_Body IsBullish := IsBullish or IsAlternativeBullish or engulfing or risingWindow or risingMethods or up_Tuski or marubozuWhiteBullish or dragonflyDojiBullish IsBullish // Define a function to detect bearish engulfing patterns export candlepatternbearish(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5) => [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody, C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = 2) [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices() IsBearish = prevClose > prevOpen and currClose < currOpen and currClose < prevOpen and currOpen > prevClose and currHigh > prevHigh and currLow < prevLow isAlternativeBearish = prevOpen < prevClose ? currClose < currOpen ? currHigh <=prevHigh ? currOpen >= prevClose ? currOpen - currClose > prevClose - prevOpen ? true : false : false : false : false : false //1. Falling Window fallingWindow = C_Range != 0 and C_Range[1] != 0 and currHigh < prevLow //2. Falling Three Methods falling_3_Methods = C_LongBody[4] and C_BlackBody[4] and C_SmallBody[3] and C_WhiteBody[3] and open[3] > low[4] and close[3] < high[4] and C_SmallBody[2] and C_WhiteBody[2] and open[2] > low[4] and close[2] < high[4] and C_SmallBody[1] and C_WhiteBody[1] and prevOpen > low[4] and prevClose < high[4] and C_LongBody and C_BlackBody and currClose < close[4] //3. Down Side Tuski dwn_Tuski = C_LongBody[2] and C_SmallBody[1] and C_BlackBody[2] and C_BodyHi[1] < C_BodyLo[2] and C_BlackBody[1] and C_WhiteBody and C_BodyHi <= C_BodyLo[2] and C_BodyHi >= C_BodyHi[1] //4. MarooBhuju C_MarubozuShadowPercentBearish = 5.0 marubozuBlackBearish = C_BlackBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentBearish / 100 * C_Body and C_DnShadow <= C_MarubozuShadowPercentBearish / 100 * C_Body and C_BlackBody //5. Gravestone Doji gravestoneDojiBearish = C_IsDojiBody and C_DnShadow <= C_Body //6. Dark Cloud Cover dark_CC = C_WhiteBody[1] and C_LongBody[1] and C_BlackBody and currOpen >= prevHigh and currClose < C_BodyMiddle[1] and currClose > prevOpen IsBearish := IsBearish or isAlternativeBearish or fallingWindow or falling_3_Methods or dwn_Tuski or marubozuBlackBearish or gravestoneDojiBearish or dark_CC IsBearish export BullishCandlePatternOnDownTrend(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5,int C_Factor = 2) => [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody, C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = C_Factor) [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices() Bullish = false //1 hammer = C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow //2 Bullish Hammer C_BullishHammer = C_LongBody and C_HasDnShadow and not C_HasUpShadow and C_WhiteBody and C_Doji and C_IsInsideBar and C_DnShadow > C_Factor * C_BodyAvg //3. Tweezer Bottom tw_Bottom = (not C_IsDojiBody or C_HasUpShadow and C_HasDnShadow) and math.abs(currLow - prevLow) <= C_BodyAvg * 0.05 and C_BlackBody[1] and C_WhiteBody and C_LongBody[1] //4. Doji Star Bullish dj_Star = C_BlackBody[1] and C_LongBody[1] and C_IsDojiBody and C_BodyHi < C_BodyLo[1] //5. Morning Star Doji mrng_StraDoji = C_LongBody[2] and C_IsDojiBody[1] and C_LongBody and C_BlackBody[2] and C_BodyHi[1] < C_BodyLo[2] and C_WhiteBody and C_BodyHi >= C_BodyMiddle[2] and C_BodyHi < C_BodyHi[2] and C_BodyHi[1] < C_BodyLo //6. Pearsing Bulish pearcing_Bullish = C_BlackBody[1] and C_LongBody[1] and C_WhiteBody and currOpen <= prevLow and currClose > C_BodyMiddle[1] and currClose < prevOpen //7. Inverted Hammer inver_Hammer = C_SmallBody and C_Body > 0 and C_BodyHi < hl2 and C_UpShadow >= C_Factor * C_Body and not C_HasDnShadow Bullish := hammer or C_BullishHammer or tw_Bottom or dj_Star or mrng_StraDoji or pearcing_Bullish or inver_Hammer Bullish export BearishCandlePatternOnUpTrend(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5,int C_Factor = 2) => [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody, C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = C_Factor) [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices() //1.Tweezer Top\nTweezer Top dwn_tweezer = (not C_IsDojiBody or C_HasUpShadow and C_HasDnShadow) and math.abs(currHigh - prevHigh) <= C_BodyAvg * 0.05 and C_WhiteBody[1] and C_BlackBody and C_LongBody[1] //2. dark_cloud_cover dark_cloud_cover = currOpen > currClose and currClose < C_BodyMiddle[1] - 0.5 * C_BodyAvg //3. Evening Doji Star evn_Doji = C_LongBody[2] and C_IsDojiBody[1] and C_LongBody and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_BlackBody and C_BodyLo <= C_BodyMiddle[2] and C_BodyLo > C_BodyLo[2] and C_BodyLo[1] > C_BodyHi //4. Doji Star Bearish doji_Star = C_WhiteBody[1] and C_LongBody[1] and C_IsDojiBody and C_BodyLo > C_BodyHi[1] //5. Hanging Man hang_man = C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow //6. Shooting Star shoot_Star = C_SmallBody and C_Body > 0 and C_BodyHi < hl2 and C_UpShadow >= C_Factor * C_Body and not C_HasDnShadow //7. Evening Star evening_Star = C_LongBody[2] and C_SmallBody[1] and C_LongBody and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_BlackBody and C_BodyLo <= C_BodyMiddle[2] and C_BodyLo > C_BodyLo[2] and C_BodyLo[1] > C_BodyHi //8. Harami Bearish haramiBearish = C_LongBody[1] and C_WhiteBody[1] and C_BlackBody and C_SmallBody and currHigh <= C_BodyHi[1] and currLow >= C_BodyLo[1] Bearish = dwn_tweezer or dark_cloud_cover or evn_Doji or doji_Star or hang_man or shoot_Star or evening_Star or haramiBearish Bearish export entryExitinStrategy(bool longCondition = false, bool shortCondition = false, bool window = false, float longTakeProfit = 10.0, float shortTakeProfit = 10.0, float LossstratA = 100.0, float trailingTakeProfit = 0.5) => float longStopLossprice = na float longTakeProfitPrice = na float shortStopLossprice = na float shortTakeProfitPrice = na bool openLongPosition = window and (longCondition or strategy.position_size > 0) bool openShortPosition = window and (shortCondition or strategy.position_size < 0) longIsActive = openLongPosition shortIsActive = openShortPosition longTakeProfitPerc = longTakeProfit/close shortTakeProfitPerc = shortTakeProfit/close trailingTakeProfitPerc = trailingTakeProfit == 0.01 ? syminfo.mintick/close : trailingTakeProfit/close //Long Stop Loss added longStopLossprice := if longIsActive if openLongPosition and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) low - LossstratA else nz(longStopLossprice[1], low - longStopLossprice) else na //Long Take Profir Added longTakeProfitPrice := if longIsActive if openLongPosition and not (strategy.position_size > 0) close * (1 + longTakeProfitPerc) else nz(longTakeProfitPrice[1], close + longTakeProfitPerc) else na //Short StopLoss added shortStopLossprice := if shortIsActive if openShortPosition and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) high + LossstratA else nz(shortStopLossprice[1], high * (1 + shortStopLossprice)) else na //Short Take profit added shortTakeProfitPrice := if shortIsActive if openShortPosition and not (strategy.position_size < 0) close * (1 - shortTakeProfitPerc) else nz(shortTakeProfitPrice[1], close * (1 - shortTakeProfitPrice)) else na float longTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick float shortTrailingTakeProfitStepTicks = shortTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick if window switch longCondition => strategy.entry("Long", strategy.long) shortCondition => strategy.entry("Short", strategy.short) strategy.exit(id = 'Long Take Profit', from_entry = 'Long', profit = high + longTakeProfitPrice, trail_price = longTakeProfitPrice , trail_offset = longTrailingTakeProfitStepTicks , stop = longStopLossprice) strategy.exit(id = 'Short Take Profit', from_entry = 'Short', profit = low + shortTakeProfitPrice, trail_price = shortTakeProfitPrice , trail_offset = shortTrailingTakeProfitStepTicks, stop = shortStopLossprice)
CurrentlyPositionIndicator
https://www.tradingview.com/script/0WIoCFGS-CurrentlyPositionIndicator/
boitoki
https://www.tradingview.com/u/boitoki/
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/ // © boitoki //@version=5 import boitoki/Utilities/5 as util // @description Currently position indicator library("CurrentlyPositionIndicator", overlay=true) f_chg_string (_value, _type) => switch str.lower(_type) 'price' => str.tostring(_value, format.mintick) 'pips' => str.tostring(util.toPips(_value), '0.0') => str.tostring(_value, format.mintick) f_history (_x, _price, _stoploss, _high, _low, _side, _entered, _colors, _show, _number_format = 'Price') => var color_buy = array.get(_colors, 0) var color_sell = array.get(_colors, 1) var color_sl = array.get(_colors, 2) var color_tp = array.get(_colors, 3) var color_default = array.get(_colors, 4) var color_none = color.new(#000000, 100) var color_text = color.black var color_text_tp = color.from_gradient(85, 0, 100, color_tp, #000000) var color_text_sl = color.from_gradient(75, 0, 100, color_sl, #ffffff) var text_font = font.family_monospace var text_size = size.small var text_num_format = _number_format if barstate.isconfirmed and (bar_index - _x > 1) and _show x1 = _x x2 = bar_index - 1 x3 = math.floor(math.avg(x1, x2)) y1 = _price y2 = _stoploss chg = _side == 1 ? _high - y1 : y1 - _low tp_y = _side == 1 ? _high : _low sl_y = _side == 1 ? _low : _high sl_s = _side == 1 ? label.style_label_up : label.style_label_down color_entry = _side == 1 ? color_buy : color_sell label_text = f_chg_string(chg, text_num_format) line_style_sl = line.style_solid // StopLoss level に 到達していないなら color_gray if (_side == -1 and _stoploss > _high) or (_side == 1 and _stoploss < _low) line_style_sl := line.style_dotted if _entered and (chg != 0.0) line.new(x1, y1, x2, y1, width=1, color=color.new(color_entry, 0)) line.new(x1, y2, x2, y2, width=1, color=color.new(color_sl, 30), style=line_style_sl) // StopLoss level box.new (x1, y1, x2, tp_y, bgcolor=color.new(color_tp, 90), border_color=color.new(color_tp, 70)) box.new (x1, y1, x2, sl_y, bgcolor=color.new(color_default, 90), border_color=color.new(color_default, 70)) label.new(x3, tp_y, label_text, color=color_tp, textcolor=color_text_tp, size=text_size, yloc=yloc.price, style=label.style_text_outline) true else box.new (x1, _high, x2, _low, bgcolor=color.new(color_default, 85), border_color=color.new(color_default, 30), border_style=line.style_dotted) true f_main (_x, _y, _lc, _high, _low, _side, _entered, _colors, _position_left = 4, _box_width = 3) => var a_boxes = array.new<box>() var a_lines = array.new<line>() var a_labels = array.new<label>() // Defines // Colors var color_buy = array.get(_colors, 0) var color_sell = array.get(_colors, 1) var color_sl = array.get(_colors, 2) var color_tp = array.get(_colors, 3) var color_gray = array.get(_colors, 4) var color_range = color_gray var color_none = color.new(#000000, 100) // Text var text_size = size.normal var text_font = font.family_monospace var text_style = label.style_label_left var BUY = 'B' var SELL = 'S' var SL = 'SL' // × if barstate.islast util.clear_boxes(a_boxes) util.clear_lines(a_lines) util.clear_labels(a_labels) x = bar_index + _position_left y = _y padding_x = 1 box_width = _box_width box_x1 = x + padding_x box_x2 = box_x1 + box_width label_x = box_x2 + padding_x label_text = str.tostring(_y , format.mintick) + ' ' + (_side == 1 ? BUY : SELL) label_text_lc = str.tostring(_lc, format.mintick) + ' ' + SL color_entry = _side == 1 ? color_buy : color_sell color_progress = _side == 1 ? close > y ? color_tp : color_sl : close < y ? color_tp : color_sl array.push(a_boxes, box.new(box_x1, _high, box_x2, _low, border_color=color.new(color_range, 70), bgcolor=color.new(color_range, 80)) ) // Stoploss line array.push(a_lines, line.new (label_x, _lc, x, _lc, color=color_sl, width=2)) array.push(a_lines, line.new (_x, _lc, x - 2, _lc, color=color_sl, width=1)) array.push(a_labels, label.new(label_x - 1, _lc, label_text_lc, textcolor=color_sl, style=text_style, color=color_none, text_font_family=text_font, size=text_size)) // Entry line array.push(a_lines, line.new (label_x, y, x, y, color=color_entry, width=2)) array.push(a_lines, line.new (_x, y, x - 2, y, color=color_entry, width=1)) array.push(a_labels, label.new(label_x - 1, y, label_text, textcolor=color_entry, style=text_style, color=color_none, text_font_family=text_font, size=text_size)) if _entered array.push(a_boxes, box.new (box_x1, y, box_x2, close, border_color=color.new(color_progress, 70), border_width=1, bgcolor=color.new(color_progress, 60)) ) array.push(a_lines, line.new(box_x1, close, box_x2, close, color=color_progress, width=2) ) // @function Currently positions indicator // @param _index entry index // @param _price entry price // @param _stoploss stoploss price // @param _high range high // @param _low range low // @param _is_entered is entered // @param _colors color array // @param _position_left Left position(option) // @param _box_width box's width(option) // @returns export run(int _index, float _price, float _stoploss, float _high, float _low, int _side, bool _is_entered, array<color> _colors, int _position_left = 4, int _box_width = 3) => f_main(_index, _price, _stoploss, _high, _low, _side, _is_entered, _colors, _position_left, _box_width) // @function History // @param _index Entry index // @param _price Entry price // @param _stoploss StopLoss price // @param _high Range high price // @param _low Range low price // @param _side Num. of entry side (buy is 1, sell is -1) // @param _entered Is the entry entered // @param _colors Color array // @param _show show trigger // @param _number_format Text number format 'Price' | 'Pips' export history(int _index, float _price, float _stoploss, float _high, float _low, int _side, bool _entered, array<color> _colors, bool _show, string _number_format = 'Price') => f_history(_index, _price, _stoploss, _high, _low, _side, _entered, _colors, _show, _number_format) ///////////// // Example // // Inputs i_position_left = input.int(4, minval=0) i_box_width = input.int(3, minval=1) i_num_format = input.string('Price', options=['Price', 'Pips']) // Calc rsi = ta.sma(ta.rsi(close, 14), 7) cond_buy = ta.crossover(rsi, 50) cond_sell = ta.crossunder(rsi, 50) highest_high = ta.highest(high, 5) lowest_low = ta.lowest(low, 5) var colors = array.from(color.blue, color.red, color.purple, color.orange, color.gray) var entry_index = 0 var entry_price = 0.0 var entry_sl = 0.0 var entry_side = 0 var entry_range_high = 0.0 var entry_range_low = 0.0 var entry_entered = false f_history(entry_index, entry_price, entry_sl, entry_range_high, entry_range_low, entry_side, entry_entered, colors, (cond_buy or cond_sell), i_num_format) if cond_buy entry_index := bar_index entry_price := high entry_sl := lowest_low entry_side := 1 entry_range_high := high entry_range_low := low else if cond_sell entry_index := bar_index entry_price := low entry_sl := highest_high entry_side := -1 entry_range_high := high entry_range_low := low else entry_range_high := math.max(entry_range_high, high) entry_range_low := math.min(entry_range_low, low) if (entry_side == 1 and entry_price < high) or (entry_side == -1 and entry_price > low) entry_entered := true run(entry_index, entry_price, entry_sl, entry_range_high, entry_range_low, entry_side, entry_entered, colors, i_position_left, i_box_width)
MACD Pulse Check
https://www.tradingview.com/script/T8t0V6vV-MACD-Pulse-Check/
TheRealDrip2Rip
https://www.tradingview.com/u/TheRealDrip2Rip/
29
study
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/ // © TheRealDrip2Rip //@version=5 indicator("MACD Pulse Check", shorttitle="MACD Pulse Check", overlay=false) // Time filter for alerts allow_alerts = time(timeframe.period, "0955-1550") allow_alerts1 = time(timeframe.period, "0930-1550") // Pre-defined MACD Inputs fastLength1 = 12 slowLength1 = 26 signalLength1 = 9 fastLength2 = 5 slowLength2 = 13 signalLength2 = 5 fastLength3 = 8 slowLength3 = 21 signalLength3 = 8 fastLength4 = 9 slowLength4 = 19 signalLength4 = 6 fastLength5 = 7 slowLength5 = 15 signalLength5 = 7 fastLength6 = 10 slowLength6 = 30 signalLength6 = 10 ////////Overall Trend overlay primaryFast = 12 primarySlow = 26 primarySignal = 9 secondaryFast = 5 secondarySlow = 13 secondarySignal = 5 tertiaryFast = 8 tertiarySlow = 21 tertiarySignal = 8 // User-defined input for threshold userThreshold = input.float(0.001, title="Sideways Threshold", minval=0.001, step=0.0001) // Calculate MACD values [macdLine1, signalLine1, _] = ta.macd(close, fastLength1, slowLength1, signalLength1) [macdLine2, signalLine2, _] = ta.macd(close, fastLength2, slowLength2, signalLength2) [macdLine3, signalLine3, _] = ta.macd(close, fastLength3, slowLength3, signalLength3) [macdLine4, signalLine4, _] = ta.macd(close, fastLength4, slowLength4, signalLength4) [macdLine5, signalLine5, _] = ta.macd(close, fastLength5, slowLength5, signalLength5) [macdLine6, signalLine6, _] = ta.macd(close, fastLength6, slowLength6, signalLength6) // Overlay MACD Value calculation // Calculate MACD values [primaryMacd, primarySignalLine, _] = ta.macd(close, primaryFast, primarySlow, primarySignal) [secondaryMacd, secondarySignalLine, _] = ta.macd(close, secondaryFast, secondarySlow, secondarySignal) [tertiaryMacd, tertiarySignalLine, _] = ta.macd(close, tertiaryFast, tertiarySlow, tertiarySignal) // Calculate the average of all four MACD lines avgMACD = (macdLine1 + macdLine2 + macdLine3 + macdLine4 + macdLine5 + macdLine6) / 6 // Overlay MACD average calculation averageMacd = (primaryMacd + secondaryMacd + tertiaryMacd) / 3 // Plot the combined signal line combinedSignal = avgMACD - ta.sma(avgMACD, 9) // Overlay signal line // Plot the combined signal line consolidatedSignal = averageMacd - ta.sma(averageMacd, 9) // Determine if price action is sideways price_5_candles_ago = ta.valuewhen(1, close, 4) isSideways = math.abs(close - price_5_candles_ago) <= price_5_candles_ago * userThreshold // Define color based on trend and sideways condition signalColor = isSideways ? color.gray : (combinedSignal > 0 ? color.green : color.red) // Plot shape based on signalColor plotshape(allow_alerts1, color=signalColor, style=shape.circle, size=size.tiny, location=location.top) // Plot overlay plotshape(allow_alerts1 and consolidatedSignal < 0, color=color.rgb(255, 82, 82, 55), style=shape.circle, size=size.tiny, location = location.top) // Plot green circle when all values are above the zero line plotshape(allow_alerts1 and consolidatedSignal > 0, color=color.rgb(76, 175, 80, 55), style=shape.circle, size=size.tiny, location = location.top)
Boxes_Plot
https://www.tradingview.com/script/EP7sKHjT-Boxes-Plot/
peacefulLizard50262
https://www.tradingview.com/u/peacefulLizard50262/
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/ // © peacefulLizard50262 //@version=5 library("Boxes_Plot") grad(src)=> color out = switch int(src) 0 => color.new(#1500FF , 20) 1 => color.new(#1709F6 , 20) 2 => color.new(#1912ED , 20) 3 => color.new(#1B1AE5 , 20) 4 => color.new(#1D23DC , 20) 5 => color.new(#1F2CD3 , 20) 6 => color.new(#2135CA , 20) 7 => color.new(#233EC1 , 20) 8 => color.new(#2446B9 , 20) 9 => color.new(#264FB0 , 20) 10 => color.new(#2858A7 , 20) 11 => color.new(#2A619E , 20) 12 => color.new(#2C6A95 , 20) 13 => color.new(#2E728D , 20) 14 => color.new(#307B84 , 20) 15 => color.new(#32847B , 20) 16 => color.new(#348D72 , 20) 17 => color.new(#36956A , 20) 18 => color.new(#389E61 , 20) 19 => color.new(#3AA758 , 20) 20 => color.new(#3CB04F , 20) 21 => color.new(#3EB946 , 20) 22 => color.new(#3FC13E , 20) 23 => color.new(#41CA35 , 20) 24 => color.new(#43D32C , 20) 25 => color.new(#45DC23 , 20) 26 => color.new(#47E51A , 20) 27 => color.new(#49ED12 , 20) 28 => color.new(#4BF609 , 20) 29 => color.new(#4DFF00 , 20) 30 => color.new(#53FF00 , 20) 31 => color.new(#59FF00 , 20) 32 => color.new(#5FFE00 , 20) 33 => color.new(#65FE00 , 20) 34 => color.new(#6BFE00 , 20) 35 => color.new(#71FE00 , 20) 36 => color.new(#77FD00 , 20) 37 => color.new(#7DFD00 , 20) 38 => color.new(#82FD00 , 20) 39 => color.new(#88FD00 , 20) 40 => color.new(#8EFC00 , 20) 41 => color.new(#94FC00 , 20) 42 => color.new(#9AFC00 , 20) 43 => color.new(#A0FB00 , 20) 44 => color.new(#A6FB00 , 20) 45 => color.new(#ACFB00 , 20) 46 => color.new(#B2FB00 , 20) 47 => color.new(#B8FA00 , 20) 48 => color.new(#BEFA00 , 20) 49 => color.new(#C4FA00 , 20) 50 => color.new(#CAF900 , 20) 51 => color.new(#D0F900 , 20) 52 => color.new(#D5F900 , 20) 53 => color.new(#DBF900 , 20) 54 => color.new(#E1F800 , 20) 55 => color.new(#E7F800 , 20) 56 => color.new(#EDF800 , 20) 57 => color.new(#F3F800 , 20) 58 => color.new(#F9F700 , 20) 59 => color.new(#FFF700 , 20) 60 => color.new(#FFEE00 , 20) 61 => color.new(#FFE600 , 20) 62 => color.new(#FFDE00 , 20) 63 => color.new(#FFD500 , 20) 64 => color.new(#FFCD00 , 20) 65 => color.new(#FFC500 , 20) 66 => color.new(#FFBD00 , 20) 67 => color.new(#FFB500 , 20) 68 => color.new(#FFAC00 , 20) 69 => color.new(#FFA400 , 20) 70 => color.new(#FF9C00 , 20) 71 => color.new(#FF9400 , 20) 72 => color.new(#FF8C00 , 20) 73 => color.new(#FF8300 , 20) 74 => color.new(#FF7B00 , 20) 75 => color.new(#FF7300 , 20) 76 => color.new(#FF6B00 , 20) 77 => color.new(#FF6200 , 20) 78 => color.new(#FF5A00 , 20) 79 => color.new(#FF5200 , 20) 80 => color.new(#FF4A00 , 20) 81 => color.new(#FF4200 , 20) 82 => color.new(#FF3900 , 20) 83 => color.new(#FF3100 , 20) 84 => color.new(#FF2900 , 20) 85 => color.new(#FF2100 , 20) 86 => color.new(#FF1900 , 20) 87 => color.new(#FF1000 , 20) 88 => color.new(#FF0800 , 20) 89 => color.new(#FF0000 , 20) 90 => color.new(#F60000 , 20) 91 => color.new(#DF0505 , 20) 92 => color.new(#C90909 , 20) 93 => color.new(#B20E0E , 20) 94 => color.new(#9B1313 , 20) 95 => color.new(#851717 , 20) 96 => color.new(#6E1C1C , 20) 97 => color.new(#572121 , 20) 98 => color.new(#412525 , 20) 99 => color.new(#2A2A2A , 20) 100 => color.new(#1A1818 , 20) => color.white // A function to plot colored boxes representing the values of multiple indicators // @param source - an array of floating-point values representing the indicator values to display // @param name - an array of strings representing the names of the indicators // @param boxes_per_row - the number of boxes to display per row // @param offset - an optional integer to offset the boxes horizontally (default: 0) // @param scale - an optional floating-point value to scale the size of the boxes (default: 1) export boxes_plot(float[] source, string[] name, int boxes_per_row, int offset = 0, float scale = 1)=> left = chart.left_visible_bar_time right = chart.right_visible_bar_time screen_size = math.abs(right - left) unit = int((time - time[1])/2) boxes = array.new<box>(array.size(source)) multiplier = int(screen_size/unit/(boxes_per_row*2)/scale) offset_x = boxes_per_row * multiplier * unit * (offset + 1) if barstate.islast var row = 0 var col = 0 if array.size(source) == array.size(name) for i = 0 to array.size(source) - 1 xPos = (time + col * multiplier * unit - offset_x) yPos = row * multiplier/2 value = array.get(source, i) colour = grad(value) array.push(boxes, box.new(xPos, yPos, xPos + multiplier * unit, yPos - multiplier/2, colour, bgcolor = colour, text = array.get(name, i), text_color = color.white, xloc = xloc.bar_time)) col += 1 if col >= boxes_per_row col := 0 row -= 1 if row >= boxes_per_row row := 0 else for i = 0 to array.size(source) - 1 xPos = (time + col * multiplier * unit - offset_x) yPos = row * multiplier/2 value = array.get(source, i) colour = grad(value) array.push(boxes, box.new(xPos, yPos, xPos + multiplier * unit, yPos - multiplier/2, colour, bgcolor = colour, xloc = xloc.bar_time)) col += 1 if col >= boxes_per_row col := 0 row -= 1 if row >= boxes_per_row row := 0 if barstate.isconfirmed for i = 0 to array.size(boxes) - 1 box.delete(array.get(boxes, i)) // Example usage: rsi = ta.rsi(close, 14) stoch = ta.stoch(close, high, low, 14) data_1 = array.from(rsi, stoch) data_names_1 = array.from("RSI", "STOCH") boxes_plot(data_1, data_names_1, 1, 0, 1) boxes_plot(data_1, data_names_1, 2, 1, 1)
BenfordsLaw
https://www.tradingview.com/script/RM9cFeXx-BenfordsLaw/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
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/ // © RicardoSantos //@version=5 // @description Methods to deal with Benford's law which states that a distribution of first and higher order digits // of numerical strings has a characteristic pattern. // "Benford's law is an observation about the leading digits of the numbers found in real-world data sets. // Intuitively, one might expect that the leading digits of these numbers would be uniformly distributed so that // each of the digits from 1 to 9 is equally likely to appear. In fact, it is often the case that 1 occurs more // frequently than 2, 2 more frequently than 3, and so on. This observation is a simplified version of Benford's law. // More precisely, the law gives a prediction of the frequency of leading digits using base-10 logarithms that // predicts specific frequencies which decrease as the digits increase from 1 to 9." ~(2) // --- // reference: // - 1: https://en.wikipedia.org/wiki/Benford%27s_law // - 2: https://brilliant.org/wiki/benfords-law/ // - 4: https://github.com/vineettanna/Benfords-Law/tree/master library("BenfordsLaw") //#region 0: //#region 0.1: Imports. import RicardoSantos/MathExtension/2 as me import RicardoSantos/DebugConsole/13 as console //#endregion 0.1 //#region 0.2: Variables. console.Console logger = console.new() //#endregion 0.2 //#endregion 0 //#region 1: Helpers. //#region 1.1: cumsum_difference () // @function Calculate the cumulative sum difference of two arrays of same size. // @param a `array<float>` List of values. // @param b `array<float>` List of values. // @returns List with CumSum Difference between arrays. export cumsum_difference (array<float> a, array<float> b) => switch a.size() != b.size() => runtime.error('Array `b` size does not match `a` size.') array<float> _csdiff = array.new<float>(a.size()) float _asum = 0.0 float _bsum = 0.0 for [_i, _ai] in a _asum += _ai _bsum += b.get(_i) _csdiff.set(_i, math.abs(_asum - _bsum)) _csdiff //#endregion 1.1 //#region 1.2: Methods for processing numbers. //#region 1.2.0: fractional_int () // @function Transform a floating number including its fractional part to integer form ex:. `1.2345 -> 12345`. // @param number `float` The number to transform. // @returns Transformed number. export fractional_int (float number) => float _n = number while me.fractional(_n) != 0 _n *= 10 int(_n) //#endregion 1.2.0 //#region 1.2.1: split_to_digits () // @function Transforms a integer number into a list of its digits. // @param number `int` Number to transform. // @param reverse `bool` `default=true`, Reverse the order of the digits, if true, last will be first. // @returns Transformed number digits list. export split_to_digits (int number, bool reverse=true) => int _n = number array<int> _digits = array.new<int>(0) if reverse while _n > 0 _digits.push(_n % 10) _n := int(_n / 10) else while _n > 0 _digits.unshift(_n % 10) _n := int(_n / 10) _digits //#endregion 1.2.1 //#region 1.2.2: digit_in () // @function Digit at index. // @param number `int` Number to parse. // @param digit `int` `default=0`, Index of digit. // @returns Digit found at the index. export digit_in (int number, int digit=0) => array<int> _n = split_to_digits(number, false) if digit < _n.size() _n.get(digit) else int(na) //#endregion 1.2.2 //#endregion 1.2 //#region 1.3: Methods to extract digit information from lists of numbers. //#region 1.3.0: digits_from () // @function Process a list of `int` values and get the list of digits. // @param data `array<int>` List of numbers. // @param dindex `int` `default=0`, Index of digit. // @returns List of digits at the index. export digits_from (array<int> data, int dindex=0) => _clean = array.new<int>(0) for [_i, _e] in data int _d = digit_in(_e, dindex) if _d != 0 and not na(_d) _clean.push(_d) _clean //#endregion 1.3.0 //#region 1.3.1: digit_counters () // @function Score digits. // @param digits `array<int>` List of digits. // @returns List of counters per digit (1-9). export digit_counters (array<int> digits) => switch digits.min() < 0 => runtime.error('Digits must be positive integers.') digits.max() > 9 => runtime.error('Not a single digit.') array<int> _counters = array.new<int>(9, 0) array<int> _sorted = digits.copy() , _sorted.sort() int _base_idx = 0 for _i = 1 to 9 int _idx = _sorted.lastindexof(_i) if _idx >= 0 _counters.set(_i-1, _idx - _base_idx) _base_idx := _idx _counters //#endregion 1.3.1 //#region 1.3.2: digit_distribution () // @function Calculates the frequency distribution based on counters provided. // @param counters `array<int>` List of counters, must have size(9). // @returns Distribution of the frequency of the digits. export digit_distribution (array<int> counters) => switch counters.size() != 9 => runtime.error('Counters list must have size 9.') int _sum = counters.sum() array<float> _distribution = array.new<float>(9, 0.0) for _i = 0 to 8 // array index starts at 0 _distribution.set(_i, counters.get(_i) / _sum) _distribution //#endregion 1.3.2 //#endregion 1.3 //#region 1.4: Benford's Law Expected Distribution. //#region 1.4.0: digit_p (): Expected probability for digit. // P(d|i) = log10(1 + 1 / d) // where i = 1 and 1 <= d <= 9 // @function Expected probability for digit according to Benford. // @param digit `int` Digit number reference in range `1 -> 9`. // @returns Probability of digit according to Benford's law. export digit_p (int digit) => switch digit < 1 and digit > 9 => runtime.error('Must provide a integer digit within 1 >= d <= 9 range') math.log10(1.0 + 1.0 / digit) //#endregion 1.4.0 //#region 1.4.1: benfords_distribution () // @function Calculated Expected distribution per digit according to Benford's Law. // @returns List with the expected distribution. export benfords_distribution () => _b = array.new<float>(9) for _i = 1 to 9 _b.set(_i, digit_p(_i)) _b //#endregion 1.4.1 //#region 1.4.2: benfords_distribution_aprox () // @function Aproximate Expected distribution per digit according to Benford's Law. // @returns List with the expected distribution. export benfords_distribution_aprox () => // 1 2 3 4 5 6 7 8 9 array.from(0.301030, 0.176091, 0.124939, 0.096910, 0.079181, 0.066947, 0.057992, 0.051153, 0.045757) // int d = input.int(1) // plot(benfords_distribution(d)) //#endregion 1.4.2 //#endregion 1.4 //#endregion 1 //#region 2: Test. //#region 2.0: Calculate the distribution and error. // @function Tests Benford's Law on provided list of digits. // @param digits `array<int>` List of digits. // @returns Tuple with: // - Counters: Score of each digit. // - Sample distribution: Frequency for each digit. // - Expected distribution: Expected frequency according to Benford's. // - Cumulative Sum of difference: export test_benfords (array<int> digits, bool calculate_benfords=false) => array<int> _series_counters = digit_counters(digits) array<float> _series_distribution = digit_distribution(_series_counters) array<float> _benfords_distribution = calculate_benfords? benfords_distribution() : benfords_distribution_aprox() array<float> _cumsum_difference = cumsum_difference(_series_distribution, _benfords_distribution) [_series_counters, _series_distribution, _benfords_distribution, _cumsum_difference] //#endregion 2.0 //#region 2.1: Display results to a table. // @function Runs the test and displays the tested data in a table. // @param digits `array<int>` List of digits. // @param _text_color `color` `default=#e3e3e3`, Color of the table text. // @param _border_color `color` `default=#a0a0a0`, Color of the table border. // @param _frame_color `color` `default=#5a5a5a`, Color of the table frame. export to_table ( array<int> digits , color _text_color = #e3e3e3 , color _border_color = #a0a0a0 , color _frame_color = #5a5a5a ) => [_scounters, _sdist, _bdist, _csdiff] = test_benfords(digits) _T = table.new(position.top_right, 6, 11, #000000, _frame_color, 3, _border_color, 1) _T.cell(0, 0, 'Digit:' , text_color=_text_color) _T.cell(1, 0, 'Counters:' , text_color=_text_color) _T.cell(2, 0, 'Actual Distribution:' , text_color=_text_color) _T.cell(3, 0, 'Expected Distribution:', text_color=_text_color) _T.cell(4, 0, 'Cum. Sum. Difference:' , text_color=_text_color) for _i = 1 to 9 _idx = _i - 1 _T.cell(0, _i, str.tostring(_i) , text_color=_text_color) _T.cell(1, _i, str.tostring(_scounters.get(_idx)), text_color=_text_color) _T.cell(2, _i, str.tostring(_sdist.get(_idx)) , text_color=_text_color) _T.cell(3, _i, str.tostring(_bdist.get(_idx)) , text_color=_text_color) _T.cell(4, _i, str.tostring(_csdiff.get(_idx)) , text_color=_text_color) float _actual = _csdiff.max() float _cuttoff = 1.36 / math.sqrt(_scounters.sum()) bool _is_benfords = _actual <= _cuttoff _T.cell(2, 10, str.format('actual: {0}', _actual) , text_color=_text_color) _T.cell(3, 10, str.format('cuttoff: {0}', _cuttoff) , text_color=_text_color) _T.cell(4, 10, str.format('is benford? {0}', _is_benfords), text_color=_text_color) // _T //#endregion 2.1 //#endregion 2 //#region 3: Example. //#region 3.0: Inputs. int window = input.int(100) int idx = input.int(0) //#endregion 3.0 //#region 3.1: Extract digits from price data. int price = math.round(close * 100000) var array<int> prices = array.new<int>(window, price) prices.unshift(price), prices.pop() digits = digits_from(prices, idx) //#endregion 3.1 //#region 3.2: Output. to_table(digits) logger.queue(str.tostring(digits)) // if barstate.islast // digits = array.new<int>(100) // for _i=0 to 99 // digits.set(_i, math.round(math.random() * 100000)) // digits := digits_from(digits, idx) // test_benfords_to_table(digits) // logger.queue_one(str.tostring(digits)) logger.update() //#endregion 3.2 //#endregion 3
MM Detector (Long)
https://www.tradingview.com/script/SNc19Vhb-MM-Detector-Long/
carlpwilliams2
https://www.tradingview.com/u/carlpwilliams2/
24
study
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/ // © carlpwilliams2 //@version=5 indicator("MM Detector (Long)", overlay=true, max_bars_back = 5000) import carlpwilliams2/CarlLib/5 as carlLib numberOfPushes = input.int(2,title="Number Of Pushes", minval = 1) ma50 = ta.ema(close,50) [bodySize, wickSize, upperShadow,lowerShadow, lowerShadowPercentage,upperShadowPercentage,shadowRatio,wickPercentage]= carlLib.candleDetails(open,high,low,close) var mmIsValid = false var lowOfBullClimaxCandle = low var highOfBullClimaxCandle = high var pushCount = 0 var pushRun = false var inTrade = false var bullishCandleLbls = array.new_label(0) var pushCandleLbls = array.new_label(0) if(ta.crossunder(close,ma50)) inTrade:=false // climax detector showPushCandles = input.bool(true,title="Show Push Candles") climaxShadowThreshold = input.int(30,title="Shadow Length Minimum %", group="Short Climax Candle") climaxWickThreshold = input.int(10, title="Wick Length Maximum %", group="Short Climax Candle") volSpikeThresh = input.float(30,title="Spike Threshold") volAverage = ta.sma(volume,10) volumeDifference = ((volume-volume[1])/volume)*100 volumeAverageDifference = ((volume-volAverage)/volume)*100 plot(volumeDifference, title="Volume Spke %", display = display.data_window) plot(volumeAverageDifference, title="Volume avg Spke %", display = display.data_window) plot(upperShadowPercentage, title="Upper Shadow", display = display.data_window) plot(lowerShadowPercentage, title="Lower Shadow", display = display.data_window) plot(shadowRatio, title="Shadow Ratio", display = display.data_window) // Print the wick percentage plot(wickPercentage, title="wick %", display = display.data_window) plot(volumeDifference, title="volume Diff", display= display.data_window) volumeSpike = volumeDifference>volSpikeThresh and volumeAverageDifference>60 bearishCandle = close < open bullishCandle = close > open bullishClimaxCandle = close< ma50 and volumeSpike and bearishCandle and wickPercentage>climaxShadowThreshold and close > low and lowerShadowPercentage>climaxShadowThreshold and shadowRatio>60 bearishClimaxCandle = volumeSpike and bullishCandle and wickPercentage>climaxShadowThreshold and close > low and upperShadowPercentage>climaxShadowThreshold and shadowRatio<40 barsSinceClimax = ta.barssince(bullishClimaxCandle) if(bullishClimaxCandle) lowOfBullClimaxCandle := mmIsValid ? low < lowOfBullClimaxCandle ? low : lowOfBullClimaxCandle : low highOfBullClimaxCandle := high mmIsValid := true array.push(bullishCandleLbls,label.new(bar_index,low,"Low\nof\nBullish\nClimax",style=label.style_label_upper_right, textcolor = color.white)) // lowOfBullClimaxCandle := low[barsSinceClimax] sizeOfClimaxCandle = math.abs(close[barsSinceClimax] - open[barsSinceClimax]) pushCandle = volumeSpike and not bearishCandle and bodySize> sizeOfClimaxCandle and bodySize> bodySize[1] if(pushCandle and not pushRun) pushCount := pushCount + 1 pushRun := true if(showPushCandles and (inTrade or mmIsValid)) array.push(pushCandleLbls,label.new(bar_index,low,text="Push Run" + str.tostring(pushCount), style=label.style_label_upper_left, textcolor = color.white)) if(barstate.isconfirmed and close < open) pushRun :=false barsSincePush = ta.barssince(pushCandle) lastLow = barsSinceClimax > 0 ? ta.lowest(low,barsSinceClimax) : low // tdi lengthrsi=input(13) src=close lengthband=input(34) lengthrsipl=input(2) lengthtradesl=input(7) r=ta.rsi(src, lengthrsi) ma=ta.sma(r,lengthband) offs=(1.6185 * ta.stdev(r, lengthband)) up=ma+offs dn=ma-offs mid=(up+dn)/2 mab=ta.sma(r, lengthrsipl) mbb=ta.sma(r, lengthtradesl) mabCross = ta.crossover(mab,mid) sharkFin = ta.crossover(mab,up) // if(barsSinceClimax < 300 and barsSinceClimax < barsSincePush and (lowOfBullClimaxCandle < lastLow or barsSinceClimax == 0)) // mmIsValid := true // highOfBullClimaxCandle := high // pushCount := 0 if(barsSinceClimax<300 and pushCandle and mmIsValid) inTrade:=true if(close > highOfBullClimaxCandle) highOfBullClimaxCandle :=na if(close < lowOfBullClimaxCandle) mmIsValid:=false lowOfBullClimaxCandle := na // highOfBullClimaxCandle := na pushRun:=false pushCount:=0 if(barsSinceClimax > barsSincePush and pushCount>=numberOfPushes) mmIsValid:=false pushCount:=0 lowOfBullClimaxCandle := na highOfBullClimaxCandle := na plot(lastLow, title="last Low", display = display.data_window) plot(barsSinceClimax, title="Bars since Climax Candle", display = display.data_window) plot(mmIsValid ? lowOfBullClimaxCandle : na, title="Climax candle low", style = plot.style_linebr, color=color.yellow) plot(mmIsValid ? highOfBullClimaxCandle : na, title="Climax candle high", style = plot.style_linebr, color=color.rgb(118, 185, 240)) plotshape(bullishClimaxCandle?lowOfBullClimaxCandle:na, location = location.absolute, text = "Bullish\nClimax\nCandle",title="Bullish Climax Candles", style = shape.labelup, textcolor = color.white, display = display.none) plotshape(bearishClimaxCandle?close:na, location = location.top, text = "Bearish\nClimax\nCandle",title="Bearish Climax Candles", style = shape.labeldown, textcolor = color.white, display = display.none) plotshape(mmIsValid and mabCross?lowOfBullClimaxCandle:na, location = location.absolute) plotshape(mmIsValid[1] and pushCandle?lowOfBullClimaxCandle:na, location = location.absolute, text = "Push", style = shape.labelup, textcolor = color.white, title="Push Label") plotshape(mmIsValid and sharkFin?lowOfBullClimaxCandle:na, location = location.absolute, text = "Long", style = shape.labelup, textcolor = color.white, title="Long Label") bgcolor(mmIsValid? color.new(color.green,95):na, title="Market Maker Possible") // bgcolor(bullishClimaxCandle? color.new(color.green,50):na, title="Market Maker Possible") // bgcolor(pushRun and (mmIsValid or mmIsValid[1])?color.new(color.red,50):na) // bgcolor(inTrade?color.new(color.blue,70):na) alertcondition(bullishClimaxCandle,title="Market Maker Climax Candle", message = "Possible Market Maker Pattern on {{ticker}}({{interval}}), price = {{close}}") alertcondition(mmIsValid[1] and pushCandle,title="Market Maker Push Candle", message = "Push Candle whilst Market Maker pattern is valid on {{ticker}}({{interval}}), price = {{close}}") alertcondition(mmIsValid and sharkFin,title="Market Maker Long", message = "Go long signal detected whilst Market Maker Pattern is valid on {{ticker}}({{interval}}), price = {{close}}")
peacefulIndicators
https://www.tradingview.com/script/nPrmJntS-peacefulIndicators/
peacefulLizard50262
https://www.tradingview.com/u/peacefulLizard50262/
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/ // © peacefulLizard50262 //@version=5 // @description A custom library of technical indicators for trading analysis, including MACD with Dynamic Length, Stochastic RSI with ATR Stop Loss, Bollinger Bands with RSI Divergence, and more. library("peacefulIndicators") import lastguru/DominantCycle/2 as d ema(float source = close, float length = 9)=> alpha = 3 / (length + 1) var float smoothed = na smoothed := alpha * source + (1 - alpha) * nz(smoothed[1]) // @function Moving Average Convergence Divergence with Dynamic Length // @param src Series to use // @param shortLen Shorter moving average length // @param longLen Longer moving average length // @param signalLen Signal line length // @param dynLow Lower bound for the dynamic length // @param dynHigh Upper bound for the dynamic length // @returns tuple of MACD line and Signal line // Computes MACD using lengths adapted based on the dominant cycle period export macdDynamicLength(float src, int shortLen, int longLen, int signalLen, int dynLow, int dynHigh) => // Get dominant cycle period using Pearson Autocorrelation dominantCycle = d.paPeriod(src, dynLow, dynHigh) // Calculate adapted lengths based on the dominant cycle period shortAdaptedLen = int(math.max(2, math.min(shortLen * dominantCycle / math.avg(dynHigh, dynLow), shortLen))) longAdaptedLen = int(math.max(2, math.min(longLen * dominantCycle / math.avg(dynHigh, dynLow), longLen))) signalAdaptedLen = int(math.max(2, math.min(signalLen * dominantCycle / math.avg(dynHigh, dynLow), signalLen))) // Calculate MACD line and Signal line using adapted lengths shortMa = ema(src, shortAdaptedLen) longMa = ema(src, longAdaptedLen) macdLine = shortMa - longMa signalLine = ta.sma(macdLine, signalAdaptedLen) [macdLine, signalLine] // @function RSI Divergence Detection // @param src Series to use // @param rsiLen Length for RSI calculation // @param divThreshold Divergence threshold for RSI // @param linRegLength Length for linear regression calculation // @returns tuple of RSI Divergence (positive, negative) // Computes RSI Divergence detection that identifies bullish (positive) and bearish (negative) divergences export rsiDivergence(float src, int rsiLen, float divThreshold, int linRegLength) => source = src - ta.linreg(src, linRegLength, 0) // Calculate RSI rsiLine = ta.rsi(source, rsiLen) // Detect RSI Divergence priceDelta = (source - source[2])/2 rsiDelta = (rsiLine - rsiLine[2])/2 positiveDivergence = priceDelta < 0 and rsiDelta > divThreshold negativeDivergence = priceDelta > 0 and rsiDelta < -divThreshold [positiveDivergence, negativeDivergence] // @function Trend Reversal Detection (TRD) // @param src Series to use // @param rocLength Length for Rate of Change calculation // @param maLength Length for Moving Average calculation // @param maType Type of Moving Average to use (default: "sma") // @returns A tuple containing trend reversal direction and the reversal point // Detects trend reversals using the Rate of Change (ROC) and Moving Averages. export trendReversalDetection(series float src, int rocLength, int maLength, string maType) => // Calculate Rate of Change (ROC) roc = (src - src[rocLength]) / src[rocLength] ema = ema(src, maLength) wma = ta.wma(src, maLength) sma = ta.sma(src, maLength) // Calculate Moving Average ma = maType == "ema" ? ema : maType == "wma" ? wma : sma // Detect trend reversals reversalDirection = 0 var reversalPoint = float(na) crossover = ta.crossover(roc, 0) and src > ma crossunder = ta.crossunder(roc, 0) and src < ma if crossover reversalDirection := 1 reversalPoint := src else if crossunder reversalDirection := -1 reversalPoint := src [reversalDirection, nz(reversalPoint, nz(reversalPoint[1]))] // @function Volume Flow Oscillator // @param src Series to use // @param vol Volume series to use // @param length Period for the calculation // @returns Custom Oscillator value // Computes the custom oscillator based on price movement strength and volume export volume_flow_oscillator(float src, int length) => price_delta = src - src[1] volume_flow = price_delta * volume positive_volume_flow = math.sum(volume_flow > 0 ? volume_flow : 0, length) negative_volume_flow = math.sum(volume_flow < 0 ? volume_flow : 0, length) vfo = 100 * (positive_volume_flow + negative_volume_flow) / (positive_volume_flow - negative_volume_flow) vfo // @function Weighted Volatility Oscillator // @param src Series to use // @param vol Volume series to use // @param length Period for the calculation // @returns Custom Oscillator value // Computes the custom oscillator based on price volatility and volume export weighted_volatility_oscillator(float src, int length) => price_change = math.abs(src - src[1]) weighted_volatility = price_change * volume wvo = math.sum(weighted_volatility, length) / math.sum(volume, length) wvo // @function Relative Volume Oscillator // @param vol_volume_series Volume series to use // @param length Period for the calculation // @returns Custom Oscillator value // Computes the custom oscillator based on relative volume export rvo(int length) => avg_volume = ta.sma(volume, length) relative_volume = volume / avg_volume rvo_value = (relative_volume - 1) * 100 rvo_value // @function Adaptive Channel Breakout // @param price_series Price series to use // @param ma_length Period for the moving average calculation // @param vol_length Period for the volatility calculation // @param multiplier Multiplier for the volatility // @returns Tuple containing the ACB upper and lower values and the trend direction (1 for uptrend, -1 for downtrend) export acb(float price_series, int ma_length, int vol_length, float multiplier) => ma = ta.sma(price_series, ma_length) volatility = ta.stdev(price_series, vol_length) upper = ma + (multiplier * volatility) lower = ma - (multiplier * volatility) var bool trend = na crossover = ta.crossover(price_series, upper) crossunder = ta.crossunder(price_series, lower) trend := crossover ? true : crossunder ? false : nz(trend[1], 1) [upper, lower, trend]
MACD_base_and_reference_TF
https://www.tradingview.com/script/puFvskb1-MACD-base-and-reference-TF/
vpirinski
https://www.tradingview.com/u/vpirinski/
30
study
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/ // © vpirinski //@version=5 //#region *********** DESCRIPTION *********** // The "MACD_with_reference" indicator aims to illustrate the MACD (Moving Average Convergence Divergence) on two distinct timeframes: // the base timeframe (typically the chart's timeframe, e.g., 1D) and the reference timeframe (defaulted to 1W). // This tool provides a means to determine momentum shifts within the stock, potentially guiding traders in adjusting or trimming positions. // ================================================== INFO ================================================== // Key Features of the Indicator: // - Dual Timeframe MACD: Displays MACD on both the primary (base) and higher (reference) timeframes - transparent. // - Momentum Analysis: indication of MACD crossdown of the signal line on the refenence TF to indicate momentum loss on the higher timeframe, guiding decisions to manage positions. // - MACD Line Status: Beneath the chart, a red/green bar line signifies the MACD line's position relative to the signal line on the higher timeframe. // - Alert Creation: Allows for alerts on the MACD and signal line crossdown on the higher timeframe, aiding in planning stop-loss settings for owned stocks. // ================================================== NOTES ================================================== // The "MACD_with_reference" indicator finds optimal usage in several scenarios: // - Chart Analysis: Replacing the MACD indicator during chart reviews. // Alert Setup: Setting alerts for owned stocks to plan ahead for stop-loss placements or position closures. // ================================================== TODO ================================================== //#endregion ======================================================================================================== //#endregion ======================================================================================================== //#region *********** STRATEGY_SETUP *********** indicator( title = "MACD_base_and_reference_TF", shorttitle = "MACD_base_and_reference_TF", overlay = false ) //#endregion ======================================================================================================== //#region *********** LIBRARIES *********** import HeWhoMustNotBeNamed/enhanced_ta/14 as eta //#endregion ======================================================================================================== //#region *********** USER_INPUT *********** var string MACD_GROUP_STR = "MACD" i_macd_base_timeframe = input.timeframe(title = "Base timeframe", defval = "", group = MACD_GROUP_STR) i_macd_reference_timeframe = input.timeframe(title = "Reference timeframe", defval = "W", group = MACD_GROUP_STR) i_macd_ma_source = input.source (title = "Source", defval = close, group = MACD_GROUP_STR) i_macd_osc_ma_type = input.string (title = "Osc MA type", defval = "ema", group = MACD_GROUP_STR, options = ["ema", "sma", "rma", "hma", "wma", "vwma", "swma"]) i_macd_signal_line_ma_type = input.string (title = "Signal MA type", defval = "ema", group = MACD_GROUP_STR, options = ["ema", "sma", "rma", "hma", "wma", "vwma", "swma"]) i_macd_fast_ma_length = input.int (title = "Fast MA Length", defval = 12, group = MACD_GROUP_STR) i_macd_slow_ma_length = input.int (title = "Slow MA Length", defval = 26, group = MACD_GROUP_STR) i_macd_signal_length = input.int (title = "Low MACD Hist", defval = 9, group = MACD_GROUP_STR) i_macd_repaint_en = input.bool (title = "MACD Repainting On/Off", defval = true, group = MACD_GROUP_STR, tooltip="Off for use as an Indicator to avoid repainting. On for use in Strategies so that trades can respond to realtime data.") i_ref_macd_transplant_perc = input.int (title = "Reference MACD transparency %", defval = 70, group = MACD_GROUP_STR) var string GENERAL_GROUP_STR = "GENERAL" i_general_gaps_on = false // input.bool (title = "Gaps On/Off", defval = true, group = GENERAL_GROUP_STR, tooltip = "Flatten out the lines or stair/steps like line") i_general_lookahead_on = false // input.bool (title = "Looakahead On/Off", defval = false, group = GENERAL_GROUP_STR) // Plot colors var string MACD_COLOR_STR = "Color Settings" var string MACD_HISTOGRAM_STR = "Histogram" i_col_macd = input(#2962FF, "MACD Line  ", group=MACD_COLOR_STR, inline="MACD") i_col_signal = input(#FF6D00, "Signal Line  ", group=MACD_COLOR_STR, inline="Signal") i_col_grow_above = input(#26A69A, "Above   Grow", group=MACD_HISTOGRAM_STR, inline="Above") i_col_fall_above = input(#B2DFDB, "Fall", group=MACD_HISTOGRAM_STR, inline="Above") i_col_grow_below = input(#FFCDD2, "Below Grow", group=MACD_HISTOGRAM_STR, inline="Below") i_col_fall_below = input(#FF5252, "Fall", group=MACD_HISTOGRAM_STR, inline="Below") //#endregion ======================================================================================================== //#region *********** COMMON_FUNCTIONS *********** // Function offering a repainting/no-repainting version of the HTF data (but does not work on tuples). // It has the advantage of using only one `security()` call for both. // The built-in MACD function behaves identically to Repainting On in the custom function below. In other words _repaint = TRUE. // https://www.tradingview.com/script/cyPWY96u-How-to-avoid-repainting-when-using-security-PineCoders-FAQ/ f_security(_symbol, _tf, _src, _repaint) => request.security(symbol = _symbol, timeframe = _tf, expression = _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0], gaps = i_general_gaps_on ? barmerge.gaps_on : barmerge.gaps_off, lookahead = i_general_lookahead_on ? barmerge.lookahead_on : barmerge.lookahead_off)[_repaint ? 0 : barstate.isrealtime ? 0 : 1] //#endregion ======================================================================================================== //#region *********** LOGIC *********** // Get the current TF MACD lines and then interpolate them for the Base and the Reference timeframes fast_ma = eta.ma(source = i_macd_ma_source, maType = i_macd_osc_ma_type, length = i_macd_fast_ma_length) slow_ma = eta.ma(source = i_macd_ma_source, maType = i_macd_osc_ma_type, length = i_macd_slow_ma_length) ctf_macd_line = fast_ma - slow_ma ctf_signal_line = eta.ma(source = ctf_macd_line, maType = i_macd_signal_line_ma_type, length = i_macd_signal_length) ctf_hist_line = ctf_macd_line - ctf_signal_line base_macd_line = f_security(syminfo.tickerid, i_macd_base_timeframe, ctf_macd_line, i_macd_repaint_en) base_signal_line = f_security(syminfo.tickerid, i_macd_base_timeframe, ctf_signal_line, i_macd_repaint_en) base_hist_line = f_security(syminfo.tickerid, i_macd_base_timeframe, ctf_hist_line, i_macd_repaint_en) ref_macd_line = f_security(syminfo.tickerid, i_macd_reference_timeframe, ctf_macd_line, i_macd_repaint_en) ref_signal_line = f_security(syminfo.tickerid, i_macd_reference_timeframe, ctf_signal_line, i_macd_repaint_en) ref_hist_line = f_security(syminfo.tickerid, i_macd_reference_timeframe, ctf_hist_line, i_macd_repaint_en) ref_macd_crossunder = ta.crossunder(ref_macd_line, ref_signal_line) //#endregion ======================================================================================================== //#region *********** DEBUG_&_PLOTS *********** color ref_macd_line_color = color.new(i_col_macd, i_ref_macd_transplant_perc) color ref_macd_signal_color = color.new(i_col_signal, i_ref_macd_transplant_perc) // Base MACD hline(price = 0, title = "Zero Line", color=color.new(#787B86, 50)) plot(base_hist_line, title="Histogram", style=plot.style_columns, color=(base_hist_line>=0 ? (base_hist_line[1] < base_hist_line ? i_col_grow_above : i_col_fall_above) : (base_hist_line[1] < base_hist_line ? i_col_grow_below : i_col_fall_below)) ) plot(base_macd_line, title="Base MACD", color=i_col_macd) plot(base_signal_line, title="Base Signal", color=i_col_signal) // Reference MACD plot(ref_macd_line, title="Ref MACD", color=ref_macd_line_color) plot(ref_signal_line, title="Ref Signal", color=ref_macd_signal_color) ref_filter_color = ref_signal_line < ref_macd_line ? color.new(color.green, 50) : color.new(color.red, 50) plotshape(series = 1, title = "Ref TF filter", style = shape.square, location = location.bottom, color = ref_filter_color, size = size.auto) plotshape(ref_macd_crossunder, style=shape.triangledown, location=location.top, size = size.tiny, color=ref_macd_crossunder ? color.rgb(216, 129, 71) : na) //#endregion ======================================================================================================== //#region *********** ALERTS *********** alertcondition(ref_macd_crossunder, "ReferenceMACDCrossUnder", "MACD line xUnder signal line for {{ticker}} at price {{close}}") //#endregion ========================================================================================================
OrderLib
https://www.tradingview.com/script/F2zE1kvF-orderlib/
Hamster-Coder
https://www.tradingview.com/u/Hamster-Coder/
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/ // © Hamster-Coder //@version=5 // @description TODO: add library description here library("OrderLib", overlay = true) import Hamster-Coder/TextLib/6 as textLib //#region Local methods // // @function Add offset to price // addOffset(int side, float price, float commision_prc) => // price * (1 + side * commision_prc / 100) // @function Get offset (% - "procent") from delta (1 = 100%) getPercent(float delta) => delta * 100 // @function Get offset delta (1 = 100%) from offset percent (% - "percent") getDelta(float percent) => percent / 100 addOffsetDelta(float price, float offset_delta) => price * (1 + offset_delta) addOffsetPercent(float price, float offset_prc) => addOffsetDelta(price, getDelta(offset_prc)) // // @function Substrate offset from price // subOffset(int side, float price, float commision_prc) => // price * (1 - side * commision_prc / 100) //#endregion Local methods // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export type exchangeFeesModel float market_order_prc = 0 float limit_order_prc = 0 export feesBinanceFutures() => exchangeFeesModel result = exchangeFeesModel.new() result.limit_order_prc := 0.02 result.market_order_prc := 0.04 result export type orderPriceModel float value = na float value_with_commision = na float offset = na float offset_with_commision = na getOffsetByValue(int side, float value, float enter_price) => side * getPercent(value / enter_price - 1) //@param side (int) Order side. "1" - buy order, "-1" sell order export createOrderPriceByValue(int position_side, int order_side, float value, float enter_price, float commision_prc) => result = orderPriceModel.new() result.value := value result.offset := getOffsetByValue(side = position_side, value = result.value, enter_price = enter_price) result.offset_with_commision := result.offset + position_side * order_side * commision_prc result.value_with_commision := addOffsetPercent(enter_price, position_side * result.offset_with_commision) result export createOrderPriceByPriceWithCommision(int position_side, int order_side, float value_with_commision, float enter_price, float commision_prc) => result = orderPriceModel.new() result.value_with_commision := value_with_commision result.offset_with_commision := getOffsetByValue(position_side, result.value_with_commision, enter_price) result.offset := result.offset_with_commision - position_side * order_side * commision_prc result.value := addOffsetPercent(enter_price, position_side * result.offset_with_commision) result export createOrderPriceByOffset(int position_side, int order_side, float offset, float enter_price, float commision_prc) => result = orderPriceModel.new() result.offset := offset result.offset_with_commision := result.offset + position_side * order_side * commision_prc result.value := addOffsetPercent(enter_price, position_side * result.offset) result.value_with_commision := addOffsetPercent(enter_price, position_side * result.offset_with_commision) result export createOrderPriceByOffsetWithCommision(int position_side, int order_side, float offset_with_commision, float enter_price, float commision_prc) => result = orderPriceModel.new() result.offset_with_commision := offset_with_commision result.offset := result.offset_with_commision - position_side * order_side * commision_prc result.value := addOffsetPercent(enter_price, position_side * result.offset) result.value_with_commision := addOffsetPercent(enter_price, position_side * result.offset_with_commision) result export type orderAmountModel // value in coin float coins = na //@field value in (usdt / busd / etc.) float value = na // float position_piece_prc = 100 export createOrderAmountFromCoins(float coins, float price) => result = orderAmountModel.new() result.coins := coins result.value := price * coins result.position_piece_prc := 100 result export createOrderAmountFromValue(float value, float price) => result = orderAmountModel.new() result.value := value result.coins := value / price result.position_piece_prc := 100 result export createOrderAmountFromOther(orderAmountModel other, float price, float piece_prc) => result = orderAmountModel.new() result.coins := other.coins * getDelta(piece_prc) result.value := result.coins * price result.position_piece_prc := piece_prc result export type orderStateModel bool is_completed = false int completed_on = na // time export type orderPointModel orderPriceModel price orderAmountModel amount orderStateModel state export type breakevenOrderModel orderPointModel target orderPriceModel trigger export type trailingStopOrderModel orderPriceModel trigger float lag_offset = na export type tradePositionModel string ticker = "" int side = 1 // "1" - buy , "-1" - sell int leverage = 20 int created_on = na // orderPointModel enter = na orderPointModel stop_loss = na breakevenOrderModel breakeven = na trailingStopOrderModel trailing_stop = na orderPointModel[] take_profit_collection = na // position state orderStateModel state export type lineView line _line = na label[] labels = na orderPriceModel model = na bool is_completed = false color color = na export type lineViewCollection lineView[] collection = na color color = na bool is_completed = false export type tradePositionView lineView enter = na lineView stop_loss = na lineViewCollection take_profit_collection = na // is completed (not need to repaint) bool is_completed = false // reference to order model tradePositionModel model = na //#region Line view logic createLineView(float price, color color) => lineView result = lineView.new() result.labels := array.new<label>() result.color := color result._line := line.new(time, price, time, price, xloc = xloc.bar_time, extend = extend.none, color = color, style = line.style_solid, width = 1) result.is_completed := false result createLineViewCollection(color color) => result = lineViewCollection.new() result.collection := array.new<lineView>() result.color := color result.is_completed := false result addLineView(lineViewCollection src, float price) => lineView result = na if (na(src)) result := na else if (na(src.collection)) result := na else result := createLineView(price, src.color) src.collection.push(result) result descructLineView(lineView src) => if (na(src) == false) line.delete(src._line) if (src.labels.size() > 0) for index = src.labels.size() - 1 to 0 label.delete(src.labels.get(index)) src.labels.remove(index) descructLineViews(lineViewCollection src) => if (na(src) == false) if (src.collection.size() > 0) for index = src.collection.size() - 1 to 0 descructLineView(src.collection.get(index)) src.collection.remove(index) src //#endregion Line view logic //#region Order view logic repaintLine(line src, int x1, int time_now) => bool result = if (na(src)) false else src.set_x1(na(x1) ? time_now : x1) src.set_x2(time_now) true result repaintEnterLine(tradePositionView src, int time_now) => bool result = if (na(src)) false else if (na(src.model)) false else if (src.is_completed == false) repaintLine(src.enter._line, src.model.created_on, time_now) true result repaintStopLossLine(tradePositionView src, int time_now) => bool result = if (na(src)) false else if (na(src.model)) false else if (na(src.model.stop_loss)) false else if (src.is_completed == false and src.stop_loss.is_completed == false) repaintLine(src.stop_loss._line, src.model.created_on, time_now) if (src.model.stop_loss.state.is_completed) src.stop_loss.is_completed := true src.stop_loss.labels.push(label.new(x = time_now, xloc = xloc.bar_time, y = src.model.stop_loss.price.value, style = label.style_xcross, color = color.red, size = size.tiny)) true result repaintTakeProfitLines(tradePositionView src, int time_now) => bool result = if (na(src)) false else if (na(src.model)) false else if (na(src.model.take_profit_collection)) false else if (src.is_completed == false) for [index, line_view] in src.take_profit_collection.collection if (line_view.is_completed == false) tp_model = src.model.take_profit_collection.get(index) repaintLine(line_view._line, src.model.created_on, time_now) if (tp_model.state.is_completed) line_view.is_completed := true line_view.labels.push(label.new(x = time_now, xloc = xloc.bar_time, y = tp_model.price.value, style = label.style_diamond, color = color.orange, size = size.tiny)) true src export createTradePositionView(tradePositionModel src, simple color profit_color = color.green, simple color loss_color = color.red, simple color enter_color = color.gray) => tradePositionView result = na if (na(src)) result := na else if (na(src.stop_loss)) result := na else if (na(src.take_profit_collection)) result := na else if (src.take_profit_collection.size() == 0) result := na else result := tradePositionView.new() result.model := src result.take_profit_collection := createLineViewCollection(profit_color) result.enter := createLineView(src.enter.price.value, enter_color) result.stop_loss := createLineView(src.stop_loss.price.value, loss_color) // add take profits lineView last_line_view = na for [index, take_profit_model] in src.take_profit_collection last_line_view := addLineView(result.take_profit_collection, take_profit_model.price.value) // add fill linefill.new(result.stop_loss._line, result.enter._line, color = color.new(result.stop_loss.color, 80)) linefill.new(last_line_view._line, result.enter._line, color = color.new(result.take_profit_collection.color, 80)) result export disposeTradePositionView(tradePositionView src) => if (na(src) == false) descructLineView(src.enter) descructLineView(src.stop_loss) descructLineViews(src.take_profit_collection) src.model := na export disposeTradePositionViews(tradePositionView[] src, bool completed_only = true, int skip = 0) => int result = 0 if (na(src)) result := 0 else if (skip < 0) result := 0 else if (src.size() <= skip) result := 0 else skipped = 0 for index = src.size() - 1 to 0 view = src.get(index) if (skipped == skip and (completed_only == false or view.is_completed == true)) disposeTradePositionView(view) result += 1 src.remove(index) else if (view.is_completed == true) skipped += 1 result export repaintTradePositionView(tradePositionView src, int time_now) => int result = if (na(src)) 0 else if (na(src.model)) 0 else if (src.is_completed == true) 0 else repaintEnterLine(src, time_now) repaintStopLossLine(src, time_now) repaintTakeProfitLines(src, time_now) if (src.model.state.is_completed) src.is_completed := true 1 result export repaintTradePositionViews(tradePositionView[] views, int time_now, bool remove_completed) => int result = 0 if (na(views)) result := 0 else if (views.size() > 0) for index = views.size() - 1 to 0 view = views.get(index) result += repaintTradePositionView(view, time_now) if (remove_completed and view.is_completed) views.remove(index) result export updateTradePositionState(tradePositionModel src, float top_price, float bottom_price, int time_now) => bool result = if (na(src)) 0 else if (na(src.stop_loss)) 0 else if (na(src.take_profit_collection)) 0 else if (src.state.is_completed == false) if (na(src.stop_loss) == false) if (src.side == 1 and src.stop_loss.price.value >= bottom_price) src.stop_loss.state.is_completed := true src.stop_loss.state.completed_on := time_now if (src.side == -1 and src.stop_loss.price.value <= top_price) src.stop_loss.state.is_completed := true src.stop_loss.state.completed_on := time_now if (src.stop_loss.state.is_completed) src.state.is_completed := true src.state.completed_on := time_now if (src.take_profit_collection.size() > 0) for [index, take_profit] in src.take_profit_collection if (take_profit.state.is_completed == false) if (src.side == 1 and take_profit.price.value <= top_price) take_profit.state.is_completed := true take_profit.state.completed_on := time_now if (src.side == -1 and take_profit.price.value >= bottom_price) take_profit.state.is_completed := true take_profit.state.completed_on := time_now if (src.take_profit_collection.last().state.is_completed) src.state.is_completed := true src.state.completed_on := time_now 1 0 result export updateTradePositionStates(tradePositionModel[] models, float top_price, float bottom_price, int time_now, bool remove_completed = true) => result = 0 if (na(models) == false) if (models.size() > 0) for index = models.size() - 1 to 0 updateTradePositionState(models.get(index), top_price, bottom_price, time_now) result += 1 if (remove_completed and models.get(index).state.is_completed) models.remove(index) result createOrderPoint(orderPriceModel price, orderAmountModel amount) => result = orderPointModel.new() result.state := orderStateModel.new() result.price := price result.amount := amount result export configureEnterPoint(tradePositionModel src, orderPriceModel price, orderAmountModel amount) => // assert bool result = if (na(src)) argument_null_exception = "src" // argument null exception false else if (na(price)) argument_null_exception = "price" // argument null exception false else if (na(amount)) argument_null_exception = "amount" false // act else src.enter := createOrderPoint(price, amount) true result export configureMarketOpenOrderByPrice(tradePositionModel src, float price_value, float amount_value, exchangeFeesModel exchange_fees) => // assert bool result = if (na(src)) argument_null_exception = "src" // argument null exception false else if (na(price_value)) argument_null_exception = "price_value" // argument null exception false else if (na(amount_value)) argument_null_exception = "amount_value" false else if (na(exchange_fees)) argument_null_exception = "exchange_fees" false // act else price = createOrderPriceByValue(src.side, src.side, price_value, price_value, exchange_fees.market_order_prc) amount = createOrderAmountFromValue(amount_value, price.value_with_commision) configureEnterPoint(src, price, amount) result export configureStopLoss(tradePositionModel src, orderPriceModel price, orderAmountModel amount) => bool result = false // validate arguments if (na(src)) argument_null_exception = "src" // argument null exception result := false else if (na(price)) argument_null_exception = "price" // argument null exception result := false else if (na(amount)) argument_null_exception = "amount" // argument null exception result := false // method body else src.stop_loss := createOrderPoint(price, amount) result := true // result result export configureStopLossByPrice(tradePositionModel src, float price_value, float max_loss, exchangeFeesModel fees) => bool result = if (na(src)) false else if (na(src.enter)) false else orderPriceModel price = createOrderPriceByValue(src.side, -src.side, price_value, src.enter.price.value_with_commision, fees.market_order_prc) if (na(max_loss) == false) src.enter.amount := createOrderAmountFromValue(math.min(max_loss / getDelta(-price.offset_with_commision), src.enter.amount.value), src.enter.price.value) orderAmountModel amount = createOrderAmountFromCoins(src.enter.amount.coins, price.value_with_commision) configureStopLoss(src, price, amount) result export addTakeProfit(tradePositionModel src, orderPriceModel price, orderAmountModel amount) => bool result = false // validate arguments if (na(src)) argument_null_exception = "src" // argument null exception result := false else if (na(price)) argument_null_exception = "price" // argument null exception result := false else if (na(amount)) argument_null_exception = "amount" // argument null exception result := false // method body else src.take_profit_collection.push(createOrderPoint(price, amount)) result := true // result result export addTakeProfitByRR(tradePositionModel src, float rr, float position_piece_prc, exchangeFeesModel exchange_fees) => bool result = false // validate arguments if (na(src)) argument_null_exception = "src" // argument null exception result := false else if (na(src.stop_loss)) argument_null_exception = "src.stop_loss" // argument null exception result := false else if (na(src.enter)) argument_null_exception = "src.enter" // argument null exception result := false else if (na(rr)) argument_null_exception = "rr" // argument null exception result := false else if (na(rr)) argument_null_exception = "rr" // argument null exception result := false else if (na(exchange_fees)) argument_null_exception = "exchange_fees" // argument null exception false // method body else price = createOrderPriceByOffset( position_side = src.side, order_side = -src.side, offset = - src.stop_loss.price.offset_with_commision * rr, //value = src.enter.price.value_with_commision + (src.enter.price.value_with_commision - src.stop_loss.price.value_with_commision) * rr, enter_price = src.enter.price.value, commision_prc = exchange_fees.limit_order_prc ) amount = createOrderAmountFromOther(src.enter.amount, price.value, position_piece_prc) addTakeProfit(src, price, amount) result export configureBreakeven( tradePositionModel src, orderPointModel target, orderPriceModel trigger ) => bool result = if (na(src)) false else src.breakeven := breakevenOrderModel.new() src.breakeven.target := target src.breakeven.trigger := trigger true result export configureBreakevenByValue( tradePositionModel src, float trigger_price, float target_offset = na, exchangeFeesModel exchange_fees ) => bool result = if (na(src)) false else if (na(src.enter)) false else if (na(trigger_price)) argument_null_exception = "trigger_offset" // argument null exception false else if (na(exchange_fees)) argument_null_exception = "exchange_fees" // argument null exception false else expected_offset = na(target_offset) ? exchange_fees.market_order_prc : target_offset target_price = createOrderPriceByOffset(src.side, -src.side, expected_offset, src.enter.price.value_with_commision, exchange_fees.market_order_prc) target_amount = createOrderAmountFromOther(src.enter.amount, target_price.value_with_commision, 100) target = createOrderPoint(target_price, target_amount) trigger = createOrderPriceByValue(src.side, src.side, trigger_price, src.enter.price.value_with_commision, 0) configureBreakeven(src, target, trigger) result export configureBreakevenByOffset( tradePositionModel src, float trigger_offset, float target_offset = na, exchangeFeesModel exchange_fees ) => bool result = if (na(src)) false else if (na(src.enter)) false else if (na(trigger_offset)) argument_null_exception = "trigger_offset" // argument null exception false else if (na(exchange_fees)) argument_null_exception = "exchange_fees" // argument null exception false else expected_offset = na(target_offset) ? exchange_fees.market_order_prc : target_offset target_price = createOrderPriceByOffset(src.side, -src.side, expected_offset, src.enter.price.value_with_commision, exchange_fees.market_order_prc) target_amount = createOrderAmountFromOther(src.enter.amount, target_price.value_with_commision, 100) target = createOrderPoint(target_price, target_amount) trigger = createOrderPriceByOffset(src.side, src.side, trigger_offset, src.enter.price.value_with_commision, 0) configureBreakeven(src, target, trigger) result export configureBreakevenBySL( tradePositionModel src, float target_offset = na, float rr = 1, exchangeFeesModel exchange_fees ) => bool result = if (na(src)) false else if (na(src.enter)) false else if (na(src.stop_loss)) false else if (na(exchange_fees)) false else expected_offset = na(target_offset) ? exchange_fees.market_order_prc : target_offset expected_rr = na(rr) ? 1 : rr target_price = createOrderPriceByOffset(src.side, -src.side, expected_offset, src.enter.price.value_with_commision, exchange_fees.market_order_prc) target_amount = createOrderAmountFromOther(src.enter.amount, target_price.value_with_commision, 100) target = createOrderPoint(target_price, target_amount) trigger = createOrderPriceByOffset(src.side, src.side, -src.stop_loss.price.offset_with_commision * expected_rr, src.enter.price.value, 0) configureBreakeven(src, target, trigger) result // @function Configures "Trailing Stop" // @param src (orderModel, required) target order model // @param lag_offset (float, percent, required) Execute stop order if price reverse back on [lag_offset] percents // @param trigger_offset (float, percent) "Trailing Stop" starts working if price moved by [trigger_offset] related to [src.enter.price] // @param trigger_price (float) "Trailing Stop" starts working if price moved to [trigger_price] // @param commision_percent (float, percent, required, default) Exchange commision for open + close orders togather (default = 0.08) export configureTrailingStop(tradePositionModel src, orderPriceModel trigger, float lag_offset) => // validate arguments bool result = if (na(src)) argument_null_exception = "src" // argument null exception false else if (na(trigger)) argument_null_exception = "trigger" false else if (na(lag_offset)) argument_null_exception = "lag_offset" false // method body else src.trailing_stop := trailingStopOrderModel.new() src.trailing_stop.lag_offset := lag_offset src.trailing_stop.trigger := trigger true // return result result export configureTrailingStopByStopLoss(tradePositionModel src, float lag_offset_rr, float trigger_offset_rr, exchangeFeesModel exchange_fees) => // validate arguments bool result = if (na(src)) argument_null_exception = "src" // argument null exception false else if (na(src.enter)) argument_null_exception = "src.stop_loss" // argument null exception false else if (na(src.stop_loss)) argument_null_exception = "src.stop_loss" // argument null exception false else if (na(lag_offset_rr)) argument_null_exception = "lag_offset_rr" // argument null exception false else if (na(trigger_offset_rr)) argument_null_exception = "trigger_offset_rr" // argument null exception false else if (na(exchange_fees)) argument_null_exception = "exchange_fees" // argument null exception false // method body else trigger = createOrderPriceByOffset(src.side, src.side, -src.stop_loss.price.offset_with_commision * trigger_offset_rr, src.enter.price.value_with_commision, 0) lag_offset = -src.stop_loss.price.offset_with_commision * lag_offset_rr configureTrailingStop( src = src, trigger = trigger, lag_offset = lag_offset ) // return result result // @function Creates empty order export createTradePosition(string ticker, int side, int started_on, int leverage = 1) => tradePositionModel result = tradePositionModel.new() result.created_on := started_on result.leverage := leverage result.ticker := ticker result.side := side result.take_profit_collection := array.new<orderPointModel>() result.state := orderStateModel.new() result // // @function Creates order with enter point // // @param ticker (string) Name of the ticker // // @param side (int) "1" - buy , "-1" - sell // // @param enter (float) enter point price // // @param max_amount_usd (float) Maximum order amount in USDT // // @param leverage (int) Order leverage (default x1) // export createTradePositionWithEnterPoint(string ticker, int side, int started_on, float enter, float max_amount_usd, int leverage = 1) => // tradePositionModel result = createTradePosition(ticker, side, started_on, leverage) // configureEnterPoint(result, createOrderPriceByPrice(enter, enter, commision), enter, amount_usd = max_amount_usd) // result // // @function Creates order with enter point, stop loss and take profit // export createTradePositionWithEST(string ticker, int side, int started_on, float enter, float max_amount_usd, float sl, float rr, float max_loss = na, int leverage = 1, float commision_percent = 0.08) => // tradePositionModel result = createOrderWithEnterPoint(ticker, side, started_on, enter, max_amount_usd, leverage) // configureStopLoss(result, sl, max_loss = max_loss, commision_percent = commision_percent) // addTakeProfit(result, 100, rr = rr, commision_percent = commision_percent) // result //#region === TRADE DATA SECTION === export type tradeStatisticsModel float income = 0 // int error = 0 int completed = 0 int in_progress = 0 int win = 0 int win_partial = 0 int loss = 0 export type tradeDebugDataModel int updated_views = 0 int updated_models = 0 int updated_statistics = 0 export type tradeDataModel tradePositionModel[] buy_model_collection tradePositionModel[] sell_model_collection tradePositionView[] buy_view_collection tradePositionView[] sell_view_collection tradeStatisticsModel statistics tradeDebugDataModel debug export initTradeData() => tradeDataModel result = tradeDataModel.new() result.buy_model_collection := array.new<tradePositionModel>() result.sell_model_collection := array.new<tradePositionModel>() result.buy_view_collection := array.new<tradePositionView>() result.sell_view_collection := array.new<tradePositionView>() result.statistics := tradeStatisticsModel.new() result.debug := tradeDebugDataModel.new() result export clearTradeData(tradeDataModel src) => if (na(src) == false) src.buy_model_collection.clear() src.sell_model_collection.clear() disposeTradePositionViews(src.buy_view_collection, completed_only = false) disposeTradePositionViews(src.sell_view_collection, completed_only = false) calculateTradePositionIncome(tradePositionModel src) => float result = 0 float p_piece = 0 for [index, tp] in src.take_profit_collection if (tp.state.is_completed) p_piece += tp.amount.position_piece_prc / 100 result += math.abs(tp.price.offset_with_commision / -src.stop_loss.price.offset_with_commision * tp.amount.position_piece_prc) / 100, if (src.stop_loss.state.is_completed) result -= p_piece > 0 ? 0 : 1 // actuall this means we have breakeven stop loss after reachin any take profit // truncating to 0.01 result := math.ceil(result * 100) / 100 result calculateTradePositionResult(tradePositionModel src) => string result = na if (na(src)) result := na else if (src.state.is_completed == false) result := "in-progress" else float p_piece = 0 for [index, tp] in src.take_profit_collection if (tp.state.is_completed) p_piece += tp.amount.position_piece_prc / 100 if (p_piece >= 1) result := "win" else if (p_piece <= 0) result := "loss" else result := "win-partial" result filterByCreatedOn(tradePositionModel[] collection, int start_date = na, int end_date = na) => result = array.new<tradePositionModel>() if (na(collection)) result := array.new<tradePositionModel>() else if (na(start_date) and na(end_date)) result := collection.copy() else for [index, item] in collection if ((na(start_date) or item.created_on >= start_date) and (na(end_date) or item.created_on < end_date)) result.push(item) result getOrderCollectionResults(tradePositionModel[] collection) => tradeStatisticsModel result = tradeStatisticsModel.new() if (na(collection) == false) for [index, src] in collection result.income += calculateTradePositionIncome(src) switch calculateTradePositionResult(src) "in-progress" => result.in_progress += 1 "win" => result.completed += 1 result.win += 1 "loss" => result.completed += 1 result.loss += 1 "win-partial" => result.completed += 1 result.win_partial += 1 => result.error += 1 result updateTradeDataStatistics(tradeDataModel src) => buy_orders_result = getOrderCollectionResults(src.buy_model_collection) sell_orders_result = getOrderCollectionResults(src.sell_model_collection) src.statistics := tradeStatisticsModel.new() src.statistics.completed := buy_orders_result.completed + sell_orders_result.completed src.statistics.error := buy_orders_result.error + sell_orders_result.error src.statistics.income := buy_orders_result.income + sell_orders_result.income src.statistics.in_progress := buy_orders_result.in_progress + sell_orders_result.in_progress src.statistics.win := buy_orders_result.win + sell_orders_result.win src.statistics.win_partial := buy_orders_result.win_partial + sell_orders_result.win_partial src.statistics.loss := buy_orders_result.loss + sell_orders_result.loss // calculate scanned models buy_orders_result.completed + sell_orders_result.completed + buy_orders_result.error + sell_orders_result.error export refreshTradeData(tradeDataModel src, float high_price, float low_price, int time, bool remove_completed) => src.debug.updated_models += updateTradePositionStates(src.buy_model_collection, high_price, low_price, time, remove_completed) src.debug.updated_models += updateTradePositionStates(src.sell_model_collection, high_price, low_price, time, remove_completed) src.debug.updated_views += repaintTradePositionViews(src.buy_view_collection, time, remove_completed) src.debug.updated_views += repaintTradePositionViews(src.sell_view_collection, time, remove_completed) src.debug.updated_statistics += updateTradeDataStatistics(src) export addBuyPosition(tradeDataModel src, tradePositionModel position) => if (na(src)) false else if (na(position)) false else src.buy_model_collection.push(position) view = createTradePositionView(position) src.buy_view_collection.push(view) true export addSellPosition(tradeDataModel src, tradePositionModel position) => if (na(src)) false else if (na(position)) false else src.sell_model_collection.push(position) view = createTradePositionView(position) src.sell_view_collection.push(view) true //#endregion === TRADE INFO SECTION === //#region === SERIALIZE POSITION === export serializeToText(tradePositionModel src, textLib.textFormatOptions text_format_options) => result = "" result := textLib.concatLine(result, str.format("Ticker: {0}", src.ticker)) result := textLib.concatLine(result, str.format("Side: {0}", src.side == 1 ? "BUY" : "SELL")) result := textLib.concatLine(result, str.format("Leverage: {0}x", src.leverage)) if (na(src.enter) == false) result := textLib.concatLine(result, "===") result := textLib.concatLine(result, str.format("Enter: {0}", str.tostring(src.enter.price.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Amount: {0}", str.tostring(src.enter.amount.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Coins: {0}", str.tostring(src.enter.amount.coins, text_format_options.basecurrency_format))) result := textLib.concatLine(result, str.format("Real Enter: {0}", str.tostring(src.enter.price.value_with_commision, text_format_options.currency_format))) if (na(src.stop_loss) == false) result := textLib.concatLine(result, "===") result := textLib.concatLine(result, str.format("Expected Stop Loss ({0}): {1}", syminfo.currency, str.tostring(src.stop_loss.price.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Expected Stop Loss (%): {0}", str.tostring(src.stop_loss.price.offset, text_format_options.percent_format))) result := textLib.concatLine(result, str.format("Actual Stop Loss ({0}): {1}", syminfo.currency, str.tostring(src.stop_loss.price.value_with_commision, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Actual Stop Loss (%): {0}", str.tostring(src.stop_loss.price.offset_with_commision, text_format_options.percent_format))) result := textLib.concatLine(result, str.format("Stop Loss Amount ({0}): {1}", syminfo.currency, str.tostring(src.stop_loss.amount.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Stop Loss Amount ({0}): {1}", syminfo.basecurrency, str.tostring(src.stop_loss.amount.coins, text_format_options.basecurrency_format))) result := textLib.concatLine(result, str.format("Stop Loss Position (%): {0}", str.tostring(src.stop_loss.amount.position_piece_prc, text_format_options.percent_format))) if (na(src.take_profit_collection) == false) result := textLib.concatLine(result, "===") for [index, tp] in src.take_profit_collection result := textLib.concatLine(result, str.format("Expected Take Profit #{0} ({1}): {2}", index, syminfo.currency, str.tostring(tp.price.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Expected Take Profit #{0} (%): {1}", index, str.tostring(tp.price.offset, text_format_options.percent_format))) result := textLib.concatLine(result, str.format("Actual Take Profit #{0} ({1}): {2}", index, syminfo.currency, str.tostring(tp.price.value_with_commision, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Actual Take Profit #{0} (%): {1}", index, str.tostring(tp.price.offset_with_commision, text_format_options.percent_format))) result := textLib.concatLine(result, str.format("Take Profit #{0} Amount ({1}): {2}", index, syminfo.currency, str.tostring(tp.amount.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Take Profit #{0} Amount ({1}): {2}", index, syminfo.basecurrency, str.tostring(tp.amount.coins, text_format_options.basecurrency_format))) result := textLib.concatLine(result, str.format("Take Profit #{0} Position (%): {1}", index, str.tostring(tp.amount.position_piece_prc, text_format_options.percent_format))) if (na(src.breakeven) == false) result := textLib.concatLine(result, "===") result := textLib.concatLine(result, str.format("Breakeven Trigger (%): {0}", str.tostring(src.breakeven.trigger.offset, text_format_options.percent_format))) result := textLib.concatLine(result, str.format("Breakeven Trigger ({0}): {1}", syminfo.currency, str.tostring(src.breakeven.trigger.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Breakeven Target (%): {0}", str.tostring(src.breakeven.target.price.offset, text_format_options.percent_format))) if (na(src.trailing_stop) == false) result := textLib.concatLine(result, "===") result := textLib.concatLine(result, str.format("Trailing Stop Trigger (%): {0}", str.tostring(src.trailing_stop.trigger.offset, text_format_options.percent_format))) result := textLib.concatLine(result, str.format("Trailing Stop Trigger ({0}): {1}", syminfo.currency, str.tostring(src.trailing_stop.trigger.value, text_format_options.currency_format))) result := textLib.concatLine(result, str.format("Trailing Stop Lag (%): {0}", str.tostring(src.trailing_stop.lag_offset, text_format_options.percent_format))) result //#endregion === SERIALIZE POSITION ===
Branch Curve
https://www.tradingview.com/script/MaiWm366-Branch-Curve/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
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/ // © kaigouthro //@version=5 import RicardoSantos/CommonTypesMath/1 //@description Generates a branch made of segments with a starting angle // and a turning angle for each segment. The branch is generated from a starting point // and a number of nodes to generate. The length of each segment and angle of each segment // can be adjusted. The branch can be generated in 2D or 3D, render as you wish. library("branch") //@function # Branch Generation. // - `origin`: CommonTypesMath.Vector3 - The starting point of the branch. If the z value is not zero, it will be used as the starting angle. // - `nodes`: int - The number of nodes to generate. // - `segment_length`: float - The length of each segment. // - `segment_growth`: float - The growth of each segment. 0 = no growth, 100 = double the length of the previous segment. // - `angle_start`: float - The starting angle of the branch in degrees. // - `angle_turn`: float - The turning angle of each segment in degrees. // @param origin The starting point of the branch. If the z value is not zero, it will be used as the starting angle. // @param nodes The number of nodes to generate. // @param segment_length The length of each segment. // @param segment_growth The growth of each segment. 0 = no growth, 100 = double the length of the previous segment. // @param angle_start The starting angle of the branch in degrees. // @param angle_turn The turning angle of each segment in degrees. // @return segments The list of segments that make up the branch. export method branch(CommonTypesMath.Vector3 origin, int nodes, float segment_length, float segment_growth, float angle_start, float angle_turn) => // create a list of Point objects points= array.new<CommonTypesMath.Vector3>() // set the initial point points.push(CommonTypesMath.Vector3.new(origin.x, origin.y, origin.z)) // set the initial angle, if origin includes a value, use it, otherise angle start prev_angle = origin.z angle= 0. angle:= na(prev_angle) ? math.toradians(angle_start + 180) : prev_angle // set the initial distance // resets to zero for gennerating muliples distance= 0. distance:= segment_length // create a list of segments segments= array.new<CommonTypesMath.Segment3>() // loop until we have enough points while points.size() < nodes // get the prev CommonTypesMath.Vector3 last_point= points.last() // calculate the next CommonTypesMath.Vector3 next_point= CommonTypesMath.Vector3.new(last_point.x + distance * math.cos(angle), last_point.y + distance * math.sin(angle), angle) // adjust the angle last_point.z := angle angle += math.toradians(angle_turn) next_point.z := angle // add the next CommonTypesMath.Vector3 points.push(next_point) // add a segment to the list segments.push(CommonTypesMath.Segment3.new(last_point, next_point)) // adjust the distance distance *= 1 + segment_growth/100 // return the segments segments
Amazing Oscillator [Algoalpha]
https://www.tradingview.com/script/PX8S1CUj-Amazing-Oscillator-Algoalpha/
AlgoAlpha
https://www.tradingview.com/u/AlgoAlpha/
32
study
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/ // © Algoalpha X © SUSHIBOI77 //@version=5 indicator("🙌 Amazing Oscillator [Algoalpha]") Length = input.int(20, minval = 1) green = input.color(#00ffbb, "Up Color") //#00ffbb red = input.color(#ff1100, "Done Color") //#ff1100 ao = ta.sma(hl2,5) - ta.sma(hl2,34) ////////////////////////// RSI up = ta.rma(math.max(ta.change(ao), 0), Length) down = ta.rma(-math.min(ta.change(ao), 0), Length) rsi = (down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))) - 50 transcon = (rsi > 30) or (rsi < -30) ? 0 : 0 fillcol = rsi > 0 ? color.new(green, transcon) : color.new(red, transcon) z = plot(rsi, color = rsi > 0 ? color.new(green, transcon) : color.new(red, transcon), style = plot.style_columns) plot(30, color = color.new(red, 80)) plot(-30, color = color.new(green, 80)) mid = plot(0, color = color.gray) //fill(mid, z, zscore, 0, fillcol, color.new(chart.bg_color, 100)) plotchar(ta.crossover(rsi, -30) ? -40 * 1.3 : na, char = "x", color = green, location = location.absolute, size = size.tiny) plotchar(ta.crossunder(rsi, 30) ? 40 * 1.3 : na, char = "x", color = red, location = location.absolute, size = size.tiny)
Polynomial
https://www.tradingview.com/script/4cXvhpSj-Polynomial/
hamta7
https://www.tradingview.com/u/hamta7/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © aminmasood54 //@version=5 // @description TODO: add library description here library("Polynomial",overlay = true) // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export PolyNomial(int Dop,int n,int step,int nonp) => // l = ta.pivotlow(low,len,len) // h = ta.pivothigh(high,len,len) // n = math.max(ta.barssince(na(l)==false),ta.barssince(na(h)==false))+len Y = matrix.new<float>(1,1,0) X = matrix.new<float>(1,Dop+1,0) dataY = array.new<float>(1) dataX = array.new<float>(Dop+1) j = n Indexes = array.new<int>() while j>0 array.push(Indexes,bar_index[j]) array.set(dataY,0,close[j]) for i=0 to Dop xv = (n-j)/step array.set(dataX,i,math.pow(xv,i)) matrix.add_row(Y,matrix.rows(Y),dataY) matrix.add_row(X,matrix.rows(X),dataX) j:=j-step matrix.remove_row(Y,0) matrix.remove_row(X,0) endIndex = j+step XtX = matrix.mult(matrix.transpose(X),X) B = matrix.mult(matrix.transpose(X),Y) A = matrix.mult(matrix.pinv(XtX),B) Error = array.avg(array.abs(matrix.col(matrix.diff(Y,matrix.mult(X,A)),0)))/n x = matrix.new<float>(nonp,Dop+1,0) for i=0 to nonp-1 array.push(Indexes,bar_index[endIndex]+(i+1)*step) for k=0 to Dop xv = (n-j)/step matrix.set(x,i,k,math.pow(xv,k)) j:=j-step // matrix.concat(X,x) Y := matrix.mult(x,A) [Y,Error] // ====================================== // Test PolyNomial=================================== // [A,X,Indexes,Error] = PolyNomial(4,50,5,4) // var Lines = array.new_line() // if barstate.islast // Y = matrix.mult(X,A) // for i=0 to array.size(Indexes)-2 // x1 = array.get(Indexes,i) // x2 = array.get(Indexes,i+1) // y1 = matrix.get(Y,i,0) // y2 = matrix.get(Y,i+1,0) // if array.size(Lines)>50 // ln = array.shift(Lines) // line.delete(ln) // array.push(Lines,line.new(x1, y1, x2, y2)) // var t = table.new(position.bottom_center,2, 1, color.green) // table.cell(t, 0, 0, "Error: ") // table.cell(t, 1, 0, str.tostring(Error)) // ======================================================
LibAndy
https://www.tradingview.com/script/tDNjFB9P-LibAndy/
andym1125
https://www.tradingview.com/u/andym1125/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © andym1125 //@version=5 // @description TODO: add library description here library("LibAndy") // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export greencandlme(float x) => //TODO : add function body and return value here x // @function Whether this candle is green or not // @returns Whether this candle is green or not export greencandle() => open < close // @function Whether this candle is red or not // @returns Whether this candle is red or not export redcandle() => open > close export boostrapSeries(float bsSeries) => ret = 0. if bar_index > 0 ret := bsSeries ret
RsiLib
https://www.tradingview.com/script/tUfnxNOq-rsilib/
Hamster-Coder
https://www.tradingview.com/u/Hamster-Coder/
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/ // © Hamster-Coder //@version=5 // @description TODO: add library description here library("RsiLib", overlay = true) highestIndex(float value, int length) => temp = value result = 0 for idx = 0 to length - 1 if (value[idx] > temp) temp := value[idx] result := idx result lowestIndex(float value, int length) => temp = value int result = 0 for idx = 0 to length - 1 if (value[idx] < temp) temp := value[idx] result := idx result export bullishDivergencePower(float rsi, int check_backward_length, int skip_length, float rsi_threshold, float rsi_overload_threshold) => power = 0 if (close[0] < open[0] and lowestIndex(close, check_backward_length) == 0) power += 1 last_rsi = rsi[0] last_price = close[0] bool found_lower_rsi = false for idx = 1 to check_backward_length - 1 if (rsi[idx] > rsi_overload_threshold) break if (rsi[idx] < rsi_threshold) found_lower_rsi := true if (close[idx] < open[idx] and rsi[idx] <= last_rsi and close[idx] >= last_price) if (idx >= skip_length) power += 1 last_price := close[idx] last_rsi := rsi[idx] if (found_lower_rsi == false) power := 0 power export bullishHiddenDivergencePower(float rsi, int check_backward_length, int skip_length, float rsi_threshold) => power = 0 if (close[0] < open[0] and lowestIndex(rsi, check_backward_length) == 0 and rsi[0] < rsi_threshold) power += 1 last_rsi = rsi[0] last_price = close[0] for idx = 1 to check_backward_length - 1 if (close[idx] < open[idx] and rsi[idx] >= last_rsi and close[idx] <= last_price) if (idx >= skip_length) power += 1 last_price := close[idx] last_rsi := rsi[idx] power export bearishDivergencePower(float rsi, int check_backward_length, int skip_length, float rsi_threshold, float rsi_overload_threshold) => power = 0 if (close[0] > open[0] and highestIndex(close, check_backward_length) == 0) power += 1 last_rsi = rsi[0] last_price = close[0] bool match_rsi_threshold = false for idx = 1 to check_backward_length - 1 if (rsi[idx] < rsi_overload_threshold) break if (rsi[idx] > rsi_threshold) match_rsi_threshold := true if (close[idx] > open[idx] and rsi[idx] >= last_rsi and close[idx] <= last_price) if (idx >= skip_length) power += 1 last_price := close[idx] last_rsi := rsi[idx] if (match_rsi_threshold == false) power := 0 power export bearishHiddenDivergencePower(float rsi, int check_backward_length, int skip_length, float rsi_threshold) => power = 0 if (close[0] > open[0] and highestIndex(rsi, check_backward_length) == 0 and rsi[0] > rsi_threshold) power += 1 last_rsi = rsi[0] last_price = close[0] for idx = 1 to check_backward_length - 1 if (close[idx] > open[idx] and rsi[idx] <= last_rsi and close[idx] >= last_price) if (idx >= skip_length) power += 1 last_price := close[idx] last_rsi := rsi[idx] power
loxxfft
https://www.tradingview.com/script/ngbvdAfp-loxxfft/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 // @description This code is a library for performing Fast Fourier Transform (FFT) operations. FFT is an algorithm that can quickly compute the discrete Fourier transform (DFT) of a sequence. The library includes functions for performing FFTs on both real and complex data. It also includes functions for fast correlation and convolution, which are operations that can be performed efficiently using FFTs. Additionally, the library includes functions for fast sine and cosine transforms. // Reference: // https://www.alglib.net/fasttransforms/ library("loxxfft") //+-------------------------------------------------------------------------------------------------------------------+ //| Fast Fourier Transform Library //+-------------------------------------------------------------------------------------------------------------------+ | //| void fastfouriertransform(float[] a, int nn, bool inversefft) | //| void realfastfouriertransform(float[] a, int tnn, bool inversefft) | //| void fastcorrelation(float[] signal, int signallen, float[] pattern, int patternlen) | //| void fastconvolution(float[] signal, int signallen, float[] response, int negativelen, int positivelen) | //| void fastsinetransform(float[] a, int tnn, bool inversefst) | //| void fastcosinetransform(float[] a, int tnn, bool inversefct) | //| void tworealffts(float[] a1, float[] a2, float[] a, float[] b, int tn) | //+-------------------------------------------------------------------------------------------------------------------+ //****************************************************************************** // Fast Fourier Transform // // The algorithm performs a fast Fourier transform of the complex // function defined by nn samples on the real axis. // // Depending on the parameters passed, it can execute // both direct and inverse conversion. // // Input parameters: // nn - Number of function values. Must be degree // deuces. Algorithm does not validate // passed value. // a - array [0 .. 2*nn-1] of Real // Function values. I-th value correspond // a[2*I] elements (real part) // and a[2*I+1] (the imaginary part). // InverseFFT // - the direction of the transformation. // True if reverse, False if direct. // // Output parameters: // a - the result of the transformation. For more details, see // description on the site. https://www.alglib.net/fasttransforms/ //****************************************************************************** // @function Returns Fast Fourier Transform // @param a float[], An array of real and imaginary parts of the function values. The real part is stored at even indices, and the imaginary part is stored at odd indices. // @param nn int, The number of function values. It must be a power of two, but the algorithm does not validate this. // @param inversefft bool, A boolean value that indicates the direction of the transformation. If True, it performs the inverse FFT; if False, it performs the direct FFT. // @returns float[], Modifies the input array a in-place, which means that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution. The transformed data will have real and imaginary parts interleaved, with the real parts at even indices and the imaginary parts at odd indices. export fastfouriertransform(float[] a, int nn, bool inversefft)=> int n = 0 int mmax = 0 int m = 0 int j = 0 int istep = 0 int i = 0 int isign = 0 float wtemp = 0. float wr = 0. float wpr = 0. float wpi = 0. float wi = 0. float theta = 0. float tempr = 0. float tempi = 0. if (inversefft) isign := -1 else isign := 1 n := 2 * nn j := 1 for ii = 1 to nn i := 2 * ii - 1 if (j > i) tempr := array.get(a, j - 1) tempi := array.get(a, j) array.set(a, j - 1, array.get(a, i - 1)) array.set(a, j, array.get(a, i)) array.set(a, i - 1, tempr) array.set(a, i, tempi) m := n / 2 while (m >= 2 and j > m) j -= m m /= 2 j += m mmax := 2 while n > mmax istep := 2 * mmax theta := 2.0 * math.pi / (isign * mmax) wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2) wpi := math.sin(theta) wr := 1.0 wi := 0.0 for ii = 1 to mmax / 2 m := 2 * ii - 1 for jj = 0 to (n - m) / istep i := m + jj * istep j := i + mmax tempr := wr * array.get(a, j - 1) - wi * array.get(a, j) tempi := wr * array.get(a, j) + wi * array.get(a, j - 1) array.set(a, j - 1, array.get(a, j - 1) - tempr) array.set(a, j, array.get(a, j) - tempi) array.set(a, i - 1, array.get(a, i) + tempr) array.set(a, i, array.get(a, i) + tempi) wtemp := wr wr := wr * wpr - wi * wpi + wr wi := wi * wpr + wtemp * wpi + wi mmax := istep if (inversefft) for ix = 1 to 2 * nn array.set(a, ix - 1, array.get(a, ix - 1) / nn) //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ //****************************************************************************** // Fast Fourier Transform // // The algorithm performs a fast Fourier transform of a real // function defined by n samples on the real axis. // // Depending on the parameters passed, it can execute // both direct and inverse conversion. // // Input parameters: // tnn - Number of function values. Must be degree // deuces. Algorithm does not validate // passed value. // a - array [0 .. nn-1] of Real // Function values. // InverseFFT // - the direction of the transformation. // True if reverse, False if direct. // // Output parameters: // a - the result of the transformation. For more details, see // description on the site. https://www.alglib.net/fasttransforms/ //****************************************************************************** // @function Returns Real Fast Fourier Transform // @param a float[], A float array containing the real-valued function samples. // @param tnn int, The number of function values (must be a power of 2, but the algorithm does not validate this condition). // @param inversefft bool, A boolean flag that indicates the direction of the transformation (True for inverse, False for direct). // @returns float[], Modifies the input array a in-place, meaning that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution. export realfastfouriertransform(float[] a, int tnn, bool inversefft)=> float twr = 0. float twi = 0. float twpr = 0. float twpi = 0. float twtemp = 0. float ttheta = 0. int i = 0 int i1 = 0 int i2 = 0 int i3 = 0 int i4 = 0 float c1 = 0. float c2 = 0. float h1r = 0. float h1i = 0. float h2r = 0. float h2i = 0. float wrs = 0. float wis = 0. int nn = 0 int n = 0 int mmax = 0 int m = 0 int j = 0 int istep = 0 int isign = 0 float wtemp = 0. float wr = 0. float wpr = 0. float wpi = 0. float wi = 0. float theta = 0. float tempr = 0. float tempi = 0. if (tnn != 1) if (not inversefft) ttheta := 2.0 * math.pi / tnn c1 := 0.5 c2 := -0.5 else ttheta := 2.0 * math.pi / tnn c1 := 0.5 c2 := 0.5 ttheta := -ttheta twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2) twpi := math.sin(ttheta) twr := 1.0 + twpr twi := twpi for ix = 2 to tnn / 4 + 1 i1 := ix + ix - 2 i2 := i1 + 1 i3 := tnn + 1 - i2 i4 := i3 + 1 wrs := twr wis := twi h1r := c1 * (array.get(a, i1) + array.get(a, i3)) h1i := c1 * (array.get(a, i2) - array.get(a, i4)) h2r := -c2 * (array.get(a, i2) + array.get(a, i4)) h2i := c2 * (array.get(a, i1) - array.get(a, i3)) array.set(a, i1, h1r + wrs * h2r - wis * h2i) array.set(a, i2, h1i + wrs * h2i + wis * h2r) array.set(a, i3, h1r - wrs * h2r + wis * h2i) array.set(a, i4, -h1i + wrs * h2i + wis * h2r) twtemp := twr twr := twr * twpr - twi * twpi + twr twi := twi * twpr + twtemp * twpi + twi h1r := array.get(a, 0) array.set(a, 0, c1 * (h1r + array.get(a, 1))) array.set(a, 1, c1 * (h1r - array.get(a, 1))) if (inversefft) isign := -1 else isign := 1 n := tnn nn := tnn / 2 j := 1 for ii = 1 to nn i := 2 * ii - 1 if (j > i) tempr := array.get(a, j - 1) tempi := array.get(a, j) array.set(a, j - 1, array.get(a, i - 1)) array.set(a, j, array.get(a, i)) array.set(a, i - 1, tempr) array.set(a, i, tempi) m := n / 2 while (m >= 2 and j > m) j := j - m m := m / 2 j := j + m mmax := 2 while (n > mmax) istep := 2 * mmax theta := 2.0 * math.pi / (isign * mmax) wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2) wpi := math.sin(theta) wr := 1.0 wi := 0.0 for ii = 1 to mmax / 2 m := 2 * ii - 1 for jj = 0 to (n - m) / istep i := m + jj * istep j := i + mmax tempr := wr * array.get(a, j - 1) - wi * array.get(a, j) tempi := wr * array.get(a, j) + wi * array.get(a, j - 1) array.set(a, j - 1, array.get(a, i - 1) - tempr) array.set(a, j, array.get(a, i) - tempi) array.set(a, i - 1, array.get(a, i - 1) + tempr) array.set(a, i, array.get(a, i) + tempi) wtemp := wr wr := wr * wpr - wi * wpi + wr wi := wi * wpr + wtemp * wpi + wi mmax := istep if (inversefft) for ix = 1 to 2 * nn array.set(a, ix - 1, array.get(a, ix - 1) / nn) if (not inversefft) twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2) twpi := math.sin(ttheta) twr := 1.0 + twpr twi := twpi for ix = 2 to tnn / 4 + 1 i1 := ix + ix - 2 i2 := i1 + 1 i3 := tnn + 1 - i2 i4 := i3 + 1 wrs := twr wis := twi h1r := c1 * (array.get(a, i1) + array.get(a, i3)) h1i := c1 * (array.get(a, i2) - array.get(a, i4)) h2r := -c2 * (array.get(a, i2) + array.get(a, i4)) h2i := c2 * (array.get(a, i1) - array.get(a, i3)) array.set(a, i1, h1r + wrs * h2r - wis * h2i) array.set(a, i2, h1i + wrs * h2i + wis * h2r) array.set(a, i3, h1r - wrs * h2r + wis * h2i) array.set(a, i4, -h1i + wrs * h2i + wis * h2r) twtemp := twr twr := twr * twpr - twi * twpi + twr twi := twi * twpr + twtemp * twpi + twi h1r := array.get(a, 0) array.set(a, 0, h1r + array.get(a, 1)) array.set(a, 1, h1r - array.get(a, 1)) //****************************************************************************** // Fast Discrete Sine Conversion // // The algorithm performs a fast sine transform of the real // function defined by nn samples on the real axis. // // Depending on the parameters passed, it can execute // both direct and inverse conversion. // // Input parameters: // nn - Number of function values. Must be degree // deuces. Algorithm does not validate // passed value. // a - array [0 .. nn-1] of Real // Function values. // Inverse FST // - the direction of the transformation. // True if reverse, False if direct. // // Output parameters: // a - the result of the transformation. For more details, see // description on the site. https://www.alglib.net/fasttransforms/ //****************************************************************************** // @function Returns Fast Discrete Sine Conversion // @param a float[], An array of real numbers representing the function values. // @param tnn int, Number of function values (must be a power of two, but the code doesn't validate this). // @param inversefst bool, A boolean flag indicating the direction of the transformation. If True, it performs the inverse FST, and if False, it performs the direct FST. // @returns float[], The output is the transformed array 'a', which will contain the result of the transformation. export fastsinetransform(float[] a, int tnn, bool inversefst)=> int j = 0 int tm = 0 int n2 = 0 float sum = 0. float y1 = 0. float y2 = 0. float theta = 0. float wi = 0. float wr = 0. float wpi = 0. float wpr = 0. float wtemp = 0. float twr = 0. float twi = 0. float twpr = 0. float twpi = 0. float twtemp = 0. float ttheta = 0. int i = 0 int i1 = 0 int i2 = 0 int i3 = 0 int i4 = 0 float c1 = 0. float c2 = 0. float h1r = 0. float h1i = 0. float h2r = 0. float h2i = 0. float wrs = 0. float wis = 0. int nn = 0 int n = 0 int mmax = 0 int m = 0 int istep = 0 int isign = 0 float tempr = 0. float tempi = 0. theta := math.pi/tnn wr := 1.0 wi := 0.0 wpr := - 2.0 * math.pow(math.sin(0.5 * theta),2) wpi := math.sin(theta) array.set(a, 0, 0.) tm := tnn / 2 n2 := tnn + 2 for jx = 2 to tm + 1 wtemp := wr wr := wr * wpr - wi * wpi + wr wi := wi * wpr + wtemp * wpi + wi y1 := wi * (array.get(a, jx - 1) + array.get(a, n2 - jx - 1)) y2 := 0.5 * (array.get(a, jx - 1) - array.get(a, n2 - jx - 1)) array.set(a, jx - 1, y1 + y2) array.set(a, n2 - jx - 1, y1 - y2) ttheta := 2.0 * math.pi/tnn c1 := 0.5 c2 := - 0.5 isign := 1 n := tnn nn := tnn / 2 j := 1 for ii = 1 to nn i := 2 * ii - 1 if j > i tempr := array.get(a, j - 1) tempi := array.get(a, j) array.set(a, j - 1, array.get(a, i - 1)) array.set(a, j, array.get(a, i)) array.set(a, i - 1, tempr) array.set(a, i, tempi) m := n/2 while(m >= 2 and j > m) j := j - m m := m/2 j := j + m mmax := 2 while(n > mmax) istep := 2 * mmax theta := 2.0 * math.pi / (isign * mmax) wpr := - 2.0 * math.pow(math.sin(0.5 * theta), 2) wpi := math.sin(theta) wr := 1.0 wi := 0.0 for ii = 1 to mmax/2 m := 2 * ii - 1 for jj = 0 to (n - m) / istep i := m + jj * istep j := i + mmax tempr := wr * array.get(a, j - 1) - wi * array.get(a, j) tempi := wr * array.get(a, j) + wi * array.get(a, j - 1) array.set(a, j - 1, array.get(a, i - 1) - tempr) array.set(a, j, array.get(a, i) - tempi) array.set(a, i - 1, array.get(a, i - 1) + tempr) array.set(a, i, array.get(a, i) + tempi) wtemp := wr wr := wr * wpr - wi * wpi + wr wi := wi * wpr + wtemp * wpi + wi mmax := istep twpr := - 2.0 * math.pow(math.sin(0.5 * ttheta),2) twpi := math.sin(ttheta) twr := 1.0 + twpr twi := twpi for ix = 2 to tnn/4 + 1 i1 := ix + ix - 2 i2 := i1 + 1 i3 := tnn + 1 - i2 i4 := i3 + 1 wrs := twr wis := twi h1r := c1 * (array.get(a, i1) + array.get(a, i3)) h1i := c1 * (array.get(a, i2) - array.get(a, i4)) h2r := - c2 * (array.get(a, i2) + array.get(a, i4)) h2i := c2 * (array.get(a, i1) - array.get(a, i3)) array.set(a, i1, h1r + wrs * h2r - wis * h2i) array.set(a, i2, h1i + wrs * h2i + wis * h2r) array.set(a, i3, h1r - wrs * h2r + wis * h2i) array.set(a, i4, - h1i + wrs * h2i + wis * h2r) twtemp := twr twr := twr * twpr - twi * twpi + twr twi := twi * twpr + twtemp * twpi + twi h1r := array.get(a, 0) array.set(a, 0, h1r + array.get(a, 1)) array.set(a, 1, h1r - array.get(a, 1)) sum := 0.0 array.set(a, 0, 0.5 * array.get(a, 0)) array.set(a, 1, 0.) for jj = 0 to tm - 1 j := 2 * jj + 1 sum := sum + array.get(a, j - 1) array.set(a, j - 1, array.get(a, j)) array.set(a, j, sum) if inversefst for jx = 1 to tnn array.set(a, jx - 1, array.get(a, jx - 1) * 2 / tnn) //****************************************************************************** // Fast Discrete Cosine Transform // // The algorithm performs a fast cosine transform of the real // function defined by nn samples on the real axis. // // Depending on the parameters passed, it can execute // both direct and inverse conversion. // // Input parameters: // tnn - Number of function values minus one. Should be 1024 // degree of two. The algorithm does not check // correct value passed. // a - array [0 .. nn] of Real 1025 // Function values. // InverseFCT // - the direction of the transformation. // True if reverse, False if direct. // // Output parameters: // a - the result of the transformation. For more details, see // description on the site. https://www.alglib.net/fasttransforms/ //****************************************************************************** // @function Returns Fast Discrete Cosine Transform // @param a float[], This is a floating-point array representing the sequence of values (time-domain) that you want to transform. The function will perform the Fast Cosine Transform (FCT) or the inverse FCT on this input array, depending on the value of the inversefct parameter. The transformed result will also be stored in this same array, which means the function modifies the input array in-place. // @param tnn int, This is an integer value representing the number of data points in the input array a. It is used to determine the size of the input array and control the loops in the algorithm. Note that the size of the input array should be a power of 2 for the Fast Cosine Transform algorithm to work correctly. // @param inversefct bool, This is a boolean value that controls whether the function performs the regular Fast Cosine Transform or the inverse FCT. If inversefct is set to true, the function will perform the inverse FCT, and if set to false, the regular FCT will be performed. The inverse FCT can be used to transform data back into its original form (time-domain) after the regular FCT has been applied. // @returns float[], The resulting transformed array is stored in the input array a. This means that the function modifies the input array in-place and does not return a new array. export fastcosinetransform(float[] a, int tnn, bool inversefct)=> int j = 0 int n2 = 0 float sum = 0. float y1 = 0. float y2 = 0. float theta = 0. float wi = 0. float wpi = 0. float wr = 0. float wpr = 0. float wtemp = 0. float twr = 0. float twi = 0. float twpr = 0. float twpi = 0. float twtemp = 0. float ttheta = 0. int i = 0 int i1 = 0 int i2 = 0 int i3 = 0 int i4 = 0 float c1 = 0. float c2 = 0. float h1r = 0. float h1i = 0. float h2r = 0. float h2i = 0. float wrs = 0. float wis = 0. int nn = 0 int n = 0 int mmax = 0 int m = 0 int istep = 0 int isign = 0 float tempr = 0. float tempi = 0. wi := 0 wr := 1 theta := math.pi / tnn wtemp := math.sin(theta * 0.5) wpr := -2.0 * wtemp * wtemp wpi := math.sin(theta) sum := 0.5 * (array.get(a, 0) - array.get(a, tnn)) array.set(a, 0, 0.5 * (array.get(a, 0) + array.get(a, tnn))) n2 := tnn + 2 for jx = 2 to tnn / 2 wtemp := wr wr := wtemp * wpr - wi * wpi + wtemp wi := wi * wpr + wtemp * wpi + wi y1 := 0.5 * (array.get(a, jx - 1) + array.get(a, n2 - jx - 1)) y2 := array.get(a, jx - 1) - array.get(a, n2 - jx - 1) array.set(a, jx - 1, y1 - wi * y2) array.set(a, n2 - jx - 1, y1 + wi * y2) sum := sum + wr * y2 ttheta := 2.0 * math.pi / tnn c1 := 0.5 c2 := -0.5 isign := 1 n := tnn nn := tnn / 2 j := 1 for ii = 1 to nn i := 2 * ii - 1 if (j > i) tempr := array.get(a, j - 1) tempi := array.get(a, j) array.set(a, j - 1, array.get(a, i - 1)) array.set(a, j, array.get(a, i)) array.set(a, i - 1, tempr) array.set(a, i, tempi) m := n / 2 while (m >= 2 and j > m) j := j - m m := m / 2 j := j + m mmax := 2 while (n > mmax) istep := 2 * mmax theta := 2.0 * math.pi / (isign * mmax) wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2) wpi := math.sin(theta) wr := 1.0 wi := 0.0 for ii = 1 to mmax / 2 m := 2 * ii - 1 for jj = 0 to (n - m) / istep i := m + jj * istep j := i + mmax tempr := wr * array.get(a, j - 1) - wi * array.get(a, j) tempi := wr * array.get(a, j) + wi * array.get(a, j - 1) array.set(a, j - 1, array.get(a, i - 1) - tempr) array.set(a, j, array.get(a, i) - tempi) array.set(a, i - 1, array.get(a, i - 1) + tempr) array.set(a, i, array.get(a, i) + tempi) wtemp := wr wr := wr * wpr - wi * wpi + wr wi := wi * wpr + wtemp * wpi + wi mmax := istep twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2) twpi := math.sin(ttheta) twr := 1.0 + twpr twi := twpi for ix = 2 to tnn / 4 + 1 i1 := ix + ix - 2 i2 := i1 + 1 i3 := tnn + 1 - i2 i4 := i3 + 1 wrs := twr wis := twi h1r := c1 * (array.get(a, i1) + array.get(a, i3)) h1i := c1 * (array.get(a, i2) - array.get(a, i4)) h2r := -c2 * (array.get(a, i2) + array.get(a, i4)) h2i := c2 * (array.get(a, i1) - array.get(a, i3)) array.set(a, i1, h1r + wrs * h2r - wis * h2i) array.set(a, i2, h1i + wrs * h2i + wis * h2r) array.set(a, i3, h1r - wrs * h2r + wis * h2i) array.set(a, i4, -h1i + wrs * h2i + wis * h2r) twtemp := twr twr := twr * twpr - twi * twpi + twr twi := twi * twpr + twtemp * twpi + twi h1r := array.get(a, 0) array.set(a, 0, h1r + array.get(a, 1)) array.set(a, 1, h1r - array.get(a, 1)) array.set(a, tnn, array.get(a, 1)) array.set(a, 1, sum) j := 4 while (j <= tnn) sum := sum + array.get(a, j - 1) array.set(a, j - 1, sum) j := j + 2 if inversefct for jx = 0 to tnn array.set(a, jx, array.get(a, jx) * 2 / tnn) //****************************************************************************** // Convolution using FFT // // One of the folded functions is treated as a signal, // with which we carry out convolution. The second is considered a response. // // At the entrance: // Signal - the signal with which we are convolving. array // real numbers, numbering of elements // 0 to SignalLen-1. // SignalLen - signal length. // Response - response function. Consists of two parts, // corresponding positive and negative // argument values. // // Array elements with numbers from 0 to // NegativeLen match response values // at points from -NegativeLen to 0, respectively. // // Array elements with numbers from // NegativeLen+1 to NegativeLen+PositiveLen // correspond to the response values in points // from 1 to PositiveLen respectively. // // NegativeLen - "Negative length" of the response. // PositiveLen - "Positive length" of the response. // Outside [-NegativeLen, PositiveLen] // response is zero. // // At the exit: // Signal - function convolution values at points from 0 to // SignalLen-1. https://www.alglib.net/fasttransforms/ //****************************************************************************** // @function Convolution using FFT // @param signal float[], This is an array of real numbers representing the input signal that will be convolved with the response function. The elements are numbered from 0 to SignalLen-1. // @param signallen int, This is an integer representing the length of the input signal array. It specifies the number of elements in the signal array. // @param response float[], This is an array of real numbers representing the response function used for convolution. The response function consists of two parts: one corresponding to positive argument values and the other to negative argument values. Array elements with numbers from 0 to NegativeLen match the response values at points from -NegativeLen to 0, respectively. Array elements with numbers from NegativeLen+1 to NegativeLen+PositiveLen correspond to the response values in points from 1 to PositiveLen, respectively. // @param negativelen int, This is an integer representing the "negative length" of the response function. It indicates the number of elements in the response function array that correspond to negative argument values. Outside the range [-NegativeLen, PositiveLen], the response function is considered zero. // @param positivelen int, This is an integer representing the "positive length" of the response function. It indicates the number of elements in the response function array that correspond to positive argument values. Similar to negativelen, outside the range [-NegativeLen, PositiveLen], the response function is considered zero. // @returns float[], The resulting convolved values are stored back in the input signal array. export fastconvolution(float[] signal, int signallen, float[] response, int negativelen, int positivelen)=> int nl = 0 int i = 0 float t1 = 0. float t2 = 0. nl := signallen if negativelen > positivelen nl += negativelen else nl += positivelen if negativelen + 1 + positivelen > nl nl := negativelen + 1 + positivelen i := 1 while (i < nl) i := i * 2 nl := i float[] a1 = array.new<float>(nl, 0.) float[] a2 = array.new<float>(nl, 0.) for ix = 0 to signallen - 1 array.set(a1, ix, array.get(signal, ix)) for ix = signallen to nl - 1 array.set(a1, ix, 0) for ix = 0 to nl - 1 array.set(a2, ix, 0) for ix = 1 to negativelen array.set(a2, nl - ix, array.get(response, negativelen - ix)) realfastfouriertransform(a1, nl, false) realfastfouriertransform(a2, nl, false) array.set(a1, 0, array.get(a1, 0) * array.get(a2, 0)) array.set(a1, 1, array.get(a1, 1) * array.get(a2, 1)) for ix = 1 to nl / 2 - 1 t1 := array.get(a1, 2 * ix) t2 := array.get(a1, 2 * ix + 1) array.set(a1, 2 * ix, t1 * array.get(a2, 2 * ix) - t2 * array.get(a2, 2 * ix + 1)) array.set(a1, 2 * ix + 1, t2 * array.get(a2, 2 * ix) + t1 * array.get(a2, 2 * ix + 1)) realfastfouriertransform(a1, nl, true) for ix = 0 to signallen - 1 array.set(signal, ix, array.get(a1, ix)) //****************************************************************************** // Correlation using FFT // // At the entrance: // Signal - an array of the signal to correlate with. // Item numbering from 0 to SignalLen-1 // SignalLen - signal length. // // Pattern - an array of the pattern, the correlation of the signal with which we are looking for // Numbering elements from 0 to PatternLen-1 // PatternLen - pattern length // // At the exit: // Signal - correlation values at points from 0 to // SignalLen-1. https://www.alglib.net/fasttransforms/ //****************************************************************************** // @function Returns Correlation using FFT // @param signal float[],This is an array of real numbers representing the signal to be correlated with the pattern. The elements are numbered from 0 to SignalLen-1. // @param signallen int, This is an integer representing the length of the input signal array. // @param pattern float[], This is an array of real numbers representing the pattern to be correlated with the signal. The elements are numbered from 0 to PatternLen-1. // @param patternlen int, This is an integer representing the length of the pattern array. // @returns float[], The signal array containing the correlation values at points from 0 to SignalLen-1. export fastcorrelation(float[] signal, int signallen, float[] pattern, int patternlen)=> int nl = 0 int i = 0 float t1 = 0. float t2 = 0. nl := signallen + patternlen i := 1 while (i < nl) i := i * 2 nl := i float[] a1 = array.new<float>(nl, 0.) float[] a2 = array.new<float>(nl, 0.) for ix = 0 to signallen - 1 array.set(a1, ix, array.get(signal, ix)) for ix = signallen to nl - 1 array.set(a1, ix, 0) for ix = 0 to patternlen - 1 array.set(a2, ix, array.get(pattern, ix)) for ix = patternlen to nl - 1 array.set(a2, ix, 0) realfastfouriertransform(a1, nl, false) realfastfouriertransform(a2, nl, false) array.set(a1, 0, array.get(a1, 0) * array.get(a2, 0)) array.set(a1, 1, array.get(a1, 1) * array.get(a2, 1)) for ix = 1 to (nl / 2) - 1 t1 := array.get(a1, 2 * ix) t2 := array.get(a1, 2 * ix + 1) array.set(a1, 2 * ix, t1 * array.get(a2, 2 * ix) + t2 * array.get(a2, 2 * ix + 1)) array.set(a1, 2 * ix + 1, t2 * array.get(a2, 2 * ix) - t1 * array.get(a2, 2 * ix + 1)) realfastfouriertransform(a1, nl, true) for ix = 0 to signallen - 1 array.set(signal, ix, array.get(a1, ix)) //****************************************************************************** // Fast Fourier Transform of Two Real Functions // // The algorithm performs a fast Fourier transform of two // real functions, each of which is given by tn // readings on the real axis. // // The algorithm saves time, but spends only // direct conversion. // // Input parameters: // tn - Number of function values. Must be degree // deuces. Algorithm does not validate // passed value. // a1 - array [0 .. nn-1] of Real // The values of the first function. // a2 - array [0 .. nn-1] of Real // Values of the second function. // // Output parameters: // a - Fourier transform of the first function // b - Fourier transform of the second function // (for details, see the website) https://www.alglib.net/fasttransforms/ //****************************************************************************** // @function Returns Fast Fourier Transform of Two Real Functions // @param a1 float[], An array of real numbers, representing the values of the first function. // @param a2 float[], An array of real numbers, representing the values of the second function. // @param a float[], An output array to store the Fourier transform of the first function. // @param b float[], An output array to store the Fourier transform of the second function. // @param tn float[], An integer representing the number of function values. It must be a power of two, but the algorithm doesn't validate this condition. // @returns float[], The a and b arrays will contain the Fourier transform of the first and second functions, respectively. Note that the function overwrites the input arrays a and b. export tworealffts(float[] a1, float[] a2, float[] a, float[] b, int tn)=> int j = 0 float rep = 0. float rem = 0. float aip = 0. float aim = 0. int n = 0 int nn = 0 int mmax = 0 int m = 0 int istep = 0 int i = 0 int isign = 0 float wtemp = 0 float wr = 0. float wpr = 0. float wpi = 0. float wi = 0. float theta = 0. float tempr = 0. float tempi = 0. nn := tn for jx = 1 to tn jj = jx + jx array.set(a, jj - 2, array.get(a1, jx - 1)) array.set(a, jj - 1, array.get(a2, jx - 1)) isign := 1 n := 2 * nn j := 1 for ii = 1 to nn i := 2 * ii - 1 if (j > i) tempr := array.get(a, j - 1) tempi := array.get(a, j) array.set(a, j - 1, array.get(a, i - 1)) array.set(a, j, array.get(a, i)) array.set(a, i - 1, tempr) array.set(a, i, tempi) m := n / 2 while (m >= 2 and j > m) j := j - m m := m / 2 j := j + m mmax := 2 while (n > mmax) istep := 2 * mmax theta := 2.0 * math.pi / (isign * mmax) wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2) wpi := math.sin(theta) wr := 1.0 wi := 0.0 for ii = 1 to mmax / 2 m := 2 * ii - 1 for jj = 0 to (n - m) / istep i := m + jj * istep j := i + mmax tempr := wr * array.get(a, j - 1) - wi * array.get(a, j) tempi := wr * array.get(a, j) + wi * array.get(a, j - 1) array.set(a, j - 1, array.get(a, i - 1) - tempr) array.set(a, j, array.get(a, i) - tempi) array.set(a, i - 1, array.get(a, i - 1) + tempr) array.set(a, i, array.get(a, i) + tempi) wtemp := wr wr := wr * wpr - wi * wpi + wr wi := wi * wpr + wtemp * wpi + wi mmax := istep array.set(b, 0, array.get(a, 1)) array.set(a, 1, 0.) array.set(b, 1, 0.) for jj = 1 to tn / 2 j := 2 * jj + 1 rep := 0.5 * (array.get(a, j - 1) + array.get(a, 2 * tn + 1 - j)) rem := 0.5 * (array.get(a, j - 1) - array.get(a, 2 * tn + 1 - j)) aip := 0.5 * (array.get(a, j) + array.get(a, 2 * tn + 2 - j)) aim := 0.5 * (array.get(a, j) - array.get(a, 2 * tn + 2 - j)) array.set(a, j - 1, rep) array.set(a, j, aim) array.set(a, 2 * tn + 1 - j, rep) array.set(a, 2 * tn + 2 - j, -aim) array.set(b, j - 1, aip) array.set(b, j, -rem) array.set(b, 2 * tn + 1 - j, aip) array.set(b, 2 * tn + 2 - j, rem) // example usage: RSI of Fast Discrete Cosine Transform float src = close int windowper = 256 // must be power of 2 int smthcutoff = 12 int arraylevl = 0 int rsiper = 15 //check that indow is power of 2 int n = int(math.log(windowper) / math.log(2)) int N = int(math.max(math.pow(2, n), 16)) var aa = array.new<float>(N + 1, 0.) //fill caculation array with source values for i = 0 to N - 1 array.set(aa, i, nz(src[i])) int M = array.size(aa) int end = M - 1 smthcutoff := int(math.min(smthcutoff, M)) //regular pass of FCT fastcosinetransform(aa, N, false) //filter of FCT, values above smthcutoff are zeroed out for k = 0 to end if k >= smthcutoff array.set(aa, k, 0.) //inverse pass of FCT fastcosinetransform(aa, N, true) //we are only interested in the first value; although accessing additional values can create ribbons and boundaries; end-pointed Cosine Transform int arraylevlout = math.min(array.size(aa) - 1, arraylevl) float out = array.get(aa, arraylevlout) out := ta.rsi(out, rsiper) float sig = nz(out[1]) int mid = 50 color colorout = (out < mid) ? color.red : (out > mid) ? color.green : color.gray plot(out, "RSI FDCT", color = colorout, linewidth = 2) plot(mid, "Middle", color = bar_index % 2 ? color.gray : na)
Console
https://www.tradingview.com/script/7l0ukRdj-Console/
cryptolinx
https://www.tradingview.com/u/cryptolinx/
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/ // © cryptolinx - jango_blockchained - open 💙 source //@version=5 // ——— Console { // // @description This script has evolved from its origins as a classic console script adaptation. \ // With the introduction of hybrid logs and direct logging to the app's native window, it now offers \ // enhanced flexibility and control over your logging experience. \ library('Console', overlay = true) // } // ▪ ——— CONST // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // ——— Brackets { // // @variable An empty string. var string EMPTY = '' // @variable A string with a single white space. var string WS = ' ' // @variable A block to use in color preview. var string BL = '▮' // @variable Line Break var string BR = '\n' // } // ▪ ——— EXPORT: USER-DEFINED TYPES // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // ——— Type Theme { // // | HEX Color Transparency Codes | // |-------------|------------|------------|-----------| // | 100% - FF | 75% - BF | 50% - 80 | 25% - 40 | // | 95% - F2 | 70% - B3 | 45% - 73 | 20% - 33 | // | 90% - E6 | 65% - A6 | 40% - 66 | 15% - 26 | // | 85% - D9 | 60% - 99 | 35% - 59 | 10% - 1A | // | 80% - CC | 55% - 8C | 30% - 4D | 5% - 0D | // | - | - | - | 0% - 00 | // -- // @type Can be used to define a theme for the console. // @field color_text The text color. // @field color_bg_table The background color. // @field color_bg_cell The background color. // @field color_frame The background color. // @field color_border The border color. // @field color_info The info message color. // @field color_warning The warning message color. // @field color_error The error message color. // @field color_success The success message color. // @field opacity_bg_cell The background opacity. // @field frame_width Border width of the outer frame. // @field border_width Width of the inner border. Can be sawed as line spacing. export type theme // -- color color_text = chart.fg_color color color_bg_table = #00000000 color color_bg_cell = #0000001A color color_frame = #CCCCCC0D color color_border = #00000000 // -- color color_info = #2962FFFF color color_warning = #FFEB3BFF color color_error = #FF5252FF color color_success = #4CAF55FF //-- int opacity_bg_cell = 90 // -- int frame_width = 1 int border_width = 0 // } // ——— Type Data { // // @type Used to store the log information. // @field message The log message. // @field level The log type. Default `na`. // @field idx Corresponding `bar_index`. // @field timestamp Corresponding timestamp. // @field opt_text_font_family Text font family. // @field opt_text_size Text size. // @field opt_text_color Text color. // @field opt_bg_color Background color. export type data // -- string message int level // 0 = na, 1 = info, 2 = warning, 3 = error, 4 = success // -- int idx = bar_index int timestamp = timenow // -- string opt_text_font_family string opt_text_size color opt_text_color color opt_bg_color // } // ——— Type Terminal { // // @type The `<terminal>` type. // @field log_position The terminal position. // @field columns The number of columns. // @field rows Number of rows. // @field width Panel width to use. // @field height Panel height to use. // @field max_logs Maximum amount of saved logs. // @field __theme Color theme of the terminal. // @field __table Table to view as a console. // @field __logs Logs of the terminal // @field text_font_family Text font family. // @field halign Horizontal alignment of the text. // @field valign Vertical alignment of the text. // @field size Text size. // @field prefix Optional prefix string, which will be shown at the start of each new line. // @field hide_on_empty Optional parameter to hide the console view on empty logs. // @field show_no Optional parameter to show a line number at the beginning of each line. export type terminal // -- string log_position = position.bottom_right // -- int columns = 1 int rows = 10 // -- int width = 25 // should be dividable by columns or gets ceiled to the next lower value. int height = 30 // should be dividable by rows or gets ceiled to the next lower value. // -- string size = size.small // -- int max_logs = 100 // -- string display = 'all' // all, chart, logs // -- theme __theme table __table // -- array <data> __logs // -- string text_font_family = font.family_monospace string halign = text.align_left string valign = text.align_center string prefix = '' // -- bool hide_on_empty = true bool show_no = false // -- bool first_call = false // } // ▪ INTERNAL: HELPER FUNCTIONS // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // ——— Built-In Overrides { // // @function Replaces NaN values with zeros (or given value) in a series. // @param _src Source to check. // @param _replacement The alternative value if `_src` is NaN. // @returns The value of `_src` if it is not `na`. If the value of `_src` is `na`, returns `zero`, or the `replacement` // argument when one is used. method nz(array <data> _src, array <data> _replacement) => na(_src) ? _replacement : _src method nz(string _src, string _replacement) => na(_src) ? _replacement : _src method nz(theme _src, theme _replacement) => na(_src) ? _replacement : _src method nz(table _src, table _replacement) => na(_src) ? _replacement : _src method nz(color _src, color _replacement) => na(_src) ? _replacement : _src // } // --------------------------------------------------------------------------------------------------------------------- // ——— Method Append String { // // @function Append a string, if the source is not `na` and not `empty`. // @param _src Source to check. // @param _str String to append. // @returns `<string>` method append(string _src, string _str) => not na(_src) and not (_src == EMPTY) ? _src + _str : _src // } // --------------------------------------------------------------------------------------------------------------------- // ——— Housekeeping { // // @function Clean up the logs. // @param this The `<terminal>` object. // @returns `<terminal>` method housekeeping(terminal this) => while this.__logs.size() > this.max_logs this.__logs.shift() this // } // --------------------------------------------------------------------------------------------------------------------- // ——— Push Data to Log { // // @function Push a `<data>` object to the logs. // @param this The `<terminal>` object. // @param _data A `<data>` object. // @returns `<terminal>` method push(terminal this, data _data) => // -- this.housekeeping().__logs.push(_data) // >> this // -- method push(data _data, terminal this) => this.push(_data) // } // ——— Format Text { // // @function Create a readable text format. // @param this The `<terminal>` object. // @returns `<terminal>` method formatText(string this) => // -- string find1 = '[' string find2 = ']' string repl1 = '\n ▪ ' str.replace_all(str.replace_all(this, find1, repl1), find2, EMPTY) // } // ——— Create Table { // // @function Create the log table. // @param this The `<terminal>` object. // @returns `<terminal>` method createTable(terminal this) => // -- this.__table := this.__table.nz(table.new( position = this.log_position, columns = this.columns, rows = this.rows, bgcolor = this.__theme.color_bg_table, frame_color = this.__theme.color_frame, border_color = this.__theme.color_border, frame_width = this.__theme.frame_width, border_width = this.__theme.border_width )) // -- this.height := math.ceil(this.height / this.rows) * this.rows this.width := math.ceil(this.width / this.columns) * this.columns // -- for c = 0 to this.columns - 1 for r = 0 to this.rows - 1 table.cell( table_id = this.__table, column = c, row = r, text_font_family = this.text_font_family, text_valign = this.valign, text_halign = this.halign, text_size = this.size, height = int(this.height / this.rows), width = int(this.width / this.columns), bgcolor = this.__theme.color_bg_cell, text_color = this.__theme.color_text ) this.__table.cell_set_text(0, 0, 'Info: Use console.show() to show up your logs.') // Friendly Reminder // >> this // } // ——— Default Array { // // @function Function creates the default array to use in the `.tostring()` method. // @param _size The size of the corresponding data. // @returns Returns a `array <string>` defaultArray(int _size) => // >> array.new<string>(1, str.format('Size: {0}', _size)) // } // ——— Default Array { // // @function Function creates the default array to use in the `.tostring()` method. // @param _size The size of the corresponding data. // @returns Returns a `array <string>` defaultArrayMatrix(int _columns, int _rows) => // >> array.new<string>(1, str.format('Size: {0}x{1} ({2})', _columns, _rows, _columns * _rows)) // } // ▪ EXPORT: POST-HELPER FUNCTIONS // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // ——— Method Option Text Size { // // @function Temporary change the text font family of the last log // ___ // **Example** // > ``` // > myConsole.log('foo').opt_textFontFamily(size.small) // > ``` // ___ // @param this The `<terminal>` object. // @param _fontFamily The temporary text font family. // @returns `<terminal>` export method opt_textFontFamily(terminal this, string _fontFamily) => // -- data last = this.__logs.last() last.opt_text_font_family := _fontFamily // >> this // } // ——— Method Option Text Size { // // @function Temporary change the text size of the last log // ___ // **Example** // > ``` // > myConsole.log('foo').opt_textSize(size.small) // > ``` // ___ // @param this The `<terminal>` object. // @param _size The temporary text size. // @returns `<terminal>` export method opt_textSize(terminal this, string _size) => // -- data last = this.__logs.last() last.opt_text_size := _size // >> this // } // ——— Method Option Text Color { // // @function Temporary change the text color of the last log. // ___ // **Example** // > ``` // > myConsole.log('foo').opt_textColor(color.red) // > ``` // ___ // @param this The `<terminal>` object. // @param _color The temporary text color. // @returns `<terminal>` export method opt_textColor(terminal this, color _color) => // -- data last = this.__logs.last() last.opt_text_color := _color // >> this // } // ——— Method Optional Table Background Color { // // @function Temporary changes the background color of the last log. // ___ // **Example** // > ``` // > myConsole.log('foo').opt_bgColor(color.red) // > ``` // @param this The `<terminal>` object. // @param _color The temporary background color. // @returns `<terminal>` export method opt_bgColor(terminal this, color _color) => // -- data last = this.__logs.last() last.opt_bg_color := _color // >> this // } // ——— Method Optional Level { // // @function Temporary changes the level of the last log. // ___ // **Example** // > ``` // > myConsole.log('foo').opt_lvl(1) // > ``` // @param this The `<terminal>` object. // @param _lvl The temporary message level. // @returns `<terminal>` export method opt_lvl(terminal this, int _lvl) => // -- data last = this.__logs.last() last.level := _lvl // >> this // } // --------------------------------------------------------------------------------------------------------------------- // ——— Clear { // // @function Clears the `<terminal>` log. // ___ // **Example** // > ``` // > myConsole.clear() // > ``` // @param this The `<terminal>` object. // @returns `<terminal>` export method clear(terminal this) => // -- this.__logs.clear() // >> this // } // ——— Reverse { // // @function Reverse the `<terminal>` log. // ___ // **Example** // > ``` // > myConsole.reverse() // > ``` // @param this The `<terminal>` object. // @returns `<terminal>` export method reverse(terminal this) => // -- this.__logs.reverse() // >> this // } // --------------------------------------------------------------------------------------------------------------------- // ——— Log Position { // // @function Sets the terminal position. // ___ // **Example** // > ``` // > myConsole.setPosition(position.bottom_right) // > ``` // @param this The `<terminal>` object. // @param _position Set one of the `build-in` position arguments. // @returns `<terminal>` export method setPosition(terminal this, string _position) => this.log_position := _position, this // } // ——— Method Set Table Background Color { // // @function Sets the default background color of the table cell. // ___ // **Example** // > ``` // > myConsole.setTextSize(size.small) // > ``` // @param this The `<terminal>` object. // @param _size Text Size. // @returns `<terminal>` export method setTextSize(terminal this, string _size) => this.size := _size, this // } // ——— Method Set Table Background Color { // // @function Sets the default background color of the table cell. // ___ // **Example** // > ``` // > myConsole.setBgColor(color.red) // > myConsole.setBgColor(color.red, 50) // > ``` // @param this The terminal object. // @param _color The background color. // @param _transp The transparency of the color. // @returns `<terminal>` export method setTextColor(terminal this, color _color, int _transp = 85) => // -- this.__theme.color_text := color.new(_color, _transp), this // } // ——— Method Set Table Background Color { // // @function Sets the default background color of the table cell. // ___ // **Example** // > ``` // > myConsole.setBgColor(color.red) // > myConsole.setBgColor(color.red, 50) // > ``` // @param this The terminal object. // @param _color The background color. // @param _transp The transparency of the color. // @returns `<terminal>` export method setBgColor(terminal this, color _color, int _transp = 85) => // -- this.__theme.color_bg_table := color.new(_color, _transp), this // } // ——— Method Prefix { // // @function Sets the prefix of the terminal. // ___ // **Example** // > ``` // > myConsole.setPrefix('>') // > ... // > ``` // @param this The terminal object. // @param _prefix The prefix of the terminal. // @returns `<terminal>` export method setPrefix(terminal this, string _prefix) => this.prefix := _prefix, this // } // ——— Method Show No { // // @function Sets the show no of the terminal // ___ // **Example** // > ``` // > myConsole.showNo(true) // 01 ... // > ``` // @param this The terminal object. // @param _show_no If true, the terminal will show the log number. // @returns `<terminal>` export method setShowNo(terminal this, bool _show_no = false) =>this.show_no := _show_no, this // } // --------------------------------------------------------------------------------------------------------------------- // ——— Method Empty Line { // // @function Added a new line (nl) to the console. // ___ // **Example** // > ``` // > myConsole.empty() // > // // > myConsole.empty().log('foo').empty() // > // // > // foo // > // // > ``` // @param this The terminal object. // @returns `<terminal>` export method empty(terminal this) => this.__logs.push(data.new(EMPTY)), this // } // ——— Method Horizontal Divider { // // @function Add an empty line to the terminal. // ___ // **Example** // > ``` // > // Standard // > myConsole.hr() // -------------------- // > // > // Chained // > myConsole // > .hr('foo') // foo ---------------- // > .log('bar') // bar // > .hr() // -------------------- // > // > // Custom // > myConsole // > .hr('my section', ':', 20) // my section ::::::::: // > .hr('my section', '=', 32) // my section ===================== // > ``` // @param this The terminal object. // @param _show_no If `true`, the terminal will show the log number. // @returns `<terminal>` export method hr(terminal this, string _prefix = '', string _str = '-', int _length = 20) => // -- string prefix = _prefix.append(WS) this.__logs.push(data.new(prefix + array.new<string>(_length - str.length(prefix), _str).join())) // >> this // } // ▪ ——— EXPORT: UTILITY METHOD - TO STRING // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // ——— Method To String { // // @function Stringify your data. // ___ // **Types** \ // \ // [![string int float bool color valid](https://img.shields.io/badge/string_int_float_bool_color-valid-4CAF55?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // [![label line box linefill chart.point valid](https://img.shields.io/badge/label_line_box_linefill_chart.point-valid-4CAF55?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // [![array matrix valid](https://img.shields.io/badge/array_matrix-valid-4CAF55?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // // [![table invalid](https://img.shields.io/badge/table_plot-invalid-FF5252?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // ___ // **Example** // > ``` // > int testInt = 100 // > testInt.toString() // > // > int testFloat = 3.145912 // > testFloat.toString() // > (1 + 2).tostring() // > // > int testBool = true // > testBool.toString() // > // > label testLabel = label.new(...) // > testLabel.tostring() // > // > line testLine = line.new(...) // > testLine.tostring() // > // > line testLinefill = linefill.new(...) // > testLinefill.tostring() // > // > line testBox = box.new(...) // > testBox.tostring() // > // > color blue = color.blue // > testColor.tostring() // > // or simply // > color.blue.tostring() // > (#FF9900).tostring() // > // > // Array & Matrix Type Support // > array <float> price = array.from(...) // > arr.tostring() // > matrix <chart.point> mtx = matrix.new<chart.point>() // > mtx.tostring() // > ``` // @param _data The data to parse. // @returns `<string>` export method tostring(array <string> _data) => str.tostring(_data) export method tostring(array <int> _data) => str.tostring(_data) export method tostring(array <float> _data) => str.tostring(_data) export method tostring(array <bool> _data) => str.tostring(_data) // -- export method tostring(int _data) => str.tostring(_data) export method tostring(float _data) => str.tostring(_data) export method tostring(bool _data) => _data ? 'true' : 'false' // -- export method tostring(label _data) => array.from( 'label', 'text:' + WS + _data.get_text(), 'x:' + WS + _data.get_x().tostring(), 'y:' + WS + _data.get_y().tostring() ).tostring() // -- export method tostring(line _data) => array.from( 'line', 'x1:' + WS + _data.get_x1().tostring(), 'x2:' + WS + _data.get_x2().tostring(), 'y1:' + WS + _data.get_y1().tostring(), 'y2:' + WS + _data.get_y2().tostring() ).tostring() // -- export method tostring(linefill _data) => array.from( 'linefill', 'line1: ' + _data.get_line1().tostring(), 'line2: ' + _data.get_line2().tostring() ).tostring() // -- export method tostring(box _data) => array.from( 'box', 'top:' + WS + _data.get_top().tostring(), 'bottom:' + WS + _data.get_bottom().tostring(), 'left:' + WS + _data.get_left().tostring(), 'right:' + WS + _data.get_right().tostring() ).tostring() // -- export method tostring(color _data) => BL + array.from( 'color', 'r:' + WS + color.r(_data).tostring(), 'g:' + WS + color.g(_data).tostring(), 'b:' + WS + color.b(_data).tostring() ).tostring() // -- export method tostring(chart.point _data) => // Pseudo label to get the data from the chart.point. label l = label.new(point = _data) int x = l.get_x() float y = l.get_y() label.delete(l) // -- array.from( 'chart.point', 'x:' + WS + x.tostring(), 'y:' + WS + y.tostring() ).tostring() // -- export method tostring(array <label> _data) => // @variable An array, holding the stringified data. array <string> tmp = defaultArray(_data.size()) for l in _data tmp.push(l.tostring()) tmp.tostring() // -- export method tostring(array <line> _data) => // @variable An array, holding the stringified data. array <string> tmp = defaultArray(_data.size()) for l in _data tmp.push(l.tostring()) tmp.tostring() // -- export method tostring(array <linefill> _data) => // @variable An array, holding the stringified data. array <string> tmp = defaultArray(_data.size()) for lf in _data tmp.push(lf.tostring()) tmp.tostring() // -- export method tostring(array <color> _data) => // @variable An array, holding the stringified data. array <string> tmp = defaultArray(_data.size()) for c in _data tmp.push(c.tostring()) tmp.tostring() // -- export method tostring(array <box> _data) => // @variable An array, holding the stringified data. array <string> tmp = defaultArray(_data.size()) for b in _data tmp.push(b.tostring()) tmp.tostring() // -- export method tostring(array <chart.point> _data) => // @variable An array, holding the stringified data. array <string> tmp = defaultArray(_data.size()) for cp in _data tmp.push(cp.tostring()) tmp.tostring() // -- export method tostring(matrix <string> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c)) tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <int> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <float> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // -- // -- export method tostring(matrix <bool> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c) ? 'true' : 'false') tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <label> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <line> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <linefill> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <box> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <color> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // -- export method tostring(matrix <chart.point> _data) => // @variable An array, holding the stringified row data. array <string> tmp = defaultArrayMatrix(_data.columns(), _data.rows()) for r = 0 to _data.rows() - 1 // @variable An array, holding the stringified column data. tmpCol = array.new<string>() for c = 0 to _data.columns() - 1 tmpCol.push(_data.get(r, c).tostring()) tmp.push(tmpCol.tostring()) tmp.tostring() // } // ▪ ——— EXPORT: PRIMARY FUNCTIONS // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // ——— Init { // // @function Init the `<terminal>` object. // ___ // **Example** // > ``` // > var myConsole = Console.terminal.new().init() // > // or // > var myConsole = Console.terminal.new() // > myConsole.init() // > ``` // @param this The `<terminal>` object. // @param _theme Optional theme. // @returns `<terminal>` export method init(terminal this, theme _theme = na) => // -- this.__theme := this.__theme.nz(_theme.nz(theme.new())) this.__logs := this.__logs.nz(array.new<data>()) if this.display == 'all' or this.display == 'chart' this.createTable() // >> this // } // --------------------------------------------------------------------------------------------------------------------- // ——— Show { // // @function Shows the terminal. // ___ // **Example 1** // > ``` // > // Place it at the end of your script or even after the last console call. // > console.show(...) // > ``` // ___ // **Example 2** // > ``` // > show = input.bool(true, 'Show Logs') // > offset = input.int(0, 'Log No. Offset') // > console.show(show, offset) // > ``` // @param this The `<terminal>` object. // @param _visible Show/Hide. // @param _offset A (+/-) offset to move througth the logs. // @returns `<terminal>` export method show(terminal this, bool _visible = true, int _offset = 0) => // -- // @variable lines Maximum amount of lines to show. int lines = this.columns * this.rows // @variable Current `index` inside the logs array. int start = this.__logs.size() < lines ? _offset : this.__logs.size() - lines + _offset start := start < 0 ? 0 : start int ctr = start // -- if this.display == 'all' or this.display == 'chart' if na(this.__table) this.createTable() // @variable True, if the option `hide_on_empty` is `true` and no logs are registered. False otherwise. bool hide = this.hide_on_empty ? this.__logs.size() == 0 : false if barstate.islast and _visible and not hide for c = 0 to this.columns - 1 for r = 0 to this.rows - 1 this.__table.cell_set_text(c, r, str.format( '{0}{1}{2}', this.show_no ? str.tostring(ctr,'00') + WS : EMPTY, this.prefix != EMPTY ? this.prefix + WS : EMPTY, this.__logs.get(ctr).message)) // -- // @variable The log level of the message. int level = this.__logs.get(ctr).level [textColor_, bgColor_] = switch level 1 => [this.__theme.color_info, this.__theme.color_info ] 2 => [this.__theme.color_warning, this.__theme.color_warning] 3 => [this.__theme.color_error, this.__theme.color_error ] 4 => [this.__theme.color_success, this.__theme.color_success] // -- => [this.__theme.color_text, this.__theme.color_bg_cell] // -- // @variable Optional text color. If not set, the associated level/default color is used. color textColor = this.__logs.get(ctr).opt_text_color.nz(textColor_) // @variable Optional background color. If not set, the associated level/default color is used. color bgColor = this.__logs.get(ctr).opt_bg_color.nz(bgColor_) // @variable Optional text size. If not set, the default text size is used. string textSize = this.__logs.get(ctr).opt_text_size.nz(this.size) // @variable Optional text font family. If not set, the default text font family is used. string textFont = this.__logs.get(ctr).opt_text_font_family.nz(this.text_font_family) this.__table.cell_set_text_font_family(c, r, textFont) this.__table.cell_set_text_size(c, r, textSize) this.__table.cell_set_text_color(c, r, textColor) this.__table.cell_set_bgcolor(c, r, color.new(bgColor, this.__theme.opacity_bg_cell)) // -- // @variable Additional information string, including the `bar_index` and `timestamp`, to show up in the tooltip of each log. string info = str.format('bar_index = #{0,number,#####}', this.__logs.get(ctr).idx) + WS + str.format_time(this.__logs.get(ctr).timestamp, 'yyyy-MM-dd HH:mm:ss', syminfo.timezone) this.__table.cell_set_tooltip(c, r, info + BR + this.__logs.get(ctr).message.formatText()) // -- ctr += 1 if ctr > this.__logs.size() - 1 break if ctr > this.__logs.size() - 1 break else this.__table.delete() // -- if this.display == 'all' or this.display == 'logs' for i = start to this.__logs.size() - 1 string msg = this.__logs.get(i).message.formatText() switch this.__logs.get(i).level 2 => log.warning(msg) 3 => log.error(msg) => log.info(msg) // >> this // } // --------------------------------------------------------------------------------------------------------------------- // ——— Method Unified Log Functions { // // @function Log data to the terminal. // ___ // **Types** \ // \ // [![string int float bool color valid](https://img.shields.io/badge/string_int_float_bool_color-valid-4CAF55?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // [![label line box linefill chart.point valid](https://img.shields.io/badge/label_line_box_linefill_chart.point-valid-4CAF55?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // [![array matrix valid](https://img.shields.io/badge/array_matrix-valid-4CAF55?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // // [![table invalid](https://img.shields.io/badge/table_plot-invalid-FF5252?style=flat)](https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html) // ___ // **Log Level** \ // \ // [![lvl 0 na](https://img.shields.io/badge/lvl_0-na-grey?style=flat)]() // [![lvl 1 info](https://img.shields.io/badge/lvl_1-info-2962ff?style=flat)]() // [![lvl 2 warning](https://img.shields.io/badge/lvl_2-warning-FFEB3B?style=flat)]() // [![lvl 3 error](https://img.shields.io/badge/lvl_3-error-FF5252?style=flat)]() // [![lvl 4 success](https://img.shields.io/badge/lvl_4-success-4CAF55?style=flat)]() // ___ // **Example** // // At first, import the library. Mostly at the beginning of the script: // > ``` // > import cryptolinx/console/<VERSION> // Namespace: 'Console' // > // > import cryptolinx/console/<VERSION> as c // Namespace: 'c' // > ``` // // Secondly // > ``` // > // Logging a string with default log level (0) // > console // > .log("Hello") // > .log("World!") // > .hr() // > // > // Logging a float // > console.log(3.14159) // > // > // Logging an integer with log-level info (1) // > console.log(42).opt_lvl(1) // > // > // Logging a boolean with the prefix // > console.log('My Value is', true) // > // > // Logging a calculation ✨inline while assigning it to a new variable. // > calculatedPrice = (close * 1.01).log(console) // > // > // Logging a color with the prefix // > console.log('My Color', testColor) // > // > // Logging an array of integers ✨inline // > myArray.log(console) // logs the data and returns it // > // > // Logging a line ✨inline // > myLine = line.new().log(console) // logs the line and returns it. Variable declaration // > // > // Logging a string with a custom prefix and delimiter // > console.log("CustomPrefix", "Hello, World!", "->") // > ``` // ___ // **Native Log Level** \ // \ // [![lvl 1 info](https://img.shields.io/badge/lvl_1-info-2962ff?style=flat)]() // [![lvl 2 warning](https://img.shields.io/badge/lvl_2-warning-FFEB3B?style=flat)]() // [![lvl 3 error](https://img.shields.io/badge/lvl_3-error-FF5252?style=flat)]() // ___ // **Direct Version Example** // > ``` // > import cryptolinx/console/<VERSION> // Namespace: 'Console' // > Console.log(data) // > // > import cryptolinx/console/<VERSION> as c // Namespace: 'c' // > int myInt = 5 // > color myColor = color.blue // > c.log(myInt) // Log Level: info (default) // > myInt.log() // > c.log(myColor, 2) // Log Level: warning // > myColor.log() // > c.log(myBool, 3) // Log Level: error // > myBool.log() // > myLine.log() // > myArray.log() // > myMatrix.log() // > // ... as short as simple ✨ // > ``` // ___ // **Direct Version** // // * _This function is called directly onto the import namespace._ // * _This function is limited to native logs only._ // // It is not recommended for standard behavior and is typically used for logging from inside a library function or any other scope that cannot modify globals. \ // The advantage of this version is the automatic conversion of all supported native types to strings, allowing them to be displayed in the app's native log window. // @param _data Any of the supported data types. // @returns `<Console.terminal>` A temporary terminal object to pass the data to the native logs. // @param this The terminal object. // @param _data The data to log // @param _prefix Appending prefix string. // @param _delimiter Delimiter between prefix and data. // @returns `<terminal>` export method log(terminal this, data _data) => this.push(_data) export method log(terminal this, string _data) => this.push(data.new(_data)) export method log(terminal this, float _data) => this.log(_data.tostring()) export method log(terminal this, int _data) => this.log(_data.tostring()) export method log(terminal this, bool _data) => this.log(_data.tostring()) export method log(terminal this, label _data) => this.log(_data.tostring()) export method log(terminal this, line _data) => this.log(_data.tostring()) export method log(terminal this, linefill _data) => this.log(_data.tostring()) export method log(terminal this, box _data) => this.log(_data.tostring()) export method log(terminal this, chart.point _data) => this.log(_data.tostring()) export method log(terminal this, color _data) => this.log(data.new(_data.tostring(), opt_text_color = _data, opt_bg_color = _data)) // -- export method log(terminal this, array <string> _data) => this.log(_data.tostring()) export method log(terminal this, array <float> _data) => this.log(_data.tostring()) export method log(terminal this, array <int> _data) => this.log(_data.tostring()) export method log(terminal this, array <bool> _data) => this.log(_data.tostring()) export method log(terminal this, array <label> _data) => this.log(_data.tostring()) export method log(terminal this, array <line> _data) => this.log(_data.tostring()) export method log(terminal this, array <linefill> _data) => this.log(_data.tostring()) export method log(terminal this, array <box> _data) => this.log(_data.tostring()) export method log(terminal this, array <color> _data) => this.log(_data.tostring()) export method log(terminal this, array <chart.point> _data) => this.log(_data.tostring()) // -- export method log(terminal this, matrix <string> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <float> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <int> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <bool> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <label> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <line> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <linefill> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <box> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <color> _data) => this.log(_data.tostring()) export method log(terminal this, matrix <chart.point> _data) => this.log(_data.tostring()) // Log data with a custom `prefix` and `delimiter` to the terminal. export method log(terminal this, string _prefix, data _data, string _delimiter = ':') => _data.message := _prefix.append(_delimiter).append(WS) + _data.message this.push(_data) export method log(terminal this, string _prefix, string _data, string _delimiter = ':') => this.push(data.new(_prefix.append(_delimiter).append(WS) + _data)) export method log(terminal this, string _prefix, float _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, int _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, bool _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, label _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, line _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, linefill _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, box _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, color _data, string _delimiter = ':') => this.log(_prefix, data.new(_data.tostring(), opt_text_color = _data, opt_bg_color = _data), _delimiter) export method log(terminal this, string _prefix, chart.point _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) // -- export method log(terminal this, string _prefix, array <string> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <float> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <int> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <bool> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <label> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <line> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <linefill> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <box> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <color> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, array <chart.point> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) // -- export method log(terminal this, string _prefix, matrix <string> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <float> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <int> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <bool> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <label> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <line> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <linefill> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <box> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <color> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) export method log(terminal this, string _prefix, matrix <chart.point> _data, string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter) // Log data `inline` ✨ to the terminal and returns the logged data instead of the terminal object. export method log(string _data, terminal this, string _prefix, string _delimiter = ':') => this.log(_prefix, _data, _delimiter), _data export method log(float _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(int _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(bool _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(label _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(line _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(linefill _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(box _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(color _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, data.new(_data.tostring(), opt_text_color = _data, opt_bg_color = _data), _delimiter) export method log(chart.point _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data // -- export method log(array <string> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <float> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <int> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <bool> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <label> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <line> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <linefill> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <box> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <color> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(array <chart.point> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data // -- export method log(matrix <string> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <float> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <int> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <bool> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <label> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <line> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <linefill> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <box> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <color> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data export method log(matrix <chart.point> _data, terminal this, string _prefix = '', string _delimiter = ':') => this.log(_prefix, _data.tostring(), _delimiter), _data // -- // Direct Version // // - This function is called directly onto the dataimport namespace. // - This function is limited to native logs only. // // The advantage of this version is the automatic conversion of all supported native types to strings, // allowing them to be displayed in the app's native log window. export method log(data _data, series int _lvl = 1) => terminal.new(display = 'logs').init().push(_data).opt_lvl(_lvl).show() // -- export method log(string _data, series int _lvl = 1) => log(data.new(_data), _lvl), _data export method log(float _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(int _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(bool _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(label _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(line _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(linefill _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(box _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(chart.point _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(color _data, series int _lvl = 1) => log(data.new(_data.tostring(), opt_text_color = _data, opt_bg_color = _data), _lvl), _data // -- export method log(array <string> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <float> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <int> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <bool> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <label> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <line> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <linefill> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <box> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <color> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(array <chart.point> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data // -- export method log(matrix <string> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <float> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <int> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <bool> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <label> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <line> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <linefill> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <box> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <color> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data export method log(matrix <chart.point> _data, series int _lvl = 1) => log(_data.tostring(), _lvl), _data // } // ▪ ——— EXAMPLES // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // ——— Inputs { // // @variable Example user input to control the output visibility. var bool _SHOW = input.bool(true, 'Show Logs') // @variable Example user input to move through the logs. (+/-) var int _OFFSET = input.int(0, 'Log No. Offset', tooltip = 'A (+/-) offset to move through the logs') // @variable Example user input to switch between a standard and an example theme. var bool _THEME = input.bool(false, 'Switch Theme') // } // ——— Setup { // // @note Do not forget to import this library first by using `import Cryptolinx/Console/<VERSION> as <NAMESPACE>`. // Do not forget to use a custom alias or even the library name to access the library functions. // Eg. `console = <NAMESPACE>.terminal.new()` // -- // @variable A custom `<terminal>` theme. theme th = theme.new( color_text = #c1a4f7, color_bg_table = #04000a80 ) // @variable A new, initialized `<terminal>` object, recreated on every bar. console = terminal.new(prefix = '>', height = 48, rows = 16, size = size.small, display = 'chart').init(_THEME ? th : na) // @variable A new, initialized `<terminal>` object, created once on the first bar. // var console_full = terminal.new(log_position=position.bottom_left, prefix = '> ', show_no = true).init() // } // ——— Inline ✨ { // // @variable An example array. array <float> testArray = array.new<float>(3, .0).log(console) // @variable A example label. label testLabel = label.new(bar_index + 25, close, 'Test Label', style = label.style_label_center).log(console) // On Built-In Variables // -- color.aqua.log(console) label.all.log(console, 'Label All') // It is also possible to use `().` for literals ✨. // -- // @variable An example integer. int a = 100 // @variable The sum of an example calculation int testCalc = (5 * 100).log(console) + a.log(console,'+','') // SUM: 600 // @note If you use inline logging on variables that get initialized by the `var` keyword, // your data will only get logged once on the first bar. // } // ——— Basic { // console .hr('TOTAL', '=') .log('SUM', testCalc) .hr('Array', ':') .log('My Array', testArray).opt_lvl(1) .hr() .log(testLabel).opt_lvl(4) .hr('Chart.Point') .log('Now', chart.point.now()).opt_textColor(color.aqua) .empty() .log(#FF46A4) // -- testLabel.delete() // } // ——— Finally // console.show(_SHOW, _OFFSET) // The _show argument is true by default. Simply turn it on or off. // } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // ——— Direct Version Example { // test_function(int a) => a.log() // -- test_function(1000) test_function(2000) // -- chart.point.now().log(2) bar_index.log() close.log(3) color.blue.log() // } // #EOF
TrendLine Cross
https://www.tradingview.com/script/SyntOR5B-TrendLine-Cross/
AleSaira
https://www.tradingview.com/u/AleSaira/
174
study
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/ // © AleSaira //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================} // _____ .__ _________ .__ // / _ \ | | ____ / _____/____ |__|___________ /// /_\ \| | _/ __ \ \_____ \\__ \ | \_ __ \__ \ /// | \ |_\ ___/ / \/ __ \| || | \// __ \_ //\____|__ /____/\___ >_______ (____ /__||__| (____ / // \/ \/ \/ \/ \/ //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================} //@version=5 indicator("TrendLine Cross", shorttitle = "TrendLine Cross" ,overlay=true, max_bars_back = 500, max_lines_count = 500) //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================} low_time = input (25, title="Low_time") high_time = input (90, title="High_time") LowerLine_period = input (250, title="Higher time") LowLine_color = input.color (color.green, title="Low Line Color") LiquidityUp_color = input.color (color.rgb(208, 182, 11), title="Liquidity Up Line Color") LowerLine_color = input.color (color.rgb(41, 47, 232), title="Lower Line Color") UpperLine_color = input.color (color.rgb(19, 19, 18), title="Upper Line Color") UpLine_color = input.color (color.red, title="Up Line Color") LiquidityDown_color = input.color (color.rgb(208, 182, 11), title="Liquidity Down Line Color") width = input.int (2, title="Width") //==================////////////////////////================================/////////////////======================} var float lowest_y1 = na var float lowest_y2 = na var float highest_y1 = na var float highest_y2 = na var float lowest_y21 = na var int lowest_x21 = na var float highest_y12 = na var int highest_x12 = na var int lowest_x2 = na var int highest_x2 = na var int lowest_x1 = na var int highest_x1 = na var float highest_y21 = na var int highest_x21 = na var float lowest_y12 = 100000 var int lowest_x12 = 0 //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================} // Calculate lowest and highest values if barstate.islast lowest_y2 := 100000, lowest_x2 := 0, highest_y2 := 0, highest_x2 := 0, lowest_y1 := 100000, lowest_x1 := 0, highest_y1 := 0, highest_x1 := 0 lowest_y21 := 100000, lowest_x21 := 0, lowest_y12 := 100000, lowest_x12 := 0, highest_y12 := 0,highest_x12 := 0 for i = 1 to low_time lowest_y2 := low[i] < lowest_y2 ? low[i] : lowest_y2 lowest_x2 := low[i] < lowest_y2 ? i : lowest_x2 highest_y2 := high[i] > highest_y2 ? high[i] : highest_y2 highest_x2 := high[i] > highest_y2 ? i : highest_x2 for j = (low_time + 1) to high_time lowest_x1 := low[j] < lowest_y1 ? j : lowest_x1 lowest_y1 := low[j] < lowest_y1 ? low[j] : lowest_y1 highest_x1 := high[j] > highest_y1 ? j : highest_x1 highest_y1 := high[j] > highest_y1 ? high[j] : highest_y1 for i = 1 to LowerLine_period lowest_x21 := low[i] < lowest_y21 ? i : lowest_x21 lowest_y21 := low[i] < lowest_y21 ? low[i] : lowest_y21 highest_x21 := high[i] > highest_y21 ? i : highest_x21 highest_y21 := high[i] > highest_y21 ? high[i] : highest_y21 for j = (low_time + 1) to LowerLine_period lowest_x12 := low[j] < lowest_y12 ? j : lowest_x12 lowest_y12 := low[j] < lowest_y12 ? low[j] : lowest_y12 highest_x12 := high[j] > highest_y12 ? j : highest_x12 highest_y12 := high[j] > highest_y12 ? high[j] : highest_y12 //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================} // Alert condition alertcondition(condition=(lowest_x12 == bar_index) or (highest_x21 == bar_index), title="TrendLine Cross Alert", message="TrendLine Cross Detected") //==================////////////////////////================================/////////////////======================} // Plotting lines sup = line.new(x1=bar_index[lowest_x1], y1=lowest_y1, x2=bar_index[lowest_x2], y2=lowest_y2, extend=extend.right, width=width, color=LowLine_color) rea = line.new(x1=bar_index[lowest_x1], y1=lowest_y1, x2=bar_index[lowest_x2], y2=lowest_y1, extend=extend.right, width=width, color=LiquidityUp_color) LowerLine = line.new(x1=bar_index[lowest_x21], y1=lowest_y1, x2=bar_index[lowest_x2], y2=lowest_y2, extend=extend.right, width=width, color=LowerLine_color) doe = line.new(x1=bar_index[highest_x12], y1=highest_y12, x2=bar_index[lowest_x2], y2=lowest_y2, extend=extend.right, width=width, color=UpperLine_color) res = line.new(x1=bar_index[highest_x1], y1=highest_y1, x2=bar_index[highest_x2], y2=highest_y2, extend=extend.right, width=width, color=UpLine_color) liquidity = line.new(x1=bar_index[highest_x1], y1=highest_y1, x2=bar_index[highest_x2], y2=highest_y1, extend=extend.right, width=width, color=LiquidityDown_color) line.delete(sup[1]),line.delete(res[1]),line.delete(LowerLine[1]),line.delete(doe[1]), line.delete(rea[1]),line.delete(liquidity[1]) //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================}
Utility
https://www.tradingview.com/script/GfcPtSz8-Utility/
derekren321
https://www.tradingview.com/u/derekren321/
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/ // © derekren321 //@version=5 library("Utility", true) import TradingView/ta/5 // Smoothed moving average export smma(series float src, simple int length) => smma = 0.0 sma = ta.sma(src, length) smma := na(smma[1]) ? sma : (smma[1] * (length - 1) + src) / length smma export ema(series float src, simple int length) => ta.ema(src, length) export dema(series float src, simple int length) => e1 = ta.ema(src, length) e2 = ta.ema(e1, length) dema = 2 * e1 - e2 export tema(series float src, simple int length) => e1 = ta.ema(src, length) e2 = ta.ema(e1, length) e3 = ta.ema(e2, length) tema = 3 * (e1 - e2) + e3 export t3(series float src = close, simple int length = 10) => axe1 = ta.ema(src, length) axe2 = ta.ema(axe1, length) axe3 = ta.ema(axe2, length) axe4 = ta.ema(axe3, length) axe5 = ta.ema(axe4, length) axe6 = ta.ema(axe5, length) ab = 0.7 ac1 = -ab*ab*ab ac2 = 3*ab*ab+3*ab*ab*ab ac3 = -6*ab*ab-3*ab-3*ab*ab*ab ac4 = 1+3*ab+ab*ab*ab+3*ab*ab maPrice = ac1 * axe6 + ac2 * axe5 + ac3 * axe4 + ac4 * axe3 export hma(series float src, simple int length) => ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length))) // https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average export zlema(series float src, simple int length) => lag = math.ceil((length - 1) / 2) emaData = src + (src - src[lag]) zl = ta.ema(emaData, length) // zlema definition from impulseMACD from Lazybear export zlema2(series float src, simple int length) => e1 = ta.ema(src, length) e2 = ta.ema(e1, length) diff = e1 - e2 e1 + diff //Kijun-sen export KijunSen(series float src, simple int length) => kijun = math.avg(ta.lowest(src, length), ta.highest(src, length)) kijun export McGinley(series float src, simple int length) => mg = 0.0 ema = ta.ema(src, length) mg := na(mg[1]) ? ema : mg[1] + (src - mg[1]) / (length * math.pow(src/mg[1], 4)) mg export stochRSI(series float src, simple int lengthRSI = 10, simple int lengthStoch = 10, simple int smoothK = 3, simple int smoothD = 3) => rsi1 = ta.rsi(src, lengthRSI) k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = ta.sma(k, smoothD) [k, d] export slope(series float src, simple int length) => (src - src[length]) / length // Monte Carlo Simulation Drift // https://www.investopedia.com/terms/m/montecarlosimulation.asp export drift(series float src, simple int length) => pc = math.log(src / src[1]) variance = ta.variance(pc, length) drift = ta.sma(pc, length) - variance / 2 drift // Impulse MACD export impulseMACD(series float src = hlc3, simple int lengthSlowMA = 34, simple int lengthFastMA = 34, simple int lengthDEM = 9, simple float addThreshold = 0.0) => upper = (1 + addThreshold) * smma(high, lengthSlowMA) lower = (1 - addThreshold) * smma(low, lengthSlowMA) mid = zlema2(src, lengthFastMA) diff = (mid > upper) ? (mid - upper) : (mid < lower) ? (mid - lower) : 0 dem = ta.sma(diff, lengthDEM) macd = 2 * (diff - dem) [diff, dem, macd] // SuperTrend with custom input // -1 for uptrend, +1 for downtrend export superTrend(series float src = hl2, simple int atrPeriod = 10, simple float atrMultiplier = 3.0) => atr = ta.atr(atrPeriod) upperBand = src + atrMultiplier * atr lowerBand = src - atrMultiplier * atr prevLowerBand = nz(lowerBand[1]) prevUpperBand = nz(upperBand[1]) lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand int direction = na float superTrend = na prevSuperTrend = superTrend[1] if na(atr[1]) direction := 1 else if prevSuperTrend == prevUpperBand direction := close > upperBand ? -1 : 1 else direction := close < lowerBand ? 1 : -1 superTrend := direction == -1 ? lowerBand : upperBand [superTrend, direction] // Sigmoid activation function export sigmoid(series float x) => 1 / (1 + math.exp(-x)) // Zero centered sigmoid, range from [-1, 1] export zcsigmoid(series float x) => 2 * (sigmoid(x) - 0.5) // Tanh, range from [-1, 1] export tanh(series float x) => (math.exp(x) - math.exp(-x)) / (math.exp(x) + math.exp(-x)) // Normalizes series with unknown min/max using historical min/max. // src: series to rescale. // min, max: min/max values of rescaled series. // length: length of previous data points to find normalize the data from. export normalize(series float src, simple float min = -1, simple float max = 1, simple int length = na) => var historicMin = 10e10 var historicMax = -10e10 // length not specified, find all time min/max if na(length) historicMin := math.min(nz(src, historicMin), historicMin) historicMax := math.max(nz(src, historicMax), historicMax) else historicMin := ta.lowest(src, length) historicMax := ta.highest(src, length) min + (max - min) * (src - historicMin) / math.max(historicMax - historicMin, 10e-10) // Calculate the normal distribution curve using mean and std. export normalDistribution(series float src, simple float mean, simple float std) => a1 = 1 / (std * math.sqrt(2 * math.pi)) a2 = math.exp(-0.5 * math.pow((src - mean) / std, 2)) a1 * a2 plot(smma(KijunSen(close, 10),10), color = color.yellow) plot(McGinley(close, 10))
Antares_messages_public
https://www.tradingview.com/script/4pTbmpHS-Antares-messages-public/
taran1tul
https://www.tradingview.com/u/taran1tul/
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/ // © taran1tul //@version=5 // @description This library add messages for yours strategy for use in Antares trading system for binance and bybit exchanges. // Данная библиотека позволяет формировать сообщения в алертах стратегий для Antares в более упрощенном для пользователя режиме, включая всплывающие подсказки и т.д. library("Antares_messages_public") // TODO: Leverage and hedge mode now in separate message . Leverage set теперь в отдельном сообщении, т.к. используются крайне редко. hedge задавать через cli или сайт биржи // add silence! in multi orders // version 3.0 at 00:35 20.07.23 // binance_spot = 'binance' // binance_futures = 'binancefru' // bybit_spot = 'bybit' // bybit_futures = 'bybitfru' // binance - спотовый рынок Binance // binancefru - USDT-фьючерсы Binance. // binancefro - COIN-M фьючерсы Binance. Рынок инвертированных фьючерсов. Сделку можно совершить продав свою монету к USD. // bybit - спотовый рынок Bybit. // bybitfu - USDT-фьючерсы Binance // bybitfi - Рынок инвертированных фьючерсов. Сделку можно совершить продав свою монету к USD. //futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') //bybit_exchanges = array.from('bybit','bybitfu', 'bybitfi') // 1 part of all messages with token (if exist), market and ticker main_mess(string token, string market, string ticker) => token_del_spaces = str.replace_all(token, ' ', '') token_mess = token_del_spaces == '0' or token_del_spaces == '' ? '' : 'token=' + token + ';' token_mess + 'market=' + market + ';symbol=' + ticker + ';' hedge_mess(string market, bool hedge, string side) => futures = str.contains(market, 'fru') // проверяем в названии биржи 'fru' - фьючи hedge_mess = futures and hedge ? 'positionside=' + side + ';' : '' closePosition_mess(bool hedge) => closePos_mess = hedge ? '' : 'closePosition=true;' //при хедже убираем данную строку qty_string(string type_qty, float qty, bool futures) => mess='' if qty > 0 qty_string_part1 = type_qty=='qty' or type_qty=='' or na(type_qty) ? 'quantity=' : type_qty=='quqty' ? 'ququantity=' : type_qty=='open%' and not futures ? 'quantityproc=' : type_qty=='open%' and futures ? 'openquantityproc=' : type_qty=='close%' ? 'closequantityproc=' : 'error_in_type_quantity' mess := qty_string_part1 + str.tostring(qty) +';' mess // @function Set leverage for ticker on specified market. // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param leverage (float) leverage level. Устанавливаемое плечо. // @returns 'Set leverage message'. export set_leverage(string token, string market, string ticker_id, float leverage) => 'setvalue=LEVERAGE;' + main_mess(token, market, ticker_id) + 'leverage=' + str.tostring(leverage) + ';' // @function Set pause in message. '::' -left and '::' -right included. export pause(int time_pause) => '::pause=' + str.tostring(time_pause) + ';::' //========================================================= Режим 1 сторонней торговли (18-270)============================================================== // @function Buy order with limit price and quantity. // Лимитный ордер на покупку(в лонг). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param price (float) price for limit order. Цена по которой должен быть установлен лимитный ордер. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @param orderId (string) if use order id you may change or cancel your order after or set it ''. Используйте OrderId если хотите изменить или отменить ордер в будущем. // @returns 'Limit Buy order'. Лимитный ордер на покупку (лонг). export LongLimit(string token, string market, string ticker_id, string type_qty, float quantity, float price, string orderId, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' orderId_string = orderId=='' or na(orderId) ? '' : 'newclientorderid=' + str.tostring(orderId) + ';' main_mess(token, market, ticker_id) + 'side=Buy;'+ qty_string(type_qty,quantity,futures) + 'orderType=LIMIT;price=' + str.tostring(price) + ';' + lvrg_qty_string + orderId_string // @function Market Buy order with quantity. // Рыночный ордер на покупку (в лонг). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns 'Market Buy order'. Маркетный ордер на покупку (лонг). export LongMarket(string token, string market, string ticker_id, string type_qty, float quantity, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' main_mess(token, market, ticker_id) + 'side=Buy;'+ qty_string(type_qty,quantity,futures) + 'orderType=MARKET;' + lvrg_qty_string // @function Sell order with limit price and quantity. // Лимитный ордер на продажу(в шорт). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param price (float) price for limit order. Цена по которой должен быть установлен лимитный ордер. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @param orderId (string) if use order id you may change or cancel your order after or set it ''. Используйте OrderId если хотите изменить или отменить ордер в будущем. // @returns 'Limit Sell order'. Лимитный ордер на продажу (шорт). export ShortLimit(string token, string market, string ticker_id, string type_qty, float quantity, float price, bool leverageforqty, string orderId) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' orderId_string = orderId=='' or na(orderId) ? '' : 'newclientorderid=' + str.tostring(orderId) + ';' main_mess(token, market, ticker_id) + 'side=Sell;'+ qty_string(type_qty,quantity,futures) + 'orderType=LIMIT;price=' + str.tostring(price) + ';' + lvrg_qty_string + orderId_string // @function Sell by market price and quantity. // Рыночный ордер на продажу(в шорт). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns 'Market Sell order'. Маркетный ордер на продажу (шорт). export ShortMarket(string token, string market, string ticker_id, string type_qty, float quantity, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' main_mess(token, market, ticker_id) + 'side=Sell;'+ qty_string(type_qty,quantity,futures) + 'orderType=MARKET;' + lvrg_qty_string //********************************************** CANCEL ORDERS ***************************************************** // @function Cancel all orders for market and ticker in setups. Отменяет все ордера на заданной бирже и заданном токене(паре). // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @returns 'Cancel all orders'. Отмена всех ордеров на заданной бирже и заданном токене(паре). export Cancel_by_ticker(string token, string market, string ticker_id) => main_mess(token, market, ticker_id) + 'cancelorder=symbol;' // @function Cancel order by Id for market and ticker in setups. Отменяет ордер по Id на заданной бирже и заданном токене(паре). // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param order_id (string) order id for cancel . Строковая переменная названия ордера, заданного при его открытии. // @returns 'Cancel order'. Отмена ордера по Id на заданной бирже и заданном токене(паре). export Cancel_by_id(string token, string market, string ticker_id, string orderId) => main_mess(token, market, ticker_id) + 'cancelorder=order;' + 'clientorderid=' + str.tostring(orderId) + ';' //*********************************************** CLOSE ORDERS ************************************************************** // @function Close all positions for market and ticker in setups. Закрывает все позиции на заданной бирже и заданном токене(паре). // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @returns 'Close positions' export Close_positions(string token, string market, string ticker_id) => main_mess(token, market, ticker_id) + 'closepos=position;' // @function Close limit order for long position. (futures) // Лимитный ордер на продажу(в шорт) для закрытия лонговой позиции(reduceonly). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param price (float) price for limit order. Цена по которой должен быть установлен лимитный ордер. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @param orderId (string) if use order id you may change or cancel your order after or set it ''. Используйте OrderId если хотите изменить или отменить ордер в будущем. // @returns 'Limit Sell order reduce only (close long position)'. Лимитный ордер на продажу для снижения текущего лонга(в шорт не входит). export CloseLongLimit(string token, string market, string ticker_id, string type_qty, float quantity, float price, string orderId, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' orderId_string = orderId=='' or na(orderId) ? '' : 'newclientorderid=' + str.tostring(orderId) + ';' main_mess(token, market, ticker_id) + 'reduceOnly=true;side=Sell;'+ qty_string(type_qty,quantity,futures) + 'orderType=LIMIT;price=' + str.tostring(price) + ';' + lvrg_qty_string + orderId_string // @function Close market order for long position. // Рыночный ордер на продажу(в шорт) для закрытия лонговой позиции(reduceonly). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param price (float) price for limit order. Цена по которой должен быть установлен лимитный ордер. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns 'Market Sell order reduce only (close long position)'. Ордер на снижение/закрытие текущего лонга(в шорт не входит) по рыночной цене. export CloseLongMarket(string token, string market, string ticker_id, string type_qty, float quantity, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' main_mess(token, market, ticker_id) + 'reduceOnly=true;side=Sell;orderType=MARKET;'+ qty_string(type_qty,quantity,futures) + lvrg_qty_string // @function Close limit order for short position. // Лимитный ордер на покупку(в лонг) для закрытия шортовой позиции(reduceonly). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param price (float) price for limit order. Цена по которой должен быть установлен лимитный ордер. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @param orderId (string) if use order id you may change or cancel your order after or set it ''. Используйте OrderId если хотите изменить или отменить ордер в будущем. // @returns'Limit Buy order reduce only (close short position)' . Лимитный ордер на покупку (лонг) для сокращения/закрытия текущего шорта. export CloseShortLimit(string token, string market, string ticker_id, string type_qty, float quantity, float price, string orderId, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' orderId_string = orderId=='' or na(orderId) ? '' : 'newclientorderid=' + str.tostring(orderId) + ';' main_mess(token, market, ticker_id) + 'reduceOnly=true;side=Buy;'+ qty_string(type_qty,quantity,futures) + 'orderType=LIMIT;price=' + str.tostring(price) + ';' + lvrg_qty_string + orderId_string // @function Set Close limit order for long position. // Рыночный ордер на покупку(в лонг) для сокращения/закрытия шортовой позиции(reduceonly). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns'Market Buy order reduce only (close short position)'. Маркетного ордера на покупку (лонг) для сокращения/закрытия текущего шорта. export CloseShortMarket(string token, string market, string ticker_id, string type_qty, float quantity, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' main_mess(token, market, ticker_id) + 'reduceOnly=true;side=Buy;'+ qty_string(type_qty,quantity,futures) + 'orderType=MARKET;' + lvrg_qty_string // @function Set string of 2 orders : CancelAll + ClosePositions // Отмена всех лимитных ордеров и закрытие всех по тикеру // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @returns Set string of 2 orders : CancelAll + ClosePositiond Закрытие позициий и отмена всех лимитных ордеров export cancel_all_close(string token, string market, string ticker_id) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false Cancel_by_ticker(token, market, ticker_id) + "::" + Close_positions(token, market, ticker_id) // @function Set multi order for Bybit : limit + takeprofit + stoploss // Выставление тройного ордера на Bybit лимитка со стоплоссом и тейкпрофитом // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param orderId (string) if use order id you may change or cancel your order after or set it ''. Используйте OrderId если хотите изменить или отменить ордер в будущем. // @param side (bool) "buy side" if true or "sell side" if false. true для лонга, false для шорта. // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param price (float) price for limit order by 'side'. Цена лимитного ордера // @param tp_price (float) price for take profit order. // @param sl_price (float) price for stoploss order // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns Set multi order for Bybit : limit + takeprofit + stoploss. export limit_tpsl_bybitfu(string token, string ticker_id,string order_id, bool side, string type_qty, float quantity, float price, float tp_price, float sl_price, bool leverageforqty) => market = 'bybitfu' futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false price_str = price > 0 ? 'price=' + str.tostring(price) + ';' : '' tp_price_str = tp_price > 0 ? 'takeprofitprice=' + str.tostring(tp_price) + ';' : '' sl_price_str = sl_price > 0 ? 'stoplossprice=' + str.tostring(sl_price) + ';' : '' prices_str = price_str + tp_price_str + sl_price_str lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' side_str = side ? 'buy' : side == false ? 'sell' : 'error side' main_mess(token, market, ticker_id) + 'side=' + side_str + ';orderType=limit;newclientorderid=' + str.tostring(order_id) + qty_string(type_qty,quantity,futures) + prices_str + lvrg_qty_string // @function Change multi order for Bybit : limit + takeprofit + stoploss // Изменение тройного ордера на Bybit лимитка со стоплоссом и тейкпрофитом // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param orderId (string) if use order id you may change or cancel your order after or set it ''. Используйте OrderId если хотите изменить или отменить ордер в будущем. // @param side (bool) "buy side" if true or "sell side" if false. true для лонга, false для шорта. // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size, see at 'type_qty'. Размер ордера, базы или % в соответствии с 'type_qty' // @param price (float) price for limit order by 'side'. Цена лимитного ордера // @param tp_price (float) price for take profit order. // @param sl_price (float) price for stoploss order // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns Set multi order for Bybit : limit + takeprofit + stoploss. export replace_limit_tpsl_bybitfu(string token, string ticker_id,string order_id, bool side, string type_qty, float quantity, float price, float tp_price, float sl_price, bool leverageforqty) => market = 'bybitfu' futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false price_str = price > 0 ? 'price=' + str.tostring(price) + ';' : '' tp_price_str = tp_price > 0 ? 'takeprofitprice=' + str.tostring(tp_price) + ';' : '' sl_price_str = sl_price > 0 ? 'stoplossprice=' + str.tostring(sl_price) + ';' : '' prices_str = price_str + tp_price_str + sl_price_str lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' side_str = side ? 'buy' : side == false ? 'sell' : 'error side' main_mess(token, market, ticker_id) + 'side=' + side_str + ';orderType=replace_limit;origclientorderid=' + str.tostring(order_id) + qty_string(type_qty,quantity,futures) + prices_str + lvrg_qty_string //****************************** STOPLOSSES **************************** // @function Stop market order for long position // Рыночный стоп-ордер на продажу для закрытия лонговой позиции. // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size. Размер ордера. // @param l_stop (float) price for activation stop order. Цена активации стоп-ордера. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns 'Stop Market Sell order (close long position)'. Маркетный стоп-ордер на снижения/закрытия текущего лонга. export long_stop(string token, string market, string ticker_id, string type_qty, float quantity, float l_stop, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' reduce_str = futures ? 'reduceonly!;' : '' main_mess(token, market, ticker_id) + qty_string(type_qty,quantity,futures) + ';orderType=stop_market;side=sell;stopPrice=' + str.tostring(l_stop) + ';' + 'newClientOrderId=stop_long;' + lvrg_qty_string + reduce_str // @function Stop market order for short position // Рыночный стоп-ордер на покупку(в лонг) для закрытия шорт позиции. // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size. Размер ордера. // @param s_stop (float) price for activation stop order. Цена активации стоп-ордера. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns 'Stop Market Buy order (close short position)'. Маркетный стоп-ордер на снижения/закрытия текущего шорта. export short_stop(string token, string market, string ticker_id, string type_qty, float quantity, float s_stop, bool leverageforqty) => futures_exchanges = array.from('binancefru','binancefro','bybitfu', 'bybitfi') futures = array.includes(futures_exchanges, market) ? true : false lvrg_qty_string = leverageforqty and futures ? 'leverageforqty=true;' : leverageforqty==false and futures ? 'leverageforqty=false;' : '' reduce_str = futures ? 'reduceonly!;' : '' main_mess(token, market, ticker_id) + qty_string(type_qty,quantity,futures) + ';orderType=stop_market;side=buy;stopPrice=' + str.tostring(s_stop) + ';' + 'newClientOrderId=stop_short;' + lvrg_qty_string + reduce_str //Смещаем стоп (трейлинг по Вашему алгоритму из tradingview): // @function Change Stop market order for long position // Изменяем стоп-ордер на продажу(в шорт) для закрытия лонг позиции. // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size. Размер ордера. // @param l_stop (float) price for activation stop order. Цена активации стоп-ордера. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns 'Change Stop Market Buy order (close long position)'. Смещает цену активации Маркетного стоп-ордер на снижения/закрытия текущего лонга. export change_stop_l(string token, string market, string ticker_id, string type_qty, float quantity, float l_stop, bool leverageforqty) => Cancel_by_id(token,market,ticker_id,'stop_long') + "::" + pause(1000) + "::" + long_stop(token, market, ticker_id, type_qty, quantity, l_stop, leverageforqty) // @function Change Stop market order for short position // Смещает цену активации Рыночного стоп-ордера на покупку(в лонг) для закрытия шорт позиции. // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param quantity (float) orders size. Размер ордера. // @param s_stop (float) price for activation stop order. Цена активации стоп-ордера. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @returns 'Change Stop Market Buy order (close short position)'. Смещает цену активации Маркетного стоп-ордер на снижения/закрытия текущего шорта. export change_stop_s(string token, string market, string ticker_id, string type_qty, float quantity, float s_stop, bool leverageforqty) => Cancel_by_id(token,market,ticker_id,'stop_short') + "::" + pause(1000) + "::" + short_stop(token, market, ticker_id, type_qty, quantity, s_stop, leverageforqty) // Вход в лонг с выставлением стопа // @function Cancel and close all orders and positions by ticker , then open Long position by market price with stop order // Отменяет все лимитки и закрывает все позы по тикеру, затем открывает лонг по маркету с выставлением стопа (переворот позиции, при необходимости). // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size. Размер ордера. // @param l_stop (float). Price for activation stop loss. Цена активации стоп-лосса. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @silence command dont send report to telegram // @returns'command_all_close + LongMarket + long_stop. export open_long_position(string token, string market, string ticker_id, string type_qty, float quantity, float l_stop, bool leverageforqty, bool silence) => silence_m = silence ? 'silence!;' : '' cancel_all_close(token, market, ticker_id) + silence_m + "::" + pause(1000) + silence_m + "::" + LongMarket(token, market, ticker_id, type_qty, quantity, leverageforqty) + silence_m + "::" + long_stop(token, market, ticker_id, type_qty, quantity, l_stop, leverageforqty) + silence_m // Вход в шорт с выставлением стопа // @function Cancel and close all orders and positions , then open Short position by market price with stop order // Отменяет все лимитки и закрывает все позы по тикеру, затем открывает шорт по маркету с выставлением стопа(переворот позиции, при необходимости). // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) orders size. Размер ордера. // @param s_stop (float). Price for activation stop loss. Цена активации стоп-лосса. // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @silence command dont send report to telegram // @returns'command_all_close + ShortMarket + short_stop'. export open_short_position(string token, string market, string ticker_id, string type_qty, float quantity, float s_stop, bool leverageforqty, bool silence) => silence_m = silence ? 'silence!;' : '' cancel_all_close(token, market, ticker_id) + silence_m + "::" + pause(1000) + silence_m + "::" + ShortMarket(token, market, ticker_id, type_qty, quantity, leverageforqty) + silence_m + "::" + short_stop(token, market, ticker_id, type_qty, quantity, s_stop, leverageforqty) + silence_m //Вход в long с выставлением стопа и тейков (переворот позиции, при необходимости): // @function Cancell and close all orders and positions , then open Long position by market price with stop order and take 1 ,take 2, take 3 // Отменяет все лимитки и закрывает все позы по тикеру, затем открывает лонг по маркету с выставлением стопа и 3 тейками (переворот позиции, при необходимости). // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param quantity (float) enter order size, see at type_qty. Размер ордера входа, согласно type_qty. // @param l_stop (float). Price for activation stop loss. Цена активации стоп-лосса. // @param qty_ex1 (float). Quantity for 1th take see at type_qty, if = 0 string for order dont set. Размер лимитного ордера для 1го тейка, согласно type_qty.. Если 0, то строка для этого тейка не формируется // @param price_ex1 (float). Price for 1th take , if = 0 string for order dont set. Цена лимитного ордера для 1го тейка. Если 0, то строка для этого тейка не формируется // @param qty_ex2 (float). Quantity for 2th take see at type_qty, if = 0 string for order dont set. Размер лимитного ордера для 2го тейка, согласно type_qty..Если 0, то строка для этого тейка не формируется // @param price_ex2 (float). Price for 2th take, if = 0 string for order dont set. Цена лимитного ордера для 2го тейка. Если 0, то строка для этого тейка не формируется // @param qty_ex3 (float). Quantity for 3th take see at type_qty, if = 0 string for order dont set. Размер лимитного ордера для 2го тейка, согласно type_qty..Если 0, то строка для этого тейка не формируется // @param price_ex3 (float). Price for 3th take, if = 0 string for order dont set. Цена лимитного ордера для 3го тейка. Если 0, то строка для этого тейка не формируется // @param leverage (integer or 0) change leverage, if = 0 then leverage part mess is empty. Установка плеча для фьючерсов, при значении 0 не включается в формирование строки алерта. // @silence command dont send report to telegram // @returns'cancel_all_close + LongMarket + long_stop + CloseLongLimit1 + CloseLongLimit2+CloseLongLimit3'. export open_long_trade(string token, string market, string ticker_id, string type_qty, float quantity, float l_stop, float qty_ex1, float price_ex1, float qty_ex2, float price_ex2, float qty_ex3, float price_ex3, bool leverageforqty, bool silence) => silence_m = silence ? 'silence!;' : '' close1_str = qty_ex1 == 0 or price_ex1 == 0 ? '' : "::" + CloseLongLimit(token, market, ticker_id, type_qty, qty_ex1, price_ex1, '', leverageforqty) + silence_m close2_str = qty_ex2 == 0 or price_ex2 == 0 ? '' : "::" + CloseLongLimit(token, market, ticker_id, type_qty, qty_ex2, price_ex2, '', leverageforqty) + silence_m close3_str = qty_ex3 == 0 or price_ex3 == 0 ? '' : "::" + CloseLongLimit(token, market, ticker_id, type_qty, qty_ex3, price_ex3, '', leverageforqty) + silence_m cancel_all_close(token, market, ticker_id) + silence_m + "::" + pause(1000) + silence_m + "::" + LongMarket(token, market, ticker_id, type_qty, quantity, leverageforqty) + silence_m + "::" + pause(1000) + silence_m + "::" + long_stop(token, market, ticker_id, type_qty, quantity, l_stop, leverageforqty) + silence_m + close1_str + close2_str + close3_str //Вход в short с выставлением стопа и тейков (переворот позиции, при необходимости): // @function Cancell and close all orders and positions , then open Short position by market price with stop order and take 1 and take 2 // Отменяет все лимитки и закрывает все позы по тикеру, затем открывает шорт по маркету с выставлением стопа и 3 тейками (переворот позиции, при необходимости). // @param market (string) 'binance' , 'binancefru' etc.. Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param qty_all_close (float) Quantity for all close command. Количество для команды на закрытие пред позиций. // @param qty_enter (float). Quantity for enter position. Размер позиции для входа. // @param s_stop (float). Price for activation stop loss. Цена активации стоп-лосса. // @param qty_ex1 (float). Quantity for 1th take see at type_qty, if = 0 string for order dont set. Размер лимитного ордера для 1го тейка, согласно type_qty.. Если 0, то строка для этого тейка не формируется // @param price_ex1 (float). Price for 1th take , if = 0 string for order dont set. Цена лимитного ордера для 1го тейка. Если 0, то строка для этого тейка не формируется // @param qty_ex2 (float). Quantity for 2th take see at type_qty, if = 0 string for order dont set. Размер лимитного ордера для 2го тейка, согласно type_qty..Если 0, то строка для этого тейка не формируется // @param price_ex2 (float). Price for 2th take, if = 0 string for order dont set. Цена лимитного ордера для 2го тейка. Если 0, то строка для этого тейка не формируется // @param qty_ex3 (float). Quantity for 3th take see at type_qty, if = 0 string for order dont set. Размер лимитного ордера для 2го тейка, согласно type_qty..Если 0, то строка для этого тейка не формируется // @param price_ex3 (float). Price for 3th take, if = 0 string for order dont set. Цена лимитного ордера для 3го тейка. Если 0, то строка для этого тейка не формируется // @param leverage (integer or 0) change leverage, if = 0 then leverage part mess is empty. Установка плеча для фьючерсов, при значении 0 не включается в формирование строки алерта. // @silence command dont send report to telegram // @returns'command_all_close + ShortMarket + short_stop + CloseShortLimit + CloseShortLimit(2)'. export open_short_trade(string token, string market, string ticker_id, string type_qty, float quantity, float s_stop, float qty_ex1, float price_ex1, float qty_ex2, float price_ex2, float qty_ex3, float price_ex3, bool leverageforqty, bool silence) => silence_m = silence ? 'silence!;' : '' close1_str = qty_ex1 == 0 or price_ex1 == 0 ? '' : "::" + CloseShortLimit(token, market, ticker_id, type_qty, qty_ex1, price_ex1, '', leverageforqty) + silence_m close2_str = qty_ex2 == 0 or price_ex2 == 0 ? '' : "::" + CloseShortLimit(token, market, ticker_id, type_qty, qty_ex2, price_ex2, '', leverageforqty) + silence_m close3_str = qty_ex3 == 0 or price_ex3 == 0 ? '' : "::" + CloseShortLimit(token, market, ticker_id, type_qty, qty_ex3, price_ex3, '', leverageforqty) + silence_m cancel_all_close(token, market, ticker_id) + silence_m + "::" + pause(1000) + silence_m + "::" + ShortMarket(token, market, ticker_id, type_qty, quantity, leverageforqty) + silence_m + "::" + pause(1000) + silence_m + "::" + short_stop(token, market, ticker_id, type_qty, quantity, s_stop, leverageforqty) + close1_str + close2_str + close3_str // @function 8 or less Buy orders with limit price and quantity. // До 8 Лимитных ордеров на покупку(в лонг). // @param token (integer or 0) token for trade in system, if = 0 then token part mess is empty. Токен, При значениb = 0 не включается в формирование строки алерта. // @param market (string) Spot 'binance' , 'bybit' . Futures ('binancefru','binancefro','bybitfu', 'bybitfi'). Строковая переменная названия биржи. // @param ticker_id (string) ticker in market ('btcusdt', 'ethusdt' etc...). Строковая переменная названия тикера (пары). // @param type_qty (string) type of quantity: 1. 'qty' or '' or na - standart (in coins), 2. 'quqty'- in assets (usdt,btc,etc..), 3.open% - open position(futures) or buy (spot) in % of base 4. close% - close in % of position (futures) or sell (spot) coins in % for current quantity // @param qty (float) orders size, see at 'type_qty'. If = 0 order is off (except 1th). Размер ордера, базы или % в соответствии с 'type_qty'. Если = 0 ордер отключен (кроме 1го) // @param price (float) price for limit order. If = 0 order is off (except 1th). Цена по которой должен быть установлен лимитный ордер. Если = 0 ордер отключен (кроме 1го) // @param leverageforqty (bool) use leverage in qty. Использовать плечо при расчете количества или нет. // @param orderId (string) if use order id you may change or cancel your order after or set it ''. Используйте OrderId если хотите изменить или отменить ордер в будущем. // @silence command dont send report to telegram // @returns 'Limit Buy order'. Лимитный ордер на покупку (лонг). export Multi_LongLimit(string token, string market, string ticker_id, string type_qty, float qty1, float price1, float qty2, float price2,float qty3, float price3, float qty4, float price4, float qty5, float price5, float qty6, float price6,float qty7, float price7,float qty8, float price8, bool leverageforqty, bool silence) => silence_m = silence ? 'silence!;' : '' lim1_str = qty1 == 0 or price1 == 0 ? '' : LongLimit(token, market, ticker_id, type_qty, qty1, price1, '', leverageforqty) + silence_m lim2_str = qty2 == 0 or price2 == 0 ? '' : "::" + LongLimit(token, market, ticker_id, type_qty, qty2, price2, '', leverageforqty) + silence_m lim3_str = qty3 == 0 or price3 == 0 ? '' : "::" + LongLimit(token, market, ticker_id, type_qty, qty3, price3, '', leverageforqty) + silence_m lim4_str = qty4 == 0 or price4 == 0 ? '' : "::" + LongLimit(token, market, ticker_id, type_qty, qty4, price4, '', leverageforqty) + silence_m lim5_str = qty5 == 0 or price5 == 0 ? '' : "::" + LongLimit(token, market, ticker_id, type_qty, qty5, price5, '', leverageforqty) + silence_m lim6_str = qty6 == 0 or price6 == 0 ? '' : "::" + LongLimit(token, market, ticker_id, type_qty, qty6, price6, '', leverageforqty) + silence_m lim7_str = qty7 == 0 or price7 == 0 ? '' : "::" + LongLimit(token, market, ticker_id, type_qty, qty7, price7, '', leverageforqty) + silence_m lim8_str = qty8 == 0 or price8 == 0 ? '' : "::" + LongLimit(token, market, ticker_id, type_qty, qty8, price8, '', leverageforqty) + silence_m lim1_str + lim2_str + lim3_str + lim4_str + lim5_str + lim6_str + lim7_str + lim8_str
Scaled Order Sizing and Take Profit Target Arrays
https://www.tradingview.com/script/Mi1lMkO4-Scaled-Order-Sizing-and-Take-Profit-Target-Arrays/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
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/ // © kaigouthro // @version=5 // @ description # WOAH Order Scaling! // This Provides a user with methods to create a list of profit targets // and order sizes which grow or shrink. // #### For size // - they will add up to the specified sum. // #### For Targets // - will include the first and last // > // `weight` leans towards start or end // library('weighted_order_array_handler') import kaigouthro/calc/6 // @type Target Objects contain Informations for the order placement // @field price The price for the order // @field size The size for the order // @field ispct_prc Is the price a percentage // @field ispct_sz Is the size a percentage export type target float price = close float size = 0 bool ispct_prc = false bool ispct_sz = false // @function # Weighted array off sizes // ---- // create an array of sizes which grow or shrink from first to last // which add up to 1.0 if set the as_percent flag , or a total value / sum. // ### `example` // ``` // total_size = input(100, 'USD order size') / close // count = input(5 , 'Order count') // weight = input(100, 'Grow/Shrink') / 100 // min_size = input(10, ' Min Required Order') / close // array<float> split = scaled_sizes(total_size, count, weight, min_size) // ``` // @param total_size (float) total size to divide ito split // @param count (int ) desired number of splits to create // @param weight (float) a weight to apply to grow or shrink the split either towards the last being most, or the first being most, or 1.0 being each is equally sized as 1/n count // @param min_size (float) a minimum size for the smallest value (in value of ttotal_size units) // @param as_percent (float) a minimum size for the smallest value (in value of ttotal_size units) // @returns Array of Sizes for each split export method scaled_sizes(float total_size, int count,float weight, float min_size, bool as_percent = false) => size = total_size / count // @variable calculate the size of each sizes = array.new<float>(count) // @variable list of sizes for i = 0 to count -1 // calculate the size of each sizes.set(i, size) for i = 0 to count -1 // apply the weight to the sizes sizes.set(i, sizes.get(i) * math.pow(weight,i+1)) for i = 0 to count -1 // apply the min size to the sizes if sizes.get(i) < min_size sizes.set(i, min_size) sum = sizes.sum() for i = 0 to count -1 // calculate the percentage of the sizes sizes.set(i, sizes.get(i)/sum * (as_percent ? 1 : total_size)) sizes // @function # Create Profit Targets // ---- // create a list of take profitt targets from the smallest to larget distance // ### `example` // ``` // targets = input.int (5,'Profit targets') // weight = input.float(1,'TP Weight (1.0 = equal growth per step)', 0.1,2, step = 0.1) // min_tp = input.float(0.1,'First TP')/100 // max_tp = input.float(0.55,'LKast TP')/100 // // Call // array<float> targets = scaled_targets(targets,weight,min_tp,max_tp) // // ``` // @param count (int ) number of targets // @param weight (float) weight to apply to growing or shrinking // @param minimum (float) first value of the output // @param maximum (float) last value of the output // @returns Array percentage targets export method scaled_targets(int count, float weight, float minimum, float maximum) => split = scaled_sizes(calc.gapSize(maximum,minimum), count-1, weight, 0) // create a list of sizes targets = array.new<float>(count) // create a list of targets for i = 0 to count -1 // calculate the size of each targets.set(i, minimum + split.slice(0,i).sum()) targets // @function # Creates target Objects with combined info. // ---- // Creates a list of take profitt targets from the smallest to larget distance // and a set of sizes for each which add up to the total size // Combines them into Target OPbjecs // ### `example` // ``` // total_size = input(100, 'USD order size') / close // count = input(5 , 'Order count') // tp_weight = input(100, 'Grow/Shrink') / 100 // tp_min = input(10, ' Min TP') / 100 // tp_max = input(0.55, 'Max TP') / 100 // size_weight = input(100, 'Grow/Shrink') / 100 // min_size = input(10, ' Min Required Order') / close // // Call // scaled_order_array(total_size, count, tp_weight, tp_min, tp_max, size_weight, min_size) // // ``` // @param total_size (float) total size to divide ito split // @param count (int ) desired number of splits to create // @param tp_weight (float) a weight to apply to grow or shrink the target prices // @param tp_min (float) a minimum target // @param tp_max (float) a maximum target // @param size_weight (float) a weight to apply to grow or shrink the split either towards the last being most, or the first being most, or 1.0 being each is equally sized as 1/n count // @param min_size (float) a minimum size for the smallest value (in value of ttotal_size units) // @param as_percent (bool) Use percent for size // @returns Array of Sizes for each split export method scaled_order_array(float total_size, int count, float tp_weight, float tp_min, float tp_max, float size_weight, float min_size, bool as_percent = false) => array<float> targets = scaled_targets(count, tp_weight, tp_min, tp_max) array<float> sizes = scaled_sizes(total_size, count, size_weight, min_size, as_percent) array<target> order_array = array.new<target>(count) for i = 0 to count -1 order_array.set(i, target.new(price = targets.get(i), size = sizes.get(i), ispct_prc = true, ispct_sz = as_percent)) order_array
DiddlyUtility
https://www.tradingview.com/script/UBnouAef-DiddlyUtility/
RobMinty
https://www.tradingview.com/u/RobMinty/
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/ // © RobMinty //@version=5 // @description This utility function contains the general functions used in our indicators library("DiddlyUtility") //***************************** // Zone Maintainance Functions* //***************************** export CheckZoneRelativeStateToPrice(int _lineType, bool _IsBroken, int _lineExceptionLevel, float _closePrice, float _lineUpperPrice, float _lineLowerPrice, int _zoneIndex, int _closedWithinZoneIndex, int _nearestResistanceZoneAboveIndex, float _nearestResistanceZoneAboveDistance, int _nearestBuyersZoneAboveIndex, float _nearestBuyersZoneAboveDistance, int _nearestSupportZoneBelowIndex, float _nearestSupportZoneBelowDistance, int _nearestSellersZoneBelowIndex, float _nearestSellersZoneBelowDistance) => int closedWithinZoneIndex = _closedWithinZoneIndex int nearestResistanceZoneAboveIndex = _nearestResistanceZoneAboveIndex float nearestResistanceZoneAboveDistance = _nearestResistanceZoneAboveDistance int nearestBuyersZoneAboveIndex = _nearestBuyersZoneAboveIndex float nearestBuyersZoneAboveDistance = _nearestBuyersZoneAboveDistance int nearestSupportZoneBelowIndex = _nearestSupportZoneBelowIndex float nearestSupportZoneBelowDistance = _nearestSupportZoneBelowDistance int nearestSellersZoneBelowIndex = _nearestSellersZoneBelowIndex float nearestSellersZoneBelowDistance = _nearestSellersZoneBelowDistance if _lineExceptionLevel >= 2 or _lineExceptionLevel <= -2// and (_lineMethod == 1 or _lineMethod == 3) // Check whether Candle has closed in the zone, if so we can mark the temp active index. It will ultimately take the most recent (maybe need to change to an array at somepoint) if _lineLowerPrice <= _closePrice and _lineUpperPrice >= _closePrice closedWithinZoneIndex := _zoneIndex else // now we want to see whether this zone is the closest from above or below of price // Check those Above if (_lineLowerPrice > _closePrice) if na(_nearestResistanceZoneAboveIndex) and not _IsBroken and _lineType == -1 // This is a resistance level - Null Check // No prevsious nearest to set this one nearestResistanceZoneAboveIndex := _zoneIndex nearestResistanceZoneAboveDistance := (_lineLowerPrice - _closePrice) else if na(_nearestBuyersZoneAboveIndex) and _lineType == 1 // This is a failed buyers block - Null Check // No prevsious nearest to set this one nearestBuyersZoneAboveIndex := _zoneIndex nearestBuyersZoneAboveDistance := (_lineLowerPrice - _closePrice) else if not na(_nearestResistanceZoneAboveIndex) and not _IsBroken and _lineType == -1 and (_lineLowerPrice - _closePrice) <= _nearestResistanceZoneAboveDistance // This is a resistance level - Where Previous Exists // Check whether this zone is closest than the previous closest. Need to ensure that this zone is above price nearestResistanceZoneAboveDistance := (_lineLowerPrice - _closePrice) nearestResistanceZoneAboveIndex := _zoneIndex else if not na(_nearestBuyersZoneAboveIndex) and _lineType == 1 and (_lineLowerPrice - _closePrice) <= _nearestBuyersZoneAboveDistance // This is a failed buyers block - Where Previous Exists nearestBuyersZoneAboveIndex := _zoneIndex nearestResistanceZoneAboveDistance := (_lineLowerPrice - _closePrice) // End Section // // Check those Below if (_closePrice > _lineUpperPrice) if na(_nearestSupportZoneBelowIndex) and not _IsBroken and _lineType == 1 // This is a support level - Null Check // No prevsious nearest to set this one nearestSupportZoneBelowIndex := _zoneIndex nearestSupportZoneBelowDistance := (_closePrice - _lineUpperPrice) else if na(nearestSellersZoneBelowIndex) and _lineType == -1 // This is a failed sellers block - Null Check // No prevsious nearest to set this one nearestSellersZoneBelowIndex := _zoneIndex nearestSellersZoneBelowDistance := (_closePrice - _lineUpperPrice) else if not na(_nearestSupportZoneBelowIndex) and not _IsBroken and _lineType == 1 and (_closePrice - _lineUpperPrice) <= _nearestSupportZoneBelowDistance // Get the closest below // Check whether this zone is closest than the previous closest. Need to ensure that this zone is above price nearestSupportZoneBelowDistance := (_closePrice - _lineUpperPrice) nearestSupportZoneBelowIndex := _zoneIndex else if not na(nearestSellersZoneBelowIndex) and _lineType == -1 and (_closePrice - _lineUpperPrice) <= nearestSellersZoneBelowDistance // This is a failed sellers block - Where Previous Exists nearestSellersZoneBelowIndex := _zoneIndex nearestSellersZoneBelowDistance := (_closePrice - _lineUpperPrice) // End Section // // // End Condition [closedWithinZoneIndex, nearestResistanceZoneAboveIndex, nearestResistanceZoneAboveDistance, nearestBuyersZoneAboveIndex, nearestBuyersZoneAboveDistance, nearestSupportZoneBelowIndex, nearestSupportZoneBelowDistance, nearestSellersZoneBelowIndex, nearestSellersZoneBelowDistance] // End Logic export completeZoneRelativeAnalysis(int _closedWithinZoneIndex, int _nearestResistanceZoneAboveIndex, float _nearestResistanceZoneAboveDistance, int _nearestBuyersZoneAboveIndex, float _nearestBuyersZoneAboveDistance, int _nearestSupportZoneBelowIndex, float _nearestSupportZoneBelowDistance, int _nearestSellersZoneBelowIndex, float _nearestSellersZoneBelowDistance) => int _activeZoneIndex = na int _activeResistanceAboveZone = na float _activeResistanceAboveZoneDistance = na int _activeSupportBelowZone = na float _activeSupportBelowZoneDistance = na int _activeBuyersAboveZone = na float _activeBuyersAboveZoneDistance = na int _activeSellersBelowZone = na float _activeSellersBelowZoneDistance = na //if _hasHTFclosed or _barstateConfirmed _activeZoneIndex := _closedWithinZoneIndex _activeResistanceAboveZone := _nearestResistanceZoneAboveIndex _activeResistanceAboveZoneDistance := _nearestResistanceZoneAboveDistance _activeSupportBelowZone := _nearestSupportZoneBelowIndex _activeSupportBelowZoneDistance := _nearestSupportZoneBelowDistance _activeBuyersAboveZone := _nearestBuyersZoneAboveIndex _activeBuyersAboveZoneDistance := _nearestBuyersZoneAboveDistance _activeSellersBelowZone := _nearestSellersZoneBelowIndex _activeSellersBelowZoneDistance := _nearestSellersZoneBelowDistance // End Logic [_activeZoneIndex, _activeResistanceAboveZone, _activeResistanceAboveZoneDistance, _activeBuyersAboveZone, _activeBuyersAboveZoneDistance, _activeSupportBelowZone, _activeSupportBelowZoneDistance, _activeSellersBelowZone, _activeSellersBelowZoneDistance] // End Function export addLabel (int _boxEnd, float _yPos, string _text, string _toolTip, color _textColor) => label uiLabel = na if not na(_text) and str.length(_text) > 0 uiLabel := label.new(x=_boxEnd, y=_yPos, xloc=xloc.bar_time, style=label.style_none, size=size.small, textcolor=_textColor, text=_text)//, textalign=text.align_left) if not na(_toolTip) label.set_tooltip(uiLabel, _toolTip) uiLabel export buidZoneUI (int _time, float _top, float _bottom, int _zoneMethod, int _zoneType1, int _exceptionLevel1, bool _zoneType1DisplayLabel, int _zoneType2, int _exceptionLevel2, bool _zoneType2DisplayLabel, int _boxEnd, string _border_style, string _text, string _toolTip, color _textColor, color _zoneColourBull1, color _zoneColourBull2, color _zoneColourBull3, color _zoneColourBull4, color _zoneColourBear1, color _zoneColourBear2, color _zoneColourBear3, color _zoneColourBear4, color _zoneLineColourBull1, color _zoneLineColourBull2, color _zoneLineColourBull3, color _zoneLineColourBull4, color _zoneLineColourBear1, color _zoneLineColourBear2, color _zoneLineColourBear3, color _zoneLineColourBear4, int _borderWidthActive) => box uiBox = na if _zoneMethod == 1 if _zoneType1 == 1 //Bullish Zones uiBox := switch _exceptionLevel1 4 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull4, bgcolor= _zoneColourBull4, border_style= _border_style, border_width=_borderWidthActive) 3 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull3, bgcolor= _zoneColourBull3, border_style= _border_style, border_width=_borderWidthActive) 2 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull2, bgcolor= _zoneColourBull2, border_style= _border_style, border_width=_borderWidthActive) 1 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull1, bgcolor= _zoneColourBull1, border_style= _border_style, border_width=_borderWidthActive) => na else if _zoneType1 == -1 //Bearish Zones uiBox := switch _exceptionLevel1 -4 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear4, bgcolor= _zoneColourBear4, border_style= _border_style, border_width=_borderWidthActive) -3 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear3, bgcolor= _zoneColourBear3, border_style= _border_style, border_width=_borderWidthActive) -2 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear2, bgcolor= _zoneColourBear2, border_style= _border_style, border_width=_borderWidthActive) -1 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear1, bgcolor= _zoneColourBear1, border_style= _border_style, border_width=_borderWidthActive) => na else if _zoneMethod == 2 if _zoneType2 == 1 //Bullish Zones uiBox := switch _exceptionLevel2 4 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull4, bgcolor= _zoneColourBull4, border_style= _border_style, border_width=_borderWidthActive) 3 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull3, bgcolor= _zoneColourBull3, border_style= _border_style, border_width=_borderWidthActive) 2 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull2, bgcolor= _zoneColourBull2, border_style= _border_style, border_width=_borderWidthActive) 1 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull1, bgcolor= _zoneColourBull1, border_style= _border_style, border_width=_borderWidthActive) => na else if _zoneType2 == -1 //Bearish Zones uiBox := switch _exceptionLevel2 -4 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear4, bgcolor= _zoneColourBear4, border_style= _border_style, border_width=_borderWidthActive) -3 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear3, bgcolor= _zoneColourBear3, border_style= _border_style, border_width=_borderWidthActive) -2 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear2, bgcolor= _zoneColourBear2, border_style= _border_style, border_width=_borderWidthActive) -1 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear1, bgcolor= _zoneColourBear1, border_style= _border_style, border_width=_borderWidthActive) => na else if _zoneMethod == 3 // because we are a combined signal we need to see the highest exception level to see which was the driving force int zoneType = na int exceptionLevel = na if _zoneType1 == 1 and _zoneType2 == 1 // Both Signals in same direction zoneType := 1 if _exceptionLevel1 >= _exceptionLevel2 exceptionLevel := _exceptionLevel1 else exceptionLevel := _exceptionLevel2 // else if _zoneType1 == -1 and _zoneType2 == -1 // Both Signals in same direction zoneType := -1 if _exceptionLevel1 <= _exceptionLevel2 exceptionLevel := _exceptionLevel1 else exceptionLevel := _exceptionLevel2 // else // Signals are in different directions if _exceptionLevel1 < 0 if _exceptionLevel2 < _exceptionLevel1 /-1 exceptionLevel := _exceptionLevel1 zoneType := _zoneType1 else exceptionLevel := _exceptionLevel2 zoneType := _zoneType2 // else if _exceptionLevel2 < 0 if _exceptionLevel2/-1 < _exceptionLevel1 /-1 exceptionLevel := _exceptionLevel1 zoneType := _zoneType1 else exceptionLevel := _exceptionLevel2 zoneType := _zoneType2 // // // if zoneType == 1 //Bullish Zones uiBox := switch exceptionLevel 4 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull4, bgcolor= _zoneColourBull4, border_style= _border_style, border_width=_borderWidthActive) 3 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull3, bgcolor= _zoneColourBull3, border_style= _border_style, border_width=_borderWidthActive) 2 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull2, bgcolor= _zoneColourBull2, border_style= _border_style, border_width=_borderWidthActive) 1 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBull1, bgcolor= _zoneColourBull1, border_style= _border_style, border_width=_borderWidthActive) => na else if zoneType == -1 //Bearish Zones uiBox := switch exceptionLevel -4 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear4, bgcolor= _zoneColourBear4, border_style= _border_style, border_width=_borderWidthActive) -3 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear3, bgcolor= _zoneColourBear3, border_style= _border_style, border_width=_borderWidthActive) -2 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear2, bgcolor= _zoneColourBear2, border_style= _border_style, border_width=_borderWidthActive) -1 => uiBox := box.new(_time, _top, _boxEnd, _bottom, xloc=xloc.bar_time, border_color =_zoneLineColourBear1, bgcolor= _zoneColourBear1, border_style= _border_style, border_width=_borderWidthActive) => na // Add any label label uiLabel = na if _zoneType1DisplayLabel and (_zoneMethod == 1 or _zoneMethod == 3) uiLabel := addLabel (_boxEnd, _bottom + (_top - _bottom), _text, _toolTip, _textColor) else if _zoneType2DisplayLabel and _zoneMethod == 2 uiLabel := addLabel (_boxEnd, _bottom + (_top - _bottom), _text, _toolTip, _textColor) [uiBox, uiLabel] export setZoneColour (box _uiBox, int _zoneMethod, int _zoneType1, bool _isBroken, int _type1ExceptionLevel, int _zoneType2, int _type2ExceptionLevel, bool _isTrapZone, color _zoneTrapBullColour, color _zoneTrapBearColour, color _zoneColourBull1, color _zoneColourBull2, color _zoneColourBull3, color _zoneColourBull4, color _zoneColourBear1, color _zoneColourBear2, color _zoneColourBear3, color _zoneColourBear4) => if not na(_uiBox) if _isBroken if _zoneMethod == 1 or _zoneMethod == 3 if _zoneType1 == 1 //Bullish Zones if _isTrapZone switch _type1ExceptionLevel 4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull4,98)), box.set_border_color(_uiBox, color.new(_zoneColourBull4,95)) 3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull3,98)), box.set_border_color(_uiBox, color.new(_zoneColourBull3,95)) 2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull2,100)), box.set_border_color(_uiBox, color.new(_zoneColourBull2,100)) 1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull1,100)), box.set_border_color(_uiBox, color.new(_zoneColourBull1,100)) else switch _type1ExceptionLevel 4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull4,95)), box.set_border_color(_uiBox, color.new(_zoneColourBull4,90)) 3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull3,95)), box.set_border_color(_uiBox, color.new(_zoneColourBull3,90)) 2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull2,99)), box.set_border_color(_uiBox, color.new(_zoneColourBull2,95)) 1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull1,99)), box.set_border_color(_uiBox, color.new(_zoneColourBull1,95)) else if _zoneType1 == -1 //Bearish Zones if _isTrapZone switch _type1ExceptionLevel -4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear4,98)), box.set_border_color(_uiBox, color.new(_zoneColourBear4,95)) -3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear3,98)), box.set_border_color(_uiBox, color.new(_zoneColourBear3,95)) -2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear2,100)), box.set_border_color(_uiBox, color.new(_zoneColourBear2,100)) -1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear1,100)), box.set_border_color(_uiBox, color.new(_zoneColourBear1,100)) else switch _type1ExceptionLevel -4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear4,95)), box.set_border_color(_uiBox, color.new(_zoneColourBear4,90)) -3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear3,95)), box.set_border_color(_uiBox, color.new(_zoneColourBear3,90)) -2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear2,99)), box.set_border_color(_uiBox, color.new(_zoneColourBear2,95)) -1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear1,99)), box.set_border_color(_uiBox, color.new(_zoneColourBear1,95)) else if _zoneMethod == 2 if _zoneType2 == 1 //Bullish Zones if _isTrapZone switch _type2ExceptionLevel 4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull4,98)), box.set_border_color(_uiBox, color.new(_zoneColourBull4,95)) 3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull3,98)), box.set_border_color(_uiBox, color.new(_zoneColourBull3,95)) 2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull2,100)), box.set_border_color(_uiBox, color.new(_zoneColourBull2,100)) 1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull1,100)), box.set_border_color(_uiBox, color.new(_zoneColourBull1,100)) else switch _type2ExceptionLevel 4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull4,95)), box.set_border_color(_uiBox, color.new(_zoneColourBull4,90)) 3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull3,95)), box.set_border_color(_uiBox, color.new(_zoneColourBull3,90)) 2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull2,99)), box.set_border_color(_uiBox, color.new(_zoneColourBull2,95)) 1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBull1,99)), box.set_border_color(_uiBox, color.new(_zoneColourBull1,95)) else if _zoneType2 == -1 //Bearish Zones if _isTrapZone switch _type2ExceptionLevel -4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear4,98)), box.set_border_color(_uiBox, color.new(_zoneColourBear4,95)) -3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear3,98)), box.set_border_color(_uiBox, color.new(_zoneColourBear3,95)) -2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear2,100)), box.set_border_color(_uiBox, color.new(_zoneColourBear2,100)) -1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear1,100)), box.set_border_color(_uiBox, color.new(_zoneColourBear1,100)) else switch _type2ExceptionLevel -4 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear4,95)), box.set_border_color(_uiBox, color.new(_zoneColourBear4,90)) -3 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear3,95)), box.set_border_color(_uiBox, color.new(_zoneColourBear3,90)) -2 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear2,95)), box.set_border_color(_uiBox, color.new(_zoneColourBear2,95)) -1 => box.set_bgcolor(_uiBox, color.new(_zoneColourBear1,95)), box.set_border_color(_uiBox, color.new(_zoneColourBear1,95)) else // Not Broken if _zoneMethod == 1 or _zoneMethod == 3 if _zoneType1 == 1 //Bullish Zones if _isTrapZone switch _type1ExceptionLevel 4 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,20)) 3 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,40)) 2 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,60)) 1 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,80)) else switch _type1ExceptionLevel 4 => box.set_bgcolor(_uiBox, _zoneColourBull4), box.set_border_color(_uiBox, _zoneColourBull4) 3 => box.set_bgcolor(_uiBox, _zoneColourBull3), box.set_border_color(_uiBox, _zoneColourBull3) 2 => box.set_bgcolor(_uiBox, _zoneColourBull2), box.set_border_color(_uiBox, _zoneColourBull2) 1 => box.set_bgcolor(_uiBox, _zoneColourBull1), box.set_border_color(_uiBox, _zoneColourBull1) else if _zoneType1 == -1 //Bearish Zones if _isTrapZone switch _type1ExceptionLevel -4 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,20)) -3 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,40)) -2 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,60)) -1 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,80)) else switch _type1ExceptionLevel -4 => box.set_bgcolor(_uiBox, _zoneColourBear4), box.set_border_color(_uiBox, _zoneColourBear4) -3 => box.set_bgcolor(_uiBox, _zoneColourBear3), box.set_border_color(_uiBox, _zoneColourBear3) -2 => box.set_bgcolor(_uiBox, _zoneColourBear2), box.set_border_color(_uiBox, _zoneColourBear2) -1 => box.set_bgcolor(_uiBox, _zoneColourBear1), box.set_border_color(_uiBox, _zoneColourBear1) else if _zoneMethod == 2 if _zoneType2 == 1 //Bullish Zones if _isTrapZone switch _type2ExceptionLevel 4 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,20)) 3 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,40)) 2 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,60)) 1 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBullColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBullColour,80)) else switch _type2ExceptionLevel 4 => box.set_bgcolor(_uiBox, _zoneColourBull4), box.set_border_color(_uiBox, _zoneColourBull4) 3 => box.set_bgcolor(_uiBox, _zoneColourBull3), box.set_border_color(_uiBox, _zoneColourBull3) 2 => box.set_bgcolor(_uiBox, _zoneColourBull2), box.set_border_color(_uiBox, _zoneColourBull2) 1 => box.set_bgcolor(_uiBox, _zoneColourBull1), box.set_border_color(_uiBox, _zoneColourBull1) else if _zoneType2 == -1 //Bearish Zones if _isTrapZone switch _type2ExceptionLevel -4 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,20)) -3 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,85)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,40)) -2 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,60)) -1 => box.set_bgcolor(_uiBox, color.new(_zoneTrapBearColour,99)), box.set_border_color(_uiBox, color.new(_zoneTrapBearColour,80)) else switch _type2ExceptionLevel -4 => box.set_bgcolor(_uiBox, _zoneColourBear4), box.set_border_color(_uiBox, _zoneColourBear4) -3 => box.set_bgcolor(_uiBox, _zoneColourBear3), box.set_border_color(_uiBox, _zoneColourBear3) -2 => box.set_bgcolor(_uiBox, _zoneColourBear2), box.set_border_color(_uiBox, _zoneColourBear2) -1 => box.set_bgcolor(_uiBox, _zoneColourBear1), box.set_border_color(_uiBox, _zoneColourBear1) export amendBrokenLevelUI (box _uiBox, int _zoneMethod, int _zoneType1, int _type1ExceptionLevel, int _zoneType2, int _type2ExceptionLevel, int _boxEnd, string _border_style, bool _isTrapZone, color _zoneTrapBullColour, color _zoneTrapBearColour, color _zoneColourBull1, color _zoneColourBull2, color _zoneColourBull3, color _zoneColourBull4, color _zoneColourBear1, color _zoneColourBear2, color _zoneColourBear3, color _zoneColourBear4, int _borderWidth) => if not na(_uiBox) setZoneColour (_uiBox, _zoneMethod, _zoneType1, true, _type1ExceptionLevel, _zoneType2, _type2ExceptionLevel, _isTrapZone, _zoneTrapBullColour, _zoneTrapBearColour, _zoneColourBull1, _zoneColourBull2, _zoneColourBull3, _zoneColourBull4, _zoneColourBear1, _zoneColourBear2, _zoneColourBear3, _zoneColourBear4) box.set_right(_uiBox, _boxEnd) box.set_border_style(_uiBox, _border_style) box.set_border_width(_uiBox, _borderWidth) export manageZoneInformation(label _label, int _textElement, string _text) => if not na(_label) if _textElement == 1 label.set_text(_label, _text) else if _textElement == 2 label.set_tooltip(_label, _text) // export getZoneName(int _zoneType) => name = switch _zoneType 1 => "Bull Zone" -1 => "Bear Zone" => "Not Classified" name // End export getZoneSetupType(int _setupType) => name = switch _setupType 1 => "Trap Move" 2 => "Trade Away" => "Not Classified" name // End //*************************** // General Utility Functions* //*************************** // Function to deal with whether the session is due to be open soon within the next minute //export isTimeComingUptoSessionOpen(int lastResetTime, string london_ssth, string london_sstm, string ny_ssth, string ny_sstm) => // Reimported functions from watchlist utility export getCurrentDayOfWeek() => fullDate = str.format("{0,date, full}",time) pos = str.pos(fullDate, ",") retDay = str.substring(fullDate, 0, pos) retDay export isInUSstockOpenMarket() => // Time check are in UCT - so not sure what happens when summer time bool ret = na currentTimeHour = str.tonumber(str.format("{0,date, HH}",time)) currentTimeMin = str.tonumber(str.format("{0,date, mm}",time)) // Check the hour time window if currentTimeHour >= 13 and currentTimeHour <= 19 if currentTimeHour == 13 and currentTimeMin <= 29 ret := false else ret := true else ret := false // Just check we are not on a weekend if ret checkDay = getCurrentDayOfWeek() if checkDay == "Saturday" or checkDay == "Sunday" ret := false ret export isInUSstockPostMarket() => // Time check are in UCT - so not sure what happens when summer time bool ret = na currentTimeHour = str.tonumber(str.format("{0,date, HH}",time)) currentTimeMin = str.tonumber(str.format("{0,date, mm}",time)) // Check the hour time window if (currentTimeHour >= 20) or (currentTimeHour < 8) ret := true else ret := false // Just check we are not on a weekend if ret checkDay = getCurrentDayOfWeek() if checkDay == "Saturday" or checkDay == "Sunday" ret := false ret export isInUSstockPreMarket() => // Time check are in UCT - so not sure what happens when summer time bool ret = na currentTimeHour = str.tonumber(str.format("{0,date, HH}",time)) currentTimeMin = str.tonumber(str.format("{0,date, mm}",time)) // Check the hour time window if currentTimeHour >= 8 and currentTimeHour <= 13 if currentTimeHour == 13 and currentTimeMin >= 30 ret := false else ret := true else ret := false // Just check we are not on a weekend if ret checkDay = getCurrentDayOfWeek() if checkDay == "Saturday" or checkDay == "Sunday" ret := false ret // End Utility Functions export getStringTimeMinus1Minute(string london_ssth, string london_sstm) => // // Get the session start times as integers london_start_session_hour_int = london_ssth == "00" ? 0 : london_ssth == "01" ? 1 : london_ssth == "02" ? 2 : london_ssth == "03" ? 3 : london_ssth == "04" ? 4 : london_ssth == "05" ? 5 : london_ssth == "06" ? 6 : london_ssth == "07" ? 7 : london_ssth == "08" ? 8 : london_ssth == "09" ? 9 : london_ssth == "10" ? 10 : london_ssth == "11" ? 11 : london_ssth == "12" ? 12 : london_ssth == "13" ? 13 : london_ssth == "14" ? 14 : london_ssth == "15" ? 15 : london_ssth == "16" ? 16 : london_ssth == "17" ? 17 : london_ssth == "18" ? 18 : london_ssth == "19" ? 19 : london_ssth == "20" ? 20 : london_ssth == "21" ? 21 : london_ssth == "22" ? 22 : london_ssth == "23" ? 23 : 0 london_start_session_minute_int = london_sstm == "00" ? 0 : london_sstm == "15" ? 15 : london_sstm == "30" ? 30 : london_sstm == "45" ? 45 : 0 string checkFirstSessionTime = "" // Make sure the last reset time was greater than 5 mins away // London Time - 1 min before open if london_start_session_minute_int == 0 if london_start_session_hour_int == 0 checkFirstSessionTime := "2359" else if london_start_session_hour_int <= 10 checkFirstSessionTime := "0" + str.tostring(london_start_session_hour_int - 1) + "59" else checkFirstSessionTime := str.tostring(london_start_session_hour_int - 1) + "59" else if london_start_session_hour_int == 0 checkFirstSessionTime := "23" + str.tostring(london_start_session_minute_int - 1) else if london_start_session_hour_int <= 9 checkFirstSessionTime := "0" + str.tostring(london_start_session_hour_int) + "" + str.tostring(london_start_session_minute_int - 1) else checkFirstSessionTime := str.tostring(london_start_session_hour_int) + "" + str.tostring(london_start_session_minute_int - 1) checkFirstSessionTime // End Function // Functions used in combination to a ladder arrays, where by a price is used to dermine the size of the range steps // eg. price 5.65 would have a step range of 0.10, where as 15k price a 5 range may be better // Function to determine what size should be used for a ladder array that will enable a value to be held at each index // so if a symbol was 10 USD, then to easily store information at each price point, there would need to be 10 x 100 indexes = 1000 // which in this case may be to many to store when considering that the price could increase by 1000 percent in one session // also consider assets like the dax or dow which are trading at 30k odd. // so we need a function that is called on startup that will determine the best way to size such and array and the start and end points. // as example for the dax we may want to start the index at 14k and have the upper range at 16k, so we can caputre a range of 2000. // so we would may not want to track values at each tick by rather for a range ie. every 10 euros on the dax. export getLadderStepIncrement(float _price) => float ladderStep = 5.0 if (_price < 1) ladderStep := 0.05 else if (_price < 10) ladderStep := 0.10 else if (_price < 100) ladderStep := 0.20 else if (_price < 1000) ladderStep := 0.30 else if (_price < 5000) ladderStep := 0.5 else if (_price < 10000) ladderStep := 1.0 else if (_price < 20000) ladderStep := 2.0 else if (_price < 40000) ladderStep := 10.0 else ladderStep := 20.0 ladderStep // End // Get the index for the range of the current price export getLadderIndexForPrice(float _price, float _ladderRange) => // so example price is 10.47 - how do we get the range it is within if the priceLadderPriceRange = 0.10 float startPriceRange = (math.round(math.floor((_price * 100) / (_ladderRange * 100))) * (_ladderRange * 100) / 100) int ladderIndex = int(math.round(startPriceRange / _ladderRange)) - 1 // 10 here needs to be an calc variable / the minus 1 is due to indexes starting at 0 and not 1 ladderIndex // End // Get the lower price for the range of the current price export getLadderStartPriceRange(float _price, float _ladderRange) => // so example price is 10.47 - how do we get the range it is within if the priceLadderPriceRange = 0.10 float startPriceRange = ((math.floor((_price * 100) / (_ladderRange * 100))) * (_ladderRange * 100) / 100) startPriceRange // End // End Ladder Functions // Volumne functions section. These probably could do with another library at some point // Format the display of volume figures export get_volume_string(float _volume) => string _volume_string = na if _volume >= 1000000000 _volume_digits = math.round(_volume / 1000000000 * 100) / 100 _volume_string := str.tostring(_volume_digits) + 'B' _volume_string else if _volume >= 1000000 _volume_digits = math.round(_volume / 1000000 * 100) / 100 _volume_string := str.tostring(_volume_digits) + 'M' _volume_string else if _volume >= 1000 _volume_digits = math.round(_volume / 1000 * 100) / 100 _volume_string := str.tostring(_volume_digits) + 'K' _volume_string else _volume_string := str.tostring(math.round(_volume * 100) / 100) _volume_string _volume_string // End // export floorDown(float number, int decimals) => factor = math.pow(10, decimals) float floorValue = math.floor(number * factor) / factor floorValue // Counts the number of digits before a decimal point export countDigitsBeforeDecimal(float n) => int c=1 c:=n==0?1:1+math.floor(math.log10(math.abs(n))) c // // Counts the number of digits after a decimal point export countDigitsAfterDecimal(float n) => int c=0 d=0.0 d:=math.abs(n) 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 // // Get the lower price for the range of the current price export getChartTimePeriodAsSeconds(string _chartPeriod) => int chartPeriodSecounds = 0 if (_chartPeriod == 'S') chartPeriodSecounds := 1 else if (_chartPeriod == '5S') chartPeriodSecounds := 5 else if (_chartPeriod == '15S') chartPeriodSecounds := 15 else if (_chartPeriod == '30S') chartPeriodSecounds := 30 else if (_chartPeriod == '1') chartPeriodSecounds := 60 else if (_chartPeriod == '3') chartPeriodSecounds := 60 * 3 else if (_chartPeriod == '5') chartPeriodSecounds := 60 * 5 else if (_chartPeriod == '15') chartPeriodSecounds := 60 * 15 else if (_chartPeriod == '30') chartPeriodSecounds := 60 * 30 else if (_chartPeriod == '45') chartPeriodSecounds := 60 * 45 else if (_chartPeriod == '60') chartPeriodSecounds := 60 * 60 else if (_chartPeriod == '120') chartPeriodSecounds := 60 * 120 else if (_chartPeriod == '180') chartPeriodSecounds := 60 * 180 else if (_chartPeriod == '240') chartPeriodSecounds := 60 * 240 else if (_chartPeriod == 'D') chartPeriodSecounds := 60 * 60 * 24 else if (_chartPeriod == '5D') chartPeriodSecounds := 60 * 60 * 24 * 5 else if (_chartPeriod == 'W') chartPeriodSecounds := 60 * 60 * 24 * 7 chartPeriodSecounds // End export debug(string _txt) => var _lbl = label(na), label.delete(_lbl), _lbl := label.new(time + (time-time[1])*3, high, _txt, xloc.bar_time, yloc.price, size = size.large)
MyLibrary
https://www.tradingview.com/script/yUOuExP7-MyLibrary/
Schwehng
https://www.tradingview.com/u/Schwehng/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Schwehng //@version=5 // @description TODO: add library description here library("MyLibrary") export MMMM(string toe) => string tex = toe export OOOO(string toe, string toe1, string toe2, string toe3, string toe4, string toe5,int init) => string tex = init == 1? toe:init == 2?toe1:init == 3?toe2:init == 4?toe3:init == 5?toe4:init == 6?toe5:na tex export XXXX(string toe) => string tex = toe export WWWW(string toe) => string tex = toe
FunctionBaumWelch
https://www.tradingview.com/script/OhWGAkLm-FunctionBaumWelch/
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 Baum-Welch Algorithm, also known as Forward-Backward Algorithm, uses the well known EM algorithm // to find the maximum likelihood estimate of the parameters of a hidden Markov model given a set of observed // feature vectors. // --- // ### Function List: // > `forward (array<float> pi, matrix<float> a, matrix<float> b, array<int> obs)` // > `forward (array<float> pi, matrix<float> a, matrix<float> b, array<int> obs, bool scaling)` // > `backward (matrix<float> a, matrix<float> b, array<int> obs)` // > `backward (matrix<float> a, matrix<float> b, array<int> obs, array<float> c)` // > `baumwelch (array<int> observations, int nstates)` // > `baumwelch (array<int> observations, array<float> pi, matrix<float> a, matrix<float> b)` // --- // ### Reference: // > https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm // > https://github.com/alexsosn/MarslandMLAlgo/blob/4277b24db88c4cb70d6b249921c5d21bc8f86eb4/Ch16/HMM.py // > https://en.wikipedia.org/wiki/Forward_algorithm // > https://www.rdocumentation.org/packages/HMM/versions/1.0.1/topics/forward // > https://www.rdocumentation.org/packages/HMM/versions/1.0.1/topics/backward library("FunctionBaumWelch") //#region -> Helpers: import RicardoSantos/WIPTensor/2 as Tensor import RicardoSantos/DebugConsole/13 as console logger = console.new() logger.table.set_position(position.bottom_right) logger.table.cell_set_width(0, 0, 95) // array_random () { array_random(int size, float min, float max) => array<float> _r = array.new<float>(size) for _i = 0 to size - 1 _r.set(_i, math.random(min, max)) _r array_random(int size, float max) => array<float> _r = array.new<float>(size) for _i = 0 to size - 1 _r.set(_i, math.random(max)) _r array_random(int size) => array<float> _r = array.new<float>(size) for _i = 0 to size - 1 _r.set(_i, math.random()) _r // } // matrix_random () { matrix_random (int rows, int columns, float min, float max) => matrix<float> _r = matrix.new<float>(rows, columns) for _i = 0 to rows - 1 for _j = 0 to columns - 1 _r.set(_i, _j, math.random(min, max)) _r matrix_random (int rows, int columns, float max) => matrix<float> _r = matrix.new<float>(rows, columns) for _i = 0 to rows - 1 for _j = 0 to columns - 1 _r.set(_i, _j, math.random(max)) _r matrix_random (int rows, int columns) => matrix<float> _r = matrix.new<float>(rows, columns) for _i = 0 to rows - 1 for _j = 0 to columns - 1 _r.set(_i, _j, math.random()) _r // } //#endregion // forward () { // reference: // https://github.com/alexsosn/MarslandMLAlgo/blob/4277b24db88c4cb70d6b249921c5d21bc8f86eb4/Ch16/HMM.py // https://www.rdocumentation.org/packages/HMM/versions/1.0.1/topics/forward // @function Computes forward probabilities for state `X` up to observation at time `k`, is defined as the // probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`. // @param pi Initial probabilities. // @param a Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing // states given a state matrix is size (M x M) where M is number of states. // @param b Emissions, matrix of observation probabilities b or beta = observation probabilities. Given // state matrix is size (M x O) where M is number of states and O is number of different // possible observations. // @param obs List with actual state observation data. // @returns // - `matrix<float> _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first // dimension refers to the state and the second dimension to time. export forward (array<float> pi, matrix<float> a, matrix<float> b, array<int> obs) => int _n_states = matrix.rows(b) int _size_t = array.size(obs) matrix<float> _alpha = matrix.new<float>(_n_states, _size_t, 0.0) int _obs0 = array.get(obs, 0) for _i = 0 to _n_states - 1 matrix.set(_alpha, _i, 0, array.get(pi, _i) * matrix.get(b, _i, _obs0)) // for _t = 1 to _size_t - 1 for s = 0 to _n_states - 1 float _alpha_sum = 0.0 for _i = 0 to _n_states - 1 _alpha_sum += matrix.get(_alpha, _i, _t - 1) * matrix.get(a, _i, s) matrix.set(_alpha, s, _t, matrix.get(b, s, array.get(obs, _t)) * _alpha_sum) _alpha // pi = array.from(0.25, 0.25, 0.25, 0.25) // a = matrix.new<float>(0, 4) // a.add_row(0, array.from(0.05, 0.70, 0.05, 0.20)) // a.add_row(1, array.from(0.10, 0.40, 0.30, 0.20)) // a.add_row(2, array.from(0.10, 0.60, 0.05, 0.25)) // a.add_row(3, array.from(0.25, 0.30, 0.40, 0.05)) // b = matrix.new<float>(0, 0) // b.add_row(0, array.from(0.3,0.4,0.2,0.1)) // b.add_row(1, array.from(0.2,0.1,0.2,0.5)) // b.add_row(2, array.from(0.4,0.2,0.1,0.3)) // b.add_row(3, array.from(0.3,0.05,0.3,0.35)) // array<int> obs = array.from(3,1,1,3,0,3,3,3,1,1,0,2,2) // if barstate.islast // fw = forward(pi, a, b, obs) // label.new(bar_index, 0.0, str.tostring(fw)) // @function Computes forward probabilities for state `X` up to observation at time `k`, is defined as the // probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`. // @param pi Initial probabilities. // @param a Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing // states given a state matrix is size (M x M) where M is number of states. // @param b Emissions, matrix of observation probabilities b or beta = observation probabilities. Given // state matrix is size (M x O) where M is number of states and O is number of different // possible observations. // @param obs List with actual state observation data. // @param scaling Normalize `alpha` scale. // @returns // - #### Tuple with: // > - `matrix<float> _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first // dimension refers to the state and the second dimension to time. // > - `array<float> _c`: Array with normalization scale. export forward (array<float> pi, matrix<float> a, matrix<float> b, array<int> obs, bool scaling) => _alpha = forward(pi, a, b, obs) int _n_states = matrix.rows(b) int _size_t = array.size(obs) // array<float> _c = array.new<float>(_size_t, 1.0) if scaling for _t = 0 to _size_t - 1 _alpha_sum = array.sum(matrix.col(_alpha, _t)) array.set(_c, _t, _alpha_sum) for _i = 0 to _n_states - 1 matrix.set(_alpha, _i, _t, matrix.get(_alpha, _i, _t) / _alpha_sum) [_alpha, _c] // } // backward () { // reference: // https://github.com/alexsosn/MarslandMLAlgo/blob/4277b24db88c4cb70d6b249921c5d21bc8f86eb4/Ch16/HMM.py // https://www.rdocumentation.org/packages/HMM/versions/1.0.1/topics/backward // @function Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`. // @param a Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states // given a state matrix is size (M x M) where M is number of states // @param b Emissions, matrix of observation probabilities b or beta = observation probabilities. given state // matrix is size (M x O) where M is number of states and O is number of different possible observations // @param obs Array with actual state observation data. // @returns // - `matrix<float> _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time. export backward (matrix<float> a, matrix<float> b, array<int> obs) => int _n_states = matrix.rows(b) int _size_t = array.size(obs) matrix<float> _beta = matrix.new<float>(_n_states, _size_t, 0.0) for _i = 0 to _n_states - 1 matrix.set(_beta, _i, _size_t - 1, 1.0) // aLast // for _t = _size_t - 2 to 0 int _obs_t1 = array.get(obs, _t + 1) for s = 0 to _n_states - 1 float _beta_sum = 0.0 for _i = 0 to _n_states - 1 _beta_sum += matrix.get(b, _i, _obs_t1) * matrix.get(_beta, _i, _t + 1) * matrix.get(a, s, _i) matrix.set(_beta, s, _t, _beta_sum) _beta // @function Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`. // @param a Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states // given a state matrix is size (M x M) where M is number of states // @param b Emissions, matrix of observation probabilities b or beta = observation probabilities. given state // matrix is size (M x O) where M is number of states and O is number of different possible observations // @param obs Array with actual state observation data. // @param c Array with Normalization scaling coefficients. // @returns // - `matrix<float> _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time. export backward (matrix<float> a, matrix<float> b, array<int> obs, array<float> c) => int _n_states = matrix.rows(b) int _size_t = array.size(obs) _beta = backward(a, b, obs) for _t = 0 to _size_t - 1 for _i = 0 to _n_states - 1 matrix.set(_beta, _i, _t, matrix.get(_beta, _i, _t) / array.get(c, _t)) _beta // baumwelch () { // AKA: Forward-Backward Algorithm // reference: // https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm // https://github.com/alexsosn/MarslandMLAlgo/blob/4277b24db88c4cb70d6b249921c5d21bc8f86eb4/Ch16/HMM.py // @function **(Random Initialization)** Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the // unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm // to compute the statistics for the expectation step. // @param observations List of observed states. // @param nstate Number of hidden states. // @returns // - #### Tuple with: // > - `array<float> _pi`: Initial probability distribution. // > - `matrix<float> _a`: Transition probability matrix. // > - `matrix<float> _b`: Emission probability matrix. // --- // requires: `import RicardoSantos/WIPTensor/2 as Tensor` export baumwelch (array<int> observations, int nstates) => int _nobs = observations.size() int _obsmax = observations.max() // Initialise pi, a, b randomly array<float> _pi = array.new<float>(nstates, 1.0 / nstates) matrix<float> _a = matrix.new<float>(nstates, nstates) matrix<float> _b = matrix.new<float>(nstates, _obsmax + 1) for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _a.set(_i, _j, math.random()) for _j = 0 to _obsmax _b.set(_i, _j, math.random()) // float _tol = 1.0e-5 float _error = _tol + 1.0 int _maxits = 100 int _nits = 0 while (_error > _tol) and (_nits < _maxits) _nits += 1 array<float> _oldpi = _pi.copy() matrix<float> _olda = _a.copy() matrix<float> _oldb = _b.copy() // E step matrix<float> _alpha = forward(_pi, _a, _b, observations) matrix<float> _beta = backward(_a, _b, observations) Tensor.Tensor _xi = Tensor.new(nstates, nstates, _nobs, 0.0) for _t = 0 to _nobs - 2 for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _xi.set(_i, _j, _t, _alpha.get(_i, _t) * _a.get(_i, _j) * _b.get(_j, observations.get(_t + 1)) * _beta.get(_j, _t + 1)) float _sum = 0.0 for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _sum += _xi.get(_i, _j, _t) for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _xi.set(_i, _j, _t, nz(_xi.get(_i, _j, _t) / _sum)) for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _xi.set(_i, _j, _nobs - 1, _alpha.get(_i, _nobs - 1) * _a.get(_i, _j)) // The last step has no b, beta in float _sum = 0.0 for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _sum += _xi.get(_i, _j, _nobs - 1) for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _xi.set(_i, _j, _nobs - 1, nz(_xi.get(_i, _j, _nobs - 1) / _sum)) // M step for _i = 0 to nstates - 1 float _sum2 = 0.0 for _j = 0 to nstates - 1 _sum2 += _xi.get(_i, _j, 0) _pi.set(_i, _sum2) for _j = 0 to nstates - 1 float _numerator_a = _xi.get_vector_xy(_i, _j).sum() float _denominator_a = 0.0 for _k = 0 to nstates - 1 _denominator_a += _xi.get_vector_xy(_i, _k).sum() _a.set(_i, _j, nz(_numerator_a / _denominator_a)) for _k = 0 to _obsmax array<int> _found = array.new<int>() for [_idx, _o] in observations if _k == _o _found.push(_idx) float _numerator_b = 0.0 float _denominator_b = 0.0 for _j = 0 to nstates - 1 for _f in _found _numerator_b += _xi.get(_i, _j, _f) for _s = 0 to nstates - 1 _denominator_b += _xi.get_vector_xy(_i, _s).sum() _b.set(_i, _k, nz(_numerator_b / _denominator_b)) // float _max_e = 0.0 for _i = 0 to nstates - 1 for _j = 0 to nstates - 1 _max_e := math.max(_max_e, math.abs(_a.get(_i, _j) - _olda.get(_i, _j))) _error := _max_e _max_e := 0.0 for _o = 0 to _obsmax _max_e := math.max(_max_e, math.abs(_b.get(_i, _o) - _oldb.get(_i, _o))) _error += _max_e [_pi, _a, _b] // @function Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the // unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm // to compute the statistics for the expectation step. // @param observations List of observed states. // @param pi Initial probability distribution. // @param a Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states // given a state matrix is size (M x M) where M is number of states // @param b Emissions, matrix of observation probabilities b or beta = observation probabilities. given state // matrix is size (M x O) where M is number of states and O is number of different possible observations // @returns // - #### Tuple with: // > - `array<float> _pi`: Initial probability distribution. // > - `matrix<float> _a`: Transition probability matrix. // > - `matrix<float> _b`: Emission probability matrix. // --- // requires: `import RicardoSantos/WIPTensor/2 as Tensor` export baumwelch (array<int> observations, array<float> pi, matrix<float> a, matrix<float> b) => int _nobs = observations.size() , int _obsmax = observations.max() int _nstates = a.rows() , int _nstates1 = _nstates - 1 // Initialise pi, a, b array<float> _pi = pi.copy() matrix<float> _a = a.copy() matrix<float> _b = b.copy() // float _tol = 1.0e-5 float _error = _tol + 1.0 int _maxits = 100 int _nits = 0 while (_error > _tol) and (_nits < _maxits) _nits += 1 array<float> _oldpi = _pi.copy() matrix<float> _olda = _a.copy() matrix<float> _oldb = _b.copy() // E step matrix<float> _alpha = forward(_pi, _a, _b, observations) matrix<float> _beta = backward(_a, _b, observations) Tensor.Tensor _xi = Tensor.new(_nstates, _nstates, _nobs, 0.0) for _t = 0 to _nobs - 2 for _i = 0 to _nstates1 for _j = 0 to _nstates1 _xi.set(_i, _j, _t, _alpha.get(_i, _t) * _a.get(_i, _j) * _b.get(_j, observations.get(_t + 1)) * _beta.get(_j, _t + 1)) float _sum = 0.0 for _i = 0 to _nstates1 for _j = 0 to _nstates1 _sum += _xi.get(_i, _j, _t) for _i = 0 to _nstates1 for _j = 0 to _nstates1 _xi.set(_i, _j, _t, nz(_xi.get(_i, _j, _t) / _sum)) for _i = 0 to _nstates1 for _j = 0 to _nstates1 _xi.set(_i, _j, _nobs - 1, _alpha.get(_i, _nobs - 1) * _a.get(_i, _j)) // The last step has no b, beta in float _sum = 0.0 for _i = 0 to _nstates1 for _j = 0 to _nstates1 _sum += _xi.get(_i, _j, _nobs - 1) for _i = 0 to _nstates1 for _j = 0 to _nstates1 _xi.set(_i, _j, _nobs - 1, nz(_xi.get(_i, _j, _nobs - 1) / _sum)) // M step for _i = 0 to _nstates1 float _sum2 = 0.0 for _j = 0 to _nstates1 _sum2 += _xi.get(_i, _j, 0) _pi.set(_i, _sum2) for _j = 0 to _nstates1 float _numerator_a = _xi.get_vector_xy(_i, _j).sum() float _denominator_a = 0.0 for _k = 0 to _nstates1 _denominator_a += _xi.get_vector_xy(_i, _k).sum() _a.set(_i, _j, nz(_numerator_a / _denominator_a)) for _k = 0 to _obsmax array<int> _found = array.new<int>() for [_idx, _o] in observations if _k == _o _found.push(_idx) float _numerator_b = 0.0 float _denominator_b = 0.0 for _j = 0 to _nstates1 for _f in _found _numerator_b += _xi.get(_i, _j, _f) for _s = 0 to _nstates1 _denominator_b += _xi.get_vector_xy(_i, _s).sum() _b.set(_i, _k, nz(_numerator_b / _denominator_b)) // float _max_e = 0.0 for _i = 0 to _nstates1 for _j = 0 to _nstates1 _max_e := math.max(_max_e, math.abs(_a.get(_i, _j) - _olda.get(_i, _j))) _error := _max_e _max_e := 0.0 for _o = 0 to _obsmax _max_e := math.max(_max_e, math.abs(_b.get(_i, _o) - _oldb.get(_i, _o))) _error += _max_e [_pi, _a, _b] array<int> obs = array.from(1, 0, 2, 1, 0, 2, 1, 1, 0, 2, 0, 0, 1) ns = input.int(2) log_line = input.int(1) if barstate.islast [pi, a, b] = baumwelch(obs, ns) logger.queue_one(str.format('Initial probability: {0}\n\nTransition probability:\n{1}\n\nEmission probability:\n{2}', str.tostring(pi,'0.000'), str.tostring(a,'0.000'), str.tostring(b,'0.000'))) // def evenings(): // pi = np.array([0.25, 0.25, 0.25, 0.25]) // a = np.array([[0.05,0.7, 0.05, 0.2],[0.1,0.4,0.3,0.2],[0.1,0.6,0.05,0.25],[0.25,0.3,0.4,0.05]]) // b = np.array([[0.3,0.4,0.2,0.1],[0.2,0.1,0.2,0.5],[0.4,0.2,0.1,0.3],[0.3,0.05,0.3,0.35]]) // obs = np.array([3,1,1,3,0,3,3,3,1,1,0,2,2]) // print Viterbi(pi,a,b,obs)[0] // alpha,c = HMMfwd(pi,a,b,obs) // print np.sum(alpha[:,-1]) // def test(): // np.random.seed(4) // pi = np.array([0.25,0.25,0.25,0.25]) // aLast = np.array([0.25,0.25,0.25,0.25]) // #a = np.array([[.7,.3],[.4,.6]] ) // a = np.array([[.4,.3,.1,.2],[.6,.05,.1,.25],[.7,.05,.05,.2],[.3,.4,.25,.05]]) // #b = np.array([[.2,.4,.4],[.5,.4,.1]] ) // b = np.array([[.2,.1,.2,.5],[.4,.2,.1,.3],[.3,.4,.2,.1],[.3,.05,.3,.35]]) // obs = np.array([0,0,3,1,1,2,1,3]) // #obs = np.array([2,0,2]) // HMMfwd(pi,a,b,obs) // Viterbi(pi,a,b,obs) // print BaumWelch(obs,4) // def biased_coins(): // a = np.array([[0.4,0.6],[0.9,0.1]]) // b = np.array([[0.49,0.51],[0.85,0.15]]) // pi = np.array([0.5,0.5]) // obs = np.array([0,1,1,0,1,1,0,0,1,1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,1,1,0,1,0,0,1,0,1,0,0,1,1,1,0]) // print Viterbi(pi,a,b,obs)[0] // print BaumWelch(obs,2) // } logger.update()
new_line_dot_3
https://www.tradingview.com/script/PY11tkgO-new-line-dot-3/
Quantkr
https://www.tradingview.com/u/Quantkr/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © MBYLAB //@version=5 // @description TODO: plot line based on 3 points. library("new_line") // @function TODO: plot line based on 3 points. (each different) // @param x TODO: bar_index or location x // @returns TODO: new line based on each different 3 values. export new_line(int x_1, int x_2, int x_3, float y_1, float y_2, float y_3) => line_1 = line.new(x_1, y_1, x_2, y_2) line_2 = line.new(x_2, y_2, x_3, y_3) [line_1, line_2] //example // @param [example_line_1, example_line_2] <= this is is the name. [example_line_1, example_line_2] = new_line(bar_index, bar_index+1, bar_index+3, 100, 200, 300)
OHLC
https://www.tradingview.com/script/F2tbSR4s-OHLC/
cryptolinx
https://www.tradingview.com/u/cryptolinx/
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/ // © cryptolinx - jango_blockchained - open 💙 source //@version=5 // ▪ ──── LIBRARY // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // @description // This library provides a simple way to calculate OHLC values for any source. library('OHLC', overlay = false) // >> // ▪ ──── TYPES // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // -- OHLC Source { // // @type A source that can be used to calculate OHLC values. // @field close The last close value. // @field open The last open value. // @field high The last high value. // @field low The last low value. // @field update_no The number of bars since the last open. export type src // -- float close float open float high float low int update_no // } // ▪ ──── INTERNAL // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // -- Build-In Overloaded/Expanded Functions { // method nz(series float _src, series float _target) => na(_src) ? _target : _src method nz(series src _src, series src _target) => na(_src) ? _target : _src // } // ▪ ──── EXPORT // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // -- OHLC Source Methods { // // @function Hydrates the OHLC source with a new value. // ___ // **Example** // ``` // // basic // mySrc.hydrateOHLC(rsi) // ``` // or // ``` // // inline // rsi = ta.rsi(close, 14).hydrateOHLC(mySrc) // ``` // @param this The source to hydrate. // @param _src The new value. // @returns src export method hydrateOHLC(src this, float _src) => if not na(_src) this.close := _src if barstate.isnew this.open := this.close this.low := this.close this.high := this.close this.update_no := 0 this.low := math.min(this.low.nz(this.close), this.close) this.high := math.max(this.high.nz(this.close), this.close) this.update_no += 1 // >> this // -- // @note The "method overloading" and "argument flipping" pattern used in this code can also be manually applied to any // custom function inside your script. This can be useful for creating more flexible and versatile functions that can be // used in different contexts and with different argument orders. export method hydrateOHLC(float _src, src this) => this.hydrateOHLC(_src), _src // } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // -- New OHLC Source { // // @function Creates a new OHLC source. // ___ // [![required varip](https://img.shields.io/badge/required-varip-blue?logo=tradingview&style=flat-square)](https://www.tradingview.com/pine-script-docs/en/v5/language/Variable_declarations.html?highlight=varip#varip) // [![issue repainting](https://img.shields.io/badge/issue-repainting-red?logo=tradingview&style=flat-square)](https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html?highlight=repainting) // ___ // **Example** // ``` // varip mySrc = src.new() // ``` // **Notes** \ // Needs to be initialized by using the `varip` keyword. // @returns **src** A new blank OHLC source object. export new() => src.new() // } // ▪ ──── EXAMPLES // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ // -- Inputs { // // @variable __PLOT_CANDLE Holds the user inputs option. // @variable __PLOT_CANDLE Holds the user inputs option. var __PLOT_CANDLE = input.bool(true, title='Plot Candle') var __RSI_LENGTH = input.int(14, title='RSI Length') // } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // -- Example #1 { // // @variable rsi Example RSI calculation // @variable mySrc Example `<OHLC.src>` object. rsi = ta.rsi(close, __RSI_LENGTH) varip mySrc = src.new() mySrc.hydrateOHLC(rsi) // equals to rsi.hydrateOHLC(mySrc) // } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // -- Example #2 { // @variable mySrc2 Example `<OHLC.src>` object. // @variable rsi2 Example RSI calculation. varip mySrc2 = src.new() rsi2 = ta.rsi(close, __RSI_LENGTH).hydrateOHLC(mySrc2) // equals to mySrc2.hydrateOHLC(rsi) // } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // -- Plotting { // // @variable confirmationPlot Holds the RSI plot `id` for `mySrc2`. confirmationPlot = plot( series = not barstate.islast ? mySrc2.close : na, color = color.silver, style = plot.style_circles, linewidth = 1) // -- // @variable rsiPlot Holds the RSI plot `id` for `mySrc`. rsiPlot = plot( series = not __PLOT_CANDLE or not barstate.islast ? mySrc.close : na, color = mySrc.close > mySrc.open ? color.green : mySrc.close < mySrc.open ? color.red : color.blue, linewidth = 1) // -- fill( plot1 = plot(not __PLOT_CANDLE and barstate.islast ? mySrc.high : na, color = color.new(color.white, 80)), plot2 = rsiPlot, bottom_value = 0, top_value = 100, bottom_color = #00000000, top_color = color.new(color.red, 90)) // -- fill( plot1 = rsiPlot, plot2 = plot(not __PLOT_CANDLE and barstate.islast ? mySrc.low : na, color = color.new(color.white, 80)), bottom_value = 0, top_value = 100, bottom_color = color.new(color.green, 90), top_color = #00000000) // -- plotcandle( open = __PLOT_CANDLE and barstate.islast ? mySrc.open : na, high = __PLOT_CANDLE and barstate.islast ? mySrc.high : na, low = __PLOT_CANDLE and barstate.islast ? mySrc.low : na, close = __PLOT_CANDLE and barstate.islast ? mySrc.close : na, title = 'RSI Candle', color = mySrc.open > mySrc.close ? color.red : color.green, wickcolor = mySrc.open > mySrc.close ? color.red : color.green, bordercolor = mySrc.open > mySrc.close ? color.red : color.green) // } // #EOF
FunctionProbabilityViterbi
https://www.tradingview.com/script/4LxrPLxI-FunctionProbabilityViterbi/
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 The Viterbi Algorithm calculates the most likely sequence of hidden states *(called Viterbi path)* // that results in a sequence of observed events. library("FunctionProbabilityViterbi") import RicardoSantos/DebugConsole/13 as console console.Console logger = console.new() logger.table.set_position(position.bottom_right) logger.table.cell_set_width(0, 0, 95) // viterbi () { // reference: // https://en.wikibooks.org/wiki/Algorithm_Implementation/Viterbi_algorithm // https://viterbischool.usc.edu/news/2017/03/viterbi-algorithm-demystified/ // https://github.com/WuLC/ViterbiAlgorithm/blob/master/Viterbi.py // https://github.com/pandeydivesh15/AI_lab-codes/blob/master/HMM_Viterbi/hmm_model.py // https://www.pythonpool.com/viterbi-algorithm-python/ // https://www.cs.princeton.edu/courses/archive/fall15/cos402/assignments/programs/viterbi/ // https://www.freecodecamp.org/news/a-deep-dive-into-part-of-speech-tagging-using-viterbi-algorithm-17c8de32e8bc/ // https://www.adeveloperdiary.com/data-science/machine-learning/implement-viterbi-algorithm-in-hidden-markov-model-using-python-and-r/ // @function Calculate most probable path in a Markov model. // @param observations array<int> . Observation states data. // @param transitions matrix<float> . Transition probability table, (HxH, H:Hidden states). // @param emissions matrix<float> . Emission probability table, (OxH, O:Observed states). // @param initial_distribution array<float> . Initial probability distribution for the hidden states. // @returns array<int>. Most probable path. export viterbi ( array<int> observations , matrix<float> transitions , matrix<float> emissions , array<float> initial_distribution ) => // int _n_obs = observations.size() int _n_states = transitions.rows() matrix<float> _omega = matrix.new<float>(_n_obs, _n_states, 0.0) matrix<int> _prev = matrix.new<int>(_n_obs - 1, _n_states, 0) // for [_i, _e] in initial_distribution _omega.set(0, _i, math.log(_e * emissions.get(_i, observations.get(0)))) // for _t = 1 to _n_obs - 1 for _j = 0 to _n_states - 1 // Forward Probability: _probability = _omega.row(_t - 1) for [_i, _p] in _probability _probability.set(_i, _p + math.log(transitions.get(_i, _j)) + math.log(emissions.get(_j, observations.get(_t)))) // most probable state given previous state at time t: _maxp = _probability.max() _prev.set(_t - 1, _j, _probability.indexof(_maxp)) // probability of the most probable state: _omega.set(_t, _j, _maxp) // // Path Array array<int> _S = array.new<int>(_n_obs, 0) // Find the most probable last hidden state array<float> _o = _omega.row(_n_obs - 1) float _maxo = _o.max() int _last_state = _o.indexof(_maxo) // _S.set(0, _last_state) int _backtrack_index = 1 for _i = _n_obs - 2 to 0 int _ps = _prev.get(_i, _last_state) _S.set(_backtrack_index, _ps) _last_state := _ps _backtrack_index += 1 // // Flip the path array since we were backtracking _S.reverse() _S // TEST: 20230318 RS: match with 2 diferent sources. VT = matrix.new<float>(0, 2, 0.0) matrix.add_row(VT, 0, array.from(0.7, 0.3)) matrix.add_row(VT, 1, array.from(0.4, 0.6)) VE = matrix.new<float>(0, 3, 0.0) matrix.add_row(VE, 0, array.from(0.5, 0.4, 0.1)) matrix.add_row(VE, 1, array.from(0.1, 0.3, 0.6)) // matrix.add_row(VE, 2, array.from(0.1, 0.6)) v_init_p = array.from(0.6, 0.4) v_obs = array.from(0, 1, 2) // // v_MC = hidden.new( // name = 'Viterbi test', // states_hidden = array.from( // state.new('healthy', 0, array.from(targetNode.new(0, 0.7), targetNode.new(1, 0.3))), // state.new('fever' , 1, array.from(targetNode.new(0, 0.4), targetNode.new(1, 0.6))) // ), // states_obs = array.from( // state.new('normal', 0, array.from(targetNode.new(0, 0.5), targetNode.new(1, 0.1))), // state.new('cold' , 1, array.from(targetNode.new(0, 0.4), targetNode.new(1, 0.3))), // state.new('dizzy' , 2, array.from(targetNode.new(0, 0.1), targetNode.new(1, 0.6))) // ), // size_hidden = 2, // size_obs = 3, // transitions = VT, // emissions = VE // ) if barstate.islast new_obs = array.from(1, 2, 0, 2, 1, 0, 1) _str = '' for _o in new_obs v_obs.push(_o) vpath = viterbi(v_obs, VT, VE, v_init_p) _str += '\n' + str.format('Most likely path for observed states: {0} => {1}', str.tostring(v_obs, '0'), str.tostring(vpath, '0')) logger.queue_one(_str) // } logger.update()
Lex_3CR_Functions_Library2
https://www.tradingview.com/script/IT2DSMaN-Lex-3CR-Functions-Library2/
LexingtonStanley
https://www.tradingview.com/u/LexingtonStanley/
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/ // © LexingtonStanley //@version=5 // testing // @description This is a source code for a technical analysis library in Pine Script language, //designed to identify and mark Bullish and Bearish Three Candle Reversal (3CR) chart patterns. //The library provides three functions to be used in a trading algorithm. //The first function, Bull_3crMarker, adds a dashed line and label to a Bullish 3CR chart pattern, indicating the 3CR point. //The second function, Bear_3crMarker, adds a dashed line and label to a Bearish 3CR chart pattern. //The third function, Bull_3CRlogicals, checks for a Bullish 3CR pattern where the first candle's low is greater than the second candle's low and the second candle's low is less than the third candle's low. //If found, creates a line at the breakout point and a label at the fail point, //if specified. All functions take parameters such as the chart pattern's characteristics and output colors, labels, and markers. library("Lex_3CR_Functions_Library2", overlay = true) // @function Bull_3crMarker Adds a 3CR marker to a Bullish 3CR chart pattern // @description Adds a dashed line and label to a 3CR up chart pattern, indicating the 3CR (3 Candle Reversal) point. // @param array linearray: An array of lines to which the marker will be added // @param int barnum: The bar number at which to add the marker // @param float breakpoint: The price level at which to draw the marker // @param array failpointB: An array of 3cr float pivot point price levels // @param float failpoint: The current pivot point price // @param color linecolorbull: The color of the marker line // @param array labelarray: An array of labels to which the marker label will be added // @param color labelcolor: The color of the marker label // @param color textcolor: The color of the marker label text // @param bool labelon: Determines whether the marker label is displayed export Bull_3crMarker(line[] bulllinearray, int barnum, float breakpoint, float[] failpointB, float failpoint , color linecolorbull, label[] bulllabelarray, color labelcolor, color textcolor, bool labelon)=> colored = linecolorbull coloredlabel = labelcolor colortext = textcolor array.push(bulllinearray,line.new(barnum-3, breakpoint, barnum-1, breakpoint, extend = extend.right, style = line.style_dashed, width = 1, color = colored)) array.push(failpointB, failpoint) if labelon array.push(bulllabelarray,label.new(barnum-2, failpoint, "3CR Up", color = coloredlabel,style= label.style_triangleup, textcolor = colortext, size = size.small, yloc = yloc.belowbar)) // @function Bear_3crMarker Adds a 3CR marker to a Bearish 3CR chart pattern // @description Adds a dashed line and label to a 3CR down chart pattern, indicating the 3CR (3 Candle Reversal) point. // @param array linearray An array of lines to which the marker will be added // @param int barnum The bar number at which to add the marker // @param float breakpoint The price level at which to draw the marker // @param array failpointB An array of 3cr float pivot point price levels // @param float failpoint The current pivot point price // @param color linecolorbear The color of the marker line // @param array labelarray An array of labels to which the marker label will be added // @param color labelcolor The color of the marker label // @param color textcolor The color of the marker label text // @param bool labelon Determines whether the marker label is displayed export Bear_3crMarker(line[] bearlinearray, int barnum, float breakpoint, float[] failpointB, float failpoint , color linecolorbear, label[] bearlabelarray, color labelcolor, color textcolor, bool labelon)=> colored = linecolorbear coloredlabel = labelcolor colortext = textcolor array.push(bearlinearray,line.new(barnum-3, breakpoint, barnum-1, breakpoint, extend = extend.right, style = line.style_dashed, width = 1, color = colored)) array.push(failpointB, failpoint) if labelon array.push(bearlabelarray,label.new(barnum-2, failpoint, "3CR Down", color = coloredlabel,style= label.style_triangledown, textcolor = colortext, size = size.small, yloc = yloc.abovebar)) // @function Checks for a bullish three candle reversal pattern and creates a line and label at the breakout point if found // @description Checks for a bullish three candle reversal pattern where the first candle's low is greater than the second candle's low and the second candle's low is less than the third candle's low. If found, creates a line at the breakout point and a label at the fail point, if specified. // @param float low1 The low of the first candle in the pattern // @param float low2 The low of the second candle in the pattern // @param float low3 The low of the third candle in the pattern // @param line bulllinearray The array containing the bullish lines // @param label bulllabelarray The array containing the bullish labels // @param float failpointB An array to store the fail point value (pass by reference) // @param color linecolorbull The color of the bullish line // @param color labelcolor The color of the bullish label // @param color textcolor The color of the label text // @param bool labelon Whether to create a label at the fail point (default = false) export Bull_3CRlogicals(float low1, float low2, float low3, line[]bulllinearray, label[]bulllabelarray, float[]failpointB, color linecolorbull, color labelcolor, color textcolor, bool labelon)=> if low1 > low2 and low2 < low3 barnum = bar_index breakpoint = high[3] failpoint = low[2] boolies = labelon colorline = linecolorbull colortext = textcolor colorlabel = labelcolor bullarraye = bulllinearray bullarrayl = bulllabelarray failbull = failpointB Bull_3crMarker(bullarraye,barnum,breakpoint,failbull,failpoint,colorline,bullarrayl, colorlabel, colortext,boolies) // @function Checks for a Bearish 3CR pattern and draws a bearish marker on the chart at the appropriate location // @description This function checks for a Bearish 3CR (Three-Candle Reversal) pattern, which is defined as the second candle having a higher high than the first and third candles, and the third candle having a lower high than the first candle. If the pattern is detected, a bearish marker is drawn on the chart at the appropriate location, and an optional label can be added to the marker. // @param float high1 The highest high of the first candle in the pattern // @param float high2 The highest high of the second candle in the pattern // @param float high3 The highest high of the third candle in the pattern // @param line bearlinearray The array containing the bearish lines to be drawn // @param label bearlabelarray The array containing the bearish labels to be added (if any) // @param float failpointB The array containing the fail points for the bearish markers (if any) // @param color linecolorbear The color of the bearish marker line // @param color labelcolor The color of the bearish marker label (if any) // @param color textcolor The color of the text in the bearish marker label (if any) // @param bool labelon Whether to add a label to the bearish marker (default = true) export Bear_3CRlogicals(float high1, float high2, float high3,line[]bearlinearray, label[]bearlabelarray, float[]failpointB, color linecolorbear, color labelcolor, color textcolor, bool labelon)=> if high1 < high2 and high2 > high3 barnum = bar_index breakpoint = low[3] failpoint = high[2] boolies = labelon colorline = linecolorbear colortext = textcolor colorlabel = labelcolor beararraye = bearlinearray beararrayl = bearlabelarray failbear = failpointB Bear_3crMarker(beararraye,barnum,breakpoint,failbear,failpoint,colorline,beararrayl, colorlabel, colortext,boolies) // @function Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line // @description Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line. // @param int i The index of the line to remove // @param int barbreak The index of the bar at which the new line will begin // @param line bulllinearray The array containing the bullish lines // @param label bulllabelarray The array containing the bullish labels // @param bool labelon Whether to also remove the label associated with the line (default = true) // @param color bullcolor The color of the bullish line (default = na) // @return a new bullish 3cr line export bullLineDelete(int i, line[]bulllinearray, float[]failarray, label[]bulllabelarray, bool labelon)=> x = array.get(bulllinearray, i) highp = line.get_y1(x) barnum = line.get_x1(x) array.remove(failarray, i) if labelon currentlabel = array.get(bulllabelarray, i) array.remove(bulllabelarray,i) label.delete(currentlabel) array.remove(bulllinearray, i) line.delete(x) //p = line.new(barbreak-1, highp, barnum, highp, style = line.style_solid, width = 2, color = bullcolor ) // @function Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line // @description Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line. // @param int i The index of the line to remove // @param int barbreak The index of the bar at which the new line will begin // @param line bearlinearray The array containing the bearish lines // @param label bearlabelarray The array containing the bearish labels // @param bool labelon Whether to also remove the label associated with the line (default = true) // @param color bearcolor The color of the bearish line (default = na) // @return a new bearish 3cr line export bearLineDelete(int i, line[] bearlinearray,float[]failarray, label[]bearlabelarray, bool labelon)=> x = array.get(bearlinearray, i) lowp = line.get_y1(x) barnum = line.get_x1(x) array.remove(failarray, i) if labelon currentlabel = array.get(bearlabelarray, i) array.remove(bearlabelarray,i) label.delete(currentlabel) array.remove(bearlinearray, i) line.delete(x) //p = line.new(barbreak, lowp, barnum, lowp, style = line.style_solid, width = 2, color = bearcolor ) // @function Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line // @description Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line. // @param int i The index of the line to remove // @param line bulllinearray The array containing the bullish lines // @param label0 bulllabelarray The array containing the bullish labels // @param bool labelon Whether to also remove the label associated with the line (default = true) // @return void export bulloffsetdelete(int i, line[]bulllinearray, float[]failarray, label[]bulllabelarray, bool labelon)=> x = array.get(bulllinearray, i) array.remove(failarray, i) if labelon currentlabel = array.get(bulllabelarray, i) array.remove(bulllabelarray,i) label.delete(currentlabel) array.remove(bulllinearray, i) line.delete(x) // @function Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line // @description Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line. // @param int i The index of the line to remove // @param line bearlinearray The array containing the bearish lines // @param label bearlabelarray The array containing the bearish labels // @param bool labelon Whether to also remove the label associated with the line (default = true) // @return void export bearoffsetdelete(int i, line[]bearlinearray, float[]failarray, label[]bearlabelarray, bool labelon) => x = array.get(bearlinearray, i) array.remove(failarray, i) if labelon currentlabel = array.get(bearlabelarray, i) array.remove(bearlabelarray,i) label.delete(currentlabel) array.remove(bearlinearray, i) line.delete(x) // @function Checks if the specified value is greater than the break point of any bullish line in an array, and removes that line if true // @description Checks if the s pecified value is greater than the break point of any bullish line in an array, and removes that line if true. // @param float close1 The value to compare against the bullish lines' break points // @param line bulllinearray The array containing the bullish lines // @param label bulllabelarray The array containing the bullish labels // @param bool labelt Whether to remove the label associated with the line (default = true) // @param color bullcolored The color of the bullish line (default = na) //float riskperc = input.float(1,"Risk %",1,100) //float tp = input.float(1, "RR", 0.1, 100,0.5) //float RRperc = input.float(1,"Perc to close all") //bool RRbool = input.bool(true, "Use RR for Close or not for perc") //line a = na //float b = na //float c = na //RRperc := RRperc / 100 //equity = strategy.equity //riskperc := riskperc/100 //if Q and (RSI < rsihigh) and array.size(bullLinet) > 0 // a := array.get(bullLinet, array.size(bullLinet) - 1) // b := line.get_y1(a) // c := array.get(failarraybull, array.size(failarraybull) - 1) // lotss = (equity * riskperc) / (b - c) // lots = math.round(lotss,00) // entry = b - ((b - c) / 2) // stop = c// - ATR // RR = entry - stop // strategy.entry("3CR Long", strategy.long, lots,limit = entry) // if RRbool // strategy.exit("r", "3CR Long" ,qty_percent = 100, limit = entry + tp * RR,stop = stop) export BullEntry_setter(int i, line[]bulllinearray, float[]failpointB, float[]entrystopB, float[]entryB, bool[]entryboolB)=> bool QB = false a = array.get(bulllinearray, i) b = line.get_y1(a) c = array.get(failpointB , i) array.push(entrystopB,c) array.push(entryB, b) array.push(entryboolB, QB) //strategy.entry("3CR Bull", strategy.long, lots, entry, stop) //if RRbool // strategy.exit("EXIT", "3CR Bull",qty_percent = 100, limit = entry + (tp * RR)) export Bull3CRchecker(float close1, line[]bulllinearray,float[]FailpointB,float[]rsiB, label[]bulllabelarray, bool labelt, color bullcolored, label[]directionarray, float rsi, line[]secondbullline)=>//, float[]entrystopB, float[]entryB, bool[]entryboolB) => labelon = labelt bullybline = bulllinearray bullyblabel = bulllabelarray bullcolor = bullcolored failarray = FailpointB rizza = rsi bool Q = false if array.size(bulllinearray) > 0 for i = array.size(bulllinearray) - 1 to 0 r3c = array.get(bulllinearray, i) breakp = line.get_y1(r3c) l = line.get_x1(r3c) if close1 > breakp //and rsi < rsiinput barindex = bar_index array.push(directionarray,label.new(bar_index,close,labelt ? "Up" : na,text_font_family = font.family_monospace,yloc = yloc.abovebar, color = bullcolor, style = label.style_arrowup, textcolor = bullcolor, size = size.small, textalign = text.align_right)) if array.size(directionarray) >= 2 x = array.remove(directionarray,array.size(directionarray) - 2) label.delete(x) array.push(secondbullline,line.new(bar_index[1], breakp, l, breakp, style = line.style_solid, width = 2, color = bullcolor )) array.push(rsiB, rsi) //BullEntry_setter(i,bullybline,failarray,entrystopB,entryB,entryboolB) bullLineDelete(i,bullybline,failarray,bullyblabel,labelon) Q := true Q // @function Checks if the specified value is less than the break point of any bearish line in an array, and removes that line if true // @description Checks if the specified value is less than the break point of any bearish line in an array, and removes that line if true. // @param float close1 The value to compare against the bearish lines' break points // @param line bearlinearray The array containing the bearish lines // @param label bearlabelarray The array containing the bearish labels // @param bool labelt Whether to remove the label associated with the line // @param color bearcolored The color of the bearish line export Bear3CRchecker(float close1, line[]bearlinearray,float[]FailpointB, label[]bearlabelarray, bool labelt, color bearcolored, label[]directionarray, float rsi, line[]secondbearline, float[]rsiB) => labelon = labelt bearybline = bearlinearray bearyblabel = bearlabelarray bearcolor = bearcolored failarray = FailpointB rizza = rsi bool Q = false if array.size(bearlinearray) > 0 for i = array.size( bearlinearray) - 1 to 0 r3c = array.get(bearlinearray, i) breakp = line.get_y1(r3c) l = line.get_x1(r3c) if close1 < breakp //and rsi > rsiinput barindex = bar_index array.push(directionarray,label.new(bar_index,close,labelt ? "Down" : na, text_font_family = font.family_monospace,yloc = yloc.belowbar, color = bearcolor, style = label.style_arrowdown, textcolor = bearcolor, size = size.small, textalign = text.align_right)) if array.size(directionarray) >= 2 x = array.remove(directionarray,array.size(directionarray) - 2) label.delete(x) array.push(secondbearline,line.new(bar_index[1], breakp, l, breakp, style = line.style_solid, width = 2, color = bearcolor )) array.push(rsiB, rsi) bearLineDelete(i,bearybline,failarray,bearyblabel,labelon) Q := true Q // @function Checks the offset of bullish lines and deletes them if they are beyond a certain offset from the current bar index // @description Checks the offset of bullish lines and deletes them if they are beyond a certain offset from the current bar index // @param float FailpointB The array of fail points to check against // @param label bulllabelarray The array containing the bullish labels // @param line linearray The array containing the bullish lines // @param bool labelt Whether to remove the label associated with the line (default = true) // @param int offset The maximum allowed offset from the current bar index export Bulloffsetcheck(float[]FailpointB, label[]bulllabelarray, line[]linearray, bool labelt, int offset)=> labelon = labelt failarray = FailpointB bulllabel = bulllabelarray lineyface = linearray if array.size(lineyface) > 0 for i = array.size(linearray) - 1 to 0 barting = array.get(linearray, i ) bartingb = line.get_x1(barting) if bar_index - bartingb > offset bulloffsetdelete(i,lineyface,failarray,bulllabel,labelon) // @function Checks the offset of bearish lines and deletes them if they are beyond a certain offset from the current bar index // @description Checks the offset of bearish lines and deletes them if they are beyond a certain offset from the current bar index // @param float FailpointB The array of fail points to check against // @param label bearlabelarray The array containing the bearish labels // @param line linearray The array containing the bearish lines // @param bool labelt Whether to remove the label associated with the line (default = true) // @param int offset The maximum allowed offset from the current bar index export Bearoffsetcheck(float[]FailpointB, label[]bearlabelarray, line[]linearray, bool labelt, int offset)=> labelon = labelt failarray = FailpointB bearlabel = bearlabelarray lineyface = linearray if array.size(lineyface) > 0 for i = array.size(linearray) - 1 to 0 barting = array.get(linearray, i ) bartingb = line.get_x1(barting) if bar_index - bartingb > offset bearoffsetdelete(i,lineyface,failarray,bearlabel,labelon) // @function Checks if the current price has crossed above a bullish fail point and deletes the corresponding line and label // @description Checks if the current price has crossed above a bullish fail point and deletes the corresponding line and label // @param float close1 The current price // @param float FailpointB The array of bullish fail points // @param label bulllabelarray The array containing the bullish labels // @param line linearray The array containing the lines to check for deletion // @param bool labelt Whether to delete the label associated with the line (default = true) export Bullfailchecker(float close1, float[]FailpointB, label[]bulllabelarray, line[]linearray, bool labelt)=> labelon = labelt failarray = FailpointB bulllabel = bulllabelarray lineyface = linearray if array.size(lineyface) > 0 for i = array.size(failarray) - 1 to 0 fail = array.get(failarray, i) if close1 < fail bulloffsetdelete(i,lineyface,failarray,bulllabel,labelon) // @function Checks for bearish lines that have failed to trigger and removes them from the chart // @description This function checks for bearish lines that have failed to trigger (i.e., where the current price is above the fail point) and removes them from the chart along with any associated label. // @param float close1 The current closing price // @param float FailpointB An array containing the fail points of the bearish lines // @param label bearlabelarray The array containing the bearish labels // @param line linearray The array containing the bearish lines // @param bool labelt Whether to also remove the label associated with the line (default = true) // @return void export Bearfailchecker(float close1, float[]FailpointB, label[]bearlabelarray, line[]linearray, bool labelt)=> labelon = labelt failarray = FailpointB bearlabel = bearlabelarray lineyface = linearray if array.size(lineyface) > 0 for i = array.size(failarray) - 1 to 0 fail = array.get(failarray, i) if close1 > fail bearoffsetdelete(i,lineyface,failarray,bearlabel,labelon) // @function Checks for bullish RSI lines that have failed to trigger and removes them from the chart // @description This function checks for bullish RSI lines that have failed to trigger (i.e., where the current RSI value is below the line's trigger level) and removes them from the chart along with any associated line. // @param float rsiinput The current RSI value // @param float rsiBull An array containing the trigger levels for bullish RSI lines // @param line secondbullline The array containing the bullish RSI lines // @return void export rsibullchecker(float rsiinput, float[]rsiBull, line[]secondbullline)=> bool Q = true if array.size(rsiBull) > 0 for i = array.size(rsiBull) -1 to 0 rizza = array.get(rsiBull,i) u = array.get(secondbullline, i) if rizza > rsiinput array.remove(rsiBull, i) array.remove(secondbullline , i) line.delete(u) Q := false Q // @function Checks for bearish RSI lines that have failed to trigger and removes them from the chart // @description This function checks for bearish RSI lines that have failed to trigger (i.e., where the current RSI value is above the line's trigger level) and removes them from the chart along with any associated line. // @param float rsiinput The current RSI value // @param float rsiBear An array containing the trigger levels for bearish RSI lines // @param line secondbearline The array containing the bearish RSI lines // @return void export rsibearchecker(float rsiinput, float[]rsiBear, line[]secondbearline)=> bool Q = true if array.size(rsiBear) > 0 for i = array.size(rsiBear) -1 to 0 rizza = array.get(rsiBear,i) u = array.get(secondbearline, i) if rizza < rsiinput array.remove(rsiBear, i) array.remove(secondbearline , i) line.delete(u) Q := false Q
AstroLib
https://www.tradingview.com/script/mvz71Xp1-AstroLib/
BarefootJoey
https://www.tradingview.com/u/BarefootJoey/
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/ // Authors: © badsector666 and © BarefootJoey // ██████████████████████████████████████████████████████████████████████ _____ __ _ _______ _____ _______ _______ _______ // █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█ | | \ | |______ |_____] |_____| | |______ // ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██ __|__ | \_| ______| | | | |_____ |______ // █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██ //@version=5 library("AstroLib", overlay=true) // Internal constants tpi = math.pi * 2 pi = math.pi // // @function ToString: Easy to.string() function export t_(string txt) => str.tostring(txt) export JDNv2(float t, bool withFraction) => withFraction ? (t / 86400000) + 2440587.5 : math.floor(t / 86400000) + 2440587.5 export J2K(float t) => (t - 2451545.0) export J2KtoUnix(float TimeInJDN) => int(math.round((TimeInJDN - 2440587.5) * 86400) * 1000) export atan2(float y, float x) => if x > 0 math.atan(y/x) else if x < 0 and y >= 0 math.atan(y/x) + pi else if x < 0 and y < 0 math.atan(y/x) - pi else if x == 0 and y > 0 math.sign(x / 2) else if x == 0 and y < 0 math.sign(x / 2) else 0 // // @function DegSinRad: Input degrees, convert to radians, and output the trigonometric sine of the angle. export DegSin(float x) => DegSin = math.sin(math.toradians(x)) // // @function DegCosRad: Input degrees, convert to radians, and output the trigonometric cosine of the angle. export DegCos(float x) => DegCos = math.cos(math.toradians(x)) // // @function DegTanRad: Input degrees, convert to radians, and output the trigonometric tangent of the angle. export DegTan(float x) => DegTan = math.tan(math.toradians(x)) // // @function DegASinRad: Input radians, compute the trigonometric ArcSine of the angle, and convert to degrees. export DegArcsin(float x) => DegArcsin = math.todegrees(math.asin(x)) // // @function DegACosRad: Input radians, compute the trigonometric ArcCosine of the angle, and convert to degrees. export DegArccos(float x) => DegArccos = math.todegrees(math.acos(x)) // // @function DegATanRad: Input radians, compute the trigonometric ArcTangent of the angle, and convert to degrees. export DegArctan(float x) => DegArctan = math.todegrees(math.atan(x)) export DegAtan2(float y, float x) => DegAtan2 = math.todegrees(atan2(y, x)) < 0 ? math.todegrees(atan2(y, x)) + 360: math.todegrees(atan2(y, x)) export range2pi(float x) => x < 0 ? x - tpi * int(math.sign(x / tpi)) : x - tpi * int(x / tpi) export range360(float x) => x < 0 ? x - 360 * int(math.sign(x / 360)) : x - 360 * int(x / 360) // // @function GreenwichSidereal: Compute Sidereal time at Greenwich. export gst(float days) => T = days / 36525 gst = 280.46061837 + 360.98564736629 * days gst := gst + 0.000387933 * math.pow(T, 2) - math.pow(T, 3) / 38710000 gst := range360(gst) // // @function DegDecimal: Input degrees/minutes/seconds, and convert to a float value. export DegDecimal(float Degrees, float Minutes, float Seconds) => if Degrees < 0 Minutes > 0 ? Minutes * (-1) : Minutes Seconds > 0 ? Seconds * (-1) : Seconds DegDecimal = Degrees + (Minutes) + (Seconds / 3600) export Rectangular(float R, float theta, float phi, float Index) => r_cos_theta = R * DegCos(theta) switch Index 1 => Rectangular = r_cos_theta * DegCos(phi) 2 => Rectangular = r_cos_theta * DegSin(phi) 3 => Rectangular = R * DegSin(theta) export rLength(float x, float y, float z) => rLength = math.sqrt(x * x + y * y + z * z) export spherical(float x, float y, float z, float Index) => rho = x * x + y * y switch Index 1 => spherical = math.sqrt(rho + z * z) 2 => rho := math.sqrt(rho) spherical = DegArctan(z / rho) 3 => rho := math.sqrt(rho) spherical = DegAtan2(y, x) // // @function Obliquity: Input a day, and calculate obliquity. export obliquity(float d) => T = d / 36525 obliquity = -(46.815 + (0.00059 - 0.001813 * T) * T) * T / 3600 obliquity2 = obliquity + 23.43929111 // // @function Equitorial: Calculate the equatorial coordinates. export requatorial(float x, float y, float z, float d, float Index) => obl = obliquity(d) switch Index 1 => requatorial = x 2 => requatorial = y * DegCos(obl) - z * DegSin(obl) 3 => requatorial = y * DegSin(obl) + z * DegCos(obl) // // @function Ecliptic: Calculate the ecliptic coordinates. export recliptic(float x, float y, float z, float d, float Index) => obl = obliquity(d) switch Index 1 => recliptic = x 2 => recliptic = y * DegCos(obl) + z * DegSin(obl) 3 => recliptic = -y * DegSin(obl) + z * DegCos(obl) export sequatorial(float R, float theta, float phi, float d, float Index) => x = Rectangular(R, theta, phi, 1) y = Rectangular(R, theta, phi, 2) z = Rectangular(R, theta, phi, 3) sequatorial = spherical(requatorial(x, y, z, d, 1), requatorial(x, y, z, d, 2), requatorial(x, y, z, d, 3), Index) export secliptic(float R, float theta, float phi, float d, float Index) => x = Rectangular(R, theta, phi, 1) y = Rectangular(R, theta, phi, 2) z = Rectangular(R, theta, phi, 3) secliptic = spherical(recliptic(x, y, z, d, 1), recliptic(x, y, z, d, 2), recliptic(x, y, z, d, 3), Index) export precess(float d1, float d2, float DEC, float RA, float Index, float ddec, float dra) => dra2 = na(dra) ? 0 : dra ddec2 = na(ddec) ? 0 : ddec T = d1 / 36525 m = 0.01281233333333 + 0.00000775 * T N = 0.005567527777778 - 2.361111111111E-06 * T T2 = (d2 - d1) / 365.25 switch Index 1 => precess = DEC + (N * DegCos(RA) + ddec2 / 3600) * T2 2 => precess = RA + (m + N * DegSin(RA) * DegTan(DEC) + dra2 / 3600) * T2 export riset(float J2000, float DEC, float RA, float GLat, float GLong, float Index) => lst = gst(J2000) + GLong tau = DegSin(-34 / 60) - DegSin(GLat) * DegSin(DEC) tau := tau / (DegCos(GLat) * DegCos(DEC)) tau := DegArccos(tau) switch Index 1 => riset = range360(360 - 0.9972696 * (lst - RA + tau)) 2 => if RA > lst riset = math.abs(0.9972696 * (lst - RA)) else riset = 360 - 0.9972696 * (lst - RA) 3 => riset = range360(0.9972696 * (RA + tau - lst)) export ssun(float d, float Index) => g = range360(357.528 + 0.9856003 * d) L = range360(280.461 + 0.9856474 * d) switch Index 1 => ssun = 1.00014 - 0.01671 * DegCos(g) - 0.00014 * DegCos(2 * g) 2 => ssun = 0 3 => ssun = range360(L + 1.915 * DegSin(g) + 0.02 * DegSin(2 * g)) 4 => lambda = range360(L + 1.915 * DegSin(g) + 0.02 * DegSin(2 * g)) ssun = -1.915 * DegSin(g) - 0.02 * DegSin(2 * g) ssun := ssun + 2.466 * DegSin(2 * lambda) ssun := ssun - 0.053 * DegSin(4 * lambda) export rsun(float d, float Index) => rsun = Rectangular(ssun(d, 1), ssun(d, 2), ssun(d, 3), Index) export sun(float d, float Index) => sun = sequatorial(ssun(d, 1), ssun(d, 2), ssun(d, 3), d, Index) export SunLongitude(float d, float Index) => T = d / 36525 L0 = 280.46646 + 36000.76983 * T + 0.0003032 * T * T L0 := range360(L0) m = 357.52911 + 35999.05029 * T - (0.0001537 * T * T) m := range360(m) e = 0.016708634 - 0.000042037 * T - (0.0000001267 * T * T) C = (1.914602 - 0.004817 * T - 0.000014 * T * T) * DegSin(m) + (0.019993 - 0.000101 * T) * DegSin(2 * m) + 0.000289 * DegSin(3 * m) O = L0 + C lam = 0.0 if Index == 2 ohm = 125.04 - 1934.136 * T lam := O - 0.00569 - 0.00478 * DegSin(ohm) if Index == 1 SunLongitude = O else SunLongitude = lam export Sunrise(float J2000, float GLat, float GLong, float Index, float altitudex) => altitude = na(altitudex) or altitudex == 0 ? -0.833 : altitudex utold = 180.0 utnew = 0.0 sinalt = math.sin(math.toradians(altitude)) sinphi = DegSin(GLat) cosphi = DegCos(GLat) signt = Index == 1 ? 1 : -1 while math.abs(utold - utnew) > 0.1 utold := utnew days = J2000 + utold / 360 T = days / 36525 L = range360(280.46 + 36000.77 * T) g = 357.528 + 35999.05 * T lambda = L + 1.915 * DegSin(g) + 0.02 * DegSin(2 * g) e = -1.915 * DegSin(g) - 0.02 * DegSin(2 * g) + 2.466 * DegSin(2 * lambda) - 0.053 * DegSin(4 * lambda) obl = 23.4393 - 0.13 * T gha = utold + (-180 + e) delta = DegArcsin(DegSin(obl) * DegSin(lambda)) C = (sinalt - sinphi * DegSin(delta)) / (cosphi * DegCos(delta)) act = DegArccos(C) if C > 1 act := 0 if C < -1 act := 180 utnew := range360(utold - (gha + GLong + signt * act)) Sunrise = utnew export smoon(float dx, float Index) => d = dx + 1.5 Nm = math.toradians(range360(125.1228 - 0.0529538083 * d)) im = math.toradians(5.1454) * 100 wm = math.toradians(range360(318.0634 + 0.1643573223 * d)) am = 60.2666 ecm = 0.0549 Mm = math.toradians(range360(115.3654 + 13.0649929509 * d)) em = Mm + ecm * math.sin(Mm) * (1 + ecm * math.cos(Mm)) xv = am * (math.cos(em) - ecm) yv = am * (math.sqrt(1 - ecm * ecm) * math.sin(em)) vm = atan2(yv, xv) rm = math.sqrt(xv * xv + yv * yv) x = math.cos(Nm) * math.cos(vm + wm)- math.sin(Nm) * math.sin(vm + wm) * math.cos((im / 100)) x := rm * x y = math.sin(Nm) * math.cos(vm + wm) + math.cos(Nm) * math.sin(vm + wm) * math.cos((im / 100)) y := rm * y z = rm * (math.sin(vm + wm) * math.sin((im / 100))) lon = atan2(y, x) lon2 = lon < 0 ? tpi + lon : lon lat = math.atan(z / math.sqrt(x * x + y * y)) ws = math.toradians(range360(282.9404 + 0.0000470935 * d)) Ms = math.toradians(range360(356.047 + 0.9856002585 * d)) ls = Ms + ws lm = Mm + wm + Nm dm = lm - ls f = lm - Nm switch Index 1 => rm := rm - 0.58 * math.cos(Mm - 2 * dm) rm := rm - 0.46 * math.cos(2 * dm) smoon = rm 2 => dlat = -0.173 * math.sin(f - 2 * dm) dlat := dlat - 0.055 * math.sin(Mm - f - 2 * dm) dlat := dlat - 0.046 * math.sin(Mm + f - 2 * dm) dlat := dlat + 0.033 * math.sin(f + 2 * dm) dlat := dlat + 0.017 * math.sin(2 * Mm + f) smoon = math.todegrees(lat) + dlat 3 => dlon = -1.274 * math.sin(Mm - 2 * dm) dlon := dlon + 0.658 * math.sin(2 * dm) dlon := dlon - 0.186 * math.sin(Ms) dlon := dlon - 0.059 * math.sin(2 * Mm - 2 * dm) dlon := dlon - 0.057 * math.sin(Mm - 2 * dm + Ms) dlon := dlon + 0.053 * math.sin(Mm + 2 * dm) dlon := dlon + 0.046 * math.sin(2 * dm - Ms) dlon := dlon + 0.041 * math.sin(Mm - Ms) dlon := dlon - 0.035 * math.sin(dm) dlon := dlon - 0.031 * math.sin(Mm + Ms) dlon := dlon - 0.015 * math.sin(2 * f - 2 * dm) dlon := dlon + 0.011 * math.sin(Mm - 4 * dm) smoon = math.todegrees(lon2) + dlon export rmoon(float d, float Index) => rmoon = Rectangular(smoon(d, 1), smoon(d, 2), smoon(d, 3), Index) export tmoon(float d, float GLat, float GLong, float Index) => x = rmoon(d, 1) y = rmoon(d, 2) z = rmoon(d, 3) xe = requatorial(x, y, z, d, 1) ye = requatorial(x, y, z, d, 2) ze = requatorial(x, y, z, d, 3) R = rLength(x, y, z) lst = gst(d) + GLong xt = xe - DegCos(GLat) * DegCos(lst) yt = ye - DegCos(GLat) * DegSin(lst) zt = ze - DegSin(GLat) tmoon = spherical(xt, yt, zt, Index) export moon(float d, float Index) => if Index == 4 nigel = smoon(d, 2) moon = d else moon = sequatorial(smoon(d, 1), smoon(d, 2), smoon(d, 3), d, Index) // // @function KeplerianElements: Input a day and planet number, and outputs the following Keplerian Elements: semi major axis, eccentricity, inclination, mean longitude, longitude of the ascending node, and longitude of the perhelion. export Element(float d, int pnum) => switch pnum 1 => // Mercury I = math.toradians(7.00487 - 0.000000178797 * d) O = math.toradians(48.33167 - 0.0000033942 * d) P = math.toradians(77.45645 + 0.00000436208 * d) a = 0.38709893 + 1.80698E-11 * d e = 0.20563069 + 0.000000000691855 * d L = range2pi(math.toradians(252.25084 + 4.092338796 * d)) [I, O, P, a, e, L] 2 => // Venus I = math.toradians(3.39471 - 0.0000000217507 * d) O = math.toradians(76.68069 - 0.0000075815 * d) P = math.toradians(131.53298 - 0.000000827439 * d) a = 0.72333199 + 2.51882E-11 * d e = 0.00677323 - 0.00000000135195 * d L = range2pi(math.toradians(181.97973 + 1.602130474 * d)) [I, O, P, a, e, L] 3 => // Earth I = math.toradians(0.00005 - 0.000000356985 * d) O = math.toradians(-11.26064 - 0.00013863 * d) P = math.toradians(102.94719 + 0.00000911309 * d) a = 1.00000011 - 1.36893E-12 * d e = 0.01671022 - 0.00000000104148 * d L = range2pi(math.toradians(100.46435 + 0.985609101 * d)) [I, O, P, a, e, L] 4 => // Mars I = math.toradians(1.85061 - 0.000000193703 * d) O = math.toradians(49.57854 - 0.0000077587 * d) P = math.toradians(336.04084 + 0.00001187 * d) a = 1.52366231 - 0.000000001977 * d e = 0.09341233 - 0.00000000325859 * d L = range2pi(math.toradians(355.45332 + 0.524033035 * d)) [I, O, P, a, e, L] 5 => // Jupiter I = math.toradians(1.3053 - 0.0000000315613 * d) O = math.toradians(100.55615 + 0.00000925675 * d) P = math.toradians(14.75385 + 0.00000638779 * d) a = 5.20336301 + 0.0000000166289 * d e = 0.04839266 - 0.00000000352635 * d L = range2pi(math.toradians(34.40438 + 0.083086762 * d)) [I, O, P, a, e, L] 6 => // Saturn I = math.toradians(2.48446 + 0.0000000464674 * d) O = math.toradians(113.71504 - 0.0000121 * d) P = math.toradians(92.43194 - 0.0000148216 * d) a = 9.53707032 - 0.0000000825544 * d e = 0.0541506 - 0.0000000100649 * d L = range2pi(math.toradians(49.94432 + 0.033470629 * d)) [I, O, P, a, e, L] 7 => // Uranus I = math.toradians(0.76986 - 0.0000000158947 * d) O = math.toradians(74.22988 + 0.0000127873 * d) P = math.toradians(170.96424 + 0.0000099822 * d) a = 19.19126393 + 0.0000000416222 * d e = 0.04716771 - 0.00000000524298 * d L = range2pi(math.toradians(313.23218 + 0.011731294 * d)) [I, O, P, a, e, L] 8 => // Neptune I = math.toradians(1.76917 - 0.0000000276827 * d) O = math.toradians(131.72169 - 0.0000011503 * d) P = math.toradians(44.97135 - 0.00000642201 * d) a = 30.06896348 - 0.0000000342768 * d e = 0.00858587 + 0.000000000688296 * d L = range2pi(math.toradians(304.88003 + 0.0059810572 * d)) [I, O, P, a, e, L] 9 => // Pluto? I = math.toradians(17.14175 + 0.0000000841889 * d) O = math.toradians(110.30347 - 0.0000002839 * d) P = math.toradians(224.06676 - 0.00000100578 * d) a = 39.48168677 - 0.0000000210574 * d e = 0.24880766 + 0.00000000177002 * d L = range2pi(math.toradians(238.92881 + 3.97557152635181E-03 * d)) [I, O, P, a, e, L] // // @function KeplerSolve: Input mean anomaly, eccintricity, and eps, Solution of Kepler's Equation. export kepler(float m, float ecc, float eps) => e = m delta = 0.05 eps2 = na(eps) ? 8 : eps while math.abs(delta) >= math.pow(10, -eps2) delta := e - ecc * math.sin(e) - m e := e - delta / (1 - ecc * math.cos(e)) V = 2 * math.atan( math.pow( ((1 + ecc) / (1 - ecc)), 0.5) * math.tan(0.5 * e)) if V < 0 V := V + tpi kepler = V export rplanet(float d, int pnumber, float Index) => [I, O, P, a, e, L] = Element(d, pnumber) m = range2pi(L - P) V = kepler(m, e, 8) R = a * (1 - e * e) / (1 + e * math.cos(V)) switch Index 1 => rplanet = math.cos(O) * math.cos(V + P - O) - math.sin(O) * math.sin(V + P - O) * math.cos(I) rplanet := rplanet * R 2 => rplanet = math.sin(O) * math.cos(V + P - O) + math.cos(O) * math.sin(V + P - O) * math.cos(I) rplanet := rplanet * R 3 => rplanet = R * (math.sin(V + P - O) * math.sin(I)) export planet(float d, int pnumber, float Index) => [I, O, P, a, e, L] = Element(d, pnumber) m = range2pi(L - P) V = kepler(m, e, 8) R = a * (1 - e * e) / (1 + e * math.cos(V)) s1 = math.sin(V + P - O) si = math.sin(I) so = math.sin(O) C1 = math.cos(V + P - O) CI = math.cos(I) co = math.cos(O) x = R * (co * C1 - so * s1 * CI) y = R * (so * C1 + co * s1 * CI) z = R * (s1 * si) [Ie, Oe, Pe, ae, ee, Le] = Element(d, 3) m2 = range2pi(Le - Pe) V2 = kepler(m2, ee, 8) R2 = ae * (1 - ee * ee) / (1 + ee * math.cos(V2)) s12 = math.sin(V2 + Pe - Oe) si2 = math.sin(Ie) so2 = math.sin(Oe) C12 = math.cos(V2 + Pe - Oe) CI2 = math.cos(Ie) co2 = math.cos(Oe) xe = R2 * (co2 * C12 - so2 * s12 * CI2) ye = R2 * (so2 * C12 + co2 * s12 * CI2) ze = R2 * (s12 * si2) x := x - xe y := y - ye ecl = math.toradians(23.429292) xe := x ye := y * math.cos(ecl) - z * math.sin(ecl) ze := y * math.sin(ecl) + z * math.cos(ecl) switch Index 3 => planet = math.todegrees(atan2(ye, xe)) < 0 ? math.todegrees(atan2(ye, xe)) + 360: math.todegrees(atan2(ye, xe)) 2 => planet = math.todegrees(math.atan(ze / math.sqrt(xe * xe + ye * ye))) 1 => planet = math.sqrt(xe * xe + ye * ye + ze * ze) export altaz(float d, float DEC, float RA, float GLat, float GLong, float Index) => h = gst(d) + GLong - RA sa = DegSin(DEC) * DegSin(GLat) sa := sa + DegCos(DEC) * DegCos(GLat) * DegCos(h) a = DegArcsin(sa) cz = DegSin(DEC) - DegSin(GLat) * sa cz := cz / (DegCos(GLat) * DegCos(a)) switch Index 1 => altaz = a 2 => if DegSin(h) < 0 altaz = DegArccos(cz) else altaz = 360 - DegArccos(cz) export prise(float d, int P, float GLat, float GLong, float Index) => count = 0 flag = 2 - Index ut0 = 0.0 ut1 = 180.0 slt = DegSin(GLat) clt = DegCos(GLat) while math.abs(ut0 - ut1) > 0.1 and count < 10 count := count + 1 ut0 := ut1 DEC = planet(d + ut0 / 360, P, 2) RA = planet(d + ut0 / 360, P, 3) tau = (-0.009890037858741 - slt * DegSin(DEC)) / (clt * DegCos(DEC)) switch tau tau >= 1 => tau := 180 tau <= -1 => tau := -180 => tau := DegArccos(tau) lst = gst(d + ut0 / 360) + GLong ut1 := range360(ut0 - 0.9972696 * (lst - RA + flag * tau)) prise = ut1 export MoonSize(float d) => EarthMoonDist = moon(d, 1) MoonSize = DegArctan(3476.28 / (EarthMoonDist * 6371)) * 3600 export Refraction(float Temperature_C, float Atmospheric_Pressure_mBar, float Altitude_Deg) => P = Atmospheric_Pressure_mBar a = Altitude_Deg T = Temperature_C if a >= 15 Refraction = (0.00452 * P) / ((273 + T) * DegTan(a)) else Refraction = (P * (0.1594 + 0.0196 * a + 0.00002 * a * a)) / ((273 + T) * (1 + 0.505 * a + 0.0845 * a * a)) export MoonRise(float d, float Longitude, float Latitude, float Index) => dr = int(d) + 0.5 RA = tmoon(dr, Latitude, Longitude, 3) DEC = tmoon(dr, Latitude, Longitude, 2) Time0 = (riset(dr, DEC, RA, Latitude, Longitude, Index)) / 360 Time0 := Time0 + dr RA := tmoon(Time0, Latitude, Longitude, 3) DEC := tmoon(Time0, Latitude, Longitude, 2) Time1 = (riset(dr, DEC, RA, Latitude, Longitude, Index)) / 360 Time1 := Time1 + dr RA := tmoon(Time1 - (1.0 / 24), Latitude, Longitude, 3) DEC := tmoon(Time1 - (1.0 / 24), Latitude, Longitude, 2) Alt_old = altaz(Time1 - 1.0 / 24, DEC, RA, Latitude, Longitude, 1) moonRadius = MoonSize(Time1) / 3600 moonRadius := moonRadius / 2 MoonRefraction = Refraction(0, 1013.25, 0) Alt_old := math.abs(Alt_old + moonRadius + MoonRefraction) fraction = (1.0 / 24 / 60) for i = -59 to 60 RA := tmoon(Time1 + fraction * i, Latitude, Longitude, 3) DEC := tmoon(Time1 + fraction * i, Latitude, Longitude, 2) Alt = altaz(Time1 + fraction * i, DEC, RA, Latitude, Longitude, 1) Alt := math.abs(Alt + moonRadius + MoonRefraction) if Index == 2 if Alt < Alt_old Alt := Alt_old Time1 := Time1 + ((i - 1) / 24 / 60) break Alt_old := Alt else if Alt > Alt_old Alt := Alt_old Time1 := Time1 + ((i - 1) / 24 / 60) break Alt_old := Alt continue MoonRise = Time1 - dr if Time1 - dr < 0 MoonRise := Time1 - dr + 1 else MoonRise := Time1 - dr export f_to_sec(float dec) => sec = (dec * 24 * 60 * 60) export f_to_time(float sec) => hh = math.floor(sec / 3600) % 24 mm = math.floor(sec / 60 % 60) ss = math.floor(sec % 60) totime = str.tostring(hh) + ":" + str.tostring(mm) + ":" + str.tostring(ss) export deg_to_time(float deg) => hh = int(deg) mm = int((deg - int(deg)) * 60) ss = int((((deg-hh)*60)-mm)*60) totime = str.tostring(hh) + ":" + str.tostring(mm) + ":" + str.tostring(ss) export toDMS(float coordinate) => absolute = math.abs(coordinate) degrees = math.floor(absolute) minutesNotTruncated = (absolute - degrees) * 60 minutes = math.floor(minutesNotTruncated) seconds = math.floor((minutesNotTruncated - minutes) * 60) str.tostring(degrees) + "° " + str.tostring(minutes) + "' " + str.tostring(seconds) export convertDMS(float lat, float lng) => lati = toDMS(lat) latitudeCardinal = lat >= 0 ? "N" : "S" longi = toDMS(lng) longitudeCardinal = lng >= 0 ? "E" : "W" str.tostring(lati) + " " + str.tostring(latitudeCardinal) + "\n" + str.tostring(longi) + " " + str.tostring(longitudeCardinal) export convlatdec(float deg) => cCardinal = deg >= 0 ? "N" : "S" absolute = math.abs(deg) degrees = math.floor(absolute) minutesNotTruncated = (absolute - degrees) * 60 minutes = math.floor(minutesNotTruncated) str.tostring(degrees) + "° " + cCardinal + " " + str.tostring(minutes) + "'" // // @function PlanetName: Input planet number and output the name export PlanetName(int pnum) => switch pnum 1 => " Mercury " 2 => " Venus " 3 => " Moon " 4 => " Mars " 5 => " Jupiter " 6 => " Saturn " 7 => " Uranus " 8 => " Neptune " 9 => " Pluto " 10 => " Sun " 11 => " Earth " 12 => " Juno " 13 => " Vesta " 14 => " Ceres " 15 => " True Lilith " 16 => " Mean Lilith " 17 => " North Node " 18 => " South Node " // // @function PlanetNameVedic: Input planet number and output the Vedic name export PlanetNameV(int pnum) => switch pnum 1 => " Bhudha " 2 => " Shukra " 3 => " Chandra Sandu " 4 => " Mangal " 5 => " Guru " 6 => " Shani " 7 => " Uranus " 8 => " Neptune " 9 => " Pluto " // // @function PlanetName: Input planet number and output the name export PlanetSign(int pnum) => switch pnum 1 => " ☿ " 2 => " ♀ " 3 => " ☽︎ " 4 => " ♂ " 5 => " ♃ " 6 => " ♄ " 7 => " ⛢ " 8 => " ♆ " 9 => " ♇ " 10 => " ☉︎ " 11 => " 🜨 " 12 => " ⚵ " 13 => " ⚶ " 14 => " ⚳ " 15 => " ⚸ " 16 => " ⚸ " 17 => " ☊ " 18 => " ☋ " // // @function PlanetColor: Input planet number and output the color export PlanetColor(int pnum) => switch pnum 1 => color.maroon 2 => color.green 3 => color.silver 4 => color.red 5 => color.orange 6 => color.gray 7 => color.blue 8 => color.fuchsia 9 => color.black 10 => color.yellow 11 => color.gray 12 => #856c44 13 => #856c44 14 => color.gray 15 => color.black 16 => color.black 17 => color.white 18 => color.black // // @function DegreeToZodiacColor: Input degrees and output the Zodiac color export zodiaccolor(float deg) => deg > 0 and deg < 30 ? color.red : deg >= 30 and deg < 60 ? color.orange : deg >= 60 and deg < 90 ? color.yellow : deg >= 90 and deg < 120 ? color.green : deg >= 120 and deg < 150 ? color.blue : deg >= 150 and deg < 180 ? color.navy : deg >= 180 and deg < 210 ? color.purple : deg >= 210 and deg < 240 ? color.navy : deg >= 240 and deg < 270 ? color.blue : deg >= 270 and deg < 300 ? color.green : deg >= 300 and deg < 330 ? color.yellow : deg >= 330 and deg < 360 ? color.orange : color.gray // // @function DegreeToSign: Input degrees and output the Zodiac symbol export degsign(float deg) => sign = math.floor(deg / 30) switch sign 0 => str.tostring(int(deg % 30)) + " ♈︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 1 => str.tostring(int(deg % 30)) + " ♉︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 2 => str.tostring(int(deg % 30)) + " ♊︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 3 => str.tostring(int(deg % 30)) + " ♋︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 4 => str.tostring(int(deg % 30)) + " ♌︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 5 => str.tostring(int(deg % 30)) + " ♍︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 6 => str.tostring(int(deg % 30)) + " ♎︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 7 => str.tostring(int(deg % 30)) + " ♏︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 8 => str.tostring(int(deg % 30)) + " ♐︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 9 => str.tostring(int(deg % 30)) + " ♑︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 10 => str.tostring(int(deg % 30)) + " ♒︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 11 => str.tostring(int(deg % 30)) + " ♓︎ " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) // // @function DegreeToSignFull: Input degrees and output the full Zodiac symbol export degsignf(float deg) => sign = math.floor(deg / 30) switch sign 0 => str.tostring(int(deg % 30)) + " ♈︎ Aries " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 1 => str.tostring(int(deg % 30)) + " ♉︎ Taurus " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 2 => str.tostring(int(deg % 30)) + " ♊︎ Gemini " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 3 => str.tostring(int(deg % 30)) + " ♋︎ Cancer " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 4 => str.tostring(int(deg % 30)) + " ♌︎ Leo " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 5 => str.tostring(int(deg % 30)) + " ♍︎ Virgo " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 6 => str.tostring(int(deg % 30)) + " ♎︎ Libra " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 7 => str.tostring(int(deg % 30)) + " ♏︎ Scorpio " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 8 => str.tostring(int(deg % 30)) + " ♐︎ Saggitarius " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 9 => str.tostring(int(deg % 30)) + " ♑︎ Capricorn " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 10 => str.tostring(int(deg % 30)) + " ♒︎ Aquarius " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 11 => str.tostring(int(deg % 30)) + " ♓︎ Pisces " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) // // @function DegreeToNakshatra: Input degrees and output the Vedic Nakshatra export degnash(float deg) => sign = math.floor(deg / 13.20) switch sign 0 => "Ashwini" 1 => "Bharani" 2 => "Krittika" 3 => "Rohini" 4 => "Mrigashirsha" 5 => "Ardra" 6 => "Punarvasu" 7 => "Pushya" 8 => "Ashlesha" 9 => "Magha" 10 => "Purva Phalguni" 11 => "Uttara Phalguni" 12 => "Hasta" 13 => "Chitra" 14 => "Swati" 15 => "Vishakha" 16 => "Anuradha" 17 => "Jyeshta" 18 => "Mula" 19 => "Purva Ashadha" 20 => "Uttara Ashadha" 21 => "Shravana" 22 => "Dhanistha" 23 => "Shatabhisha" 24 => "Purva Bhadrapada" 25 => "Uttara Bhadrapada" 26 => "Revathi" // // @function DegreeToSignName: Input degrees and output the Zodiac name export degname(float deg) => sign = math.floor(deg / 30) switch sign 0 => str.tostring(int(deg % 30)) + " Aries " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 1 => str.tostring(int(deg % 30)) + " Taurus " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 2 => str.tostring(int(deg % 30)) + " Gemini " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 3 => str.tostring(int(deg % 30)) + " Cancer " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 4 => str.tostring(int(deg % 30)) + " Leo " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 5 => str.tostring(int(deg % 30)) + " Virgo " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 6 => str.tostring(int(deg % 30)) + " Libra " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 7 => str.tostring(int(deg % 30)) + " Scorpio " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 8 => str.tostring(int(deg % 30)) + " Sagittarius " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 9 => str.tostring(int(deg % 30)) + " Capricorn " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 10 => str.tostring(int(deg % 30)) + " Aquarius " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) 11 => str.tostring(int(deg % 30)) + " Pisces " + str.tostring(math.round(((deg % 30) - int(deg % 30)) * 60, 2)) // // @function RetrogradeSymbol: Input the variable for a planet's longitude and if the planet is in retrograde display a ℞ symbol export retrogradesym(float deg) => deg > deg[1] ? "" : " ℞ " // // @function DegreeToAspect: Input degrees and output the (English) Planetary Aspect sign export degaspsign(float deg) => sign = math.floor(deg / 30) switch sign 0 => " ☌ " 1 => " ⊻ " 2 => " 🞶 " 3 => " □ " 4 => " △ " 5 => " ⊼ " 6 => " ☍ " 7 => " ⊼ " 8 => " △ " 9 => " □ " 10 => " 🞶 " 11 => " ⊻ " // // @function DegreeToAspectName: Input degrees and output the (English) Planetary Aspect name export degaspname(float deg) => sign = math.floor(deg / 30) switch sign 0 => " Conjunction " 1 => " Semi Sextile " 2 => " Sextile " 3 => " Square " 4 => " Trine " 5 => " Inconjunct " 6 => " Opposition " 7 => " Inconjunct " 8 => " Trine " 9 => " Square " 10 => " Sextile " 11 => " Semi Sextile " // // @function DegreeToAspect: Input degrees and output the (English) Planetary Aspect sign, name, and angle export degaspfull(float deg) => sign = math.floor(deg / 30) switch sign 0 => " ☌ Conjunction 0° " 1 => " ⊻ Semi Sextile 30° " 2 => " 🞶 Sextile 60° " 3 => " □ Square 90° " 4 => " △ Trine 120° " 5 => " ⊼ Inconjunct 150° " 6 => " ☍ Opposition 180° " 7 => " ⊼ Inconjunct 210° " 8 => " △ Trine 240° " 9 => " □ Square 270° " 10 => " 🞶 Sextile 300° " 11 => " ⊻ Semi Sextile 330° " // // @function DegreeToAspect: Version 2: Input degrees and output the (English) Planetary Aspect sign, name, and angle export degaspfullV2(float deg) => sign = math.round(deg / 30) switch sign 0 => " ☌ Conjunction 0° " 1 => " ⊻ Semi Sextile 30° " 2 => " 🞶 Sextile 60° " 3 => " □ Square 90° " 4 => " △ Trine 120° " 5 => " ⊼ Inconjunct 150° " 6 => " ☍ Opposition 180° " 7 => " ⊼ Inconjunct 210° " 8 => " △ Trine 240° " 9 => " □ Square 270° " 10 => " 🞶 Sextile 300° " 11 => " ⊻ Semi Sextile 330° " // // @function DegreeToAspectName: Input degrees and output the (English) Planetary Aspect name export degaspnameV2(float deg) => sign = math.floor(deg / 30) switch sign 0 => " Conjunction " 1 => " Semi Sextile " 2 => " Sextile " 3 => " Square " 4 => " Trine " 5 => " Inconjunct " 6 => " Opposition " 7 => " Inconjunct " 8 => " Trine " 9 => " Square " 10 => " Sextile " 11 => " Semi Sextile " export degtolowest180(float deg) => degout = deg>180 ? 360-deg : deg degout2 = degout>180 ? 360-degout : degout // // @function DegreeToApproachingAspect: Input degrees and output the (English) approaching Planetary Aspect sign, name, and angle export degaspfullapproach(float deg) => sign = math.floor(deg / 30) switch sign 11 => " ☌ Conjunction 0° " 0 => " ⊻ Semi Sextile 30° " 1 => " 🞶 Sextile 60° " 2 => " □ Square 90° " 3 => " △ Trine 120° " 4 => " ⊼ Inconjunct 150° " 5 => " ☍ Opposition 180° " 6 => " ⊼ Inconjunct 210° " 7 => " △ Trine 240° " 8 => " □ Square 270° " 9 => " 🞶 Sextile 300° " 10 => " ⊻ Semi Sextile 330° " // // @function AspectColors: Input an angle and output the corresponding bullish or bearish aspect color. export virinchiaspectcol(float deg, color bull_col, color bear_col) => deg_out = math.round(deg) deg_out == 0 ? bull_col: deg_out == 6 ? bull_col : deg_out == 9 ? bull_col : deg_out == 12 ? bull_col : deg_out == 15 ? bear_col : deg_out == 18 ? bull_col : deg_out == 20 ? bear_col : //deg_out == 22.5 ? bear_col : deg_out == 24 ? bull_col : deg_out == 30 ? bull_col : deg_out == 36 ? bull_col : deg_out == 40 ? bull_col : deg_out == 45 ? bull_col : deg_out == 60 ? bull_col : deg_out == 72 ? bull_col : deg_out == 90 ? bear_col : deg_out == 120 ? bear_col : deg_out == 135 ? bull_col : deg_out == 144 ? bear_col : deg_out == 150 ? bull_col : deg_out == 180 ? bear_col : na // // @function AspectEmojis: Input an angle and output the corresponding bullish or bearish aspect emoji. export virinchiaspectemo(float deg, string bull_emo, string bear_emo) => deg_out = math.round(deg) deg_out == 0 ? bull_emo: deg_out == 6 ? bull_emo : deg_out == 9 ? bull_emo : deg_out == 12 ? bull_emo : deg_out == 15 ? bear_emo : deg_out == 18 ? bull_emo : deg_out == 20 ? bear_emo : //deg_out == 22.5 ? bear_emo : deg_out == 24 ? bull_emo : deg_out == 30 ? bull_emo : deg_out == 36 ? bull_emo : deg_out == 40 ? bull_emo : deg_out == 45 ? bull_emo : deg_out == 60 ? bull_emo : deg_out == 72 ? bull_emo : deg_out == 90 ? bear_emo : deg_out == 120 ? bear_emo : deg_out == 135 ? bull_emo : deg_out == 144 ? bear_emo : deg_out == 150 ? bull_emo : deg_out == 180 ? bear_emo : na // // @function FastAspectSign&Degree: Input an angle and output the corresponding aspect sign & degree for fast planets (within 3 degrees). export aspectfastsigndeg(float deg) => deg > 0 and deg < 3 ? " ☌ 0° " : deg > 27 and deg < 33 ? " ⊻ 30° " : deg > 57 and deg < 63 ? " 🞶 60° " : deg > 87 and deg < 93 ? " □ 90° " : deg > 117 and deg < 123 ? " △ 120° " : deg > 147 and deg < 153 ? " ⊼ 150° " : deg > 177 and deg < 180 ? " ☍ 180° " : str.tostring(deg,"#") // // @function FastAspectFull: Input an angle and output the corresponding aspect details for fast planets (within 3 degrees). export aspectfastfull(float deg) => deg > 0 and deg < 3 ? " ☌ Conjunction 0° " : deg > 27 and deg < 33 ? " ⊻ Semi Sextile 30° " : deg > 57 and deg < 63 ? " 🞶 Sextile 60° " : deg > 87 and deg < 93 ? " □ Square 90° " : deg > 117 and deg < 123 ? " △ Trine 120° " : deg > 147 and deg < 153 ? " ⊼ Inconjunct 150° " : deg > 177 and deg < 180 ? " ☍ Oppostiion 180° " : str.tostring(deg,"#") // // @function SlowAspectFull: Input an angle and output the corresponding aspect details for slow planets (within 6 degrees). export aspectslowfull(float deg) => deg > 0 and deg < 6 ? " ☌ Conjunction 0° " : deg > 24 and deg < 36 ? " ⊻ Semi Sextile 30° " : deg > 54 and deg < 66 ? " 🞶 Sextile 60° " : deg > 84 and deg < 96 ? " □ Square 90° " : deg > 114 and deg < 126 ? " △ Trine 120° " : deg > 144 and deg < 156 ? " ⊼ Inconjunct 150° " : deg > 174 and deg < 180 ? " ☍ Oppostiion 180° " : str.tostring(deg,"#") // // @function SlowAspectSign&Degree: Input an angle and output the corresponding aspect sign & degree for slow planets (within 6 degrees). export aspectslowsigndeg(float deg) => deg > 0 and deg < 6 ? " ☌ 0° " : deg > 24 and deg < 36 ? " ⊻ 30° " : deg > 54 and deg < 66 ? " 🞶 60° " : deg > 84 and deg < 96 ? " □ 90° " : deg > 114 and deg < 126 ? " △ 120° " : deg > 144 and deg < 156 ? " ⊼ 150° " : deg > 174 and deg < 180 ? " ☍ 180° " : str.tostring(deg,"#") // // @function SlowAspectSign: Input an angle and output the corresponding aspect sign for slow planets (within 6 degrees). export aspectslowsign(float deg) => deg > 0 and deg < 6 ? " ☌ " + str.tostring(deg,"#") : deg > 24 and deg < 36 ? " ⊻ " + str.tostring(deg,"#") : deg > 54 and deg < 66 ? " 🞶 " + str.tostring(deg,"#") : deg > 84 and deg < 96 ? " □ " + str.tostring(deg,"#") : deg > 114 and deg < 126 ? " △ " + str.tostring(deg,"#") : deg > 144 and deg < 156 ? " ⊼ " + str.tostring(deg,"#") : deg > 174 and deg < 180 ? " ☍ " + str.tostring(deg,"#") : str.tostring(deg,"#") // // @function PrecisionAspectSign: Input an angle & precision, then output the corresponding aspect sign for the planets. Precision 1 = +/-6°. Precision 2 = +/-3°. Precision 3 = Rounded to the nearest 1°. export aspectsignprecision(float deg, int precision) => if precision == 1 deg > 0 and deg < 6 ? " ☌ " + str.tostring(deg,"#") : deg > 24 and deg < 36 ? " ⊻ " + str.tostring(deg,"#") : deg > 54 and deg < 66 ? " 🞶 " + str.tostring(deg,"#") : deg > 84 and deg < 96 ? " □ " + str.tostring(deg,"#") : deg > 114 and deg < 126 ? " △ " + str.tostring(deg,"#") : deg > 144 and deg < 156 ? " ⊼ " + str.tostring(deg,"#") : deg > 174 and deg < 180 ? " ☍ " + str.tostring(deg,"#") : str.tostring(deg,"#") if precision == 2 deg > 0 and deg < 3 ? " ☌ " + str.tostring(deg,"#") : deg > 27 and deg < 33 ? " ⊻ " + str.tostring(deg,"#") : deg > 57 and deg < 63 ? " 🞶 " + str.tostring(deg,"#") : deg > 87 and deg < 93 ? " □ " + str.tostring(deg,"#") : deg > 117 and deg < 123 ? " △ " + str.tostring(deg,"#") : deg > 147 and deg < 153 ? " ⊼ " + str.tostring(deg,"#") : deg > 177 and deg < 183 ? " ☍ " + str.tostring(deg,"#") : str.tostring(deg,"#") else math.round(deg) == 0 ? " ☌ " + str.tostring(deg,"#") : math.round(deg) == 30 ? " ⊻ " + str.tostring(deg,"#") : math.round(deg) == 60 ? " 🞶 " + str.tostring(deg,"#") : math.round(deg) == 90 ? " □ " + str.tostring(deg,"#") : math.round(deg) == 120 ? " △ " + str.tostring(deg,"#") : math.round(deg) == 150 ? " ⊼ " + str.tostring(deg,"#") : math.round(deg) == 180 ? " ☍ " + str.tostring(deg,"#") : str.tostring(deg,"#") // // @function PrecisionAspectSignV2: Input an angle & precision (both in degrees°), then output the corresponding aspect sign & angle for the planets. export aspectsignprecisionV2(float deg, float precision) => deg > 0 and deg < (0+precision) ? " ☌ " + str.tostring(deg,"#") : deg > (30-precision) and deg < (30+precision) ? " ⊻ " + str.tostring(degtolowest180(deg),"#") : deg > (60-precision) and deg < (60+precision) ? " 🞶 " + str.tostring(degtolowest180(deg),"#") : deg > (90-precision) and deg < (90+precision) ? " □ " + str.tostring(degtolowest180(deg),"#") : deg > (120-precision) and deg < (120+precision) ? " △ " + str.tostring(degtolowest180(deg),"#") : deg > (150-precision) and deg < (150+precision) ? " ⊼ " + str.tostring(degtolowest180(deg),"#") : deg > (180-precision) and deg < 180 ? " ☍ " + str.tostring(degtolowest180(deg),"#") : str.tostring(degtolowest180(deg),"#") // // @function PrecisionAspectSignV2Extended: Input an angle & precision (both in degrees°), then output the corresponding aspect sign & angle for the planets. Great for tooltips. export aspectsignprecisionV2ext(float deg, float precision) => deg > 0 and deg < (0+precision) ? "☌ Conjunction " + str.tostring(deg,"#.#") : deg > (30-precision) and deg < (30+precision) ? "⊻ SemiSextile " + str.tostring(degtolowest180(deg),"#.#") : deg > (60-precision) and deg < (60+precision) ? "🞶 Sextile " + str.tostring(degtolowest180(deg),"#.#") : deg > (90-precision) and deg < (90+precision) ? "□ Square " + str.tostring(degtolowest180(deg),"#.#") : deg > (120-precision) and deg < (120+precision) ? "△ Trine " + str.tostring(degtolowest180(deg),"#.#") : deg > (150-precision) and deg < (150+precision) ? "⊼ Inconjunct " + str.tostring(degtolowest180(deg),"#.#") : deg > (180-precision) and deg < 180 ? "☍ Opposition " + str.tostring(degtolowest180(deg),"#.#") : "No aspect " + str.tostring(degtolowest180(deg),"#.#") // // @function PrecisionAspectSignV2: Input an angle & precision (both in degrees°), then output the corresponding aspect sign & angle for the planets. export IPaspectsignprecision(float planet1, float planet2, float precision) => deg = planet1 - planet2 deg > 0 and deg < (0+precision) ? " ☌ " + str.tostring(deg,"#") : deg > (30-precision) and deg < (30+precision) ? " ⊻ " + str.tostring(degtolowest180(deg),"#") : deg > (60-precision) and deg < (60+precision) ? " 🞶 " + str.tostring(degtolowest180(deg),"#") : deg > (90-precision) and deg < (90+precision) ? " □ " + str.tostring(degtolowest180(deg),"#") : deg > (120-precision) and deg < (120+precision) ? " △ " + str.tostring(degtolowest180(deg),"#") : deg > (150-precision) and deg < (150+precision) ? " ⊼ " + str.tostring(degtolowest180(deg),"#") : deg > (180-precision) and deg < 180 ? " ☍ " + str.tostring(degtolowest180(deg),"#") : str.tostring(degtolowest180(deg),"#") // // @function PrecisionAspectSignV2: Input an angle & precision (both in degrees°), then output the corresponding aspect sign & angle for the planets. export IPaspectsignprecisionFull(float planet1, float planet2, float precision) => deg = planet1 - planet2 deg > 0 and deg < (0+precision) ? " ☌ Conjunction " + str.tostring(deg,"#") : deg > (30-precision) and deg < (30+precision) ? " ⊻ SemiSextile " + str.tostring(degtolowest180(deg),"#") : deg > (60-precision) and deg < (60+precision) ? " 🞶 Sextile " + str.tostring(degtolowest180(deg),"#") : deg > (90-precision) and deg < (90+precision) ? " □ Square " + str.tostring(degtolowest180(deg),"#") : deg > (120-precision) and deg < (120+precision) ? " △ Trine " + str.tostring(degtolowest180(deg),"#") : deg > (150-precision) and deg < (150+precision) ? " ⊼ Inconjunct " + str.tostring(degtolowest180(deg),"#") : deg > (180-precision) and deg < 180 ? " ☍ Opposition " + str.tostring(degtolowest180(deg),"#") : str.tostring(degtolowest180(deg),"#") // // @function PrecisionAspectSignV2: Input an angle & precision (both in degrees°), then output the corresponding colored vertical aspect line on the chart. export IPaspectlineprecision(float planet1, float planet2, float precision, string style, int width) => deg = planet1 - planet2 deg > 0 and deg < (0+precision) ? line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.red, style=style, width=width) : deg > (30-precision) and deg < (30+precision) ? line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.orange, style=style, width=width) : deg > (60-precision) and deg < (60+precision) ? line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.yellow, style=style, width=width) : deg > (90-precision) and deg < (90+precision) ? line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.green, style=style, width=width) : deg > (120-precision) and deg < (120+precision) ? line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.aqua, style=style, width=width) : deg > (150-precision) and deg < (150+precision) ? line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.navy, style=style, width=width) : deg > (180-precision) and deg < 180 ? line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.purple, style=style, width=width) : na export rDeg(float deg) => h = math.abs(deg / 15) m = int((h - int(h)) * 60) rDeg = (((int(h) * 60) + m) / 1440) * 360 // Reference Angle Function // Author: Nasser Humood // // @function AngleToCircle: Input an angle (even one >360) and convert it to degrees on a circle (between 0 to 360). export AngToCirc(float angle) => // if the angle is greater than or equal to 360 if angle >= 360 firstStep = math.floor(angle / 360) * 360 returnedSolution = angle - firstStep returnedSolution // if the angle is less than or equal to zero else if angle <= 0 firstStep = math.ceil(-angle / 360) * 360 returnedSolution = angle + firstStep returnedSolution else // when the angle is correct and doesn't need any modification ex. in between 0-360 returnedSolution = angle returnedSolution // Reference Angle Function // Author: Nasser Humood // Editor: BarefootJoey // // @function AngleToCircle180: Input an angle (even one >180) and convert it to degrees on a semi-circle (between 0 to 180). export AngToCirc180(float angle) => // if the angle is greater than or equal to 360 if angle >= 180 firstStep = math.floor(angle / 180) * 180 returnedSolution = angle - firstStep returnedSolution // if the angle is less than or equal to zero else if angle <= 0 firstStep = math.ceil(-angle / 180) * 180 returnedSolution = angle + firstStep returnedSolution else // when the angle is correct and doesn't need any modification ex. in between 0-360 returnedSolution = angle returnedSolution // // @function TropicalToSidereal: Input an angle (even one > or < than 360) and convert it to sidereal. export sidereal(float deg, bool sidereal) => if sidereal sr_in = deg - 23.42 sr_out = AngToCirc(sr_in) else sr_out = deg export J2000(float JDN) => JDN - 2451545.0 //J2000 export JDN(float t, float d, float tz) => d == 0 ? (t / 86400000) + 2440587.5 + (tz / 24) : int((t / 86400000) + 2440587.5 + (tz / 24) - 1) + 0.5 export getsun(int index, float day, float dayr, float latitude, float longitude, float tz) => xsun = rsun(day,1) ysun = rsun(day,2) zsun = rsun(day,3) srise = Sunrise(dayr, latitude, longitude, 1, 0)/360*24 + tz sset = Sunrise(dayr, latitude, longitude, 0, 0)/360*24 + tz switch index 0 => spherical(xsun, ysun, zsun, 3) 1 => spherical(xsun, ysun, zsun, 3) 2 => math.round(spherical(xsun, ysun, zsun, 2), 2) 3 => math.round(sun(day, 2), 2) 4 => math.round(altaz(day,sun(day, 2),sun(day, 3), 0, 0, 1), 2) 5 => math.round(sun(day, 3), 2) / 15 6 => srise % 24 7 => sset % 24 export getmoon(int index, float day, float dayr, float latitude, float longitude) => xmoon = rmoon(day,1) ymoon = rmoon(day,2) zmoon = rmoon(day,3) mrise = MoonRise(dayr, longitude, latitude, 1) mset = MoonRise(dayr, longitude, latitude, 3) switch index 0 => spherical(xmoon, ymoon, zmoon, 3) 1 => spherical(xmoon, ymoon, zmoon, 3) 2 => math.round(spherical(xmoon, ymoon, zmoon, 2), 2) 3 => math.round(moon(day, 2), 2) 4 => math.round(altaz(day, moon(day, 2), moon(day, 3), 0, 0, 1), 2) 5 => math.round(moon(day, 3), 2) / 15 6 => mrise * 24 7 => mset * 24 export getplanet(int planet, int index, float day, float dayr, float latitude, float longitude, float tz) => xsun = rsun(day,1) ysun = rsun(day,2) zsun = rsun(day,3) xplanet = xsun + rplanet(day, planet, 1) yplanet = ysun + rplanet(day, planet, 2) zplanet = zsun + rplanet(day, planet, 3) srise = prise(dayr, planet, latitude, longitude, 1)/360*24 + tz sset = prise(dayr, planet, latitude, longitude, 0)/360*24 + tz switch index 0 => spherical(xplanet, yplanet, zplanet, 3) 1 => spherical(rplanet(day, planet, 1), rplanet(day, planet, 2), rplanet(day, planet, 3), 3) 2 => math.round(spherical(xplanet, yplanet, zplanet, 2), 2) 3 => math.round(planet(day, planet, 2), 2) 4 => math.round(altaz(day,planet(day, planet, 2), planet(day, planet, 3), 0, 0, 1), 2) 5 => math.round(planet(day, planet, 3), 2) / 15 6 => srise % 24 7 => sset % 24 // EoS made w/ ❤ by @BarefootJoey ✌💗📈
MarkovChain
https://www.tradingview.com/script/gPZKYCjK-MarkovChain/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
49
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 Generic Markov Chain type functions. // --- // A Markov chain or Markov process is a stochastic model describing a sequence of possible events in which the // probability of each event depends only on the state attained in the previous event. // --- // reference: // Understanding Markov Chains, Examples and Applications. Second Edition. Book by Nicolas Privault. // https://en.wikipedia.org/wiki/Markov_chain // https://www.geeksforgeeks.org/finding-the-probability-of-a-state-at-a-given-time-in-a-markov-chain-set-2/ // https://towardsdatascience.com/brief-introduction-to-markov-chains-2c8cab9c98ab // https://github.com/mxgmn/MarkovJunior // https://stats.stackexchange.com/questions/36099/estimating-markov-transition-probabilities-from-sequence-data // https://timeseriesreasoning.com/contents/hidden-markov-models/ // https://www.ris-ai.com/markov-chain // https://github.com/coin-or/jMarkov/blob/master/src/jmarkov/MarkovProcess.java // https://gist.github.com/mschauer/4c81a0529220b21fdf819e097f570f06 // https://github.com/rasmusab/bayes.js/blob/master/mcmc.js // https://gist.github.com/sathomas/cf526d6495811a8ca779946ef5558702 // https://writings.stephenwolfram.com/2022/06/games-and-puzzles-as-multicomputational-systems/ // https://kevingal.com/blog/boardgame.html // https://towardsdatascience.com/brief-introduction-to-markov-chains-2c8cab9c98ab // https://spedygiorgio.github.io/markovchain/reference/index.html // https://github.com/alexsosn/MarslandMLAlgo/blob/4277b24db88c4cb70d6b249921c5d21bc8f86eb4/Ch16/HMM.py // https://www.projectrhea.org/rhea/index.php/Introduction_to_Hidden_Markov_Chains library(title='MarkovChain') //#region -> Notes: // Table 7.1 Summary of Markov chain properties // Property Definition // Absorbing (state) Pi,i = 1 // Recurrent (state) P(Tri < ∞ | X0 = i) = 1 // Transient (state) P(Tri < ∞ | X0 = i) < 1 // Positive recurrent (state) Recurrent and IE[Tri | X0 = i] < ∞ // Null recurrent (state) Recurrent and IE[Tri | X0 = i] = ∞ // Aperiodic (state or chain) Period(s) = 1 // Ergodic (state or chain) Positive recurrent and aperiodic // Irreducible (chain) All states communicate // Regular (chain) All coefficients of Pn are > 0 for some n ≥ 1 // Stationary distribution π Obtained from solving π = πP // validity errors: // - states transition not probability (range 0>1) // - transition matrix not square. // - transition matrix probability row/col do not adds to 1 //#endregion //#region -> Helper Functions: import RicardoSantos/WIPTensor/2 as Tensor import RicardoSantos/FunctionBaumWelch/1 as fb import RicardoSantos/FunctionProbabilityViterbi/1 as vit // matrix_pow () { // reference: https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_power.html // @function Raise a square matrix to the provided exponent power. // @param mat matrix<float> . Source square matrix. // @param exponent int . Exponent value. // @returns matrix<float>. matrix with same shape as `A`, matrix_pow (matrix<float> mat, int exponent) => int _dim = matrix.rows(mat) matrix<float> _M = matrix.copy(mat) matrix<float> _ID = matrix.new<float>(_dim, _dim, 0.0) for _i = 0 to _dim - 1 matrix.set(_ID, _i, _i, 1.0) if matrix.columns(mat) != _dim runtime.error('Matrix is not square') int _p = exponent while true if _p > 0 if (_p % 2) == 1 _ID := matrix.mult(_ID, _M) _M := matrix.mult(_M, _M) _p /= 2 int(na) else break int(na) _M // } //#endregion //#region -> Structure: // Node { // @type Target node. // @field index . Key index of the node. // @field probability . Probability rate of activation. export type Node int index float probability //} // state { // @type State reference. // @field name . Name of the state. // @field index . Key index of the state. // @field target_nodes . List of index references and probabilities to target states. export type state string name int index array<Node> target_nodes //} // MC { // @type Markov Chain reference object. // @field name . Name of the chain. // @field states . List of state nodes and its name, index, targets and transition probabilities. // @field size . Number of unique states // @field transitions . Transition matrix export type MC string name = 'Unnamed Markov Chain' array<state> states int size matrix<float> transitions //} // HMC { // @type Hidden Markov Chain reference object. // @field name . Name of thehidden chain. // @field states_hidden . List of state nodes and its name, index, targets and transition probabilities. // @field states_obs . List of state nodes and its name, index, targets and transition probabilities. // @field transitions . Transition matrix // @field emissions . Emission matrix export type HMC string name = 'Unnamed Markov Chain' array<state> states_hidden array<state> states_obs matrix<float> transitions matrix<float> emissions array<float> initial_distribution // } //#endregion //#region -> Functions: // to_string () { // @function Translate a Markov Chain object to a string format. // @param this `MC` . Markov Chain object. // @returns string export method to_string (MC this) => string _str = this.name + '\n' for _state in this.states string _str1 = '' for _target_node in _state.target_nodes _str1 += str.format(' ({0,number,integer}: {1,number,percent})', _target_node.index, _target_node.probability) _str += str.format('{0,number,integer} {1}: ({2} )\n', _state.index, _state.name, _str1) _str += str.format('\n{0}', str.tostring(this.transitions)) _str // } // to_table () { // @function Translate a Markov Chain object to a table. // @param this MC, Markov Chain object. // @returns table export method to_table (MC this, string position = position.bottom_right, color text_color = #e2e2e2, string text_size = size.auto) => table _T = table.new(position, this.size + 2, this.size + 3) table.merge_cells(_T, 0, 0, this.size + 1, 0) table.cell(_T, 0, 0, this.name, text_color=text_color, text_size=text_size) for [_i, _state] in this.states table.cell(_T, 0, 2 + _i, str.format('{0,number,integer}: \"{1}\"', _state.index, _state.name), text_color=text_color, text_size=text_size) table.cell(_T, 1 + _i, 1, str.format('{0,number,integer}: \"{1}\"', _state.index, _state.name), text_color=text_color, text_size=text_size) for [_j, _target_node] in _state.target_nodes table.cell(_T, 1 + _j, 2 + _i, str.format('{0,number,percent}', _target_node.probability), text_color=text_color, text_size=text_size) _T // } // create_transition_matrix () { // @function Creates a transition matrix from a Markov Chain object. // @param this MC, Markov Chain object. // @returns matrix<float> export method create_transition_matrix (MC this) => matrix<float> _T = matrix.new<float>(this.size, this.size, 0.0) for _state in this.states for _tnode in _state.target_nodes matrix.set(_T, _state.index, _tnode.index, _tnode.probability) _T //} // generate_transition_matrix () { // @function Generate the transitions matrix property of the Markov Chain. // @param this MC, Markov Chain object. // @returns void, updates the Markov Chain object MC. export method generate_transition_matrix (MC this) => matrix<float> _T = this.create_transition_matrix() this.transitions := _T this // } // new_chain () { // @function Create a new Markov Chain object from a list of provided states. // @param states array<state>, List of states and its properties. // @param name string , Name of the Markov Chain Object, optional. // @returns MC, Markov Chain object. export new_chain (array<state> states, string name = 'Unnamed Markov Chain') => MC _MC = MC.new(name, states, array.size(states)) _MC.generate_transition_matrix() _MC //} // from_data () { // @function Create a new Markov Chain object from a list of provided states. // @param data array<string>, Formated array with classes or states to extract Markov Chain. // @param name string , Name of the Markov Chain Object, optional. // @returns MC, Markov Chain object. export from_data (array<string> data, string name = 'Unnamed Markov Chain') => // identify unique states: array<string> _unique = array.new<string>(0) for _e in data if not array.includes(_unique, _e) array.push(_unique, _e) // generate transition counts for state to state: int _size_u = array.size(_unique) matrix<int> _transition_counters = matrix.new<int>(_size_u, _size_u, 0) int _previous = 0 int _total_count = array.size(data) for _i = 1 to _total_count-1 int _current = array.indexof(_unique, array.get(data, _i)) int _counter = matrix.get(_transition_counters, _previous, _current) + 1 matrix.set(_transition_counters, _previous, _current, _counter) _previous := _current // generate probabilities based on counters: matrix<float> _transition_probability = matrix.new<float>(_size_u, _size_u, 0.0) for _i = 0 to _size_u - 1 _total_count := array.sum(matrix.row(_transition_counters, _i)) for _j = 0 to _size_u - 1 matrix.set(_transition_probability, _i, _j, float(matrix.get(_transition_counters, _i, _j) / _total_count)) // generate chain: array<state> _states = array.new<state>(_size_u) for _i = 0 to _size_u - 1 string _name = array.get(_unique, _i) array<Node> _tnodes = array.new<Node>(0) for _j = 0 to _size_u - 1 float _p = matrix.get(_transition_probability, _i, _j) if _p != 0.0 array.push(_tnodes, Node.new(_j, _p)) array.set(_states, _i, state.new(_name, _i, _tnodes)) MC _MC = new_chain(_states, name) //} // probability_at_step () { // reference: // https://www.geeksforgeeks.org/finding-the-probability-of-a-state-at-a-given-time-in-a-markov-chain-set-2/ // @function Probability of reaching target_state at target_step after starting from start_state // @param this MC, Markov Chain object. // @param target_step int , Number of steps to find probability. // @returns // - `matrix<float>`: Probability. export method probability_at_step (MC this, int target_step) => matrix_pow(this.transitions, target_step) //} // state_at_step () { // reference: // https://www.geeksforgeeks.org/finding-the-probability-of-a-state-at-a-given-time-in-a-markov-chain-set-2/ // @function Probability of reaching target_state at target_step after starting from start_state // @param this MC, Markov Chain object. // @param start_state int , State at which to start. // @param target_state int , State to find probability. // @param target_step int , Number of steps to find probability. // @returns // - `float`: Probability. export method state_at_step (MC this, int start_state, int target_state, int target_step) => matrix<float> _T = matrix_pow(this.transitions, target_step) matrix.get(_T, target_state - 1, start_state - 1) //} // forward () { // @function Computes forward probabilities for state `X` up to observation at time `k`, is defined as the // probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`. // @param this Hidden markov chain object (states, transitions, emissions and parameters). // > - transitions matrix<float> Transition matrix(T) where T(i,j) stores the transition probability of transitioning from State(i) to State(j) // > - emissions matrix<float> Emission matrix(E) where E(i, j) stores the probability of observing Observation(j) from State(i) // > - initial_distribution array<float> Initial probability distribution. // @param obs List with actual state observation data. // @returns // - `matrix<float> _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first // dimension refers to the state and the second dimension to time. export method forward (HMC this, array<int> obs) => fb.forward(this.initial_distribution, this.transitions, this.emissions, obs) // } // backward () { // @function Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`. // @param this hidden Hidden markov chain object (states, transitions, emissions and parameters). // > - transitions matrix<float> Transition matrix(T) where T(i,j) stores the transition probability of transitioning from State(i) to State(j) // > - emissions matrix<float> Emission matrix(E) where E(i, j) stores the probability of observing Observation(j) from State(i) // @param obs Array with actual state observation data. // @returns // - `matrix<float> _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time. export method backward (HMC this, array<int> obs) => fb.backward(this.transitions, this.emissions, obs) // } // viterbi () { // @function Calculate most probable path in a Markov model. // Given a Hidden Markov chain (A,B,P) and an observation sequence X, find out the best hidden state sequence S. // @param HMC Hidden markov chain object (states, transitions, emissions and parameters). // > - transitions matrix<float> Transition matrix(T) where T(i,j) stores the transition probability of transitioning from State(i) to State(j) // > - emissions matrix<float> Emission matrix(E) where E(i, j) stores the probability of observing Observation(j) from State(i) // > - initial_distribution array<float> Initial probability distribution. // @param observations array<int> Observation space. // @returns // - `array<int>`. Array with the most probable sequence of hidden states. export method viterbi (HMC this, array<int> observations) => vit.viterbi(observations, this.transitions, this.emissions, this.initial_distribution) // TEST: 20230318 RS: match with 2 diferent sources. // VT = matrix.new<float>(0, 2, 0.0) // matrix.add_row(VT, 0, array.from(0.7, 0.3)) // matrix.add_row(VT, 1, array.from(0.4, 0.6)) // VE = matrix.new<float>(0, 3, 0.0) // matrix.add_row(VE, 0, array.from(0.5, 0.4, 0.1)) // matrix.add_row(VE, 1, array.from(0.1, 0.3, 0.6)) // // matrix.add_row(VE, 2, array.from(0.1, 0.6)) // v_init_p = array.from(0.6, 0.4) // v_obs = array.from(0, 1, 2) // // // // v_MC = hidden.new( // // name = 'Viterbi test', // // states_hidden = array.from( // // state.new('healthy', 0, array.from(Node.new(0, 0.7), Node.new(1, 0.3))), // // state.new('fever' , 1, array.from(Node.new(0, 0.4), Node.new(1, 0.6))) // // ), // // states_obs = array.from( // // state.new('normal', 0, array.from(Node.new(0, 0.5), Node.new(1, 0.1))), // // state.new('cold' , 1, array.from(Node.new(0, 0.4), Node.new(1, 0.3))), // // state.new('dizzy' , 2, array.from(Node.new(0, 0.1), Node.new(1, 0.6))) // // ), // // size_hidden = 2, // // size_obs = 3, // // transitions = VT, // // emissions = VE // // ) // if barstate.islast // new_obs = array.from(1, 2, 0, 2, 1, 0, 1) // _str = '' // for _o in new_obs // v_obs.push(_o) // vpath = viterbi(v_obs, VT, VE, v_init_p) // _str += '\n' + str.tostring(vpath) // label.new(bar_index, 0.0, str.format('{0}', _str)) // } // baumwelch () { // @function Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the // unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm // to compute the statistics for the expectation step. // @param this Hidden markov chain object (states, transitions, emissions and parameters). // > - transitions matrix<float> Transition matrix(T) where T(i,j) stores the transition probability of transitioning from State(i) to State(j) // > - emissions matrix<float> Emission matrix(E) where E(i, j) stores the probability of observing Observation(j) from State(i) // > - initial_distribution array<float> Initial probability distribution. // @param observations List of observed states. // @returns // - #### Tuple with: // > - `array<float> _pi`: Initial probability distribution. // > - `matrix<float> _a`: Transition probability matrix. // > - `matrix<float> _b`: Emission probability matrix. // --- // requires: `import RicardoSantos/WIPTensor/2 as Tensor` export method baumwelch (HMC this, array<int> observations) => fb.baumwelch(observations, this.initial_distribution, this.transitions, this.emissions) // } //#endregion // _MC = MC.new(array.from( // state.new( 'up', 0, array.from(Node.new(0, 0.1), Node.new(1, 0.1), Node.new(2, 0.1))), // state.new('down', 1, array.from(Node.new(0, 0.1), Node.new(2, 0.1), Node.new(3, 0.1))), // state.new('fast', 2, array.from(Node.new(1, 0.1), Node.new(3, 0.1), Node.new(5, 0.1))), // state.new('doub', 3, array.from(Node.new(1, 0.1), Node.new(2, 0.1), Node.new(5, 0.1))), // state.new('trip', 4, array.from(Node.new(2, 0.1), Node.new(3, 0.1), Node.new(4, 0.1))), // state.new('slow', 5, array.from(Node.new(0, 0.1), Node.new(4, 0.1), Node.new(5, 0.1))) // ), 6) atr = ta.atr(100) diff = ta.change(close) classify = switch diff > atr => "> +1" diff < -atr => "< -1" => "> 0 <" var array<string> data = array.new<string>() if not na(atr) array.push(data, classify) plot(classify=='> +1'?1:(classify=='< -1'?-1:0)) if barstate.islast _MC = from_data(data, 'Returns to ATR Odds MC') // label.new(bar_index, 0.0, to_string(MC) + '\n' + str.tostring(MC.transitions)) to_table(_MC)
HarmonicPatternTracking
https://www.tradingview.com/script/y1qRVAnK-HarmonicPatternTracking/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
77
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // ░▒ // ▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒ // ▒▒▒▒▒▒▒░ ▒ ▒▒ // ▒▒▒▒▒▒ ▒ ▒▒ // ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ // ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒ // ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒ ▒▒▒▒▒ // ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗ // ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗ // ▒▒ ▒ //@version=5 // @description Library contains few data structures and methods for tracking harmonic pattern trades via pinescript. library("HarmonicPatternTracking", overlay = true) import HeWhoMustNotBeNamed/FibRatios/1 as fibs // @type Drawing objects of Harmonic Pattern // @field xa xa line // @field ab ab line // @field bc bc line // @field cd cd line // @field xb xb line // @field bd bd line // @field ac ac line // @field xd xd line // @field x label for pivot x // @field a label for pivot a // @field b label for pivot b // @field c label for pivot c // @field d label for pivot d // @field xabRatio label for XAB Ratio // @field abcRatio label for ABC Ratio // @field bcdRatio label for BCD Ratio // @field xadRatio label for XAD Ratio export type HarmonicDrawing line xa line ab line bc line cd line xb line bd line ac line xd label x label a label b label c label d label xabRatio label abcRatio label bcdRatio label xadRatio // @type Trade tracking parameters of Harmonic Patterns // @field initialEntry initial entry when pattern first formed. // @field entry trailed entry price. // @field initialStop initial stop when trade first entered. // @field stop current stop updated as per trailing rules. // @field target1 First target value // @field target2 Second target value // @field target3 Third target value // @field target4 Fourth target value // @field status Trade status referenced as integer // @field retouch Flag to show if the price retouched after entry export type HarmonicTrade float initialEntry float entry float initialStop float stop float target1 float target2 float target3 float target4 int status bool retouch // @type Display and trade calculation properties for Harmonic Patterns // @field fillMajorTriangles Display property used for using linefill for harmonic major triangles // @field fillMinorTriangles Display property used for using linefill for harmonic minor triangles // @field majorFillTransparency transparency setting for major triangles // @field minorFillTransparency transparency setting for minor triangles // @field showXABCD Display XABCD pivot labels // @field lblSizePivots Pivot label size // @field showRatios Display Ratio labels // @field useLogScaleForScan Use log scale to determine fib ratios for pattern scanning // @field useLogScaleForTargets Use log scale to determine fib ratios for target calculation // @field base base on which calculation of stop/targets are made. // @field entryRatio fib ratio to calculate entry // @field stopRatio fib ratio to calculate initial stop // @field target1Ratio fib ratio to calculate first target // @field target2Ratio fib ratio to calculate second target // @field target3Ratio fib ratio to calculate third target // @field target4Ratio fib ratio to calculate fourth target export type HarmonicProperties bool fillMajorTriangles bool fillMinorTriangles int majorFillTransparency int minorFillTransparency bool showXABCD string lblSizePivots bool showRatios bool useLogScaleForScan bool useLogScaleForTargets string base float entryRatio float stopRatio float target1Ratio float target2Ratio float target3Ratio float target4Ratio // @type Harmonic pattern object to track entire pattern trade life cycle // @field id Pattern Id // @field dir pattern direction // @field x X Pivot // @field a A Pivot // @field b B Pivot // @field c C Pivot // @field d D Pivot // @field xBar Bar index of X Pivot // @field aBar Bar index of A Pivot // @field bBar Bar index of B Pivot // @field cBar Bar index of C Pivot // @field dBar Bar index of D Pivot // @field przStart Start of PRZ range // @field przEnd End of PRZ range // @field patterns array representing the patterns // @field patternLabel string representation of list of patterns // @field patternColor color assigned to pattern // @field properties HarmonicProperties object containing display and calculation properties // @field trade HarmonicTrade object to track trades // @field drawing HarmonicDrawing object to manage drawings export type HarmonicPattern int id int dir float x float a float b float c float d int xBar int aBar int bBar int cBar int dBar float przStart float przEnd array<bool> patterns string patternLabel color patternColor HarmonicProperties properties HarmonicTrade trade HarmonicDrawing drawing // @function Creates and draws HarmonicDrawing object for given HarmonicPattern // @param this HarmonicPattern object // @returns current HarmonicPattern object export method draw(HarmonicPattern this)=> HarmonicDrawing drawing = HarmonicDrawing.new() this.drawing := drawing drawing.xa := line.new(this.xBar, this.x, this.aBar, this.a, xloc.bar_index, extend.none, this.patternColor, line.style_solid, 1) drawing.ab := line.new(this.aBar, this.a, this.bBar, this.b, xloc.bar_index, extend.none, this.patternColor, line.style_solid, 1) drawing.bc := line.new(this.bBar, this.b, this.cBar, this.c, xloc.bar_index, extend.none, this.patternColor, line.style_solid, 1) drawing.cd := line.new(this.cBar, this.c, this.dBar, this.d, xloc.bar_index, extend.none, this.patternColor, line.style_solid, 1) drawing.xb := line.new(this.xBar, this.x, this.bBar, this.b, xloc.bar_index, extend.none, this.patternColor, line.style_dashed, 1) drawing.bd := line.new(this.bBar, this.b, this.dBar, this.d, xloc.bar_index, extend.none, this.patternColor, line.style_dashed, 1) drawing.ac := line.new(this.aBar, this.a, this.cBar, this.c, xloc.bar_index, extend.none, this.patternColor, line.style_dashed, 1) drawing.xd := line.new(this.xBar, this.x, this.dBar, this.d, xloc.bar_index, extend.none, this.patternColor, line.style_dashed, 1) if(this.properties.fillMajorTriangles) linefill.new(drawing.xa, drawing.ab, color.new(this.patternColor, this.properties.majorFillTransparency)) linefill.new(drawing.xb, drawing.ab, color.new(this.patternColor, this.properties.majorFillTransparency)) linefill.new(drawing.bc, drawing.cd, color.new(this.patternColor, this.properties.majorFillTransparency)) linefill.new(drawing.bd, drawing.cd, color.new(this.patternColor, this.properties.majorFillTransparency)) if(this.properties.fillMinorTriangles) linefill.new(drawing.ab, drawing.bc, color.new(this.patternColor, this.properties.minorFillTransparency)) linefill.new(drawing.ac, drawing.bc, color.new(this.patternColor, this.properties.minorFillTransparency)) linefill.new(drawing.xb, drawing.bd, color.new(this.patternColor, this.properties.minorFillTransparency)) linefill.new(drawing.xd, drawing.bd, color.new(this.patternColor, this.properties.minorFillTransparency)) if this.properties.showXABCD drawing.x := label.new(this.xBar, this.x, 'X', textcolor = this.patternColor, style = label.style_none, yloc = this.dir > 0 ? yloc.belowbar : yloc.abovebar, size = this.properties.lblSizePivots) drawing.a := label.new(this.aBar, this.a, 'A', textcolor = this.patternColor, style = label.style_none, yloc = this.dir < 0 ? yloc.belowbar : yloc.abovebar, size = this.properties.lblSizePivots) drawing.b := label.new(this.bBar, this.b, 'B', textcolor = this.patternColor, style = label.style_none, yloc = this.dir > 0 ? yloc.belowbar : yloc.abovebar, size = this.properties.lblSizePivots) drawing.c := label.new(this.cBar, this.c, 'C', textcolor = this.patternColor, style = label.style_none, yloc = this.dir < 0 ? yloc.belowbar : yloc.abovebar, size = this.properties.lblSizePivots) drawing.d := label.new(this.dBar, this.d, 'D', textcolor = this.patternColor, style = label.style_none, yloc = this.dir > 0 ? yloc.belowbar : yloc.abovebar, size = this.properties.lblSizePivots) if this.properties.showRatios xabRatio = fibs.retracementRatio(this.x, this.a, this.b, this.properties.useLogScaleForScan) xabRatioBar = (this.xBar + this.bBar) / 2 xabRatioPrice = (this.x + this.b) / 2 abcRatio = fibs.retracementRatio(this.a, this.b, this.c, this.properties.useLogScaleForScan) abcRatioBar = (this.aBar + this.cBar) / 2 abcRatioPrice = (this.a + this.c) / 2 bcdRatio = fibs.retracementRatio(this.b, this.c, this.d, this.properties.useLogScaleForScan) bcdRatioBar = (this.bBar + this.dBar) / 2 bcdRatioPrice = (this.b + this.d) / 2 xadRatio = fibs.retracementRatio(this.x, this.a, this.d, this.properties.useLogScaleForScan) xadRatioBar = (this.xBar + this.dBar) / 2 xadRatioPrice = (this.x + this.d) / 2 axcRatio = fibs.retracementRatio(this.a, this.x, this.c, this.properties.useLogScaleForScan) xcdRatio = fibs.retracementRatio(this.x, this.c, this.d, this.properties.useLogScaleForScan) isCypher = this.patterns.get(6) abcRatioLabelText = str.tostring(abcRatio) + '(ABC)' + (isCypher ? '\n' + str.tostring(axcRatio) + '(AXC)' : '') xadRatioLabelText = str.tostring(xadRatio) + '(XAD)' + (isCypher ? '\n' + str.tostring(xcdRatio) + '(XCD)' : '') drawing.xabRatio := label.new(xabRatioBar, xabRatioPrice, str.tostring(xabRatio) + '(XAB)', textcolor = this.patternColor, style=label.style_none, yloc = yloc.price, size = this.properties.lblSizePivots) drawing.abcRatio := label.new(abcRatioBar, abcRatioPrice, abcRatioLabelText, textcolor = this.patternColor, style=label.style_none, yloc = yloc.price, size = this.properties.lblSizePivots) drawing.bcdRatio := label.new(bcdRatioBar, bcdRatioPrice, str.tostring(bcdRatio) + '(BCD)', textcolor = this.patternColor, style=label.style_none, yloc = yloc.price, size = this.properties.lblSizePivots) drawing.xadRatio := label.new(xadRatioBar, xadRatioPrice, xadRatioLabelText, textcolor = this.patternColor, style=label.style_none, yloc = yloc.price, size = this.properties.lblSizePivots) this // @function calculates HarmonicTrade and sets trade object for HarmonicPattern // @param this HarmonicPattern object // @returns bool true if pattern trades are valid, false otherwise export method addTrade(HarmonicPattern this)=> impulse = math.max(math.abs(this.x-this.a), math.abs(this.x-this.c)) correction = math.max(math.abs(this.c - this.d), math.abs(this.a - this.d)) baseVal = this.properties.base == 'max' ? math.max(impulse, correction) : this.properties.base == 'min'? math.min(impulse, correction) : this.properties.base == 'impulse'? impulse : this.properties.base == 'correction' ? correction : this.properties.base == 'AD'? math.abs(this.a-this.d) : math.abs(this.c-this.d) baseProp = this.properties.base == 'max'? (impulse > correction? 'impulse' : 'correction') : this.properties.base == 'min'? (impulse < correction? 'impulse' : 'correction') : this.properties.base peak = this.a*this.dir > this.c*this.dir? this.a : this.c target1 = baseProp == 'impulse'? fibs.extension(this.x, peak, this.d, this.properties.target1Ratio, this.properties.useLogScaleForTargets) : baseProp == 'correction'? fibs.retracement(peak, this.d, this.properties.target1Ratio, this.properties.useLogScaleForTargets): baseProp == 'AD'? fibs.retracement(this.a, this.d, this.properties.target1Ratio, this.properties.useLogScaleForTargets): fibs.retracement(this.c, this.d, this.properties.target1Ratio, this.properties.useLogScaleForTargets) target2 = baseProp == 'impulse'? fibs.extension(this.x, peak, this.d, this.properties.target2Ratio, this.properties.useLogScaleForTargets) : baseProp == 'correction'? fibs.retracement(peak, this.d, this.properties.target2Ratio, this.properties.useLogScaleForTargets): baseProp == 'AD'? fibs.retracement(this.a, this.d, this.properties.target2Ratio, this.properties.useLogScaleForTargets): fibs.retracement(this.c, this.d, this.properties.target2Ratio, this.properties.useLogScaleForTargets) target3 = baseProp == 'impulse'? fibs.extension(this.x, peak, this.d, this.properties.target3Ratio, this.properties.useLogScaleForTargets) : baseProp == 'correction'? fibs.retracement(peak, this.d, this.properties.target3Ratio, this.properties.useLogScaleForTargets): baseProp == 'AD'? fibs.retracement(this.a, this.d, this.properties.target3Ratio, this.properties.useLogScaleForTargets): fibs.retracement(this.c, this.d, this.properties.target3Ratio, this.properties.useLogScaleForTargets) target4 = baseProp == 'impulse'? fibs.extension(this.x, peak, this.d, this.properties.target4Ratio, this.properties.useLogScaleForTargets) : baseProp == 'correction'? fibs.retracement(peak, this.d, this.properties.target4Ratio, this.properties.useLogScaleForTargets): baseProp == 'AD'? fibs.retracement(this.a, this.d, this.properties.target4Ratio, this.properties.useLogScaleForTargets): fibs.retracement(this.c, this.d, this.properties.target4Ratio, this.properties.useLogScaleForTargets) entry = baseProp == 'impulse'? fibs.extension(this.x, peak, this.d, this.properties.entryRatio, this.properties.useLogScaleForTargets) : baseProp == 'correction'? fibs.retracement(peak, this.d, this.properties.entryRatio, this.properties.useLogScaleForTargets): baseProp == 'AD'? fibs.retracement(this.a, this.d, this.properties.entryRatio, this.properties.useLogScaleForTargets): fibs.retracement(this.c, this.d, this.properties.entryRatio, this.properties.useLogScaleForTargets) stop = baseProp == 'impulse'? fibs.extension(this.x, peak, this.d, this.properties.stopRatio, this.properties.useLogScaleForTargets) : baseProp == 'correction'? fibs.retracement(peak, this.d, this.properties.stopRatio, this.properties.useLogScaleForTargets): baseProp == 'AD'? fibs.retracement(this.a, this.d, this.properties.stopRatio, this.properties.useLogScaleForTargets): fibs.retracement(this.c, this.d, this.properties.stopRatio, this.properties.useLogScaleForTargets) this.trade := HarmonicTrade.new(entry, entry, stop, stop, target1, target2, target3, target4, 0, false) valid = stop > 0 and target4 > 0 // @function Deletes drawing objects of HarmonicDrawing // @param this HarmonicDrawing object // @returns current HarmonicDrawing object export method delete(HarmonicDrawing this)=> this.xa.delete() this.ab.delete() this.bc.delete() this.cd.delete() this.xb.delete() this.bd.delete() this.ac.delete() this.xd.delete() this.x.delete() this.a.delete() this.b.delete() this.c.delete() this.d.delete() this.xabRatio.delete() this.abcRatio.delete() this.bcdRatio.delete() this.xadRatio.delete() this // @function Deletes drawings of harmonic pattern // @param this HarmonicPattern object // @returns current HarmonicPattern object export method delete(HarmonicPattern this)=> this.drawing.delete() this
MarkovAlgorithm
https://www.tradingview.com/script/MLkBP8gp-MarkovAlgorithm/
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 Markov algorithm is a string rewriting system that uses grammar-like rules to operate on strings of // symbols. Markov algorithms have been shown to be Turing-complete, which means that they are suitable as a // general model of computation and can represent any mathematical expression from its simple notation. // ~ wikipedia // . // reference: // https://en.wikipedia.org/wiki/Markov_algorithm // https://rosettacode.org/wiki/Execute_a_Markov_algorithm#Nim library(title = 'MarkovAlgorithm') import RicardoSantos/DebugConsole/13 as console console.Console logger = console.new() logger.table.set_position(position.bottom_right) logger.table.cell_set_width(0, 0, 95) // rule { // @type String pair that represents `pattern -> replace`, each rule may be ordinary or terminating. // @field pattern Pattern to replace. // @field replacement Replacement patterns. // @field termination Termination rule. export type rule string pattern string replacement bool termination = false // } // parse () { // @function Parse the rules provided, the rules should formatted in a `pattern -> replace` way and separated by a new line or provided separator. // @param rules `string`: Expression containing the rules. // @param separator `string`: Separator, default=`newline`. // @returns // - `array<rule> _rules`: List of rules. // --- // Usage: // - `parse("|0 -> 0||\n1 -> 0|\n0 -> ")` export parse (string rules, string separator='\n') => array<string> _lines = str.split(rules, separator) array<rule> _rules = array.new<rule>(0) for _line in _lines if str.startswith(_line, '#') continue if str.replace_all(_line, ' ', '') == '' continue array<string> _t = str.split(_line, ' -> ') if array.size(_t) > 1 rule _rule = rule.new(array.get(_t, 0), array.get(_t, 1)) if str.startswith(_rule.replacement, '.') _rule.termination := true _rule.replacement := str.replace(_rule.replacement, '.', '', 0) array.push(_rules, _rule) _rules // } // apply () { // @function Aplies rules to a expression. // @param expression `string` : Text expression to be formated by the rules. // @param rules `array<rule>`: Rules to apply to expression. // @returns // - `string _result`: Formated expression. // --- // Usage: // - `apply("101", parse("|0 -> 0||\n1 -> 0|\n0 -> "))` export apply (string expression, array<rule> rules) => string _result = expression bool _changed = true while _changed _changed := false for _rule in rules if str.contains(_result, _rule.pattern) _result := str.replace_all(_result, _rule.pattern, _rule.replacement) if _rule.termination break _changed := true break _result // @function Aplies rules to a expression. // @param expression `string`: Text expression to be formated by the rules. // @param rules `string`: Rules to apply to expression on a string format to be parsed. // @returns // - `string _result`: Formated expression. // --- // Usage: // - `apply("101", parse("|0 -> 0||\n1 -> 0|\n0 -> "))` export apply (string expression, string rules) => apply(expression, parse(rules)) // } //#region -> Preview: string ruleset1 = str.format('{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n', '# This rules file is extracted from Wikipedia:', '# http://en.wikipedia.org/wiki/Markov_Algorithm', 'A -> apple', 'B -> bag', 'S -> shop', 'T -> the', 'the shop -> my brother', 'a never used -> .terminating rule') string ruleset2 = str.format('{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n', '# Slightly modified from the rules on Wikipedia', 'A -> apple', 'B -> bag', 'S -> .shop', 'T -> the', 'the shop -> my brother', 'a never used -> .terminating rule') string ruleset3 = '' + '# BNF Syntax testing rules' + '\n' + 'A -> apple' + '\n' + 'WWWW -> with' + '\n' + 'Bgage -> ->.*' + '\n' + 'B -> bag' + '\n' + '->.* -> money' + '\n' + 'W -> WW' + '\n' + 'S -> .shop' + '\n' + 'T -> the' + '\n' + 'the shop -> my brother' + '\n' + 'a never used -> .terminating rule' string ruleset4 = '' + '### Unary Multiplication Engine, for testing Markov Algorithm implementations' + '\n' + '### By Donal Fellows.' + '\n' + '# Unary addition engine' + '\n' + '_+1 -> _1+' + '\n' + '1+1 -> 11+' + '\n' + '# Pass for converting from the splitting of multiplication into ordinary' + '\n' + '# addition' + '\n' + '1! -> !1' + '\n' + ',! -> !+' + '\n' + '_! -> _' + '\n' + '# Unary multiplication by duplicating left side, right side times' + '\n' + '1*1 -> x,@y' + '\n' + '1x -> xX' + '\n' + 'X, -> 1,1' + '\n' + 'X1 -> 1X' + '\n' + '_x -> _X' + '\n' + ',x -> ,X' + '\n' + 'y1 -> 1y' + '\n' + 'y_ -> _' + '\n' + '# Next phase of applying' + '\n' + '1@1 -> x,@y' + '\n' + '1@_ -> @_' + '\n' + ',@_ -> !_' + '\n' + '++ -> +' + '\n' + '# Termination cleanup for addition' + '\n' + '_1 -> 1' + '\n' + '1+_ -> 1' + '\n' + '_+_ -> ' string ruleset5 = '' + '# Turing machine: three-state busy beaver' + '\n' + '#' + '\n' + '# state A, symbol 0 => write 1, move right, new state B' + '\n' + 'A0 -> 1B' + '\n' + '# state A, symbol 1 => write 1, move left, new state C' + '\n' + '0A1 -> C01' + '\n' + '1A1 -> C11' + '\n' + '# state B, symbol 0 => write 1, move left, new state A' + '\n' + '0B0 -> A01' + '\n' + '1B0 -> A11' + '\n' + '# state B, symbol 1 => write 1, move right, new state B' + '\n' + 'B1 -> 1B' + '\n' + '# state C, symbol 0 => write 1, move left, new state B' + '\n' + '0C0 -> B01' + '\n' + '1C0 -> B11' + '\n' + '# state C, symbol 1 => write 1, move left, halt' + '\n' + '0C1 -> H01' + '\n' + '1C1 -> H11' string phrase1 = 'I bought a B of As from T S.' string phrase2 = 'I bought a B of As from T S.' string phrase3 = 'I bought a B of As W my Bgage from T S.' string phrase4 = '_1111*11111_' string phrase5 = '000000A000000' test_set = input.int(1, options=[1, 2, 3, 4, 5]) if barstate.islast switch test_set 1 => logger.queue_one(apply(phrase1, parse(ruleset1))) 2 => logger.queue_one(apply(phrase2, parse(ruleset2))) 3 => logger.queue_one(apply(phrase3, parse(ruleset3))) 4 => logger.queue_one(apply(phrase4, parse(ruleset4))) 5 => logger.queue_one(apply(phrase5, parse(ruleset5))) logger.update() //#endregion
SMC + 2BB
https://www.tradingview.com/script/EB5iPDwh-SMC-2BB/
Xcribbles
https://www.tradingview.com/u/Xcribbles/
23
study
5
CC-BY-NC-SA-4.0
//// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // © LuxAlgo //@version=5 indicator("KAPOK MELARAT" , overlay = true , max_labels_count = 500 , max_lines_count = 500 , max_boxes_count = 500 , max_bars_back = 500) //-----------------------------------------------------------------------------{ //Constants //-----------------------------------------------------------------------------{ color TRANSP_CSS = #ffffff00 //Tooltips string MODE_TOOLTIP = 'Allows to display historical Structure or only the recent ones' string STYLE_TOOLTIP = 'Indicator color theme' string COLOR_CANDLES_TOOLTIP = 'Display additional candles with a color reflecting the current trend detected by structure' string SHOW_INTERNAL = 'Display internal market structure' string CONFLUENCE_FILTER = 'Filter non significant internal structure breakouts' string SHOW_SWING = 'Display swing market Structure' string SHOW_SWING_POINTS = 'Display swing point as labels on the chart' string SHOW_SWHL_POINTS = 'Highlight most recent strong and weak high/low points on the chart' string INTERNAL_OB = 'Display internal order blocks on the chart\n\nNumber of internal order blocks to display on the chart' string SWING_OB = 'Display swing order blocks on the chart\n\nNumber of internal swing blocks to display on the chart' string FILTER_OB = 'Method used to filter out volatile order blocks \n\nIt is recommended to use the cumulative mean range method when a low amount of data is available' string SHOW_EQHL = 'Display equal highs and equal lows on the chart' string EQHL_BARS = 'Number of bars used to confirm equal highs and equal lows' string EQHL_THRESHOLD = 'Sensitivity threshold in a range (0, 1) used for the detection of equal highs & lows\n\nLower values will return fewer but more pertinent results' string SHOW_FVG = 'Display fair values gaps on the chart' string AUTO_FVG = 'Filter out non significant fair value gaps' string FVG_TF = 'Fair value gaps timeframe' string EXTEND_FVG = 'Determine how many bars to extend the Fair Value Gap boxes on chart' string PED_ZONES = 'Display premium, discount, and equilibrium zones on chart' //-----------------------------------------------------------------------------{ //Settings //-----------------------------------------------------------------------------{ //General //----------------------------------------{ mode = input.string('Historical' , options = ['Historical', 'Present'] , group = 'Smart Money Concepts' , tooltip = MODE_TOOLTIP) style = input.string('Colored' , options = ['Colored', 'Monochrome'] , group = 'Smart Money Concepts' , tooltip = STYLE_TOOLTIP) show_trend = input(false, 'Color Candles' , group = 'Smart Money Concepts' , tooltip = COLOR_CANDLES_TOOLTIP) //----------------------------------------} //Internal Structure //----------------------------------------{ show_internals = input(true, 'Show Internal Structure' , group = 'Real Time Internal Structure' , tooltip = SHOW_INTERNAL) show_ibull = input.string('All', 'Bullish Structure' , options = ['All', 'BOS', 'CHoCH'] , inline = 'ibull' , group = 'Real Time Internal Structure') swing_ibull_css = input(#089981, '' , inline = 'ibull' , group = 'Real Time Internal Structure') //Bear Structure show_ibear = input.string('All', 'Bearish Structure' , options = ['All', 'BOS', 'CHoCH'] , inline = 'ibear' , group = 'Real Time Internal Structure') swing_ibear_css = input(#f23645, '' , inline = 'ibear' , group = 'Real Time Internal Structure') ifilter_confluence = input(false, 'Confluence Filter' , group = 'Real Time Internal Structure' , tooltip = CONFLUENCE_FILTER) internal_structure_size = input.string('Tiny', 'Internal Label Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'Real Time Internal Structure') //----------------------------------------} //Swing Structure //----------------------------------------{ show_Structure = input(true, 'Show Swing Structure' , group = 'Real Time Swing Structure' , tooltip = SHOW_SWING) //Bull Structure show_bull = input.string('All', 'Bullish Structure' , options = ['All', 'BOS', 'CHoCH'] , inline = 'bull' , group = 'Real Time Swing Structure') swing_bull_css = input(#089981, '' , inline = 'bull' , group = 'Real Time Swing Structure') //Bear Structure show_bear = input.string('All', 'Bearish Structure' , options = ['All', 'BOS', 'CHoCH'] , inline = 'bear' , group = 'Real Time Swing Structure') swing_bear_css = input(#f23645, '' , inline = 'bear' , group = 'Real Time Swing Structure') swing_structure_size = input.string('Small', 'Swing Label Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'Real Time Swing Structure') //Swings show_swings = input(false, 'Show Swings Points' , inline = 'swings' , group = 'Real Time Swing Structure' , tooltip = SHOW_SWING_POINTS) length = input.int(50, '' , minval = 10 , inline = 'swings' , group = 'Real Time Swing Structure') show_hl_swings = input(true, 'Show Strong/Weak High/Low' , group = 'Real Time Swing Structure' , tooltip = SHOW_SWHL_POINTS) //----------------------------------------} //Order Blocks //----------------------------------------{ show_iob = input(true, 'Internal Order Blocks' , inline = 'iob' , group = 'Order Blocks' , tooltip = INTERNAL_OB) iob_showlast = input.int(5, '' , minval = 1 , inline = 'iob' , group = 'Order Blocks') show_ob = input(false, 'Swing Order Blocks' , inline = 'ob' , group = 'Order Blocks' , tooltip = SWING_OB) ob_showlast = input.int(5, '' , minval = 1 , inline = 'ob' , group = 'Order Blocks') ob_filter = input.string('Atr', 'Order Block Filter' , options = ['Atr', 'Cumulative Mean Range'] , group = 'Order Blocks' , tooltip = FILTER_OB) ibull_ob_css = input.color(color.new(#3179f5, 80), 'Internal Bullish OB' , group = 'Order Blocks') ibear_ob_css = input.color(color.new(#f77c80, 80), 'Internal Bearish OB' , group = 'Order Blocks') bull_ob_css = input.color(color.new(#1848cc, 80), 'Bullish OB' , group = 'Order Blocks') bear_ob_css = input.color(color.new(#b22833, 80), 'Bearish OB' , group = 'Order Blocks') //----------------------------------------} //EQH/EQL //----------------------------------------{ show_eq = input(true, 'Equal High/Low' , group = 'EQH/EQL' , tooltip = SHOW_EQHL) eq_len = input.int(3, 'Bars Confirmation' , minval = 1 , group = 'EQH/EQL' , tooltip = EQHL_BARS) eq_threshold = input.float(0.1, 'Threshold' , minval = 0 , maxval = 0.5 , step = 0.1 , group = 'EQH/EQL' , tooltip = EQHL_THRESHOLD) eq_size = input.string('Tiny', 'Label Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'EQH/EQL') //----------------------------------------} //Fair Value Gaps //----------------------------------------{ show_fvg = input(false, 'Fair Value Gaps' , group = 'Fair Value Gaps' , tooltip = SHOW_FVG) fvg_auto = input(true, "Auto Threshold" , group = 'Fair Value Gaps' , tooltip = AUTO_FVG) fvg_tf = input.timeframe('', "Timeframe" , group = 'Fair Value Gaps' , tooltip = FVG_TF) bull_fvg_css = input.color(color.new(#00ff68, 70), 'Bullish FVG' , group = 'Fair Value Gaps') bear_fvg_css = input.color(color.new(#ff0008, 70), 'Bearish FVG' , group = 'Fair Value Gaps') fvg_extend = input.int(1, "Extend FVG" , minval = 0 , group = 'Fair Value Gaps' , tooltip = EXTEND_FVG) //----------------------------------------} //Previous day/week high/low //----------------------------------------{ //Daily show_pdhl = input(false, 'Daily' , inline = 'daily' , group = 'Highs & Lows MTF') pdhl_style = input.string('⎯⎯⎯', '' , options = ['⎯⎯⎯', '----', '····'] , inline = 'daily' , group = 'Highs & Lows MTF') pdhl_css = input(#2157f3, '' , inline = 'daily' , group = 'Highs & Lows MTF') //Weekly show_pwhl = input(false, 'Weekly' , inline = 'weekly' , group = 'Highs & Lows MTF') pwhl_style = input.string('⎯⎯⎯', '' , options = ['⎯⎯⎯', '----', '····'] , inline = 'weekly' , group = 'Highs & Lows MTF') pwhl_css = input(#2157f3, '' , inline = 'weekly' , group = 'Highs & Lows MTF') //Monthly show_pmhl = input(false, 'Monthly' , inline = 'monthly' , group = 'Highs & Lows MTF') pmhl_style = input.string('⎯⎯⎯', '' , options = ['⎯⎯⎯', '----', '····'] , inline = 'monthly' , group = 'Highs & Lows MTF') pmhl_css = input(#2157f3, '' , inline = 'monthly' , group = 'Highs & Lows MTF') //----------------------------------------} //Premium/Discount zones //----------------------------------------{ show_sd = input(false, 'Premium/Discount Zones' , group = 'Premium & Discount Zones' , tooltip = PED_ZONES) premium_css = input.color(#f23645, 'Premium Zone' , group = 'Premium & Discount Zones') eq_css = input.color(#b2b5be, 'Equilibrium Zone' , group = 'Premium & Discount Zones') discount_css = input.color(#089981, 'Discount Zone' , group = 'Premium & Discount Zones') //-----------------------------------------------------------------------------} //Functions //-----------------------------------------------------------------------------{ n = bar_index atr = ta.atr(200) cmean_range = ta.cum(high - low) / n //HL Output function hl() => [high, low] //Get ohlc values function get_ohlc()=> [close[1], open[1], high, low, high[2], low[2]] //Display Structure function display_Structure(x, y, txt, css, dashed, down, lbl_size)=> structure_line = line.new(x, y, n, y , color = css , style = dashed ? line.style_dashed : line.style_solid) structure_lbl = label.new(int(math.avg(x, n)), y, txt , color = TRANSP_CSS , textcolor = css , style = down ? label.style_label_down : label.style_label_up , size = lbl_size) if mode == 'Present' line.delete(structure_line[1]) label.delete(structure_lbl[1]) //Swings detection/measurements swings(len)=> var os = 0 upper = ta.highest(len) lower = ta.lowest(len) os := high[len] > upper ? 0 : low[len] < lower ? 1 : os[1] top = os == 0 and os[1] != 0 ? high[len] : 0 btm = os == 1 and os[1] != 1 ? low[len] : 0 [top, btm] //Order block coordinates function ob_coord(use_max, loc, target_top, target_btm, target_left, target_type)=> min = 99999999. max = 0. idx = 1 ob_threshold = ob_filter == 'Atr' ? atr : cmean_range //Search for highest/lowest high within the structure interval and get range if use_max for i = 1 to (n - loc)-1 if (high[i] - low[i]) < ob_threshold[i] * 2 max := math.max(high[i], max) min := max == high[i] ? low[i] : min idx := max == high[i] ? i : idx else for i = 1 to (n - loc)-1 if (high[i] - low[i]) < ob_threshold[i] * 2 min := math.min(low[i], min) max := min == low[i] ? high[i] : max idx := min == low[i] ? i : idx array.unshift(target_top, max) array.unshift(target_btm, min) array.unshift(target_left, time[idx]) array.unshift(target_type, use_max ? -1 : 1) //Set order blocks display_ob(boxes, target_top, target_btm, target_left, target_type, show_last, swing, size)=> for i = 0 to math.min(show_last-1, size-1) get_box = array.get(boxes, i) box.set_lefttop(get_box, array.get(target_left, i), array.get(target_top, i)) box.set_rightbottom(get_box, array.get(target_left, i), array.get(target_btm, i)) box.set_extend(get_box, extend.right) color css = na if swing if style == 'Monochrome' css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) : color.new(#5d606b, 80) border_css = array.get(target_type, i) == 1 ? #b2b5be : #5d606b box.set_border_color(get_box, border_css) else css := array.get(target_type, i) == 1 ? bull_ob_css : bear_ob_css box.set_border_color(get_box, css) box.set_bgcolor(get_box, css) else if style == 'Monochrome' css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) : color.new(#5d606b, 80) else css := array.get(target_type, i) == 1 ? ibull_ob_css : ibear_ob_css box.set_border_color(get_box, css) box.set_bgcolor(get_box, css) //Line Style function get_line_style(style) => out = switch style '⎯⎯⎯' => line.style_solid '----' => line.style_dashed '····' => line.style_dotted //Set line/labels function for previous high/lows phl(h, l, tf, css)=> var line high_line = line.new(na,na,na,na , xloc = xloc.bar_time , color = css , style = get_line_style(pdhl_style)) var label high_lbl = label.new(na,na , xloc = xloc.bar_time , text = str.format('P{0}H', tf) , color = TRANSP_CSS , textcolor = css , size = size.small , style = label.style_label_left) var line low_line = line.new(na,na,na,na , xloc = xloc.bar_time , color = css , style = get_line_style(pdhl_style)) var label low_lbl = label.new(na,na , xloc = xloc.bar_time , text = str.format('P{0}L', tf) , color = TRANSP_CSS , textcolor = css , size = size.small , style = label.style_label_left) hy = ta.valuewhen(h != h[1], h, 1) hx = ta.valuewhen(h == high, time, 1) ly = ta.valuewhen(l != l[1], l, 1) lx = ta.valuewhen(l == low, time, 1) if barstate.islast ext = time + (time - time[1])*20 //High line.set_xy1(high_line, hx, hy) line.set_xy2(high_line, ext, hy) label.set_xy(high_lbl, ext, hy) //Low line.set_xy1(low_line, lx, ly) line.set_xy2(low_line, ext, ly) label.set_xy(low_lbl, ext, ly) //-----------------------------------------------------------------------------} //Global variables //-----------------------------------------------------------------------------{ var trend = 0, var itrend = 0 var top_y = 0., var top_x = 0 var btm_y = 0., var btm_x = 0 var itop_y = 0., var itop_x = 0 var ibtm_y = 0., var ibtm_x = 0 var trail_up = high, var trail_dn = low var trail_up_x = 0, var trail_dn_x = 0 var top_cross = true, var btm_cross = true var itop_cross = true, var ibtm_cross = true var txt_top = '', var txt_btm = '' //Alerts bull_choch_alert = false bull_bos_alert = false bear_choch_alert = false bear_bos_alert = false bull_ichoch_alert = false bull_ibos_alert = false bear_ichoch_alert = false bear_ibos_alert = false bull_iob_break = false bear_iob_break = false bull_ob_break = false bear_ob_break = false eqh_alert = false eql_alert = false //Structure colors var bull_css = style == 'Monochrome' ? #b2b5be : swing_bull_css var bear_css = style == 'Monochrome' ? #b2b5be : swing_bear_css var ibull_css = style == 'Monochrome' ? #b2b5be : swing_ibull_css var ibear_css = style == 'Monochrome' ? #b2b5be : swing_ibear_css //Labels size var internal_structure_lbl_size = internal_structure_size == 'Tiny' ? size.tiny : internal_structure_size == 'Small' ? size.small : size.normal var swing_structure_lbl_size = swing_structure_size == 'Tiny' ? size.tiny : swing_structure_size == 'Small' ? size.small : size.normal var eqhl_lbl_size = eq_size == 'Tiny' ? size.tiny : eq_size == 'Small' ? size.small : size.normal //Swings [top, btm] = swings(length) [itop, ibtm] = swings(5) //-----------------------------------------------------------------------------} //Pivot High //-----------------------------------------------------------------------------{ var line extend_top = na var label extend_top_lbl = label.new(na, na , color = TRANSP_CSS , textcolor = bear_css , style = label.style_label_down , size = size.tiny) if top top_cross := true txt_top := top > top_y ? 'HH' : 'LH' if show_swings top_lbl = label.new(n-length, top, txt_top , color = TRANSP_CSS , textcolor = bear_css , style = label.style_label_down , size = swing_structure_lbl_size) if mode == 'Present' label.delete(top_lbl[1]) //Extend recent top to last bar line.delete(extend_top[1]) extend_top := line.new(n-length, top, n, top , color = bear_css) top_y := top top_x := n - length trail_up := top trail_up_x := n - length if itop itop_cross := true itop_y := itop itop_x := n - 5 //Trailing maximum trail_up := math.max(high, trail_up) trail_up_x := trail_up == high ? n : trail_up_x //Set top extension label/line if barstate.islast and show_hl_swings line.set_xy1(extend_top, trail_up_x, trail_up) line.set_xy2(extend_top, n + 20, trail_up) label.set_x(extend_top_lbl, n + 20) label.set_y(extend_top_lbl, trail_up) label.set_text(extend_top_lbl, trend < 0 ? 'Strong High' : 'Weak High') //-----------------------------------------------------------------------------} //Pivot Low //-----------------------------------------------------------------------------{ var line extend_btm = na var label extend_btm_lbl = label.new(na, na , color = TRANSP_CSS , textcolor = bull_css , style = label.style_label_up , size = size.tiny) if btm btm_cross := true txt_btm := btm < btm_y ? 'LL' : 'HL' if show_swings btm_lbl = label.new(n - length, btm, txt_btm , color = TRANSP_CSS , textcolor = bull_css , style = label.style_label_up , size = swing_structure_lbl_size) if mode == 'Present' label.delete(btm_lbl[1]) //Extend recent btm to last bar line.delete(extend_btm[1]) extend_btm := line.new(n - length, btm, n, btm , color = bull_css) btm_y := btm btm_x := n-length trail_dn := btm trail_dn_x := n-length if ibtm ibtm_cross := true ibtm_y := ibtm ibtm_x := n - 5 //Trailing minimum trail_dn := math.min(low, trail_dn) trail_dn_x := trail_dn == low ? n : trail_dn_x //Set btm extension label/line if barstate.islast and show_hl_swings line.set_xy1(extend_btm, trail_dn_x, trail_dn) line.set_xy2(extend_btm, n + 20, trail_dn) label.set_x(extend_btm_lbl, n + 20) label.set_y(extend_btm_lbl, trail_dn) label.set_text(extend_btm_lbl, trend > 0 ? 'Strong Low' : 'Weak Low') //-----------------------------------------------------------------------------} //Order Blocks Arrays //-----------------------------------------------------------------------------{ var iob_top = array.new_float(0) var iob_btm = array.new_float(0) var iob_left = array.new_int(0) var iob_type = array.new_int(0) var ob_top = array.new_float(0) var ob_btm = array.new_float(0) var ob_left = array.new_int(0) var ob_type = array.new_int(0) //-----------------------------------------------------------------------------} //Pivot High BOS/CHoCH //-----------------------------------------------------------------------------{ //Filtering var bull_concordant = true if ifilter_confluence bull_concordant := high - math.max(close, open) > math.min(close, open - low) //Detect internal bullish Structure if ta.crossover(close, itop_y) and itop_cross and top_y != itop_y and bull_concordant bool choch = na if itrend < 0 choch := true bull_ichoch_alert := true else bull_ibos_alert := true txt = choch ? 'CHoCH' : 'BOS' if show_internals if show_ibull == 'All' or (show_ibull == 'BOS' and not choch) or (show_ibull == 'CHoCH' and choch) display_Structure(itop_x, itop_y, txt, ibull_css, true, true, internal_structure_lbl_size) itop_cross := false itrend := 1 //Internal Order Block if show_iob ob_coord(false, itop_x, iob_top, iob_btm, iob_left, iob_type) //Detect bullish Structure if ta.crossover(close, top_y) and top_cross bool choch = na if trend < 0 choch := true bull_choch_alert := true else bull_bos_alert := true txt = choch ? 'CHoCH' : 'BOS' if show_Structure if show_bull == 'All' or (show_bull == 'BOS' and not choch) or (show_bull == 'CHoCH' and choch) display_Structure(top_x, top_y, txt, bull_css, false, true, swing_structure_lbl_size) //Order Block if show_ob ob_coord(false, top_x, ob_top, ob_btm, ob_left, ob_type) top_cross := false trend := 1 //-----------------------------------------------------------------------------} //Pivot Low BOS/CHoCH //-----------------------------------------------------------------------------{ var bear_concordant = true if ifilter_confluence bear_concordant := high - math.max(close, open) < math.min(close, open - low) //Detect internal bearish Structure if ta.crossunder(close, ibtm_y) and ibtm_cross and btm_y != ibtm_y and bear_concordant bool choch = false if itrend > 0 choch := true bear_ichoch_alert := true else bear_ibos_alert := true txt = choch ? 'CHoCH' : 'BOS' if show_internals if show_ibear == 'All' or (show_ibear == 'BOS' and not choch) or (show_ibear == 'CHoCH' and choch) display_Structure(ibtm_x, ibtm_y, txt, ibear_css, true, false, internal_structure_lbl_size) ibtm_cross := false itrend := -1 //Internal Order Block if show_iob ob_coord(true, ibtm_x, iob_top, iob_btm, iob_left, iob_type) //Detect bearish Structure if ta.crossunder(close, btm_y) and btm_cross bool choch = na if trend > 0 choch := true bear_choch_alert := true else bear_bos_alert := true txt = choch ? 'CHoCH' : 'BOS' if show_Structure if show_bear == 'All' or (show_bear == 'BOS' and not choch) or (show_bear == 'CHoCH' and choch) display_Structure(btm_x, btm_y, txt, bear_css, false, false, swing_structure_lbl_size) //Order Block if show_ob ob_coord(true, btm_x, ob_top, ob_btm, ob_left, ob_type) btm_cross := false trend := -1 //-----------------------------------------------------------------------------} //Order Blocks //-----------------------------------------------------------------------------{ //Set order blocks var iob_boxes = array.new_box(0) var ob_boxes = array.new_box(0) //Delete internal order blocks box coordinates if top/bottom is broken for element in iob_type index = array.indexof(iob_type, element) if close < array.get(iob_btm, index) and element == 1 array.remove(iob_top, index) array.remove(iob_btm, index) array.remove(iob_left, index) array.remove(iob_type, index) bull_iob_break := true else if close > array.get(iob_top, index) and element == -1 array.remove(iob_top, index) array.remove(iob_btm, index) array.remove(iob_left, index) array.remove(iob_type, index) bear_iob_break := true //Delete internal order blocks box coordinates if top/bottom is broken for element in ob_type index = array.indexof(ob_type, element) if close < array.get(ob_btm, index) and element == 1 array.remove(ob_top, index) array.remove(ob_btm, index) array.remove(ob_left, index) array.remove(ob_type, index) bull_ob_break := true else if close > array.get(ob_top, index) and element == -1 array.remove(ob_top, index) array.remove(ob_btm, index) array.remove(ob_left, index) array.remove(ob_type, index) bear_ob_break := true iob_size = array.size(iob_type) ob_size = array.size(ob_type) if barstate.isfirst if show_iob for i = 0 to iob_showlast-1 array.push(iob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time)) if show_ob for i = 0 to ob_showlast-1 array.push(ob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time)) if iob_size > 0 if barstate.islast display_ob(iob_boxes, iob_top, iob_btm, iob_left, iob_type, iob_showlast, false, iob_size) if ob_size > 0 if barstate.islast display_ob(ob_boxes, ob_top, ob_btm, ob_left, ob_type, ob_showlast, true, ob_size) //-----------------------------------------------------------------------------} //EQH/EQL //-----------------------------------------------------------------------------{ var eq_prev_top = 0. var eq_top_x = 0 var eq_prev_btm = 0. var eq_btm_x = 0 if show_eq eq_top = ta.pivothigh(eq_len, eq_len) eq_btm = ta.pivotlow(eq_len, eq_len) if eq_top max = math.max(eq_top, eq_prev_top) min = math.min(eq_top, eq_prev_top) if max < min + atr * eq_threshold eqh_line = line.new(eq_top_x, eq_prev_top, n-eq_len, eq_top , color = bear_css , style = line.style_dotted) eqh_lbl = label.new(int(math.avg(n-eq_len, eq_top_x)), eq_top, 'EQH' , color = #00000000 , textcolor = bear_css , style = label.style_label_down , size = eqhl_lbl_size) if mode == 'Present' line.delete(eqh_line[1]) label.delete(eqh_lbl[1]) eqh_alert := true eq_prev_top := eq_top eq_top_x := n-eq_len if eq_btm max = math.max(eq_btm, eq_prev_btm) min = math.min(eq_btm, eq_prev_btm) if min > max - atr * eq_threshold eql_line = line.new(eq_btm_x, eq_prev_btm, n-eq_len, eq_btm , color = bull_css , style = line.style_dotted) eql_lbl = label.new(int(math.avg(n-eq_len, eq_btm_x)), eq_btm, 'EQL' , color = #00000000 , textcolor = bull_css , style = label.style_label_up , size = eqhl_lbl_size) eql_alert := true if mode == 'Present' line.delete(eql_line[1]) label.delete(eql_lbl[1]) eq_prev_btm := eq_btm eq_btm_x := n-eq_len //-----------------------------------------------------------------------------} //Fair Value Gaps //-----------------------------------------------------------------------------{ var bullish_fvg_max = array.new_box(0) var bullish_fvg_min = array.new_box(0) var bearish_fvg_max = array.new_box(0) var bearish_fvg_min = array.new_box(0) float bullish_fvg_avg = na float bearish_fvg_avg = na bullish_fvg_cnd = false bearish_fvg_cnd = false [src_c1, src_o1, src_h, src_l, src_h2, src_l2] = request.security(syminfo.tickerid, fvg_tf, get_ohlc()) if show_fvg delta_per = (src_c1 - src_o1) / src_o1 * 100 change_tf = timeframe.change(fvg_tf) threshold = fvg_auto ? ta.cum(math.abs(change_tf ? delta_per : 0)) / n * 2 : 0 //FVG conditions bullish_fvg_cnd := src_l > src_h2 and src_c1 > src_h2 and delta_per > threshold and change_tf bearish_fvg_cnd := src_h < src_l2 and src_c1 < src_l2 and -delta_per > threshold and change_tf //FVG Areas if bullish_fvg_cnd array.unshift(bullish_fvg_max, box.new(n-1, src_l, n + fvg_extend, math.avg(src_l, src_h2) , border_color = bull_fvg_css , bgcolor = bull_fvg_css)) array.unshift(bullish_fvg_min, box.new(n-1, math.avg(src_l, src_h2), n + fvg_extend, src_h2 , border_color = bull_fvg_css , bgcolor = bull_fvg_css)) if bearish_fvg_cnd array.unshift(bearish_fvg_max, box.new(n-1, src_h, n + fvg_extend, math.avg(src_h, src_l2) , border_color = bear_fvg_css , bgcolor = bear_fvg_css)) array.unshift(bearish_fvg_min, box.new(n-1, math.avg(src_h, src_l2), n + fvg_extend, src_l2 , border_color = bear_fvg_css , bgcolor = bear_fvg_css)) for bx in bullish_fvg_min if low < box.get_bottom(bx) box.delete(bx) box.delete(array.get(bullish_fvg_max, array.indexof(bullish_fvg_min, bx))) for bx in bearish_fvg_max if high > box.get_top(bx) box.delete(bx) box.delete(array.get(bearish_fvg_min, array.indexof(bearish_fvg_max, bx))) //-----------------------------------------------------------------------------} //Previous day/week high/lows //-----------------------------------------------------------------------------{ //Daily high/low [pdh, pdl] = request.security(syminfo.tickerid, 'D', hl() , lookahead = barmerge.lookahead_on) //Weekly high/low [pwh, pwl] = request.security(syminfo.tickerid, 'W', hl() , lookahead = barmerge.lookahead_on) //Monthly high/low [pmh, pml] = request.security(syminfo.tickerid, 'M', hl() , lookahead = barmerge.lookahead_on) //Display Daily if show_pdhl phl(pdh, pdl, 'D', pdhl_css) //Display Weekly if show_pwhl phl(pwh, pwl, 'W', pwhl_css) //Display Monthly if show_pmhl phl(pmh, pml, 'M', pmhl_css) //-----------------------------------------------------------------------------} //Premium/Discount/Equilibrium zones //-----------------------------------------------------------------------------{ var premium = box.new(na, na, na, na , bgcolor = color.new(premium_css, 80) , border_color = na) var premium_lbl = label.new(na, na , text = 'Premium' , color = TRANSP_CSS , textcolor = premium_css , style = label.style_label_down , size = size.small) var eq = box.new(na, na, na, na , bgcolor = color.rgb(120, 123, 134, 80) , border_color = na) var eq_lbl = label.new(na, na , text = 'Equilibrium' , color = TRANSP_CSS , textcolor = eq_css , style = label.style_label_left , size = size.small) var discount = box.new(na, na, na, na , bgcolor = color.new(discount_css, 80) , border_color = na) var discount_lbl = label.new(na, na , text = 'Discount' , color = TRANSP_CSS , textcolor = discount_css , style = label.style_label_up , size = size.small) //Show Premium/Discount Areas if barstate.islast and show_sd avg = math.avg(trail_up, trail_dn) box.set_lefttop(premium, math.max(top_x, btm_x), trail_up) box.set_rightbottom(premium, n, .95 * trail_up + .05 * trail_dn) label.set_xy(premium_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_up) box.set_lefttop(eq, math.max(top_x, btm_x), .525 * trail_up + .475*trail_dn) box.set_rightbottom(eq, n, .525 * trail_dn + .475 * trail_up) label.set_xy(eq_lbl, n, avg) box.set_lefttop(discount, math.max(top_x, btm_x), .95 * trail_dn + .05 * trail_up) box.set_rightbottom(discount, n, trail_dn) label.set_xy(discount_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_dn) //-----------------------------------------------------------------------------} //Trend //-----------------------------------------------------------------------------{ var color trend_css = na if show_trend if style == 'Colored' trend_css := itrend == 1 ? bull_css : bear_css else if style == 'Monochrome' trend_css := itrend == 1 ? #b2b5be : #5d606b plotcandle(open, high, low, close , color = trend_css , wickcolor = trend_css , bordercolor = trend_css , editable = false) //-----------------------------------------------------------------------------} //Alerts //-----------------------------------------------------------------------------{ //Internal Structure alertcondition(bull_ibos_alert, 'Internal Bullish BOS', 'Internal Bullish BOS formed') alertcondition(bull_ichoch_alert, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH formed') alertcondition(bear_ibos_alert, 'Internal Bearish BOS', 'Internal Bearish BOS formed') alertcondition(bear_ichoch_alert, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH formed') //Swing Structure alertcondition(bull_bos_alert, 'Bullish BOS', 'Internal Bullish BOS formed') alertcondition(bull_choch_alert, 'Bullish CHoCH', 'Internal Bullish CHoCH formed') alertcondition(bear_bos_alert, 'Bearish BOS', 'Bearish BOS formed') alertcondition(bear_choch_alert, 'Bearish CHoCH', 'Bearish CHoCH formed') //order Blocks alertcondition(bull_iob_break, 'Bullish Internal OB Breakout', 'Price broke bullish internal OB') alertcondition(bear_iob_break, 'Bearish Internal OB Breakout', 'Price broke bearish internal OB') alertcondition(bull_ob_break, 'Bullish Swing OB Breakout', 'Price broke bullish swing OB') alertcondition(bear_ob_break, 'Bearish Swing OB Breakout', 'Price broke bearish swing OB') //EQH/EQL alertcondition(eqh_alert, 'Equal Highs', 'Equal highs detected') alertcondition(eql_alert, 'Equal Lows', 'Equal lows detected') //FVG alertcondition(bullish_fvg_cnd, 'Bullish FVG', 'Bullish FVG formed') alertcondition(bearish_fvg_cnd, 'Bearish FVG', 'Bearish FVG formed') //-----------------------------------------------------------------------------} // CONFIG iBBThreshold = input.float(0.0015, minval=0.0, title='Bollinger Lower Threshold', tooltip='0.003 for daily, 0.0015 for 30 min candles', group='General Settings') RSIThreshold = input.int(25, minval=1, title='RSI Lower Threshold', tooltip='Normally 25', group='General Settings') RSIDown = input.int(72, minval=1, title='RSI Upper Threshold', tooltip='Normally 75', group='General Settings') rsiLengthInput = input.int(14, minval=1, title='RSI Length', group='RSI Settings') rsiSourceInput = input.source(close, 'Source', group='RSI Settings') lengthBB = input.int(20, minval=1, group='Bollinger Bands') srcBB = input.source(close, title='Source', group='Bollinger Bands') multBB = input.float(2.0, minval=0.001, maxval=50, title='StdDev', group='Bollinger Bands') offsetBB = input.int(0, 'Offset', minval=-500, maxval=500, group='Bollinger Bands') isRed = close < open isGreen = close > open // BOLLINGER BANDS basisBB = ta.sma(srcBB, lengthBB) devBB = multBB * ta.stdev(srcBB, lengthBB) upperBB = basisBB + devBB lowerBB = basisBB - devBB downBB = low < lowerBB or high < lowerBB upBB = low > upperBB or high > upperBB bbw = (upperBB - lowerBB) / basisBB // RSI up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput) down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput) rsiM = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down) back1 = isRed[1] and rsiM[1] <= RSIThreshold and close[1] < lowerBB[1] and bbw[1] > iBBThreshold back2 = isRed[2] and rsiM[2] <= RSIThreshold and close[2] < lowerBB[2] and bbw[2] > iBBThreshold back3 = isRed[3] and rsiM[3] <= RSIThreshold and close[3] < lowerBB[3] and bbw[3] > iBBThreshold back4 = isRed[4] and rsiM[4] <= RSIThreshold and close[4] < lowerBB[4] and bbw[4] > iBBThreshold back5 = isRed[5] and rsiM[5] <= RSIThreshold and close[5] < lowerBB[5] and bbw[5] > iBBThreshold for1 = isGreen[1] and rsiM[1] >= RSIDown and close[1] > upperBB[1] and bbw[1] > iBBThreshold for2 = isGreen[2] and rsiM[2] >= RSIDown and close[2] > upperBB[2] and bbw[2] > iBBThreshold for3 = isGreen[3] and rsiM[3] >= RSIDown and close[3] > upperBB[3] and bbw[3] > iBBThreshold for4 = isGreen[4] and rsiM[4] >= RSIDown and close[4] > upperBB[4] and bbw[4] > iBBThreshold for5 = isGreen[5] and rsiM[5] >= RSIDown and close[5] > upperBB[5] and bbw[5] > iBBThreshold weGoUp = isGreen and (back1 or back2 or back3 or back4 or back5) and high > high[1] upThrust = weGoUp and not weGoUp[1] and not weGoUp[2] and not weGoUp[3] and not weGoUp[4] weGoDown = isRed and (for1 or for2 or for3 or for4 or for5) and low < low[1] downThrust = weGoDown and not weGoDown[1] and not weGoDown[2] and not weGoDown[3] and not weGoDown[4] // PLOT THE THINGS plotshape(upThrust ? hl2 : na, title='Buy', text='TUKU', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.rgb(46, 173, 84), textcolor=color.new(color.white, 0)) plotshape(downThrust ? hl2 : na, title='Sell', text='ADOL', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.rgb(173, 46, 69), textcolor=color.new(color.white, 0)) atrUp = high + ta.atr(14) * 1.2 atrDown = low - ta.atr(14) * 1.6 plotshape(upThrust ? atrUp : na, title='ATR ceiling', color=color.new(color.lime, 0), style=shape.xcross, size=size.tiny, location=location.absolute) plotshape(upThrust ? atrDown : na, title='ATR floor', color=color.new(color.red, 0), style=shape.xcross, size=size.tiny, location=location.absolute) atrUp2 = high + ta.atr(14) * 1.6 atrDown2 = low - ta.atr(14) * 1.2 plotshape(downThrust ? atrDown2 : na, title='ATR ceiling', color=color.new(color.lime, 0), style=shape.xcross, size=size.tiny, location=location.absolute) plotshape(downThrust ? atrUp2 : na, title='ATR floor', color=color.new(color.red, 0), style=shape.xcross, size=size.tiny, location=location.absolute) // ALERTS alertcondition(upThrust, title='Trampoline BUY', message='Trampoline BUY') alertcondition(downThrust, title='Trampoline SELL', message='Trampoline SELL') //2 Bollinger Bands lengthshort = input.int(30, minval=1) lengthlong = input.int(200, minval=1) // std devs mult1 = 1.0 mult2 = 2.0 mult3 = 3.0 // smas basisshort = ta.sma(close, lengthshort) basislong = ta.sma(close, lengthlong) // short sma measurements lengthshortstd1 = mult1 * ta.stdev(close, lengthshort) lengthshortstd1upper = basisshort + lengthshortstd1 lengthshortstd1lower = basisshort - lengthshortstd1 lengthshortstd2 = mult2 * ta.stdev(close, lengthshort) lengthshortstd2upper = basisshort + lengthshortstd2 lengthshortstd2lower = basisshort - lengthshortstd2 lengthshortstd3 = mult3 * ta.stdev(close, lengthshort) lengthshortstd3upper = basisshort + lengthshortstd3 lengthshortstd3lower = basisshort - lengthshortstd3 // long sma measurements lengthlongstd1 = mult1 * ta.stdev(close, lengthlong) lengthlongstd1upper = basislong + lengthlongstd1 lengthlongstd1lower = basislong - lengthlongstd1 lengthlongstd2 = mult2 * ta.stdev(close, lengthlong) lengthlongstd2upper = basislong + lengthlongstd2 lengthlongstd2lower = basislong - lengthlongstd2 lengthlongstd3 = mult3 * ta.stdev(close, lengthlong) lengthlongstd3upper = basislong + lengthlongstd3 lengthlongstd3lower = basislong - lengthlongstd3 offset = input.int(0, 'Offset', minval=-500, maxval=500) // plot midlines, remove to unclutter plot(basisshort, 'Basis Line Short', color=color.new(color.rgb(128, 128, 128), transp=20), offset=offset) plot(basislong, 'Basis Line Long', color=color.new(color.rgb(249, 0, 0), transp=20), offset=offset) //plot short length stddev lines lengthshortstd1upperplot = plot(lengthshortstd1upper, 'Upper short - 1.0', color=color.new(color.rgb(246, 246, 246), transp=95), offset=offset) lengthshortstd1lowerplot = plot(lengthshortstd1lower, 'Lower short -1.0', color=color.new(color.rgb(246, 246, 246), transp=95), offset=offset) lengthshortstd2upperplot = plot(lengthshortstd2upper, 'Upper short- 2.0', color=color.new(color.rgb(86, 86, 86), transp=95), offset=offset) lengthshortstd2lowerplot = plot(lengthshortstd2lower, 'Lower short - 2.0', color=color.new(color.rgb(86, 86, 86), transp=95), offset=offset) lengthshortstd3upperplot = plot(lengthshortstd3upper, 'Upper short - 3.0', color=color.new(color.rgb(57, 57, 57), transp=90), offset=offset) lengthshortstd3lowerplot = plot(lengthshortstd3lower, 'Lower short - 3.0', color=color.new(color.rgb(57, 57, 57), transp=90), offset=offset) //plot long length stddev lines lengthlongstd1upperplot = plot(lengthlongstd1upper, 'Upper long - 1.0', color=color.new(color.purple, transp=70), offset=offset) lengthlongstd1lowerplot = plot(lengthlongstd1lower, 'Lower long -1.0', color=color.new(color.purple, transp=70), offset=offset) lengthlongstd2upperplot = plot(lengthlongstd2upper, 'Upper long- 2.0', color=color.new(color.purple, transp=70), offset=offset) lengthlongstd2lowerplot = plot(lengthlongstd2lower, 'Lower long - 2.0', color=color.new(color.purple, transp=70), offset=offset) lengthlongstd3upperplot = plot(lengthlongstd3upper, 'Upper long - 3.0', color=color.new(color.purple, transp=70), offset=offset) lengthlongstd3lowerplot = plot(lengthlongstd3lower, 'Lower long - 3.0', color=color.new(color.purple, transp=70), offset=offset) // fill short length regions // inner, stddev 1.0 fill(lengthshortstd1upperplot, lengthshortstd1lowerplot, title='Background: Length short - stddev 1', color=color.new(color.rgb(246, 246, 246), transp=93)) // upper and lower std dev 2.0 fill(lengthshortstd1upperplot, lengthshortstd2upperplot, title='Background: Length short - stddev 2.0 Upper', color=color.new(color.rgb(81, 81, 81), transp=94)) fill(lengthshortstd1lowerplot, lengthshortstd2lowerplot, title='Background: Length short = stddev 2.0 Lower', color=color.new(color.rgb(81, 81, 81), transp=94)) // upper and lower std dev 3.0 fill(lengthshortstd2upperplot, lengthshortstd3upperplot, title='Background: Length short - stddev 3.0 Upper', color=color.new(color.rgb(57, 57, 57), transp=90)) fill(lengthshortstd2lowerplot, lengthshortstd3lowerplot, title='Background: Length short - stddev 3.0 Lower', color=color.new(color.rgb(57, 57, 57), transp=90)) // fill long length regions // inner, stddev 1.0 fill(lengthlongstd1upperplot, lengthlongstd1lowerplot, title='Background: Length long - stddev 1', color=color.new(color.white, transp=97)) // upper and lower std dev 2.0 fill(lengthlongstd1upperplot, lengthlongstd2upperplot, title='Background: Length long - stddev 2.0 Upper', color=color.new(color.white, transp=97)) fill(lengthlongstd1lowerplot, lengthlongstd2lowerplot, title='Background: Length long = stddev 2.0 Lower', color=color.new(color.white, transp=97)) // upper and lower std dev 3.0 fill(lengthlongstd2upperplot, lengthlongstd3upperplot, title='Background: Length long - stddev 3.0 Upper', color=color.new(color.white, transp=97)) fill(lengthlongstd2lowerplot, lengthlongstd3lowerplot, title='Background: Length long - stddev 3.0 Lower', color=color.new(color.white, transp=97)) // Volume Candle emaPeriod = input(20, 'Volume EMA Period') volumeRatio = volume / ta.ema(volume, emaPeriod) isUp = close > open //{ //============================================================================================================================= //Green and red color repository. 6 is darkest. 1 is lightest. g_01 = #d2d4d2 g_02 = #d2d4d2 g_03 = #d2d4d2 g_04 = #cff9ff g_05 = #5af7ff g_06 = #00b2df r_01 = #6b6767 r_02 = #6b6767 r_03 = #6b6767 r_04 = #ffb3b3 r_05 = #fb6767 r_06 = #da0202 //----------------------------------------------------------------------------------------------------------------------------- //} color candleColor = na if volume and isUp candleColor := volumeRatio > 2 ? g_06 : volumeRatio > 1.5 ? g_05 : volumeRatio > 1.2 ? g_04 : volumeRatio > 0.8 ? g_03 : volumeRatio > 0.4 ? g_02 : g_01 candleColor else if volume candleColor := volumeRatio > 2 ? r_06 : volumeRatio > 1.5 ? r_05 : volumeRatio > 1.2 ? r_04 : volumeRatio > 0.8 ? r_03 : volumeRatio > 0.4 ? r_02 : r_01 candleColor barcolor(candleColor)
Portfolio Heat
https://www.tradingview.com/script/zn0dhdX7-Portfolio-Heat/
Amphibiantrading
https://www.tradingview.com/u/Amphibiantrading/
91
study
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/ // © Amphibiantrading //@version=5 indicator('Portfolio Heat', overlay = true) //----------settings----------// acct = input.float(100000., 'Account Size', confirm = true) view = input.string('Detailed View', 'Detail Options', ['Detailed View', 'Summary']) levels = input.bool(false, 'Show Levels On Holdings') entCol = input.color(color.green, 'Entry Color', inline = '0') stopCol = input.color(color.red, 'Stop Color', inline = '0') yPos = input.string('Bottom', 'Table Position ', options = ['Top', 'Middle', 'Bottom'], inline = '1') xPos = input.string('Center', ' ', options = ['Right','Center', 'Left'], inline = '1') headCol = input.color(color.rgb(0, 111, 202), 'Header Background Color') headTxtCol = input.color(color.white, 'Header Text Color') listCol = input.color(color.gray, 'Symbols Background Color') txtDataCol = input.color(color.white, 'Data Text Color') txtTotalCol = input.color(color.red, 'Total Text Color') txtSize = input.string('Normal', 'Table Size', ['Tiny', 'Small', 'Normal', 'Large']) var g0 = 'Symbol 1' useSym0 = input.bool(true, ' ', inline = '1', group = g0, confirm = true) sym0 = input.symbol('CELH', ' ', inline = '1', group = g0, confirm = true) shares0 = input.int(0, 'Shares', inline = '1', group = g0, confirm = true) entry0 = input.float(0.0, 'Entry', inline = '2', group = g0, confirm = true) stop0 = input.float(0.0, 'Stop', inline = '2', group = g0, confirm = true) var g1 = 'Symbol 2' useSym1 = input.bool(false, '', inline = '1', group = g1) sym1 = input.symbol('AAPL', ' ', inline = '1', group = g1) shares1 = input.int(0, 'Shares', inline = '1', group = g1) entry1 = input.float(0.0, 'Entry', inline = '2', group = g1) stop1 = input.float(0.0, 'Stop', inline = '2', group = g1) var g2 = 'Symbol 3' useSym2 = input.bool(false, '', inline = '1', group = g2) sym2 = input.symbol('TSLA', ' ', inline = '1', group = g2) shares2 = input.int(0, 'Shares', inline = '1', group = g2) entry2 = input.float(0.0, 'Entry', inline = '2', group = g2) stop2 = input.float(0.0, 'Stop', inline = '2', group = g2) var g3 = 'Symbol 4' useSym3 = input.bool(false, '', inline = '1', group = g3) sym3 = input.symbol('NVDA', ' ', inline = '1', group = g3) shares3 = input.int(0, 'Shares', inline = '1', group = g3) entry3 = input.float(0.0, 'Entry', inline = '2', group = g3) stop3 = input.float(0.0, 'Stop', inline = '2', group = g3) var g4 = 'Symbol 5' useSym4 = input.bool(false, '', inline = '1', group = g4) sym4 = input.symbol('GOOGL', ' ', inline = '1', group = g4) shares4 = input.int(0, 'Shares', inline = '1', group = g4) entry4 = input.float(0.0, 'Entry', inline = '2', group = g4) stop4 = input.float(0.0, 'Stop', inline = '2', group = g4) var g5 = 'Symbol 6' useSym5 = input.bool(false, '', inline = '1', group = g5) sym5 = input.symbol('MSFT', ' ', inline = '1', group = g5) shares5 = input.int(0, 'Shares', inline = '1', group = g5) entry5 = input.float(0.0, 'Entry', inline = '2', group = g5) stop5 = input.float(0.0, 'Stop', inline = '2', group = g5) var g6 = 'Symbol 7' useSym6 = input.bool(false, '', inline = '1', group = g6) sym6 = input.symbol('AMD', ' ', inline = '1', group = g6) shares6 = input.int(0, 'Shares', inline = '1', group = g6) entry6 = input.float(0.0, 'Entry', inline = '2', group = g6) stop6 = input.float(0.0, 'Stop', inline = '2', group = g6) var g7 = 'Symbol 8' useSym7 = input.bool(false, '', inline = '1', group = g7) sym7 = input.symbol('NFLX', ' ', inline = '1', group = g7) shares7 = input.int(0, 'Shares', inline = '1', group = g7) entry7 = input.float(0.0, 'Entry', inline = '2', group = g7) stop7 = input.float(0.0, 'Stop', inline = '2', group = g7) var g8 = 'Symbol 9' useSym8 = input.bool(false, '', inline = '1', group = g8) sym8 = input.symbol('NFLX', ' ', inline = '1', group = g8) shares8 = input.int(0, 'Shares', inline = '1', group = g8) entry8 = input.float(0.0, 'Entry', inline = '2', group = g8) stop8 = input.float(0.0, 'Stop', inline = '2', group = g8) var g9 = 'Symbol 10' useSym9 = input.bool(false, '', inline = '1', group = g9) sym9 = input.symbol('NFLX', ' ', inline = '1', group = g9) shares9 = input.int(0, 'Shares', inline = '1', group = g9) entry9 = input.float(0.0, 'Entry', inline = '2', group = g9) stop9 = input.float(0.0, 'Stop', inline = '2', group = g9) if not useSym0 entry0 := 0.0 shares0 := 0 stop0 := 0.0 if not useSym1 entry1 := 0.0 shares1 := 0 stop1 := 0.0 if not useSym2 entry2 := 0.0 shares2 := 0 stop2 := 0.0 if not useSym3 entry3 := 0.0 shares3 := 0 stop3 := 0.0 if not useSym4 entry4 := 0.0 shares4 := 0 stop4 := 0.0 if not useSym5 entry5 := 0.0 shares5 := 0 stop5 := 0.0 if not useSym6 entry6 := 0.0 shares6 := 0 stop6 := 0.0 if not useSym7 entry7 := 0.0 shares7 := 0 stop7 := 0.0 if not useSym8 entry8 := 0.0 shares8 := 0 stop8 := 0.0 if not useSym9 entry9 := 0.0 shares9 := 0 stop9 := 0.0 //----------variables----------// var table data = table.new(str.lower(yPos) + '_' + str.lower(xPos), 12, 4, color.new(color.white,100), color.new(color.white,100), 2, color.new(color.white,100),2) var line entryLine = na var line stopLine = na //----------functions & methods----------// getPrice (sym)=> request.security(sym, 'D', close) calcRisk(curr, ent, sto, shrs)=> risk = (curr - sto) * shrs perRisk = (risk / acct) * 100 capRisk = (ent - sto) * shrs [risk, perRisk, capRisk] fsplit(a)=> test = str.split(a, ":") tableCell(col,row, txt, txtcolor, bgcolor, size)=> data.cell(col,row, txt, text_color = txtcolor, bgcolor = bgcolor, text_size = size) tblSize = switch txtSize 'Tiny' => size.tiny 'Normal' => size.normal 'Small' => size.small 'Large' => size.large //----------calculations----------// close0 = getPrice(sym0) close1 = getPrice(sym1) close2 = getPrice(sym2) close3 = getPrice(sym3) close4 = getPrice(sym4) close5 = getPrice(sym5) close6 = getPrice(sym6) close7 = getPrice(sym7) close8 = getPrice(sym8) close9 = getPrice(sym9) [dr0, pr0, cr0] = calcRisk(close0, entry0, stop0, shares0) [dr1, pr1, cr1] = calcRisk(close1, entry1, stop1, shares1) [dr2, pr2, cr2] = calcRisk(close2, entry2, stop2, shares2) [dr3, pr3, cr3] = calcRisk(close3, entry3,stop3, shares3) [dr4, pr4, cr4] = calcRisk(close4, entry4,stop4, shares4) [dr5, pr5, cr5] = calcRisk(close5, entry5,stop5, shares5) [dr6, pr6, cr6] = calcRisk(close6, entry6,stop6, shares6) [dr7, pr7, cr7] = calcRisk(close7, entry7,stop7, shares7) [dr8, pr8, cr8] = calcRisk(close8, entry8,stop8, shares8) [dr9, pr9, cr9] = calcRisk(close9, entry9,stop9, shares9) //----------data arrays----------// drArr = array.from(dr0,dr1,dr2,dr3,dr4,dr5,dr6,dr7,dr8,dr9) prArr = array.from(pr0,pr1,pr2,pr3,pr4,pr5,pr6,pr7,pr8,pr9) crArr = array.from(cr0,cr1,cr2,cr3,cr4,cr5,cr6,cr7,cr8,cr9) symArr = array.from(sym0,sym1,sym2,sym3,sym4,sym5,sym6,sym7,sym8,sym9) useArr = array.from(useSym0,useSym1,useSym2,useSym3,useSym4,useSym5,useSym6,useSym7,useSym8,useSym9) totalRisk = drArr.sum() perRisk = (totalRisk / acct) * 100 capRisk = crArr.sum() //----------create the data table----------// if barstate.islast data.cell(0,1, 'Open Dollar Risk', text_color = headTxtCol, text_halign = text.align_right, bgcolor = headCol, text_size = tblSize) data.cell(0,2, 'Open % of Portfolio Risk', text_color = headTxtCol, text_halign = text.align_right, bgcolor = headCol, text_size = tblSize) data.cell(11,1, '$' + str.tostring(totalRisk, '#,###.##'), text_color =txtTotalCol, text_size = tblSize) data.cell(11,2, str.tostring(perRisk, '#.##') + '%', text_color = txtTotalCol, text_size = tblSize) if view == 'Detailed View' data.cell(0,0, 'Symbol', text_color = headTxtCol, text_halign = text.align_right, bgcolor = headCol, text_size = tblSize) data.cell(11,0, 'Totals', text_color = headTxtCol, bgcolor = headCol, text_size = tblSize) data.cell(0,3, 'Starting Capital Risk', text_color = headTxtCol, text_halign = text.align_right, bgcolor = headCol, text_size = tblSize) data.cell(11,3, '$' + str.tostring(capRisk, format.mintick), text_color = txtTotalCol, text_size = tblSize) for i = 0 to useArr.size()-1 if useArr.get(i) == true symbol = fsplit(symArr.get(i)).get(1) tableCell(i+1,0, symbol, headTxtCol, listCol, tblSize) tableCell(i+1,1, '$' + str.tostring(drArr.get(i), '#,###.##'), txtDataCol, color.new(color.white,100), tblSize) tableCell(i+1,2, str.tostring(prArr.get(i), '#.##') + "%", txtDataCol, color.new(color.white,100), tblSize) tableCell(i+1,3, '$' + str.tostring(crArr.get(i), '#,###.##'), txtDataCol, color.new(color.white,100), tblSize) if levels and (syminfo.ticker == fsplit(sym0).get(1) and useSym0) entryLine := line.new(bar_index[1], entry0, bar_index, entry0, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop0, bar_index, stop0, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym1).get(1) and useSym1) entryLine := line.new(bar_index[1], entry1, bar_index, entry1, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop1, bar_index, stop1, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym2).get(1) and useSym2) entryLine := line.new(bar_index[1], entry2, bar_index, entry2, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop2, bar_index, stop2, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym3).get(1) and useSym3) entryLine := line.new(bar_index[1], entry3, bar_index, entry3, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop3, bar_index, stop3, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym4).get(1) and useSym4) entryLine := line.new(bar_index[1], entry4, bar_index, entry4, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop4, bar_index, stop4, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym5).get(1) and useSym5) entryLine := line.new(bar_index[1], entry5, bar_index, entry5, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop5, bar_index, stop5, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym6).get(1) and useSym6) entryLine := line.new(bar_index[1], entry6, bar_index, entry6, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop6, bar_index, stop6, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym7).get(1) and useSym7) entryLine := line.new(bar_index[1], entry7, bar_index, entry7, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop7, bar_index, stop7, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym8).get(1) and useSym8) entryLine := line.new(bar_index[1], entry8, bar_index, entry8, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop8, bar_index, stop8, color = stopCol, extend = extend.both) else if levels and (syminfo.ticker == fsplit(sym9).get(1) and useSym9) entryLine := line.new(bar_index[1], entry9, bar_index, entry9, color = entCol, extend = extend.both) stopLine := line.new(bar_index[1], stop9, bar_index, stop9, color = stopCol, extend = extend.both)