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
|
---|---|---|---|---|---|---|---|---|
Vector2FunctionClip | https://www.tradingview.com/script/fPlUufEw-Vector2FunctionClip/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 18 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Sutherland-Hodgman polygon clipping algorithm.
// reference:
// .
// https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
// .
library('Vector2FunctionClip')
//#region -> Imports and helper functions:
import RicardoSantos/CommonTypesMath/1 as TMath
import RicardoSantos/Vector2/1 as Vector2
import RicardoSantos/Vector2Array/1 as Vector2a
import RicardoSantos/Segment2/1 as Segment2
import RicardoSantos/Vector2DrawLine/1 as line
inside (TMath.Vector2 p, TMath.Vector2 cp1, TMath.Vector2 cp2) =>
(cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)
//#endregion
// clip () {
// @function Perform Clip operation on a vector with another.
// @param source array<Vector2> . Source polygon to be clipped.
// @param reference array<Vector2> . Reference polygon to clip source.
// @returns array<Vector2>.
export method clip (array<TMath.Vector2> source, array<TMath.Vector2> reference) =>
int _size_ref = array.size(source)
_outputList = array.copy(source)
_cp1 = array.get(reference, array.size(reference)-1)
for _cp2 in reference
_input_list = _outputList
_outputList := array.new<TMath.Vector2>(0)
_s = array.get(_input_list, array.size(_input_list)-1)
for [_i, _e] in _input_list
if inside(_e, _cp1, _cp2)
if not inside(_s, _cp1, _cp2)
array.push(_outputList, Segment2.intersection(Segment2.new(_cp1, _cp2), Segment2.new(_s, _e)))
array.push(_outputList, _e)
else if inside(_s, _cp1, _cp2)
array.push(_outputList, Segment2.intersection(Segment2.new(_cp1, _cp2), Segment2.new(_s, _e)))
_s := _e
_cp1 := _cp2
_outputList
// TEST: 20230221 RS
array<TMath.Vector2> source = Vector2a.from(input.string('50,150 ; 200,50 ; 350,150 ; 350,300 ; 250,300 ; 200,250 ; 150,350 ; 100,250 ; 100,200'))
array<TMath.Vector2> reference = Vector2a.from(input.string('100,100 ; 300,100 ; 300,300 ; 100,300'))
for [_i, _e] in source
_e.x += bar_index
source.set(_i, _e)
for [_i, _e] in reference
_e.x += bar_index
source.set(_i, _e)
if barstate.islast
TMath.Vector2 _previous = source.last()
for [_i, _e] in source
line.new(_previous, _e, color=#a0a0a0) , _previous := _e
_previous := reference.last()
for [_i, _e] in reference
line.new(_previous, _e, color=#cc4545) , _previous := _e
array<TMath.Vector2> _clipped = clip(source, reference)
_previous := _clipped.last()
for [_i, _e] in _clipped
line.new(_previous, _e, color=#69cc45,style='dsh') , _previous := _e
// }
|
WarCalendar | https://www.tradingview.com/script/CRY4Kj2W-WarCalendar/ | trevor1617 | https://www.tradingview.com/u/trevor1617/ | 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/
// © jdehorty
//@version=5
// @description This library is a data provider for important Dates and Times from the Economic Calendar.
library(title='WarCalendar')
// @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(
"Start of War"
)
// @returns
export warstart() =>
array.from(
timestamp("7 Oct 2001 00:00:00 UTC"),
timestamp("20 Mar 2003 00:00:00 UTC"),
timestamp("15 Jun 2014 00:00:00 UTC"),
timestamp("1 Jan 2015 00:00:00 UTC"),
timestamp("1 Aug 2016 00:00:00 UTC"),
timestamp("1 Sep 2017 00:00:00 UTC"),
timestamp("22 Apr 2017 00:00:00 UTC"),
timestamp("1 Apr 2014 00:00:00 UTC"),
timestamp("14 Sep 2001 00:00:00 UTC"),
timestamp("1 Jul 2019 00:00:00 UTC"),
timestamp("1 Jan 2015 00:00:00 UTC"),
timestamp("1 Apr 2014 00:00:00 UTC"),
timestamp("12 Jun 1999 00:00:00 UTC"),
timestamp("1 Oct 2002 00:00:00 UTC"),
timestamp("12 Mar 2011 00:00:00 UTC"),
timestamp("28 Jun 2007 00:00:00 UTC"),
timestamp("19 Mar 2011 00:00:00 UTC"),
timestamp("11 Jan 2013 00:00:00 UTC"),
timestamp("26 Aug 2013 00:00:00 UTC"),
timestamp("15 Sep 2014 00:00:00 UTC"),
timestamp("25 Mar 2015 00:00:00 UTC"),
timestamp("23 Jan 2018 00:00:00 UTC"),
timestamp("8 May 2018 00:00:00 UTC"),
timestamp("9 Oct 2019 00:00:00 UTC")
)
|
Open, Open +/- EMA ATR Lines with Labels | https://www.tradingview.com/script/R3gEMmZY-Open-Open-EMA-ATR-Lines-with-Labels/ | AOSSA_Traders | https://www.tradingview.com/u/AOSSA_Traders/ | 16 | 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/
// © AOSSA_Traders
//@version=5
indicator("Open, Open +/- EMA ATR Lines with Labels", shorttitle="O, O+/-EMA ATR Lines", overlay=true)
timeframeInput = input.string(defval="D", title="Timeframe", options=["1", "5", "15", "30", "60", "240", "D", "W", "M"])
atrLength = input.int(14, title="ATR Length")
openFromTF = request.security(syminfo.tickerid, timeframeInput, open)
highFromTF = request.security(syminfo.tickerid, timeframeInput, high)
lowFromTF = request.security(syminfo.tickerid, timeframeInput, low)
closeFromTF = request.security(syminfo.tickerid, timeframeInput, close)
isNotFirstBar = not na(closeFromTF[1])
trueRange = isNotFirstBar ? math.max(highFromTF - lowFromTF, math.abs(highFromTF - closeFromTF[1]), math.abs(lowFromTF - closeFromTF[1])) : highFromTF - lowFromTF
emaATR = ta.ema(trueRange, atrLength)
upper = openFromTF + emaATR
lower = openFromTF - emaATR
calculatePips(value) =>
pips = math.round((value - openFromTF) * 10000)
pips
formatNumber(value) =>
str.tostring(math.floor(value * 100000) / 100000)
var line upperLine = line.new(x1=bar_index - 100, y1=upper, x2=bar_index, y2=upper, color=color.blue, width=2)
var line lowerLine = line.new(x1=bar_index - 100, y1=lower, x2=bar_index, y2=lower, color=color.blue, width=2)
var line openLine = line.new(x1=bar_index - 100, y1=openFromTF, x2=bar_index, y2=openFromTF, color=color.green, width=1)
var label upperLabel = label.new(x=bar_index, y=upper, text="", color=color.black, xloc=xloc.bar_index, yloc=yloc.price, size=size.normal, textcolor = color.white)
var label lowerLabel = label.new(x=bar_index, y=lower, text="", color=color.black, xloc=xloc.bar_index, yloc=yloc.price, size=size.normal, textcolor = color.white)
var label openLabel = label.new(x=bar_index, y=openFromTF, text="", color=color.black, xloc=xloc.bar_index, yloc=yloc.price, size=size.normal, textcolor = color.white)
line.set_xy1(upperLine, bar_index - 100, upper)
line.set_xy2(upperLine, bar_index +10, upper)
label.set_xy(upperLabel, bar_index +10, upper)
label.set_text(upperLabel, formatNumber(upper) + " (" + str.tostring(calculatePips(upper)) + " pips)")
line.set_xy1(lowerLine, bar_index - 100, lower)
line.set_xy2(lowerLine, bar_index +10, lower)
label.set_xy(lowerLabel, bar_index +10, lower)
label.set_text(lowerLabel, formatNumber(lower) + " (" + str.tostring(calculatePips(lower)) + " pips)")
line.set_xy1(openLine, bar_index - 100, openFromTF)
line.set_xy2(openLine, bar_index +10, openFromTF)
label.set_xy(openLabel, bar_index +10, openFromTF)
label.set_text(openLabel, formatNumber(openFromTF))
|
Linear_Regression_Slope | https://www.tradingview.com/script/cmVYMX6Y-Linear-Regression-Slope/ | Quantkr | https://www.tradingview.com/u/Quantkr/ | 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/
// © MBYLAB
//@version=5
// @description : this show slope based on linear regression
// @param : "a" must input Source, [close, open, high, low]//
// @param : "b" the length about period.
library("Linear_Regression_Slope", overlay = false)
export linreg_slope(float a, int b) =>
src = a, len = b
float sum_x = 0,
float sum_y = 0,
float sum_xy = 0,
float sum_x2 = 0
for i = 0 to len -1
sum_x := sum_x + i
sum_y := sum_y + src[i]
sum_xy := sum_xy + i * src[i]
sum_x2 := sum_x2 + i * i
result = (len * sum_xy - sum_x * sum_y) / (len * sum_x2 - sum_x * sum_x)
result |
% Above 50 DMA | https://www.tradingview.com/script/JM8DNAE8-Above-50-DMA/ | crutchie | https://www.tradingview.com/u/crutchie/ | 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/
// © crutchie
//@version=5
indicator("% Above 50 DMA")
//Inputs
exchange = input.string("NYSE", options = ["NYSE", "Nasdaq"])
perc = exchange == "NYSE" ? request.security("MMFI", timeframe.period, close) : request.security("NCFI", timeframe.period, close)
ema1 = ta.ema(perc,5)
ema2 = ta.ema(perc,20)
perccolor = perc > 80 ? color.red : perc < 20 ? color.red : color.black
plot(perc, "Percent", color = perccolor)
plot(ema1, "EMA 1" , color = color.rgb(13, 234, 230), display = display.pane)
plot(ema2, "EMA 2", color = color.blue, display = display.pane)
hline(20, "Danger Zone", color = color.red)
hline(80, "Oversold Zone", color = color.red)
//Background shading signal
signalcolor = ema1 > ema2 ? color.rgb(76, 175, 79, 90) : color.rgb(255, 82, 82, 92)
bgcolor(signalcolor, title = "Signal Shading") |
Volume peak based zones | https://www.tradingview.com/script/JOnTLW3V/ | Demech | https://www.tradingview.com/u/Demech/ | 53 | 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/
// © Demech
//@version=5
indicator("Volume peak based Zones", overlay=true)
// Parameter
length = input.int(20, "Moving average for volume")
threshold = input.float(3, "Z-Score Threshold")
boxlen = input(20, title = "Box length")
srcb = input.source(low, title = "Bull Bottom")
srcs = input.source(high, title = "Sell Top")
srcmb = input.source(close, title = "Body")
boxcolor = input.color(color.new(#000000, 70))
// Volume SMA and standard deviation
meanVolume = ta.sma(volume, length)
stdDevVolume = ta.stdev(volume, length)
// Calculation of the Z-score
zScore = (volume - meanVolume) / stdDevVolume
isVolumeSpike = zScore > threshold
// Determine the direction of the candle and the volume of the candle
isBullish = close < open and isVolumeSpike
isBearish = close > open and isVolumeSpike
// Box drawing
if(isBullish)
box.new(top_left = chart.point.from_index(bar_index, srcmb), bottom_right = chart.point.from_index(bar_index + int(boxlen), srcb), border_color = boxcolor, bgcolor = boxcolor)
if(isBearish)
box.new(top_left = chart.point.from_index(bar_index, srcmb), bottom_right = chart.point.from_index(bar_index + int(boxlen), srcs), border_color = boxcolor, bgcolor = boxcolor)
// Alarms
combined_alert = isBearish or isBullish
alertcondition(combined_alert, title='Combined Alert', message='Box detectet') |
Wave Generator Library (WGL) | https://www.tradingview.com/script/Sq8W8Jhr-Wave-Generator-Library-WGL/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
// @description Wave Generator Library
library("WaveGenerator")
n = bar_index
//@function max
//@param source is the input to take the maximum.
//@returns foat
export max(float source)=>
var float max = na
src = array.new<float>()
array.push(src, source)
max := math.max(nz(max[1]), array.get(src, 0))
//@function min
//@param source is the input to take the minimum.
//@returns foat
export min(float source)=>
var float min = na
src = array.new<float>()
array.push(src, source)
min := math.min(nz(min[1]), array.get(src, 0))
//@function min_max
//@param src is the input for the min/max
//@returns float
export min_max(float src, float height)=>
(((src - min(src))/(max(src) - min(src)) - 0.5) * 2) * height
//@function sine_wave
//@param _wave_height Maximum output level
//@param _wave_duration Wave length
//@param _phase_shift Number of harmonics
//@param _phase_shift_2_shift Phase shift
//@returns float
export sine_wave(float _wave_height, int _wave_duration, float _phase_shift, float _phase_shift_2) =>
_pi = math.pi
_w = 2 * _pi / _wave_duration
_sine_wave = _wave_height * math.sin(_w * n + _phase_shift + _phase_shift_2)
_sine_wave
//@function triangle_wave
//@param _wave_height Maximum output level
//@param _wave_duration Wave length
//@param _num_harmonics Number of harmonics
//@param _phase_shift Phase shift
//@returns float
export triangle_wave(float _wave_height, int _wave_duration, int _num_harmonics, float _phase_shift) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, sine_wave(1 / math.pow(2 * i - 1, 2), _wave_duration / (2 * i - 1), (i - 1) * _pi, int(_phase_shift) * _pi))
_triangle_wave = array.avg(sine_waves)
min_max(_triangle_wave, _wave_height)
//@function saw_wave
//@param _wave_height Maximum output level
//@param _wave_duration Wave length
//@param _num_harmonics Number of harmonics
//@param _phase_shift Phase shift
//@returns float
export saw_wave(float _wave_height, int _wave_duration, int _num_harmonics, float _phase_shift) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, sine_wave(1 / (i), _wave_duration / (i), i * _phase_shift * _pi, 0))
_saw_wave = array.avg(sine_waves)
min_max(_saw_wave, _wave_height)
//@function ramp_saw_wave
//@param _wave_height Maximum output level
//@param _wave_duration Wave length
//@param _num_harmonics Number of harmonics
//@param _phase_shift Phase shift
//@returns float
export ramp_saw_wave(float _wave_height, int _wave_duration, int _num_harmonics, float _phase_shift) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, sine_wave(1 / (i), _wave_duration / (i), i * _phase_shift * _pi, 66))
_ramp_saw_wave = array.sum(sine_waves)
min_max(_ramp_saw_wave, _wave_height)
//@function square_wave
//@param _wave_height Maximum output level
//@param _wave_duration Wave length
//@param _num_harmonics Number of harmonics
//@param _phase_shift Phase shift
//@returns float
export square_wave(float _wave_height, int _wave_duration, int _num_harmonics, float _phase_shift) =>
_pi = math.pi
sine_waves = array.new<float>()
for i = 1 to _num_harmonics
array.push(sine_waves, sine_wave(1 / (2 * i - 1), _wave_duration / (2 * i - 1), (i * 2 - 1) * _phase_shift * _pi, 0))
_square_wave = array.avg(sine_waves)
min_max(_square_wave, _wave_height)
//@function wave_select
//@peram style Select the style of wave. "Sine", "Triangle", "Saw", "Ramp Saw", "Square"
//@param _wave_height Maximum output level
//@param _wave_duration Wave length
//@param _num_harmonics Number of harmonics
//@param _phase_shift Phase shift
//@returns float
export wave_select(string style, float _wave_height, int _wave_duration, int _num_harmonics, float _phase_shift)=>
switch style
"Sine" => sine_wave(_wave_height, _wave_duration, 0, _phase_shift)
"Triangle" => triangle_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"Saw" => saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"Ramp Saw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"Square" => square_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"sine" => sine_wave(_wave_height, _wave_duration, 0, _phase_shift)
"triangle" => triangle_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"saw" => saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"ramp saw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"square" => square_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"SINE" => sine_wave(_wave_height, _wave_duration, 0, _phase_shift)
"TRIANGLE" => triangle_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"SAW" => saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"RAMP SAW" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"SQUARE" => square_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"RAMPSAW" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"RampSaw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"Ramp_Saw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"ramp_saw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"Rampsaw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"rampSaw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"rampsaw" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"1" => sine_wave(_wave_height, _wave_duration, 0, _phase_shift)
"2" => triangle_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"3" => saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"4" => ramp_saw_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
"5" => square_wave(_wave_height, _wave_duration, _num_harmonics, _phase_shift)
Wave_Select = min_max(wave_select("Saw", 1, 64, 64, 0) * wave_select("Triangle", sine_wave(1, 24, 0, 0), 32, 1, 0), 1)
plot(Wave_Select) |
DrawingTypes | https://www.tradingview.com/script/63c8VXSa-DrawingTypes/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 34 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description User Defined Types for basic drawing structure. Other types and methods will be built on these.
library("DrawingTypes", overlay = true)
// @type Point refers to point on chart
// @field price pivot price
// @field bar pivot bar
// @field bartime pivot bar time
export type Point
float price
int bar
int bartime
// @type Properties of line object
// @field xloc X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
// @field extend Property which sets line to extend towards either right or left or both. Valid values are extend.right, extend.left, extend.both, extend.none. Default is extend.none
// @field color Line color
// @field style Line style, valid values are line.style_solid, line.style_dashed, line.style_dotted, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Default is line.style_solid
// @field width Line width. Default is 1
export type LineProperties
string xloc = xloc.bar_index
string extend = extend.none
color color = color.blue
string style = line.style_solid
int width = 1
// @type Line object created from points
// @field start Starting point of the line
// @field end Ending point of the line
// @field properties LineProperties object which defines the style of line
// @field object Derived line object
export type Line
Point start
Point end
LineProperties properties
line object
// @type Properties of label object
// @field xloc X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
// @field yloc Y reference - can be yloc.price, yloc.abovebar, yloc.belowbar. Default is yloc.price
// @field color Label fill color
// @field style Label style as defined in https://www.tradingview.com/pine-script-reference/v5/#fun_label{dot}new. Default is label.style_none
// @field textcolor text color. Default is color.black
// @field size Label text size. Default is size.normal. Other values are size.auto, size.tiny, size.small, size.normal, size.large, size.huge
// @field textalign Label text alignment. Default if text.align_center. Other allowed values - text.align_right, text.align_left, text.align_top, text.align_bottom
// @field text_font_family The font family of the text. Default value is font.family_default. Other available option is font.family_monospace
export type LabelProperties
string xloc = xloc.bar_index
string yloc = yloc.price
color color = color.blue
string style = label.style_none
color textcolor = color.black
string size = size.normal
string textalign = text.align_center
string text_font_family = font.family_default
// @type Label object
// @field point Point where label is drawn
// @field lblText label text
// @field tooltip Tooltip text. Default is na
// @field properties LabelProperties object
// @field object Pine label object
export type Label
Point point
string lblText
string tooltip=na
LabelProperties properties
label object
// @type Linefill object
// @field line1 First line to create linefill
// @field line2 Second line to create linefill
// @field fillColor Fill color
// @field transparency Fill transparency range from 0 to 100
// @field object linefill object created from wrapper
export type Linefill
Line line1
Line line2
color fillColor = color.blue
int transparency = 80
linefill object
// @type BoxProperties object
// @field border_color Box border color. Default is color.blue
// @field bgcolor box background color
// @field border_width Box border width. Default is 1
// @field border_style Box border style. Default is line.style_solid
// @field extend Extend property of box. default is extend.none
// @field xloc defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
export type BoxProperties
color border_color = color.blue
color bgcolor = color.blue
int border_width = 1
string border_style = line.style_solid
string extend = extend.none
string xloc = xloc.bar_index
// @type Box Text properties.
// @field boxText Text to be printed on the box
// @field text_size Text size. Default is size.auto
// @field text_color Box text color. Default is color.yellow.
// @field text_halign horizontal align style - default is text.align_center
// @field text_valign vertical align style - default is text.align_center
// @field text_wrap text wrap style - default is text.wrap_auto
// @field text_font_family Text font. Default is
export type BoxText
string boxText = na
string text_size = size.auto
color text_color = color.yellow
string text_halign = text.align_center
string text_valign = text.align_center
string text_wrap = text.wrap_auto
string text_font_family = font.family_default
// @type Box object
// @field p1 Diagonal point one
// @field p2 Diagonal point two
// @field properties Box properties
// @field textProperties Box text properties
// @field object Box object created
export type Box
Point p1
Point p2
BoxProperties properties
BoxText textProperties
box object
|
ZigzagTypes | https://www.tradingview.com/script/uZKDIy4N-ZigzagTypes/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 31 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description Zigzag related user defined types. Depends on DrawingTypes library for basic types
library("ZigzagTypes", overlay = true)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
// @type Indicator is collection of indicator values applied on high, low and close
// @field indicatorHigh Indicator Value applied on High
// @field indicatorLow Indicator Value applied on Low
export type Indicator
float indicatorHigh
float indicatorLow
// @type PivotCandle represents data of the candle which forms either pivot High or pivot low or both
// @field _high High price of candle forming the pivot
// @field _low Low price of candle forming the pivot
// @field length Pivot length
// @field pHighBar represents number of bar back the pivot High occurred.
// @field pLowBar represents number of bar back the pivot Low occurred.
// @field pHigh Pivot High Price
// @field pLow Pivot Low Price
// @field indicators Array of Indicators - allows to add multiple
export type PivotCandle
float _high = high
float _low = low
int length = 5
int pHighBar
int pLowBar
float pHigh
float pLow
array<Indicator> indicators
// @type Pivot refers to zigzag pivot. Each pivot can contain various data
// @field point pivot point coordinates
// @field dir direction of the pivot. Valid values are 1, -1, 2, -2
// @field level is used for multi level zigzags. For single level, it will always be 0
// @field componentIndex is the lower level zigzag array index for given pivot. Used only in multi level Zigzag Pivots
// @field subComponents is the number of sub waves per each zigzag wave. Only applicable for multi level zigzags
// @field ratio Price Ratio based on previous two pivots
// @field indicatorNames Names of the indicators applied on zigzag
// @field indicatorValues Values of the indicators applied on zigzag
// @field indicatorRatios Ratios of the indicators applied on zigzag based on previous 2 pivots
export type Pivot
dr.Point point
int dir
int level = 0
int componentIndex = 0
int subComponents = 0
float ratio
array<string> indicatorNames
array<float> indicatorValues
array<float> indicatorRatios
// @type Flags required for drawing zigzag. Only used internally in zigzag calculation. Should not set the values explicitly
// @field newPivot true if the calculation resulted in new pivot
// @field doublePivot true if the calculation resulted in two pivots on same bar
// @field updateLastPivot true if new pivot calculated replaces the old one.
export type ZigzagFlags
bool newPivot = false
bool doublePivot = false
bool updateLastPivot = false
// @type Zigzag object which contains whole zigzag calculation parameters and pivots
// @field length Zigzag length. Default value is 5
// @field numberOfPivots max number of pivots to hold in the calculation. Default value is 20
// @field offset Bar offset to be considered for calculation of zigzag. Default is 0 - which means calculation is done based on the latest bar.
// @field level Zigzag calculation level - used in multi level recursive zigzags
// @field zigzagPivots array<Pivot> which holds the last n pivots calculated.
// @field flags ZigzagFlags object which is required for continuous drawing of zigzag lines.
export type Zigzag
int length = 5
int numberOfPivots = 20
int offset = 0
int level = 0
array<Pivot> zigzagPivots
ZigzagFlags flags
// @type Zigzag Drawing Object
// @field zigzagLine Line joining two pivots
// @field zigzagLabel Label which can be used for drawing the values, ratios, directions etc.
export type ZigzagObject
line zigzagLine
label zigzagLabel
// @type Object which holds properties of zigzag drawing. To be used along with ZigzagDrawing
// @field lineColor Zigzag line color. Default is color.blue
// @field lineWidth Zigzag line width. Default is 1
// @field lineStyle Zigzag line style. Default is line.style_solid.
// @field showLabel If set, the drawing will show labels on each pivot. Default is false
// @field textColor Text color of the labels. Only applicable if showLabel is set to true.
// @field maxObjects Max number of zigzag lines to display. Default is 300
// @field xloc Time/Bar reference to be used for zigzag drawing. Default is Time - xloc.bar_time.
export type ZigzagProperties
color lineColor = color.blue
int lineWidth = 1
string lineStyle = line.style_solid
bool showLabel = false
color textColor = color.black
int maxObjects = 300
string xloc = xloc.bar_time
// @type Object which holds complete zigzag drawing objects and properties.
// @field zigzag Zigzag object which holds the calculations.
// @field properties ZigzagProperties object which is used for setting the display styles of zigzag
// @field drawings array<ZigzagObject> which contains lines and labels of zigzag drawing.
export type ZigzagDrawing
Zigzag zigzag
ZigzagProperties properties
array<ZigzagObject> drawings
|
DrawingMethods | https://www.tradingview.com/script/eNM7BFaR-DrawingMethods/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 29 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
library("DrawingMethods", overlay = true)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
//******************************************************************* tostring *******************************************************/
method get(dr.Point this, string key)=>key == "price"? str.tostring(this.price) : key == "bar"? str.tostring(this.bar) : key == "bartime"? str.tostring(this.bartime) : na
// @function Converts DrawingTypes/Point object to string representation
// @param this DrawingTypes/Point object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/Point
export method tostring(dr.Point this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("price", "bar", "bartime") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.LineProperties this, string key)=> key == "xloc"? this.xloc : key == "extend"? this.extend : key == "style"? this.style : key == "width"? str.tostring(this.width) : na
// @function Converts DrawingTypes/LineProperties object to string representation
// @param this DrawingTypes/LineProperties object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/LineProperties
export method tostring(dr.LineProperties this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("xloc", "extend", "style", "width") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.Line this, string key)=>key == "start"? this.start.tostring() : key == "end"? this.end.tostring() : key == "properties"? this.properties.tostring() : na
// @function Converts DrawingTypes/Line object to string representation
// @param this DrawingTypes/Line object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/Line
export method tostring(dr.Line this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("start", "end", "properties") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.LabelProperties this, string key)=> key == "xloc"? this.xloc : key == "yloc"? this.yloc : key == "style"? this.style :
key == "size"? str.tostring(this.size) : key == "textalign"? this.textalign : key == "text_font_family"? this.text_font_family : na
// @function Converts DrawingTypes/LabelProperties object to string representation
// @param this DrawingTypes/LabelProperties object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/LabelProperties
export method tostring(dr.LabelProperties this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("xloc", "yloc", "style", "size", "textalign", "text_font_family") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.Label this, string key)=>key == "point"? this.point.tostring() : key == "lblText"? this.lblText : key == "tooltip"? this.tooltip : key == "properties"? this.properties.tostring() : na
// @function Converts DrawingTypes/Label object to string representation
// @param this DrawingTypes/Label object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/Label
export method tostring(dr.Label this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("point", "lblText", "tooltip", "properties") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.Linefill this, string key)=>key == "line1"? this.line1.tostring() : key == "line2"? this.line2.tostring() : key == "transparency"? str.tostring(this.transparency) : na
// @function Converts DrawingTypes/Linefill object to string representation
// @param this DrawingTypes/Linefill object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/Linefill
export method tostring(dr.Linefill this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("line1", "line2", "transparency") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.BoxProperties this, string key)=>key == "border_width"? str.tostring(this.border_width) :
key == "border_style"? this.border_style :
key == "extend"? this.extend :
key == "xloc"? this.xloc : na
// @function Converts DrawingTypes/BoxProperties object to string representation
// @param this DrawingTypes/BoxProperties object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/BoxProperties
export method tostring(dr.BoxProperties this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("border_width", "border_style", "extend", "xloc") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.BoxText this, string key)=>key == "boxText"? this.boxText :
key == "text_size"? this.text_size :
key == "text_halign"? this.text_halign :
key == "text_valign"? this.text_valign :
key == "text_wrap"? this.text_wrap :
key == "text_font_family"? this.text_font_family : na
// @function Converts DrawingTypes/BoxText object to string representation
// @param this DrawingTypes/BoxText object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/BoxText
export method tostring(dr.BoxText this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("boxText", "text_size", "text_halign", "text_valign", "text_wrap", "text_font_family") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(dr.Box this, string key)=>key == "p1"? this.p1.tostring() :
key == "p2"? this.p2.tostring() :
key == "properties"? this.properties.tostring() :
key == "textProperties"? this.textProperties.tostring() : na
// @function Converts DrawingTypes/Box object to string representation
// @param this DrawingTypes/Box object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of DrawingTypes/Box
export method tostring(dr.Box this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("p1", "p2", "properties", "textProperties") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
//******************************************************************* delete and clear *******************************************************/
deleteObj(this)=>
this.object.delete()
this
// @function Deletes line from DrawingTypes/Line object
// @param this DrawingTypes/Line object
// @returns Line object deleted
export method delete(dr.Line this)=>deleteObj(this)
// @function Deletes label from DrawingTypes/Label object
// @param this DrawingTypes/Label object
// @returns Label object deleted
export method delete(dr.Label this)=>deleteObj(this)
// @function Deletes Linefill from DrawingTypes/Linefill object
// @param this DrawingTypes/Linefill object
// @returns Linefill object deleted
export method delete(dr.Linefill this)=>deleteObj(this)
// @function Deletes box from DrawingTypes/Box object
// @param this DrawingTypes/Box object
// @returns DrawingTypes/Box object deleted
export method delete(dr.Box this)=>deleteObj(this)
deleteAll(this)=>
if(not na(this))
for obj in this
obj.delete()
this
// @function Deletes lines from array of DrawingTypes/Line objects
// @param this Array of DrawingTypes/Line objects
// @returns Array of DrawingTypes/Line objects
export method delete(array<dr.Line> this)=>deleteAll(this)
// @function Deletes labels from array of DrawingTypes/Label objects
// @param this Array of DrawingTypes/Label objects
// @returns Array of DrawingTypes/Label objects
export method delete(array<dr.Label> this)=>deleteAll(this)
// @function Deletes linefill from array of DrawingTypes/Linefill objects
// @param this Array of DrawingTypes/Linefill objects
// @returns Array of DrawingTypes/Linefill objects
export method delete(array<dr.Linefill> this)=>deleteAll(this)
// @function Deletes boxes from array of DrawingTypes/Box objects
// @param this Array of DrawingTypes/Box objects
// @returns Array of DrawingTypes/Box objects
export method delete(array<dr.Box> this)=>deleteAll(this)
// @function clear items from array of DrawingTypes/Line while deleting underlying objects
// @param this array<DrawingTypes/Line>
// @returns void
export method clear(array<dr.Line> this)=>this.delete().clear()
// @function clear items from array of DrawingTypes/Label while deleting underlying objects
// @param this array<DrawingTypes/Label>
// @returns void
export method clear(array<dr.Label> this)=>this.delete().clear()
// @function clear items from array of DrawingTypes/Linefill while deleting underlying objects
// @param this array<DrawingTypes/Linefill>
// @returns void
export method clear(array<dr.Linefill> this)=>this.delete().clear()
// @function clear items from array of DrawingTypes/Box while deleting underlying objects
// @param this array<DrawingTypes/Box>
// @returns void
export method clear(array<dr.Box> this)=>this.delete().clear()
//******************************************************************* draw *******************************************************/
// @function Creates line from DrawingTypes/Line object
// @param this DrawingTypes/Line object
// @returns line created from DrawingTypes/Line object
export method draw(dr.Line this)=>
this.object.delete()
this.properties := na(this.properties)? dr.LineProperties.new() : this.properties
this.object := line.new(this.properties.xloc==xloc.bar_index?this.start.bar:this.start.bartime, this.start.price,
this.properties.xloc == xloc.bar_index? this.end.bar:this.end.bartime, this.end.price,
this.properties.xloc, this.properties.extend, this.properties.color, this.properties.style, this.properties.width)
this.object
// @function Creates lines from array of DrawingTypes/Line objects
// @param this Array of DrawingTypes/Line objects
// @returns Array of DrawingTypes/Line objects
export method draw(array<dr.Line> this)=>
if(not na(this))
for ln in this
ln.draw()
this
// @function Creates label from DrawingTypes/Label object
// @param this DrawingTypes/Label object
// @returns label created from DrawingTypes/Label object
export method draw(dr.Label this)=>
this.object.delete()
this.properties := na(this.properties)? dr.LabelProperties.new() : this.properties
this.object := label.new(this.properties.xloc==xloc.bar_index?this.point.bar:this.point.bartime, this.point.price,
this.lblText, this.properties.xloc, this.properties.yloc, this.properties.color, this.properties.style, this.properties.textcolor,
this.properties.size, this.properties.textalign, this.tooltip, this.properties.text_font_family)
this.object
// @function Creates labels from array of DrawingTypes/Label objects
// @param this Array of DrawingTypes/Label objects
// @returns Array of DrawingTypes/Label objects
export method draw(array<dr.Label> this)=>
if(not na(this))
for lbl in this
lbl.draw()
this
// @function Creates linefill object from DrawingTypes/Linefill
// @param this DrawingTypes/Linefill objects
// @returns linefill object created
export method draw(dr.Linefill this)=>
if(not na(this.line1) and not na(this.line2) and not na(this.line1.object) and not na(this.line2.object))
this.object := linefill.new(this.line1.object, this.line2.object, color.new(this.fillColor, this.transparency))
this.object
// @function Creates linefill objects from array of DrawingTypes/Linefill objects
// @param this Array of DrawingTypes/Linefill objects
// @returns Array of DrawingTypes/Linefill used for creating linefills
export method draw(array<dr.Linefill> this)=>
if(not na(this))
for lfl in this
lfl.draw()
this
// @function Creates box from DrawingTypes/Box object
// @param this DrawingTypes/Box object
// @returns box created from DrawingTypes/Box object
export method draw(dr.Box this)=>
this.object.delete()
this.properties := na(this.properties)? dr.BoxProperties.new() : this.properties
top = math.max(this.p1.price, this.p2.price)
bottom = math.min(this.p1.price, this.p2.price)
left = this.properties.xloc == xloc.bar_index? math.min(this.p1.bar, this.p2.bar) : math.min(this.p1.bartime, this.p2.bartime)
right = this.properties.xloc == xloc.bar_index? math.max(this.p1.bar, this.p2.bar) : math.max(this.p1.bartime, this.p2.bartime)
this.object := na(this.textProperties)?
box.new(left, top, right, bottom, this.properties.border_color, this.properties.border_width, this.properties.border_style,
this.properties.extend, this.properties.xloc, this.properties.bgcolor) :
box.new(left, top, right, bottom, this.properties.border_color, this.properties.border_width, this.properties.border_style,
this.properties.extend, this.properties.xloc, this.properties.bgcolor, this.textProperties.boxText,
this.textProperties.text_size, this.textProperties.text_color, this.textProperties.text_halign,
this.textProperties.text_valign, this.textProperties.text_wrap, this.textProperties.text_font_family)
this.object
// @function Creates labels from array of DrawingTypes/Label objects
// @param this Array of DrawingTypes/Label objects
// @returns Array of DrawingTypes/Label objects
export method draw(array<dr.Box> this)=>
if(not na(this))
for bx in this
bx.draw()
this
//******************************************************************* createXXX *******************************************************/
// @function Creates DrawingTypes/Label object from DrawingTypes/Point
// @param this DrawingTypes/Point object
// @param lblText Label text
// @param tooltip Tooltip text. Default is na
// @param properties DrawingTypes/LabelProperties object. Default is na - meaning default values are used.
// @returns DrawingTypes/Label object
export method createLabel(dr.Point this, string lblText, string tooltip=na, dr.LabelProperties properties=na)=>
dr.Label.new(this, lblText, tooltip, na(properties)?dr.LabelProperties.new():properties)
// @function Creates DrawingTypes/Line object from one DrawingTypes/Point to other
// @param this First DrawingTypes/Point object
// @param other Second DrawingTypes/Point object
// @param properties DrawingTypes/LineProperties object. Default set to na - meaning default values are used.
// @returns DrawingTypes/Line object
export method createLine(dr.Point this, dr.Point other, dr.LineProperties properties = na)=>
dr.Line.new(this, other, na(properties)? dr.LineProperties.new():properties)
// @function Creates DrawingTypes/Linefill object from DrawingTypes/Line object to other DrawingTypes/Line object
// @param this First DrawingTypes/Line object
// @param other Other DrawingTypes/Line object
// @param fillColor fill color of linefill. Default is color.blue
// @param transparency fill transparency for linefill. Default is 80
// @returns Array of DrawingTypes/Linefill object
export method createLinefill(dr.Line this, dr.Line other, color fillColor=color.blue, int transparency=80)=>
dr.Linefill.new(this, other, fillColor, transparency)
// @function Creates DrawingTypes/Box object from one DrawingTypes/Point to other
// @param this First DrawingTypes/Point object
// @param other Second DrawingTypes/Point object
// @param properties DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
// @param textProperties DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
// @returns DrawingTypes/Box object
export method createBox(dr.Point this, dr.Point other, dr.BoxProperties properties = na, dr.BoxText textProperties = na)=>
dr.Box.new(this, other, na(properties)? dr.BoxProperties.new():properties, textProperties)
// @function Creates DrawingTypes/Box object from DrawingTypes/Line as diagonal line
// @param this Diagonal DrawingTypes/PoLineint object
// @param properties DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
// @param textProperties DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
// @returns DrawingTypes/Box object
export method createBox(dr.Line this, dr.BoxProperties properties = na, dr.BoxText textProperties = na)=>
dr.Box.new(this.start, this.end, na(properties)? dr.BoxProperties.new():properties, textProperties)
// ###################################################################### Tests #############################################################
// import HeWhoMustNotBeNamed/Logger/1 as l
// var logger = l.Logger.new(minimumLevel = 'DEBUG')
// logger.init()
// if(barstate.islast)
// dr.Point p = dr.Point.new(high, bar_index, time)
// logger.debug(p.tostring())
// dr.Point p2 = dr.Point.new(low, bar_index+10, time)
// dr.Label lbl = p.createLabel('This is my label')
// logger.debug(lbl.tostring())
// lbl.draw()
// dr.Line ln = p.createLine(p2)
// logger.debug(ln.tostring())
// ln.draw()
// dr.Line ln2 = dr.Line.new(dr.Point.new(low, bar_index, time), dr.Point.new(low, bar_index+10, time))
// ln2.draw()
// dr.Linefill lf = ln.createLinefill(ln2)
// logger.debug(lf.tostring())
// lf.draw()
// dr.BoxText textProps = dr.BoxText.new('This is my box')
// dr.Box bx = p.createBox(p2, textProperties=textProps)
// bx.draw()
|
Unispaces | https://www.tradingview.com/script/O5wc79U2-Unispaces/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 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/
// © FFriZz
//@version=5
// @description Easier than looking up unicode spaces
library("Unispaces",overlay=true)
// @function **UNISPACES**
// **Params**
// - `sequence - (int) required | 0 = normal " "`
// - `string1 - (str) optional | default = ""`
// - `string2 - (str) optional | default = ""`
//***
//**Info**
// - leaving `string1` or `string2` blank the function will still add unicode spaces placing them
//at the front if only `sting2` is used or at the back if only `string1` is used
// - Only 0-9 options compared to `space()'s` 15 options should still be able to get
//the perfect space
//***
// @param sequence (int) required | 123 = 3 spaces / 3 different sizes (one space per number can find spaces in hover over)
// @param string1 (str) optional | default = ""
// @param string2 (str) optional | default = ""
// @returns `string - concatenated string surrounding unispaces`
//***
//Num|‖ Example |‖ Name/Link
//|-|-|-|
//|---------|--------------|----------------------------|
//1.|‖ foobar |‖ -- [zero width no-break space](https://unicode-explorer.com/c/feff)
//2.|‖ foobar |‖ -- [zero width space](https://unicode-explorer.com/c/200)
//3.|‖ foo bar |‖ -- [hair space](https://unicode-explorer.com/c/200a)
//4.|‖ foo bar |‖ -- [narrow no-break space](https://unicode-explorer.com/c/202f)
//5.|‖ foo bar |‖ -- [six-per-em space](https://unicode-explorer.com/c/2006)
//6.|‖ foo bar |‖ -- [thin space](https://unicode-explorer.com/c/2009)
//7.|‖ foo bar |‖ -- [figure space](https://unicode-explorer.com/c/2007)
//8.|‖ foo bar |‖ -- [em space](https://unicode-explorer.com/c/2003)
//9.|‖ foo bar |‖ -- [ideographic space](https://unicode-explorer.com/c/3000)
//***
//**Examples**
// ```
// import FFriZz/Unispaces/1 as uni
// seq = 4552
// string1 = "foo"
// string2 = "bar"
// wspaces = uni.spaces(seq,string1,string2)
////out
// wspaces = "foo bar"
//```
//***
//**Function**
//```
//| uni.spaces(int sequence, string string1 = '', string string2 = '') =>
//| get = ""
//| spaces = array.from(" ","",""," "," "," "," "," "," "," ")
//| to_str = str.split(str.tostring(sequence), '')
//| for i in to_str
//| get += spaces.get(int(str.tonumber(i)))
//| out = string1+get+string2
//|
//| - "@FFriZz"
//```
export method spaces(int sequence, string string1 = '', string string2 = '') =>
get = ""
spaces = array.from(" ","",""," "," "," "," "," "," "," ")
to_str = str.split(str.tostring(sequence), '')
for i in to_str
get += spaces.get(int(str.tonumber(i)))
out = string1+get+string2
// @function **UNISPACE**
//***
// **Params**
// - `space - (int) optional | default = 0 (0 = normal " ")`
// - `string1 - (str) optional | default = ""`
// - `string2 - (str) optional | default = ""`
//***
//**Info**
// - leaving `string1` or `string2` blank function will still add unicode space placing it
//at the front if only `sting2` is used or at the back if only `string1` is used
//***
// @param space (int) optional | default = 0 | 0-15 (can find spaces in hover over)
// @param string1 (str) optional | default = ""
// @param string2 (str) optional | default = ""
// @returns `string - concatenated string surrounding a unispace `
//***
//Num|‖ Example |‖ Name/Link
//|-|-|-|
//|---------|--------------|----------------------------|
//1.|‖ foobar |‖ -- [zero width no-break space](https://unicode-explorer.com/c/feff)
//2.|‖ foobar |‖ -- [zero width space](https://unicode-explorer.com/c/200)
//3.|‖ foo bar |‖ -- [hair space](https://unicode-explorer.com/c/200a)
//4.|‖ foo bar |‖ -- [narrow no-break space](https://unicode-explorer.com/c/202f)
//5.|‖ foo bar |‖ -- [six-per-em space](https://unicode-explorer.com/c/2006)
//6.|‖ foo bar |‖ -- [thin space](https://unicode-explorer.com/c/2009)
//7.|‖ foo bar |‖ -- [punctuation space](https://unicode-explorer.com/c/2008)
//8.|‖ foo bar |‖ -- [medium mathematical space](https://unicode-explorer.com/c/205f)
//9.|‖ foo bar |‖ -- [four-per-em space](https://unicode-explorer.com/c/2005)
//10.|‖ foo bar |‖ -- [no-break space](https://unicode-explorer.com/c/00a0)
//11.|‖ foo bar |‖ -- [three-per-em space](https://unicode-explorer.com/c/2004)
//12.|‖ foo bar |‖ -- [en space](https://unicode-explorer.com/c/2002)
//13.|‖ foo bar |‖ -- [figure space](https://unicode-explorer.com/c/2007)
//14.|‖ foo bar |‖ -- [em space](https://unicode-explorer.com/c/2003)
//15.|‖ foo bar |‖ -- [ideographic space](https://unicode-explorer.com/c/3000)
//***
//**Examples**
// ```
// import FFriZz/Unispaces/1 as uni
// string1 = "foo"
// string2 = "bar"
// str1 = uni.space(string1,2,string2)
// str1 = uni.space(string1,14,string2)
////out
// str1 = "foo bar"
// str2 = "foobar"
//```
//***
//**Function**
//```
//| uni.space(int space = 0, string string1 = '', string string2 = '') =>
//| spaces = array.from(" ","",""," "," "," "," "," "," "," "," "," "," "," "," ")
//| out = string1+spaces.get(space)+string2
//|
//| - "@FFriZz"
//```
export method space(int space = 0, string string1 = '', string string2 = '') =>
spaces = array.from(" ","",""," "," "," "," "," "," "," "," "," "," "," "," ")
out = string1+spaces.get(space)+string2
// Examples - Usage
// import FFriZz/FrizBug/11 as p
// p.print(space(12,'foo','bar'),"test2", pos = '6')
// p.print(spaces(455245462,'foo','bar'),"test1",pos = '3')
// @function **repeat()**
//**Examples**
// ```
// import FFriZz/Unispaces/2 as uni
// re = uni.repeat("ABC", 10)
////out
////re = "ABCABCABCABCABCABCABCABCABCABC"
//```
//***
//**Function**
//```
//| export method repeat(string to_repeat,int count) =>
//| build = ""
//| for i = 0 to count
//| build += to_repeat
//| build
//|
//| - "@FFriZz"
//```
// **Params**
//***
//**Info**
// - repeat a given string by the count provided
//***
// @param to_repeat (str) required | "ABC"
// @param count (str) required |
// @returns `string - string of repeated strings`
//***
export method repeat(string to_repeat,int count) =>
build = ""
for i = 0 to count
build += to_repeat
build
|
PitchforkTypes | https://www.tradingview.com/script/ine0QCxF-PitchforkTypes/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 28 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description User Defined Types to be used for Pitchfork and Drawing elements of Pitchfork. Depends on DrawingTypes for Point, Line, and LineProperties objects
library("PitchforkTypes", overlay = true)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
// @type Pitchfork Drawing Properties object
// @field extend If set to true, forks are extended towards right. Default is true
// @field fill Fill forklines with transparent color. Default is true
// @field fillTransparency Transparency at which fills are made. Only considered when fill is set. Default is 80
// @field forceCommonColor Force use of common color for forks and fills. Default is false
// @field commonColor common fill color. Used only if ratio specific fill colors are not available or if forceCommonColor is set to true.
export type PitchforkDrawingProperties
bool extend = true
bool fill = true
int fillTransparency = 95
bool forceCommonColor = false
color commonColor = color.blue
// @type Pitchfork drawing components
// @field medianLine Median line of the pitchfork
// @field baseLine Base line of the pitchfork
// @field forkLines fork lines of the pitchfork
// @field linefills Linefills between forks
export type PitchforkDrawing
dr.Line medianLine
dr.Line baseLine
array<dr.Line> forkLines
array<dr.Linefill> linefills
// @type Fork object property
// @field ratio Fork ratio
// @field forkColor color of fork. Default is blue
// @field include flag to include the fork in drawing. Default is true
export type Fork
float ratio
color forkColor
bool include = true
// @type Pitchfork Properties
// @field forks Array of Fork objects
// @field type Pitchfork type. Supported values are "regular", "schiff", "mschiff", Default is regular
// @field inside Flag to identify if to draw inside fork. If set to true, inside fork will be drawn
export type PitchforkProperties
array<Fork> forks
string type = "regular"
bool inside = false
// @type Pitchfork object
// @field a Pivot Point A of pitchfork
// @field b Pivot Point B of pitchfork
// @field c Pivot Point C of pitchfork
// @field properties PitchforkProperties object which determines type and composition of pitchfork
// @field dProperties Drawing properties for pitchfork
// @field lProperties Common line properties for Pitchfork lines
// @field drawing PitchforkDrawing object
export type Pitchfork
dr.Point a
dr.Point b
dr.Point c
PitchforkProperties properties
PitchforkDrawingProperties dProperties
dr.LineProperties lProperties
PitchforkDrawing drawing
|
ZigzagMethods | https://www.tradingview.com/script/kO5FUZVr-ZigzagMethods/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 40 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description Object oriented implementation of Zigzag methods. Please refer to ZigzagTypes library for User defined types used in this library
library("ZigzagMethods", overlay=true)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import HeWhoMustNotBeNamed/ZigzagTypes/5 as Objects
//*************************************************************************************************************************************************************//
//*************************************************************** TYPE Indicator *****************************************************************************//
//*************************************************************************************************************************************************************//
method init(array<Objects.Indicator> indicators, matrix<float> indicatorValues)=>
for i=0 to na(indicatorValues) ? na : indicatorValues.rows()==0? na : indicatorValues.rows()-1
iRow = indicatorValues.row(i)
Objects.Indicator indicator = Objects.Indicator.new(iRow.first(), iRow.last())
indicators.push(indicator)
indicators
//*************************************************************************************************************************************************************//
//*************************************************************** TYPE PivotCandle ***************************************************************************//
//*************************************************************************************************************************************************************//
method init(Objects.PivotCandle candle, matrix<float> indicators=na)=>
candle.pHighBar := ta.highestbars(candle._high, candle.length)
candle.pLowBar := ta.lowestbars(candle._low, candle.length)
candle.pHigh := ta.highest(candle._high, candle.length)
candle.pLow := ta.lowest(candle._low, candle.length)
candle.indicators := array.new<Objects.Indicator>()
candle.indicators.init(indicators)
candle
//*************************************************************************************************************************************************************//
//*************************************************************** TYPE Pivot *********************************************************************************//
//*************************************************************************************************************************************************************//
method unshift(array<Objects.Pivot> arr, Objects.Pivot val, int maxItems)=>
arr.unshift(val)
if(arr.size() > maxItems)
arr.pop()
method update(Objects.Pivot this, Objects.PivotCandle candle, array<string> indicatorNames)=>
dir = math.sign(this.dir)
array<float> _indicators = array.new<float>()
for indicator in candle.indicators
indicatorValue = dir > 0? indicator.indicatorHigh : indicator.indicatorLow
_indicators.push(indicatorValue)
this.indicatorNames := indicatorNames
this.indicatorValues := _indicators
this.indicatorRatios := array.new<float>()
this
method get(Objects.Pivot this, string key)=>
key == "point"? this.point.tostring() :
key == "dir"? str.tostring(this.dir) :
key == "level"? str.tostring(this.level) :
key == "componentIndex"? str.tostring(this.componentIndex) :
key == "subComponents"? str.tostring(this.subComponents) :
key == "ratio"? str.tostring(this.ratio) :
key == "indicatorNames" ? na(this.indicatorNames)? "[]" : str.tostring(this.indicatorNames) :
key == "indicatorValues" ? na(this.indicatorValues)? "[]" : str.tostring(this.indicatorValues) :
key == "indicatorRatios" ? na(this.indicatorRatios)? "[]" : str.tostring(this.indicatorRatios) :
na
// @function Converts ZigzagTypes/Pivot object to string representation
// @param this ZigzagTypes/Pivot
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of ZigzagTypes/Pivot
export method tostring(Objects.Pivot this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
str = ''
if(not na(this))
keys = na(includeKeys)? array.from("point", "dir", "level", "componentIndex", "subComponents", "ratio", "indicatorNames", "indicatorValues", "indicatorRatios") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
// @function Converts Array of Pivot objects to string representation
// @param this Pivot object array
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of Pivot object array
export method tostring(array<Objects.Pivot> this, bool sortKeys= false, int sortOrder = 1, array<string> includeKeys=na)=>
array<string> combinedStr = array.new<string>()
if(not na(this))
for pivot in this
combinedStr.push(pivot.tostring(sortKeys, sortOrder, includeKeys))
'['+array.join(combinedStr, ",")+']'
//*************************************************************************************************************************************************************//
//*************************************************************** TYPE ZigzagFlags ***************************************************************************//
//*************************************************************************************************************************************************************//
// @function Converts ZigzagFlags object to string representation
// @param this ZigzagFlags object
// @returns string representation of ZigzagFlags
export method tostring(Objects.ZigzagFlags this)=> str.tostring(array.from(this.newPivot, this.doublePivot, this.updateLastPivot))
//*************************************************************************************************************************************************************//
//*************************************************************** TYPE Zigzag ********************************************************************************//
//*************************************************************************************************************************************************************//
method init(Objects.Zigzag this)=>
if(na(this.zigzagPivots))
this.zigzagPivots := array.new<Objects.Pivot>()
this.flags := Objects.ZigzagFlags.new()
this
method addnewpivot(Objects.Zigzag this, Objects.Pivot pivot)=>
dir = math.sign(pivot.dir)
if(this.zigzagPivots.size() >=1)
lastPivot = this.zigzagPivots.get(0)
lastValue = lastPivot.point.price
pivot.subComponents := lastPivot.componentIndex - pivot.componentIndex
if(math.sign(lastPivot.dir) == math.sign(dir))
runtime.error('Direction mismatch')
if(this.zigzagPivots.size() >=2)
llastPivot = this.zigzagPivots.get(1)
value = pivot.point.price
llastValue = llastPivot.point.price
newDir = dir * value > dir * llastValue ? dir * 2 : dir
pivot.dir := int(newDir)
pivot.ratio := math.round(math.abs(lastValue-value)/math.abs(llastValue - lastValue), 3)
llastIndicators = llastPivot.indicatorValues
indicators = pivot.indicatorValues
lastIndicators = lastPivot.indicatorValues
pivot.indicatorRatios.clear()
for [index, indicatorValue] in indicators
lastIndicatorValue = lastIndicators.get(index)
llastIndicatorValue = llastIndicators.get(index)
indicatorRatio = math.round(math.abs(lastIndicatorValue-indicatorValue)/math.abs(llastIndicatorValue - lastIndicatorValue), 3)
pivot.indicatorRatios.push(indicatorRatio)
this.zigzagPivots.unshift(pivot, this.numberOfPivots)
this
method addnewpivot(Objects.Zigzag this, Objects.Pivot pivot, Objects.PivotCandle candle, array<string> indicatorNames)=>
pivot.update(candle, indicatorNames)
this.addnewpivot(pivot)
method get(Objects.Zigzag this, string key)=>
key == "length"? str.tostring(this.length) :
key == "numberOfPivots"? str.tostring(this.numberOfPivots) :
key == "offset"? str.tostring(this.offset) :
key == "level"? str.tostring(this.level) :
key == "zigzagPivots" ? na(this.zigzagPivots)? "[]" : this.zigzagPivots.tostring() :
key == "flags" ? na(this.flags)? "[]" : this.flags.tostring() :
na
// @function Converts ZigzagTypes/Zigzag object to string representation
// @param this ZigzagTypes/Zigzagobject
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @param includeKeys Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
// @returns string representation of ZigzagTypes/Zigzag
export method tostring(Objects.Zigzag this, bool sortKeys = false, int sortOrder = 1, array<string> includeKeys=na)=>
keys = na(includeKeys)? array.from("length", "numberOfPivots", "offset", "level", "zigzagPivots", "flags") : includeKeys
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
'{'+array.join(keyValues, ",")+'}'
// @function Calculate zigzag based on input values and indicator values
// @param this Zigzag object
// @param ohlc Array containing OHLC values. Can also have custom values for which zigzag to be calculated
// @param indicators Array of indicator values
// @param indicatorNames Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
// @returns current Zigzag object
export method calculate(Objects.Zigzag this, array<float> ohlc, matrix<float> indicators, array<string> indicatorNames) =>
_ohlc = na(ohlc[this.offset])? ohlc : ohlc[this.offset]
_indicators = na(indicators[this.offset])? indicators : indicators[this.offset]
this.init()
Objects.PivotCandle candle = Objects.PivotCandle.new(_ohlc.max(), _ohlc.min(), this.length)
candle.init(_indicators)
pDir = 1
Objects.Pivot lastPivot = na
this.flags.updateLastPivot := false
this.flags.newPivot := false
this.flags.doublePivot := false
newBar = bar_index-this.offset
newbartime = time[this.offset]
distanceFromLastPivot = 0
var counter = 0
var lastCounterBar = 0
forceDoublePivot = false
if(this.zigzagPivots.size() > 0)
lastPivot := this.zigzagPivots.get( 0)
pDir := int(math.sign(lastPivot.dir))
distanceFromLastPivot := newBar - lastPivot.point.bar
if(this.zigzagPivots.size() > 1)
llastPivot = this.zigzagPivots.get(1)
llastDir = int(math.sign(llastPivot.dir))
forceDoublePivot := pDir == 1 and candle.pLowBar == 0 ? candle.pLow < llastPivot.point.price : pDir == -1 and candle.pHighBar == 0 ? candle.pHigh > llastPivot.point.price : false
overflow = distanceFromLastPivot >= this.length
if ((pDir == 1 and candle.pHighBar == 0) or (pDir == -1 and candle.pLowBar == 0)) and this.zigzagPivots.size()>=1
value = pDir == 1 ? candle.pHigh : candle.pLow
ipivot = pDir == 1? candle.pLow : candle.pHigh
removeOld = value * lastPivot.dir >= lastPivot.point.price * lastPivot.dir
if(removeOld)
this.flags.updateLastPivot := true
this.flags.newPivot := true
this.zigzagPivots.shift()
newPivotObject = Objects.Pivot.new(dr.Point.new(value, newBar, newbartime), pDir)
this.addnewpivot(newPivotObject, candle, indicatorNames)
if (pDir == 1 and candle.pLowBar == 0) or (pDir == -1 and candle.pHighBar == 0) and (not this.flags.newPivot or forceDoublePivot)
value = pDir == 1 ? candle.pLow : candle.pHigh
newPivotObject = Objects.Pivot.new(dr.Point.new(value, newBar, newbartime), -pDir)
this.addnewpivot(newPivotObject, candle, indicatorNames)
this.flags.doublePivot := this.flags.newPivot
this.flags.newPivot := true
if(overflow and not this.flags.newPivot)
ipivot = pDir == 1? candle.pLow : candle.pHigh
ipivotbar = pDir == 1? newBar+candle.pLowBar : newBar+candle.pHighBar
ipivottime = time[newBar-ipivotbar+this.offset]
iCandle = candle[newBar-ipivotbar]
newPivotObject = Objects.Pivot.new(dr.Point.new(ipivot, ipivotbar, ipivottime), -pDir)
this.addnewpivot(newPivotObject, iCandle, indicatorNames)
this.flags.newPivot := true
this
// @function Calculate zigzag based on properties embedded within Zigzag object
// @param this Zigzag object
// @returns current Zigzag object
export method calculate(Objects.Zigzag this)=>
this.calculate(array.from(high,low), matrix.new<float>(), array.new<string>())
// @function Calculate Next Level Zigzag based on the current calculated zigzag object
// @param this Zigzag object
// @returns Next Level Zigzag object
export method nextlevel(Objects.Zigzag this)=>
nextLevel = Objects.Zigzag.new(this.length, this.numberOfPivots, 0)
nextLevel.level := this.level +1
nextLevel.init()
if(this.zigzagPivots.size() > 0)
Objects.Pivot tempBullishPivot = na
Objects.Pivot tempBearishPivot = na
int currentIndex = 0
int lastIndex = 0
for i=(this.zigzagPivots.size()-1) to 0
lPivot = Objects.Pivot.copy(this.zigzagPivots.get(i))
dir = lPivot.dir
newDir = math.sign(dir)
value = lPivot.point.price
lPivot.level := lPivot.level+1
lPivot.componentIndex := i
if(nextLevel.zigzagPivots.size() > 0)
lastPivot = nextLevel.zigzagPivots.get(0)
lastDir = math.sign(lastPivot.dir)
lastValue = lastPivot.point.price
if(math.abs(dir) == 2)
if(lastDir == newDir)
if(dir*lastValue < dir*value)
nextLevel.zigzagPivots.shift()
else
tempPivot = newDir >0 ? tempBearishPivot : tempBullishPivot
if(not na(tempPivot))
nextLevel.addnewpivot(tempPivot)
else
continue
else
tempFirstPivot = newDir >0 ? tempBullishPivot : tempBearishPivot
tempSecondPivot = newDir >0 ? tempBearishPivot : tempBullishPivot
if(not na(tempFirstPivot) and not na(tempSecondPivot))
tempVal = tempFirstPivot.point.price
val = lPivot.point.price
if(newDir*tempVal > newDir*val)
nextLevel.addnewpivot(tempFirstPivot)
nextLevel.addnewpivot(tempSecondPivot)
nextLevel.addnewpivot(lPivot)
tempBullishPivot := na
tempBearishPivot := na
true
else
tempPivot = newDir > 0? tempBullishPivot : tempBearishPivot
if(not na(tempPivot))
tempDir = tempPivot.dir
tempVal = tempPivot.point.price
val = lPivot.point.price
if(val*dir > tempVal*dir)
if(newDir > 0)
tempBullishPivot := lPivot
else
tempBearishPivot := lPivot
true
else
if(newDir > 0)
tempBullishPivot := lPivot
else
tempBearishPivot := lPivot
true
else if(math.abs(dir) == 2)
nextLevel.addnewpivot(lPivot)
true
if(nextLevel.zigzagPivots.size() >= this.zigzagPivots.size())
nextLevel.zigzagPivots.clear()
nextLevel
//*************************************************************************************************************************************************************//
//*************************************************************** TYPE ZigzagObject **************************************************************************//
//*************************************************************************************************************************************************************//
method push(array<Objects.ZigzagObject> arr, val, maxItems)=>
arr.push(val)
if(arr.size() > maxItems)
Objects.ZigzagObject lastObject = arr.shift()
lastObject.zigzagLine.delete()
lastObject.zigzagLabel.delete()
method pop(array<Objects.ZigzagObject> arr)=>
Objects.ZigzagObject lastObject = arr.pop()
lastObject.zigzagLine.delete()
lastObject.zigzagLabel.delete()
//*************************************************************************************************************************************************************//
//*************************************************************** TYPE ZigzagDrawing *************************************************************************//
//*************************************************************************************************************************************************************//
method init(Objects.ZigzagDrawing this)=>
if(na(this.drawings))
this.drawings := array.new<Objects.ZigzagObject>()
if(na(this.zigzag))
this.zigzag := Objects.Zigzag.new()
this.zigzag.init()
if(na(this.properties))
this.properties := Objects.ZigzagProperties.new()
this
method clear(Objects.ZigzagDrawing this)=>
for zigzagObject in this.drawings
zigzagObject.zigzagLine.delete()
zigzagObject.zigzagLabel.delete()
this.drawings.clear()
method draw_zg_line(Objects.ZigzagDrawing this, idx1) =>
idx2 = idx1+1
if this.zigzag.zigzagPivots.size() > idx2
Objects.Pivot lastPivot = this.zigzag.zigzagPivots.get(idx1)
Objects.Pivot llastPivot = this.zigzag.zigzagPivots.get(idx2)
x1 = this.properties.xloc == xloc.bar_index ? lastPivot.point.bar : lastPivot.point.bartime
x2 = this.properties.xloc == xloc.bar_index ? llastPivot.point.bar : llastPivot.point.bartime
zline = line.new(x1=x1, y1=lastPivot.point.price , x2=x2, y2=llastPivot.point.price,
xloc=this.properties.xloc, color=this.properties.lineColor, width=this.properties.lineWidth, style=this.properties.lineStyle)
label zlabel = na
if(this.properties.showLabel)
[hhllText, labelColor] = switch lastPivot.dir
1 => ["LH", color.orange]
2 => ["HH", color.green]
-1 => ["HL", color.lime]
-2 => ["LL", color.red]
=> ["NA", color.silver]
labelStyle = lastPivot.dir > 0? label.style_label_down : label.style_label_up
zlabel := label.new(x=x1, y=lastPivot.point.price, yloc=yloc.price, xloc=this.properties.xloc,
color=labelColor, style=labelStyle, text=hhllText,
textcolor=this.properties.textColor, size = size.small)
Objects.ZigzagObject zigzagObject = Objects.ZigzagObject.new(zline, zlabel)
this.drawings.push(zigzagObject, this.properties.maxObjects)
this
// @function Clears zigzag drawings array
// @param this array<ZigzagDrawing>
// @returns void
export method clear(array<Objects.ZigzagDrawing> this)=>
for drawing in this
drawing.clear()
this.clear()
// @function draws fresh zigzag based on properties embedded in ZigzagDrawing object without trying to calculate
// @param this ZigzagDrawing object
// @returns ZigzagDrawing object
export method drawplain(Objects.ZigzagDrawing this)=>
this.init()
this.clear()
if(barstate.islast or barstate.islastconfirmedhistory)
for i=0 to this.zigzag.zigzagPivots.size()>1? this.zigzag.zigzagPivots.size()-2 : na
lastPivot = this.zigzag.zigzagPivots.get(i)
llastPivot = this.zigzag.zigzagPivots.get(i+1)
y1 = lastPivot.point.price
y2 = llastPivot.point.price
x1 = this.properties.xloc == xloc.bar_index? lastPivot.point.bar : lastPivot.point.bartime
x2 = this.properties.xloc == xloc.bar_index? llastPivot.point.bar : llastPivot.point.bartime
level = lastPivot.level
components = llastPivot.componentIndex - lastPivot.componentIndex
zline = line.new(x1=int(x1), y1=y1, x2=int(x2), y2=y2, xloc=this.properties.xloc, color=this.properties.lineColor, width=this.properties.lineWidth, style=this.properties.lineStyle)
dir = lastPivot.dir
label zlabel = na
if(this.properties.showLabel)
labelStyle = dir > 0? label.style_label_down : label.style_label_up
_indicators = lastPivot.indicatorValues
_indicatorNames = lastPivot.indicatorNames
indicatorRatios = lastPivot.indicatorRatios
labelText = '(Level '+str.tostring(level)+' : '+str.tostring(lastPivot.ratio)+')' +
(lastPivot.subComponents != 0? '\nSub Components :'+str.tostring(lastPivot.subComponents) : '')
for [index, indicatorName] in _indicatorNames
indicatorValue = _indicators.get(index)
labelText := labelText + '\n' + indicatorName + ' : ' + str.tostring(math.round(indicatorValue,2)) + ' / ' +str.tostring(indicatorRatios.get(index))
lblColor=dir==2? color.green : dir == 1? color.orange : dir == -1? color.lime : color.red
zlabel := label.new(x=int(x1), y=y1, yloc=yloc.price, color=lblColor, style=labelStyle, text=labelText,
textcolor=this.properties.textColor, size = size.small, xloc=this.properties.xloc)
this.drawings.push(Objects.ZigzagObject.new(zline, zlabel))
this
// @function draws fresh zigzag based on properties embedded in ZigzagDrawing object
// @param this ZigzagDrawing object
// @param ohlc values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
// @param indicators Array of indicator values
// @param indicatorNames Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
// @returns ZigzagDrawing object
export method drawfresh(Objects.ZigzagDrawing this, array<float> ohlc = na, matrix<float> indicators = na, array<string> indicatorNames = na)=>
this.init()
this.clear()
this.zigzag.calculate(na(ohlc)?array.from(high,low):ohlc, na(indicators)? matrix.new<float>(): indicators, na(indicatorNames)? array.new<string>():indicatorNames)
this.drawplain()
// @function draws zigzag based on the zigzagmatrix input
// @param this ZigzagDrawing object
// @param ohlc values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
// @param indicators Array of indicator values
// @param indicatorNames Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
// @returns [array<line> zigzaglines, array<label> zigzaglabels]
export method drawcontinuous(Objects.ZigzagDrawing this, array<float> ohlc = na, matrix<float> indicators = na, array<string> indicatorNames = na)=>
this.init()
this.zigzag.calculate(na(ohlc)?array.from(high,low):ohlc, na(indicators)? matrix.new<float>(): indicators, na(indicatorNames)? array.new<string>():indicatorNames)
if this.drawings.size() > 0 and this.zigzag.flags.updateLastPivot
this.drawings.pop()
if(this.zigzag.flags.newPivot)
if this.zigzag.flags.doublePivot and this.zigzag.zigzagPivots.size() >=3
this.draw_zg_line(1)
if this.zigzag.zigzagPivots.size() >= 2
this.draw_zg_line(0)
this
// ###################################################################### Tests #############################################################
// import HeWhoMustNotBeNamed/Logger/1 as l
// import HeWhoMustNotBeNamed/utils/1 as ut
// var logger = l.Logger.new(minimumLevel = 'DEBUG')
// logger.init()
// indicators = matrix.new<float>()
// indicatorNames = array.new<string>()
// themeColors = ut.getColors("dark")
// var Objects.Zigzag zigzag = Objects.Zigzag.new(10)
// var Objects.ZigzagDrawing drawing = Objects.ZigzagDrawing.new(zigzag = zigzag)
// drawing.drawcontinuous()
|
Vector2 | https://www.tradingview.com/script/uicOdAI3-Vector2/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 16 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Representation of two dimensional vectors or points.
// This structure is used to represent positions in two dimensional space or vectors,
// for example in spacial coordinates in 2D space.
// ~~~
// references:
// https://docs.unity3d.com/ScriptReference/Vector2.html
// https://gist.github.com/winduptoy/a1aa09c3499e09edbd33
// https://github.com/dogancoruh/Javascript-Vector2/blob/master/js/vector2.js
// https://gist.github.com/Dalimil/3daf2a0c531d7d030deb37a7bfeff454
// https://gist.github.com/jeantimex/7fa22744e0c45e5df770b532f696af2d
// https://gist.github.com/volkansalma/2972237
// ~~~
library(title='Vector2')
//#region ~~~ Imports and Helper Methods:
import RicardoSantos/CommonTypesMath/1 as TMath
// }
//#endregion
//#region ~~~ Constructor:
// new () {
// @function Create a new Vector2 object.
// @param x float . The x value of the vector, default=0.
// @param y float . The y value of the vector, default=0.
// @returns Vector2. Vector2 object.
// -> usage:
// `unitx = Vector2.new(1.0) , plot(unitx.x)`
export new (float x = 0.0, float y=0.0) =>
TMath.Vector2.new(x, y)
// }
// from () {
// @function Assigns value to a new vector `x,y` elements.
// @param value float, x and y value of the vector.
// @returns Vector2. Vector2 object.
// -> usage:
// `one = Vector2.from(1.0), plot(one.x)`
export from (float value) =>
new(value, value)
// @function Assigns value to a new vector `x,y` elements.
// @param value string . The `x` and `y` value of the vector in a `x,y` or `(x,y)` format, spaces and parentesis will be removed automatically.
// @param element_sep string . Element separator character, default=`,`.
// @param open_par string . Open parentesis character, default=`(`.
// @param close_par string . Close parentesis character, default=`)`.
// @returns Vector2. Vector2 object.
// -> usage:
// `one = Vector2.from("1.0,2"), plot(one.x)`
export from (string value, string element_sep=',', string open_par='(', string close_par=')') =>
_s = str.split(str.replace_all(str.replace_all(str.replace_all(value, ' ', ''), open_par, ''), close_par, ''), element_sep)
if _s.size() < 2
runtime.error('Malformed String expression.')
new(float(str.tonumber(_s.get(0))), float(str.tonumber(_s.get(1))))
// }
// copy () {
// @function Creates a deep copy of a vector.
// @param this Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = Vector2.new(1.0) , b = a.copy() , plot(b.x)`
export method copy (TMath.Vector2 this) =>
TMath.Vector2.copy(this)
// }
//#region ~~~ ~~~ Static Properties:
// down () {
// @function Vector in the form `(0, -1)`.
// @returns Vector2. Vector2 object.
export down () =>
new(0.0, -1.0)
// }
// left () {
// @function Vector in the form `(-1, 0)`.
// @returns Vector2. Vector2 object.
export left () =>
new(-1.0, 0.0)
// }
// right () {
// @function Vector in the form `(1, 0)`.
// @returns Vector2. Vector2 object.
export right () =>
new(1.0, 0.0)
// }
// up () {
// @function Vector in the form `(0, 1)`.
// @returns Vector2. Vector2 object.
export up () =>
new(0.0, 1.0)
// }
// one () {
// @function Vector in the form `(1, 1)`.
// @returns Vector2. Vector2 object.
export one () =>
new(1.0, 1.0)
// }
// zero () {
// @function Vector in the form `(0, 0)`.
// @returns Vector2. Vector2 object.
export zero () =>
new(0.0, 0.0)
// }
// minus_one () {
// @function Vector in the form `(-1, -1)`.
// @returns Vector2. Vector2 object.
export minus_one () =>
new(-1.0, -1.0)
// }
// unit_x () {
// @function Vector in the form `(1, 0)`.
// @returns Vector2. Vector2 object.
export unit_x () =>
new(1.0, 0.0)
// }
// unit_y () {
// @function Vector in the form `(0, 1)`.
// @returns Vector2. Vector2 object.
export unit_y () =>
new(0.0, 1.0)
// }
// nan () {
// @function Vector in the form `(float(na), float(na))`.
// @returns Vector2. Vector2 object.
export nan () =>
new(float(na), float(na))
// }
//#endregion
//#endregion
//#region ~~~ Properties:
// xy () {
// @function Return the values of `x` and `y` as a tuple.
// @param this Vector2 . Vector2 object.
// @returns [float, float].
// -> usage:
// `a = Vector2.new(1.0, 1.0) , [ax, ay] = a.xy() , plot(ax)`
export method xy (TMath.Vector2 this) =>
[this.x, this.y]
// }
// length_squared () {
// @function Length of vector `a` in the form. `a.x^2 + a.y^2`, for comparing vectors this is computationaly lighter.
// @param this Vector2 . Vector2 object.
// @returns float. Squared length of vector.
// -> usage:
// `a = Vector2.new(1.0, 1.0) , plot(a.length_squared())`
export method length_squared (TMath.Vector2 this) =>
this.x * this.x + this.y * this.y
// }
// length () {
// @function Magnitude of vector `a` in the form. `sqrt(a.x^2 + a.y^2)`
// @param this Vector2 . Vector2 object.
// @returns float. Length of vector.
// -> usage:
// `a = Vector2.new(1.0, 1.0) , plot(a.length())`
export method length (TMath.Vector2 this) =>
math.sqrt(this.x * this.x + this.y * this.y)
// }
// normalize () {
// @function Vector normalized with a magnitude of 1, in the form. `a / length(a)`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = normalize(Vector2.new(3.0, 2.0)) , plot(a.y)`
export method normalize (TMath.Vector2 a) =>
float _length = math.sqrt(a.x * a.x + a.y * a.y)
new(a.x / _length, a.y / _length)
// }
// isNA () {
// @function Checks if any of the components is `na`.
// @param this Vector2 . Vector2 object.
// @returns bool.
// usage:
// p = Vector2.new(1.0, na) , plot(isNA(p)?1:0)
export method isNA (TMath.Vector2 this) => na(this.x) or na(this.y)
// }
//#endregion
//#region ~~~ Operator Methods:
// add () {
// @function Adds vector `b` to `a`, in the form `(a.x + b.x, a.y + b.y)`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = one() , b = one() , c = add(a, b) , plot(c.x)`
export method add (TMath.Vector2 a, TMath.Vector2 b) =>
new(a.x + b.x, a.y + b.y)
// @function Adds vector `b` to `a`, in the form `(a.x + b, a.y + b)`.
// @param a Vector2 . Vector2 object.
// @param b float . Value.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = one() , b = 1.0 , c = add(a, b) , plot(c.x)`
export method add (TMath.Vector2 a, float b) =>
new(a.x + b, a.y + b)
// @function Adds vector `b` to `a`, in the form `(a + b.x, a + b.y)`.
// @param a float . Value.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = 1.0 , b = one() , c = add(a, b) , plot(c.x)`
export add (float a, TMath.Vector2 b) =>
new(a + b.x, a + b.y)
// }
// subtract () {
// @function Subtract vector `b` from `a`, in the form `(a.x - b.x, a.y - b.y)`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = one() , b = one() , c = subtract(a, b) , plot(c.x)`
export method subtract (TMath.Vector2 a, TMath.Vector2 b) =>
new(a.x - b.x, a.y - b.y)
// @function Subtract vector `b` from `a`, in the form `(a.x - b, a.y - b)`.
// @param a Vector2 . vector2 object.
// @param b float . Value.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = one() , b = 1.0 , c = subtract(a, b) , plot(c.x)`
export method subtract (TMath.Vector2 a, float b) =>
new(a.x - b, a.y - b)
// @function Subtract vector `b` from `a`, in the form `(a - b.x, a - b.y)`.
// @param a float . value.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = 1.0 , b = one() , c = subtract(a, b) , plot(c.x)`
export subtract (float a, TMath.Vector2 b) =>
new(a - b.x, a - b.y)
// }
// multiply () {
// @function Multiply vector `a` with `b`, in the form `(a.x * b.x, a.y * b.y)`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = one() , b = one() , c = multiply(a, b) , plot(c.x)`
export method multiply (TMath.Vector2 a, TMath.Vector2 b) =>
new(a.x * b.x, a.y * b.y)
// @function Multiply vector `a` with `b`, in the form `(a.x * b, a.y * b)`.
// @param a Vector2 . Vector2 object.
// @param b float . Value.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = one() , b = 1.0 , c = multiply(a, b) , plot(c.x)`
export method multiply (TMath.Vector2 a, float b) =>
new(a.x * b, a.y * b)
// @function Multiply vector `a` with `b`, in the form `(a * b.x, a * b.y)`.
// @param a float . Value.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = 1.0 , b = one() , c = multiply(a, b) , plot(c.x)`
export multiply (float a, TMath.Vector2 b) =>
new(a * b.x, a * b.y)
// }
// divide () {
// @function Divide vector `a` with `b`, in the form `(a.x / b.x, a.y / b.y)`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(3.0) , b = from(2.0) , c = divide(a, b) , plot(c.x)`
export method divide (TMath.Vector2 a, TMath.Vector2 b) =>
new(a.x / b.x, a.y / b.y)
// @function Divide vector `a` with value `b`, in the form `(a.x / b, a.y / b)`.
// @param a Vector2 . Vector2 object.
// @param b float . Value.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(3.0) , b = 2.0 , c = divide(a, b) , plot(c.x)`
export method divide (TMath.Vector2 a, float b) =>
new(a.x / b, a.y / b)
// @function Divide value `a` with vector `b`, in the form `(a / b.x, a / b.y)`.
// @param a float . Value.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = 3.0 , b = from(2.0) , c = divide(a, b) , plot(c.x)`
export divide (float a, TMath.Vector2 b) =>
new(a / b.x, a / b.y)
// }
// negate () {
// @function Negative of vector `a`, in the form `(-a.x, -a.y)`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(3.0) , b = a.negate , plot(b.x)`
export method negate (TMath.Vector2 a) =>
new(-a.x, -a.y)
// }
// pow () {
// @function Raise vector `a` with exponent vector `b`, in the form `(a.x ^ b.x, a.y ^ b.y)`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(3.0) , b = from(2.0) , c = pow(a, b) , plot(c.x)`
export method pow (TMath.Vector2 a, TMath.Vector2 b) =>
new(math.pow(a.x, b.x), math.pow(a.y, b.y))
// @function Raise vector `a` with value `b`, in the form `(a.x ^ b, a.y ^ b)`.
// @param a Vector2 . Vector2 object.
// @param b float . Value.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(3.0) , b = 2.0 , c = pow(a, b) , plot(c.x)`
export method pow (TMath.Vector2 a, float b) =>
new(math.pow(a.x, b), math.pow(a.y, b))
// @function Raise value `a` with vector `b`, in the form `(a ^ b.x, a ^ b.y)`.
// @param a float . Value.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = 3.0 , b = from(2.0) , c = pow(a, b) , plot(c.x)`
export pow (float a, TMath.Vector2 b) =>
new(math.pow(a, b.x), math.pow(a, b.y))
// }
// sqrt () {
// @function Square root of the elements in a vector.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(3.0) , b = sqrt(a) , plot(b.x)`
export method sqrt (TMath.Vector2 a) =>
new(math.sqrt(a.x), math.sqrt(a.y))
// }
// abs () {
// @function Absolute properties of the vector.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(-3.0) , b = abs(a) , plot(b.x)`
export method abs (TMath.Vector2 a) =>
new(math.abs(a.x), math.abs(a.y))
// }
// min () {
// @function Lowest element of a vector.
// @param a Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = min(a) , plot(b)`
export method min (TMath.Vector2 a) =>
math.min(a.x, a.y)
// }
// max () {
// @function Highest element of a vector.
// @param a Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = max(a) , plot(b)`
export method max (TMath.Vector2 a) =>
math.max(a.x, a.y)
// }
// vmax () {
// @function Highest elements of two vectors.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 2.0) , b = new(2.0, 3.0) , c = vmax(a, b) , plot(c.x)`
export vmax (TMath.Vector2 a, TMath.Vector2 b) =>
new(math.max(a.x, b.x), math.max(a.y, b.y))
// @function Highest elements of three vectors.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @param c Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 2.0) , b = new(2.0, 3.0) , c = new(1.5, 4.5) , d = vmax(a, b, c) , plot(d.x)`
export vmax (TMath.Vector2 a, TMath.Vector2 b, TMath.Vector2 c) =>
new(math.max(a.x, b.x, c.x), math.max(a.y, b.y, c.y))
// }
// vmin () {
// @function Lowest elements of two vectors.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 2.0) , b = new(2.0, 3.0) , c = vmin(a, b) , plot(c.x)`
export vmin (TMath.Vector2 a, TMath.Vector2 b) =>
new(math.min(a.x, b.x), math.min(a.y, b.y))
// @function Lowest elements of three vectors.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @param c Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 2.0) , b = new(2.0, 3.0) , c = new(1.5, 4.5) , d = vmin(a, b, c) , plot(d.x)`
export vmin (TMath.Vector2 a, TMath.Vector2 b, TMath.Vector2 c) =>
new(math.min(a.x, b.x, c.x), math.min(a.y, b.y, c.y))
// }
// perp () {
// @function Perpendicular Vector of `a`, in the form `(a.y, -a.x)`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = perp(a) , plot(b.x)`
export method perp (TMath.Vector2 a) =>
new(a.y, -a.x)
// }
// floor () {
// @function Compute the floor of vector `a`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = floor(a) , plot(b.x)`
export method floor (TMath.Vector2 a) =>
new(math.floor(a.x), math.floor(a.y))
// }
// ceil () {
// @function Ceils vector `a`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = ceil(a) , plot(b.x)`
export method ceil (TMath.Vector2 a) =>
new(math.ceil(a.x), math.ceil(a.y))
// @function Ceils vector `a`.
// @param a Vector2 . Vector2 object.
// @param digits int . Digits to use as ceiling.
// @returns Vector2. Vector2 object.
export method ceil (TMath.Vector2 a, int digits) =>
float _places = math.pow(10, digits)
new(math.ceil(a.x * _places) / _places, math.ceil(a.y * _places) / _places)
// }
// round () {
// @function Round of vector elements.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = round(a) , plot(b.x)`
export method round (TMath.Vector2 a) =>
new(math.round(a.x), math.round(a.y))
// @function Round of vector elements.
// @param a Vector2 . Vector2 object.
// @param precision int . Number of digits to round vector "a" elements.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(0.123456, 1.234567) , b = round(a, 2) , plot(b.x)`
export method round (TMath.Vector2 a, int precision) =>
new(math.round(a.x, precision), math.round(a.y, precision))
// }
// fractional () {
// @function Compute the fractional part of the elements from vector `a`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.123456, 1.23456) , b = fractional(a) , plot(b.x)`
export method fractional (TMath.Vector2 a) =>
new(a.x - math.floor(a.x), a.y - math.floor(a.y))
// }
// dot_product () {
// @function dot_product product of 2 vectors, in the form `a.x * b.x + a.y * b.y.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = dot_product(a, b) , plot(c)`
export method dot_product (TMath.Vector2 a, TMath.Vector2 b) =>
(a.x * b.x) + (a.y * b.y)
// }
// cross_product () {
// @function cross product of 2 vectors, in the form `a.x * b.y - a.y * b.x`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = cross_product(a, b) , plot(c)`
export method cross_product (TMath.Vector2 a, TMath.Vector2 b) =>
(a.x * b.y) - (a.y * b.x)
// }
// equals () {
// @function Compares two vectors
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns bool. Representing the equality.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = equals(a, b) ? 1 : 0 , plot(c)`
export method equals (TMath.Vector2 a, TMath.Vector2 b) =>
a.x == b.x and a.y == b.y
// }
//#endregion
//#region ~~~ Trigonometry:
// sin () {
// @function Compute the sine of argument vector `a`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = sin(a) , plot(b.x)`
export method sin (TMath.Vector2 a) =>
new(math.sin(a.x), math.sin(a.y))
// }
// cos () {
// @function Compute the cosine of argument vector `a`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = cos(a) , plot(b.x)`
export method cos (TMath.Vector2 a) =>
new(math.cos(a.x), math.cos(a.y))
// }
// tan () {
// @function Compute the tangent of argument vector `a`.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = tan(a) , plot(b.x)`
export method tan (TMath.Vector2 a) =>
new(math.tan(a.x), math.tan(a.y))
// }
// atan2 () {
// @function Approximation to atan2 calculation, arc tangent of `y/x` in the range (-pi,pi) radians.
// @param x float . The x value of the vector.
// @param y float . The y value of the vector.
// @returns float. Value with angle in radians. (negative if quadrante 3 or 4)
// -> usage:
// `a = new(3.0, 1.5) , b = atan2(a.x, a.y) , plot(b)`
export atan2 (float x, float y) =>
// float _one_qtr_pi = 0.25 * math.pi
// float _three_qtr_pi = 0.75 * math.pi
// float _abs_y = math.abs(y) + 1e-12 // kludge to void zero division
// float _r = 0.0, float _angle = 0.0
// if x < 0.0
// _r := (x + _abs_y) / (_abs_y - x)
// _angle := _three_qtr_pi
// else
// _r := (x - _abs_y) / (x + _abs_y)
// _angle := _one_qtr_pi
// _angle += (0.1963 * _r * _r - 0.9817) * _r
// y < 0.0 ? -_angle : _angle
// .
// https://www.medcalc.org/manual/atan2-function.php
switch
x > 0.0 => math.atan(y / x)
x < 0.0 and y >= 0.0 => math.atan(y / x) + math.pi
x < 0.0 and y < 0.0 => math.atan(y / x) - math.pi
x == 0.0 and y > 0.0 => math.pi / 2.0
x == 0.0 and y < 0.0 => -math.pi / 2.0
=> 0.0
// @function Approximation to atan2 calculation, arc tangent of `y/x` in the range (-pi,pi) radians.
// @param a Vector2 . Vector2 object.
// @returns float, value with angle in radians. (negative if quadrante 3 or 4)
// -> usage:
// `a = new(3.0, 1.5) , b = atan2(a) , plot(b)`
export method atan2 (TMath.Vector2 a) =>
atan2(a.x, a.y)
// }
//#endregion
//#region ~~~ Methods:
// distance () {
// @function Distance between vector `a` and `b`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = distance(a, b) , plot(c)`
export method distance (TMath.Vector2 a, TMath.Vector2 b) =>
length(new(a.x - b.x, a.y - b.y))
// }
// rescale () {
// @function Rescale a vector to a new magnitude.
// @param a Vector2 . Vector2 object.
// @param length float . Magnitude.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = 2.0 , c = rescale(a, b) , plot(c.x)`
export method rescale (TMath.Vector2 a, float length) =>
float _scalar = length / math.sqrt(a.x * a.x + a.y * a.y)
new(a.x * _scalar, a.y * _scalar)
// }
// rotate () {
// @function Rotates vector by a angle.
// @param a Vector2 . Vector2 object.
// @param radians float . Angle value in radians.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = 2.0 , c = rotate(a, b) , plot(c.x)`
export method rotate (TMath.Vector2 a, float radians) =>
float _cos = math.cos(radians)
float _sin = math.sin(radians)
new(a.x * _cos - a.y * _sin, a.x * _sin + a.y * _cos)
// }
// rotate_degree () {
// @function Rotates vector by a angle.
// @param a Vector2 . Vector2 object.
// @param degree float . Angle value in degrees.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = 45.0 , c = rotate_degree(a, b) , plot(c.x)`
export method rotate_degree (TMath.Vector2 a, float degree) =>
rotate(a, math.toradians(degree))
// }
// rotate_around () {
// @function Rotates vector `target` around `origin` by angle value.
// @param target Vector2 . Vector2 object.
// @param center Vector2 . Vector2 object.
// @param angle float . Angle value in degrees.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = rotate_around(a, b, 45.0) , plot(c.x)`
export method rotate_around (TMath.Vector2 this, TMath.Vector2 center, float angle) =>
if angle == 0
this
else
_d = not isNA(center) ? subtract(this, center) : this
_c = not isNA(center) ? center : zero()
_a = math.toradians(angle)
_sin = math.sin(_a)
_cos = math.cos(_a)
new(_c.x + (_d.x * _cos - _d.y * _sin), _c.y + (_d.x * _sin + _d.y * _cos))
// }
// perpendicular_distance () {
// @function Distance from point `a` to line between `b` and `c`.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @param c Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(1.5, 2.6) , b = from(1.0) , c = from(3.0) , d = perpendicular_distance(a, b, c) , plot(d.x)`
export method perpendicular_distance (TMath.Vector2 a, TMath.Vector2 b, TMath.Vector2 c) =>
TMath.Vector2 _d = new(c.x - b.x, c.y - b.y)
math.abs(cross_product(a, _d) + cross_product(c, b)) / length(_d)
// }
// project () {
// @function Project a vector onto another.
// @param a Vector2 . Vector2 object.
// @param axis Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = project(a, b) , plot(c.x)`
export method project (TMath.Vector2 a, TMath.Vector2 axis) =>
float _t = (a.x * axis.x + a.y * axis.y) / (axis.x * axis.x + axis.y * axis.y)
new(_t * axis.x, _t * axis.y)
// }
// projectN () {
// @function Project a vector onto a vector of unit length.
// @param a Vector2 . Vector2 object.
// @param axis Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = projectN(a, b) , plot(c.x)`
export method projectN (TMath.Vector2 a, TMath.Vector2 axis) =>
float _t = (a.x * axis.x + a.y * axis.y)
new(_t * axis.x, _t * axis.y)
// }
// reflect () {
// @function Reflect a vector on another.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = reflect(a, b) , plot(c.x)`
export method reflect (TMath.Vector2 a, TMath.Vector2 axis) =>
TMath.Vector2 _p = project(a, axis)
new(_p.x * 2.0 - a.x, _p.y * 2.0 - a.y)
// }
// reflectN () {
// @function Reflect a vector to a arbitrary axis.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = reflectN(a, b) , plot(c.x)`
export method reflectN (TMath.Vector2 a, TMath.Vector2 axis) =>
TMath.Vector2 _p = projectN(a, axis)
new(_p.x * 2.0 - a.x, _p.y * 2.0 - a.y)
// }
// angle () {
// @function Angle in radians of a vector.
// @param a Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = angle(a) , plot(b)`
export method angle (TMath.Vector2 a) =>
-atan2(-a.y, a.x)
// }
// angle_unsigned () {
// @function unsigned degree angle between 0 and +180 by given two vectors.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = angle_unsigned(a, b) , plot(c)`
export method angle_unsigned (TMath.Vector2 a, TMath.Vector2 b) =>
math.todegrees(math.acos(dot_product(normalize(a), normalize(b))))
// }
// angle_signed () {
// @function Signed degree angle between -180 and +180 by given two vectors.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = angle_signed(a, b) , plot(c)`
export method angle_signed (TMath.Vector2 a, TMath.Vector2 b) =>
TMath.Vector2 _na = normalize(a)
TMath.Vector2 _nb = normalize(b)
math.todegrees(math.acos(dot_product(_na, _nb))) * (cross_product(_na, _nb) >= 0 ? 1.0 : -1.0)
// }
// angle_360 () {
// @function Degree angle between 0 and 360 by given two vectors
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = angle_360(a, b) , plot(c)`
export method angle_360 (TMath.Vector2 a, TMath.Vector2 b) =>
TMath.Vector2 _na = normalize(a)
TMath.Vector2 _nb = normalize(b)
float _degree = math.todegrees(math.acos(dot_product(_na, _nb)))
cross_product(_na, _nb) > 0.0 ? _degree : 360.0 - _degree
// }
// clamp () {
// @function Restricts a vector between a min and max value.
// @param a Vector2 . Vector2 object.
// @param vmin Vector2 . Vector2 object.
// @param vmax Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = from(2.5) , d = clamp(a, b, c) , plot(d.x)`
export method clamp (TMath.Vector2 a, TMath.Vector2 min, TMath.Vector2 max) =>
float _x = math.max(math.min(a.x , max.x), min.x)
float _y = math.max(math.min(a.y, max.y), min.y)
new(_x, _y)
// @function Restricts a vector between a min and max value.
// @param a Vector2 . Vector2 object.
// @param min float . Lower boundary value.
// @param max float . Higher boundary value.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = clamp(a, 2.0, 2.5) , plot(b.x)`
export method clamp (TMath.Vector2 a, float min, float max) =>
float _x = math.max(math.min(a.x , max), min)
float _y = math.max(math.min(a.y, max), min)
new(_x, _y)
// }
// lerp () {
// @function Linearly interpolates between vectors a and b by rate.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @param rate float . Value between (a:-infinity -> b:1.0), negative values will move away from b.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = lerp(a, b, 0.5) , plot(c.x)`
export method lerp (TMath.Vector2 a, TMath.Vector2 b, float rate) =>
new(a.x + (b.x - a.x) * rate, a.y + (b.y - a.y) * rate)
// }
// herp () {
// @function Hermite curve interpolation between vectors a and b by rate.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @param rate Vector2 . Vector2 object. Value between (a:0 > 1:b).
// @returns Vector2. Vector2 object.
// -> usage:
// `a = new(3.0, 1.5) , b = from(2.0) , c = from(2.5) , d = herp(a, b, c) , plot(d.x)`
export method herp (TMath.Vector2 a, TMath.Vector2 b, TMath.Vector2 rate) =>
TMath.Vector2 _p = new((rate.x - a.x) / (b.x - a.x), (rate.y - a.y) / (b.y - a.y))
TMath.Vector2 _t = clamp(_p, 0.0, 1.0)
new(_t.x * _t.x * (3.0 - 2.0 * _t.x), _t.y * _t.y * (3.0 - 2.0 * _t.y))
// }
// Transform () {
// @function Transform a vector by the given matrix.
// @param position Vector2 . Source vector.
// @param mat M32 . Transformation matrix
// @returns Vector2. Transformed vector.
export method transform (TMath.Vector2 position, TMath.M32 mat) =>
new(
position.x * mat.m11 + position.y * mat.m21 + mat.m31 ,
position.x * mat.m12 + position.y * mat.m22 + mat.m32 )
// @function Transform a vector by the given matrix.
// @param position Vector2 . Source vector.
// @param mat M44 . Transformation matrix
// @returns Vector2. Transformed vector.
export method transform (TMath.Vector2 position, TMath.M44 mat) =>
new(
position.x * mat.m11 + position.y * mat.m21 + mat.m41 ,
position.x * mat.m12 + position.y * mat.m22 + mat.m42 )
// @function Transform a vector by the given matrix.
// @param position Vector2 . Source vector.
// @param mat matrix<float> . Transformation matrix, requires a 3x2 or a 4x4 matrix.
// @returns Vector2. Transformed vector.
export method transform (TMath.Vector2 position, matrix<float> mat) =>
if mat.rows() == 3 and mat.columns() == 2
new(
position.x * mat.get(0,0) + position.y * mat.get(1,0) + mat.get(2,0) ,
position.x * mat.get(0,1) + position.y * mat.get(1,1) + mat.get(2,1) )
else if mat.rows() == 4 and mat.columns() == 4
new(
position.x * mat.get(0,0) + position.y * mat.get(1,0) + mat.get(3,0) ,
position.x * mat.get(0,1) + position.y * mat.get(1,1) + mat.get(3,1) )
else
runtime.error('transform() incorrect shape of matrix, must be 3x2 or 4x4')
nan()
// @function Transform a vector by the given quaternion rotation value.
// @param this Vector2 . Source vector.
// @param rotation Quaternion . Rotation to apply.
// @returns Vector2. Transformed vector.
export method transform (TMath.Vector2 this, TMath.Quaternion rotation) =>
float _x2 = rotation.x + rotation.x
float _y2 = rotation.y + rotation.y
float _z2 = rotation.z + rotation.z
float _wz2 = rotation.w * _z2
float _xx2 = rotation.x * _x2
float _xy2 = rotation.x * _y2
float _yy2 = rotation.y * _y2
float _zz2 = rotation.z * _z2
new(
this.x * (1.0 - _yy2 - _zz2) + this.y * (_xy2 - _wz2) ,
this.x * (_xy2 + _wz2) + this.y * (1.0 - _xx2 - _zz2) )
// }
// area_triangle () {
// @function Find the area in a triangle of vectors.
// @param a Vector2 . Vector2 object.
// @param b Vector2 . Vector2 object.
// @param c Vector2 . Vector2 object.
// @returns float.
// -> usage:
// `a = new(1.0, 2.0) , b = from(2.0) , c = from(1.0) , d = area_triangle(a, b, c) , plot(d.x)`
export area_triangle (TMath.Vector2 a, TMath.Vector2 b, TMath.Vector2 c) =>
math.abs(0.5 * ((a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y)))
// }
// random () {
// @function 2D random value.
// @param max Vector2 . Vector2 object. Vector upper boundary.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(2.0) , b = random(a) , plot(b.x)`
export method random (TMath.Vector2 max) =>
new(math.random(0.0, max.x), math.random(0.0, max.y))
// @function 2D random value.
// @param max float, Vector upper boundary.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = random(2.0) , plot(a.x)`
export random (float max=1.0) =>
new(math.random(0.0, max), math.random(0.0, max))
// // @function 2D random value.
// // @param max Vector2 . Vector2 object., vector upper bound
// // @param seed int . Seed value.
// // @returns Vector2. Vector2 object.
// export random (Vector2 max, int seed) =>
// Vector2.new(math.random(0.0, max.x, seed), math.random(0.0, max.y, seed))
// @function 2D random value.
// @param min Vector2 . Vector2 object. Vector lower boundary.
// @param max Vector2 . Vector2 object. Vector upper boundary.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(1.0) , b = from(2.0) , c = random(a, b) , plot(c.x)`
export random (TMath.Vector2 min, TMath.Vector2 max) =>
new(math.random(min.x, max.x), math.random(min.y, max.y))
// @function 2D random value.
// @param min Vector2 . Vector2 object. Vector lower boundary.
// @param max Vector2 . Vector2 object. Vector upper boundary.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = random(1.0, 2.0) , plot(a.x)`
export random (float min, float max) =>
new(math.random(min, max), math.random(min, max))
// }
// noise () {
// reference:
// https://thebookofshaders.com/11/
// https://www.shadertoy.com/view/4dS3Wd
// @function 2D Noise based on Morgan McGuire @morgan3d.
// @param a Vector2 . Vector2 object.
// @returns Vector2. Vector2 object.
// -> usage:
// `a = from(2.0) , b = noise(a) , plot(b.x)`
export noise (TMath.Vector2 a) =>
TMath.Vector2 _i = floor(a)
TMath.Vector2 _f = fractional(a)
// compute the 4 corners of a tile in 2D
TMath.Vector2 _a = random(_i)
TMath.Vector2 _b = random(add(_i, right()))
TMath.Vector2 _c = random(add(_i, up()))
TMath.Vector2 _d = random(add(_i, one()))
// Smooth Interpolation
TMath.Vector2 _u = herp(zero(), one(), _f)
// Mix 4 coorners percentages
TMath.Vector2 _mix0 = lerp(_a, _b, _u.x)
TMath.Vector2 _mix1 = new((_c.x - _a.x) * _u.y * (1.0 - _u.x), (_c.y - _a.y) * _u.y * (1.0 - _u.x))
TMath.Vector2 _mix2 = new((_d.x - _b.x) * _u.x, (_d.y - _b.y) * _u.y)
new(_mix0.x + _mix1.x + _mix2.x, _mix0.y + _mix1.y + _mix2.y)
// }
//#region ~~~ ~~~ Translate:
// to_string () {
// @function Converts vector `a` to a string format, in the form `"(x, y)"`.
// @param a Vector2 . Vector2 object.
// @returns string. In `"(x, y)"` format.
// -> usage:
// `a = from(2.0) , l = barstate.islast ? label.new(bar_index, 0.0, to_string(a)) : label(na)`
export method to_string (TMath.Vector2 a) =>
str.format('({0}, {1})', a.x, a.y)
// @function Converts vector `a` to a string format, in the form `"(x, y)"`.
// @param a Vector2 . Vector2 object.
// @param format string . Format to apply transformation.
// @returns string. In `"(x, y)"` format.
// -> usage:
// `a = from(2.123456) , l = barstate.islast ? label.new(bar_index, 0.0, to_string(a, "#.##")) : label(na)`
export method to_string (TMath.Vector2 a, string format) =>
str.format('({0,number,'+format+'}, {1,number,'+format+'})', a.x, a.y)
// }
// to_array () {
// @function Converts vector to a array format.
// @param a Vector2 . Vector2 object.
// @returns array<float>.
// -> usage:
// `a = from(2.0) , b = to_array(a) , plot(array.get(b, 0))`
export method to_array (TMath.Vector2 a) =>
array<float> _output = array.from(float(a.x), float(a.y))
// }
// to_barycentric () {
// reference:
// https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/math/GeometryUtils.java
//
// B
// /\
// / \
// / .p \
// A /______\C
// p = position on the triangle plane
// @function Captures the barycentric coordinate of a cartesian position in the triangle plane.
// @param this Vector2 . Source cartesian coordinate position.
// @param a Vector2 . Triangle corner `a` vertice.
// @param b Vector2 . Triangle corner `b` vertice.
// @param c Vector2 . Triangle corner `c` vertice.
// @returns bool.
export method to_barycentric (TMath.Vector2 this, TMath.Vector2 a, TMath.Vector2 b, TMath.Vector2 c) =>
_v0 = b.subtract(a)
_v1 = c.subtract(a)
_v2 = this.subtract(a)
float _d00 = dot_product(_v0, _v0)
float _d01 = dot_product(_v0, _v1)
float _d11 = dot_product(_v1, _v1)
float _d20 = dot_product(_v2, _v0)
float _d21 = dot_product(_v2, _v1)
float _denom = _d00 * _d11 - _d01 * _d01
new((_d11 * _d20 - _d01 * _d21) / _denom , (_d00 * _d21 - _d01 * _d20) / _denom)
// TEST: OK 20230216 RS
// float px = input.float(50.0, step=10.0)
// float py = input.float(50.0, step=10.0)
// a = new(float(bar_index+10), 10.0)
// b = new(float(bar_index+100), 100.0)
// c = new(float(bar_index+200), 50.0)
// p = new(float(bar_index+px), py)
// if barstate.islast
// line.new(int(a.x), a.y, int(b.x), b.y, xloc.bar_index, extend.none, #e3e3e3)
// line.new(int(b.x), b.y, int(c.x), c.y, xloc.bar_index, extend.none, #e3e3e3)
// line.new(int(c.x), c.y, int(a.x), a.y, xloc.bar_index, extend.none, #e3e3e3)
// label.new(int(p.x), p.y, p.to_barycentric(a, b, c).to_string())
// }
// from_barycentric () {
// @function Captures the cartesian coordinate of a barycentric position in the triangle plane.
// @param this Vector2 . Source barycentric coordinate position.
// @param a Vector2 . Triangle corner `a` vertice.
// @param b Vector2 . Triangle corner `b` vertice.
// @param c Vector2 . Triangle corner `c` vertice.
// @returns bool.
export method from_barycentric (TMath.Vector2 this, TMath.Vector2 a, TMath.Vector2 b, TMath.Vector2 c) =>
float _u = 1.0 - this.x - this.y
new(_u * a.x + this.x * b.x + this.y * c.x , _u * a.y + this.x * b.y + this.y * c.y)
// TEST: OK 20230216 RS
// float px = input.float(50.0, step=10.0)
// float py = input.float(50.0, step=10.0)
// a = new(float(bar_index+10), 10.0)
// b = new(float(bar_index+100), 100.0)
// c = new(float(bar_index+200), 50.0)
// p = new(float(bar_index+px), py)
// if barstate.islast
// line.new(int(a.x), a.y, int(b.x), b.y, xloc.bar_index, extend.none, #e3e3e3)
// line.new(int(b.x), b.y, int(c.x), c.y, xloc.bar_index, extend.none, #e3e3e3)
// line.new(int(c.x), c.y, int(a.x), a.y, xloc.bar_index, extend.none, #e3e3e3)
// _bary_coord = p.to_barycentric(a, b, c)
// _cart_coord = _bary_coord.from_barycentric(a, b, c)
// label.new(int(p.x), p.y, str.format('B: {0}\nC: {1}\n', _bary_coord.to_string(), _cart_coord.to_string()))
// }
// to_complex () {
// @function Translate a Vector2 structure to complex.
// @param this Vector2 . Source vector.
// @returns Complex.
export method to_complex (TMath.Vector2 this) =>
TMath.complex.new(this.x, this.y)
// }
// to_polar () {
// reference:
// https://brilliant.org/wiki/convert-cartesian-coordinates-to-polar/ bugged output!
// https://keisan.casio.com/exec/system/1223526375
// @function Translate a Vector2 cartesian coordinate into polar coordinates.
// @param this Vector2 . Source vector.
// @returns Pole. The returned angle is in radians.
export method to_polar (TMath.Vector2 this) =>
float _radius = math.sqrt(this.x * this.x + this.y * this.y)
float _angle = atan2(this)
TMath.Pole.new(_radius, _angle)
// TEST: OK 20230217 RS
// float cx = input.float(3.0)
// float cy = input.float(4.0)
// if barstate.islast
// TMath.Vector2 _cart = new(cx, cy)
// TMath.Pole _p = _cart.to_polar()
// label.new(bar_index, 0.0, str.format('{0} = {1}, {2}', _cart.to_string(), _p.radius, _p.angle))
// }
//#endregion
//#endregion
|
SMA Signals | https://www.tradingview.com/script/1dHY2C8p/ | ExpertCryptoo1 | https://www.tradingview.com/u/ExpertCryptoo1/ | 7 | study | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ExpertCryptoo1
//@version=5
indicator("SMA Signals",overlay = true)
sma1_input = input(20,"SMA 1")
sma2_input = input(100,"SMA 2")
sma1= ta.sma(close,sma1_input)
sma2= ta.sma(close,sma2_input)
long = ta.crossunder(sma2, sma1)
short = ta.crossover(sma2, sma1)
plotshape(long , title = "long1" , text = 'AL', style = shape.labelup, location = location.belowbar, color= color.rgb(0, 102, 3), textcolor = color.white, size = size.tiny)
plotshape(short , title = "short1" , text = 'SAT', style = shape.labeldown, location = location.abovebar, color= color.rgb(150, 0, 0), textcolor = color.white, size = size.tiny)
alertcondition(long,title = "AL", message = "AL")
alertcondition(short,title = "SAT", message = "SAT")
// plot(sma1,color = color.rgb(82, 206, 255))
// plot(sma2,color = color.rgb(94, 82, 255)) |
keyed value types with pseudo-dict - Methods | https://www.tradingview.com/script/0Cpmg2cD-keyed-value-types-with-pseudo-dict-Methods/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// © kaigouthro
//@version=5
//@description a set of primitive single-type key/value items, and pseudo-dictionaries
// The dictionaries are single arrays of items, each item has a key and value.
// The library is 100% methods. add, remove, get and set items by key.
// It provides methods to get all the keys, values or items in the dict as arrays.
// For those familiar with python, it's similar, but typified.. and the brackets are round.
library("key_vals")
/////// description-ish, not all comments are filled, my keyboard
// is nearly at it's end, missing keys, and another dozen
// don't quite listen. but code works.. probably.. maybe...
// example syntax.. using floats.. i should do this more often.
// ... the same functions exist for Int, Bool and String
//------------------------------------------
// new float_item
//
// new ('demo', 1.0 )
//------------------------------------------
// set the key of a float_item
//
// float_item.key ('demo')
//------------------------------------------
// get the key of a float_item
//
// float_item.key ()
//------------------------------------------
// set the value of a float_item
//
// float_item.val ('demo')
//------------------------------------------
// get the value of a float_item
//
// float_item.val ()
//------------------------------------------
// get the number of items in a dict
//
// float_dict.count ()
//------------------------------------------
// set an item to a dict by key ( add / update)
//
// float_dict.set ( 'demo', 2.0 )
//------------------------------------------
// remove an item from a dict by key (changes index, but this is about keys, not ids)
//
// float_dict.remove ( 'demo' )
//------------------------------------------
// get an item from a dict array
//
// array<float_dict>.get ( 0 )
//------------------------------------------
// get an item from a dict by key
//
// float_dict.get ( 'demo' )
//------------------------------------------
// get an item from a dict by id (remember, ids change if removed by key)
// mainlyy an internal function
//
// float_dict.get ( 0 )
//------------------------------------------
// return all keys as string[]
//
// float_dict.get_keys()
//------------------------------------------
// return all values as float[]
//
// float_dict.get_values()
//------------------------------------------
// return all items as float[]
//
// float_dict.get_items()
//------------------------------------------
// create a new float dict in the multi dict and return the index of it
//
// multi_dict.add_float_dict()
//------------------------------------------
// get the float dict at index 0 from the multi dict
//
// multi_dict.get_float_dict( 0)
//------------------------------------------
// set an item in a float dict in a multi dict
//
// multi_dict.set_float( 'demo', 2.0 )
//------------------------------------------
// get an item from a float dict in a multi dict
//
// multi_dict.get_float( 'demo' )
// @type float_item
// @field key (string)
// @field val (float)
// @field next (float_item)
export type float_item
string key = ''
float val = 0.
float_item next
// @type float_dict
export type float_dict
float_item[] content
// @type int_item
// @field key (string)
// @field val (int)
// @field next (int_item)
export type int_item
string key = ''
int val = 0
int_item next
// @type int_dict
export type int_dict
int_item[] content
// @type string_item
// @field key (string)
// @field val (string)
// @field next (string_item)
export type string_item
string key = ''
string val = ''
string_item next
// @type string_dict
export type string_dict
string_item[] content
// @type bool_item
// @field key (string)
// @field val (bool)
// @field next (bool_item)
export type bool_item
string key = ''
bool val = na
bool_item next
// @type bool_dict
export type bool_dict
bool_item[] content
// @type multi_dict
export type multi_dict
float_dict [] f_dicts
int_dict f_registry
int_dict [] i_dicts
int_dict i_registry
string_dict[] s_dicts
int_dict s_registry
bool_dict [] b_dicts
int_dict b_registry
// @function new
// @param key string
// @param val float
// @returns
export new ( string key , float val ) => float_item.new (key,val)
// @function key
// @param this float_item
// @param key string
// @returns
export method key ( float_item this , string key ) => this.key := key , this
// @function key
// @param this float_item
// @returns
export method key ( float_item this ) => this.key
// @function val
// @param this float_item
// @returns
export method val ( float_item this ) => this.val
// @function val
// @param this float_item
// @param val float
// @returns
export method val ( float_item this , float val ) => this.val := val , this
// @function count
// @param dict float_dict
// @returns
export method count ( float_dict dict ) => array.size (dict.content)
// @function get
// @param dict float_dict
// @param index int
// @returns
export method get ( float_dict dict , int index ) => (index >= 0 and index < array.size(dict.content)) ? array.get(dict.content , index ) : na
// @function get
// @param dict float_dict
// @param index int
// @returns
export method get ( float_dict[] dict , int index ) => (index >= 0 and index < array.size(dict)) ? array.get(dict , index ) : na
// @function set
// @param d float_dict
// @param key string
// @param val float
// @returns
export method set(float_dict d, string key, float val) =>
int index = -1
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
v = d.get(i).val
v := val
break
index := i
if index < 0
array.push(d.content, float_item.new(key,val))
// @function get
// @param d float_dict
// @param key string
// @returns
export method get(float_dict d, string key) =>
float out = na
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
out := d.get(i).val
out
// @function get_keys
// @param d float_dict
// @returns
export method get_keys(float_dict d) =>
string[] keys = array.new_string()
for i = 0 to array.size(d.content) - 1
array.push(keys, d.get(i).key)
keys
// @function get_values
// @param d float_dict
// @returns
export method get_values(float_dict d) =>
float[] values = array.new_float()
for i = 0 to array.size(d.content) - 1
array.push(values, d.get(i).val)
values
// @function get_items
// @param d float_dict
// @returns
export method get_items(float_dict d) =>
float_item[] content = array.new<float_item>()
for i = 0 to array.size(d.content) - 1
array.push(content, d.get(i))
content
// @function new
// @param key string
// @param val bool
// @returns
export new ( string key , bool val ) => bool_item.new (key,val)
// @function key
// @param this bool_item
// @param key string
// @returns
export method key ( bool_item this , string key ) => this.key := key , this
// @function key
// @param this bool_item
// @returns
export method key ( bool_item this ) => this.key
// @function val
// @param this bool_item
// @returns
export method val ( bool_item this ) => this.val
// @function val
// @param this bool_item
// @param val bool
// @returns
export method val ( bool_item this , bool val ) => this.val := val , this
// @function count
// @param dict bool_dict
// @returns
export method count ( bool_dict dict ) => array.size (dict.content)
// @function get
// @param dict bool_dict
// @param index int
// @returns
export method get ( bool_dict dict , int index ) => (index >= 0 and index < array.size(dict.content)) ? array.get(dict.content , index ) : na
// @function get
// @param dict bool_dict
// @param index int
// @returns
export method get ( bool_dict[] dict , int index ) => (index >= 0 and index < array.size(dict)) ? array.get(dict , index ) : na
// @function set
// @param d bool_dict
// @param key string
// @param val bool
// @returns
export method set(bool_dict d, string key, bool val) =>
int index = -1
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
v = d.get(i).val
v := val
break
index := i
if index < 0
array.push(d.content, bool_item.new(key,val))
// @function get
// @param d bool_dict
// @param key string
// @returns
export method get(bool_dict d, string key) =>
bool out = na
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
out := d.get(i).val
out
// @function get_keys
// @param d bool_dict
// @returns
export method get_keys(bool_dict d) =>
string[] keys = array.new_string()
for i = 0 to array.size(d.content) - 1
array.push(keys, d.get(i).key)
keys
// @function get_values
// @param d bool_dict
// @returns
export method get_values(bool_dict d) =>
bool[] values = array.new_bool()
for i = 0 to array.size(d.content) - 1
array.push(values, d.get(i).val)
values
// @function get_items
// @param d bool_dict
// @returns
export method get_items(bool_dict d) =>
bool_item[] content = array.new<bool_item>()
for i = 0 to array.size(d.content) - 1
array.push(content, d.get(i))
content
// @function new
// @param key string
// @param val int
// @returns
export new ( string key , int val ) => int_item.new (key,val)
// @function key
// @param this int_item
// @param key string
// @returns
export method key ( int_item this , string key ) => this.key := key , this
// @function key
// @param this int_item
// @returns
export method key ( int_item this ) => this.key
// @function val
// @param this int_item
// @returns
export method val ( int_item this ) => this.val
// @function val
// @param this int_item
// @param val int
// @returns
export method val ( int_item this , int val ) => this.val := val , this
// @function count
// @param dict int_dict
// @returns
export method count ( int_dict dict ) => array.size (dict.content)
// @function get
// @param dict int_dict
// @param index int
// @returns
export method get ( int_dict dict , int index ) => (index >= 0 and index < array.size(dict.content)) ? array.get(dict.content , index ) : na
// @function get
// @param dict int_dict
// @param index int
// @returns
export method get ( int_dict[] dict , int index ) => (index >= 0 and index < array.size(dict)) ? array.get(dict , index ) : na
// @function set
// @param d int_dict
// @param key string
// @param val int
// @returns
export method set(int_dict d, string key, int val) =>
int index = -1
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
v = d.get(i).val
v := val
break
index := i
if index < 0
array.push(d.content, int_item.new(key,val))
// @function get
// @param d int_dict
// @param key string
// @returns
export method get(int_dict d, string key) =>
int out = na
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
out := d.get(i).val
out
// @function get_keys
// @param d int_dict
// @returns
export method get_keys(int_dict d) =>
string[] keys = array.new_string()
for i = 0 to array.size(d.content) - 1
array.push(keys, d.get(i).key)
keys
// @function get_values
// @param d int_dict
// @returns
export method get_values(int_dict d) =>
int[] values = array.new_int()
for i = 0 to array.size(d.content) - 1
array.push(values, d.get(i).val)
values
// @function get_items
// @param d int_dict
// @returns
export method get_items(int_dict d) =>
int_item[] content = array.new<int_item>()
for i = 0 to array. size(d.content) - 1
array.push(content, d.get(i))
content
// @function new
// @param key string
// @param val string
// @returns
export new ( string key , string val ) => string_item.new (key,val)
// @function key
// @param this string_item
// @param key string
// @returns
export method key ( string_item this , string key ) => this.key := key , this
// @function key
// @param this string_item
// @returns
export method key ( string_item this ) => this.key
// @function val
// @param this string_item
// @returns
export method val ( string_item this ) => this.val
// @function val
// @param this string_item
// @param val string
// @returns
export method val ( string_item this , string val ) => this.val := val , this
// @function count
// @param dict string_dict
// @returns
export method count ( string_dict dict ) => array.size (dict.content)
// @function get
// @param dict string_dict
// @param index int
// @returns
export method get ( string_dict dict , int index ) => (index >= 0 and index < array.size(dict.content)) ? array.get(dict.content , index ) : na
// @function get
// @param dict string_dict
// @param index int
// @returns
export method get ( string_dict[] dict , int index ) => (index >= 0 and index < array.size(dict)) ? array.get(dict , index ) : na
// @function set
// @param d string_dict
// @param key string
// @param val string
// @returns
export method set(string_dict d, string key, string val) =>
int index = -1
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
v = d.get(i).val
v := val
break
index := i
if index < 0
array.push(d.content, string_item.new(key,val))
// @function get
// @param d string_dict
// @param key string
// @returns
export method get(string_dict d, string key) =>
string out = na
for i = 0 to array.size(d.content) - 1
if d.get(i).key == key
out := d.get(i).val
out
// @function get_keys
// @param d string_dict
// @returns
export method get_keys(string_dict d) =>
string[] keys = array.new_string()
for i = 0 to array.size(d.content) - 1
array.push(keys, d.get(i).key)
keys
// @function get_values
// @param d string_dict
// @returns
export method get_values(string_dict d) =>
string[] values = array.new_string()
for i = 0 to array.size(d.content) - 1
array.push(values, d.get(i).val)
values
// @function get_items
// @param d string_dict
// @returns
export method get_items(string_dict d) =>
string_item[] content = array.new<string_item>()
for i = 0 to array.size(d.content) - 1
array.push(content, d.get(i))
content
// @function remove an item by key
// @param key string
// @returns true if found and removed
export method remove(float_dict dict, string key)=>
for [i,n] in dict.content
if dict.get(i).key == key
array.remove(dict.content, i)
true
else
false
// @function remove an item by key
// @param key string
// @returns true if found and removed
export method remove(string_dict dict, string key)=>
for [i,n] in dict.content
if dict.get(i).key == key
array.remove(dict.content, i)
true
else
false
// @function remove an item by key
// @param key string
// @returns true if found and removed
export method remove(int_dict dict, string key)=>
for [i,n] in dict.content
if dict.get(i).key == key
array.remove(dict.content, i)
true
else
false
// @function remove an item by key
// @param key string
// @returns true if found and removed
export method remove(bool_dict dict, string key)=>
for [i,n] in dict.content
if dict.get(i).key == key
array.remove(dict.content, i)
true
else
false
// @function Create a multi dict with some deep layers available (for the intrepid)
export create_multi_dict() => multi_dict.new()
// @function add_float_dict
// @param this multi_dict
// @returns
export method add_float_dict(multi_dict this) =>
int index = math.max ( array.size(this.f_registry.content),0)
fd = float_dict.new ( )
array.push ( this.f_dicts, fd)
id = int_item.new ( 'fd' + str.tostring(index), index)
array.push ( this.f_registry.content, id)
index
// @function add_int_dict
// @param this multi_dict
// @returns
export method add_int_dict(multi_dict this) =>
int index = math.max ( array.size(this.i_registry.content),0)
id = int_dict.new ( )
array.push ( this.i_dicts, id)
ii = int_item.new ( 'id' + str.tostring(index), index)
array.push ( this.i_registry.content, ii)
index
// @function add_string_dict
// @param this multi_dict
// @returns
export method add_string_dict(multi_dict this) =>
int index = math.max ( array.size(this.s_registry.content),0)
sd = string_dict.new ( )
array.push ( this.s_dicts, sd)
si = int_item.new ( 'sd' + str.tostring(index), index)
array.push ( this.s_registry.content, si)
index
// @function add_bool_dict
// @param this multi_dict
// @returns
export method add_bool_dict(multi_dict this) =>
int index = math.max ( array.size(this.b_registry.content),0)
bd = bool_dict.new ( )
array.push ( this.b_dicts, bd)
bi = int_item.new ( 'bd' + str.tostring(index), index)
array.push ( this.b_registry.content, bi)
index
// @function get_float_dict
// @param this multi_dict
// @param index int
// @returns
export method get_float_dict(multi_dict this, int index) => (index >= 0 and index < array.size(this.f_dicts)) ? array.get(this.f_dicts,index) : na
// @function get_int_dict
// @param this multi_dict
// @param index int
// @returns
export method get_int_dict(multi_dict this, int index) => (index >= 0 and index < array.size(this.i_dicts)) ? array.get(this.i_dicts,index) : na
// @function get_string_dict
// @param this multi_dict
// @param index int
// @returns
export method get_string_dict(multi_dict this, int index) => (index >= 0 and index < array.size(this.s_dicts)) ? array.get(this.s_dicts,index) : na
// @function get_bool_dict
// @param this multi_dict
// @param index int
// @returns
export method get_bool_dict(multi_dict this, int index) => (index >= 0 and index < array.size(this.b_dicts)) ? array.get(this.b_dicts,index) : na
// @function get_float_dict
// @param this multi_dict
// @param key string
// @returns
export method get_float_dict(multi_dict this, string key) =>
int index = -1
for i = 0 to array.size(this.f_registry.content) - 1
if this.f_registry.content.get(i).key == key
index := this.f_registry.content.get(i).val
(index >= 0 and index < array.size(this.f_dicts)) ? array.get(this.f_dicts,index) : na
// @function get_int_dict
// @param this multi_dict
// @param key string
// @returns
export method get_int_dict(multi_dict this, string key) =>
int index = -1
for i = 0 to array.size(this.i_registry.content) - 1
if this.i_registry.content.get(i).key == key
index := this.i_registry.content.get(i).val
(index >= 0 and index < array.size(this.i_dicts)) ? array.get(this.i_dicts,index) : na
// @function get_string_dict
// @param this multi_dict
// @param key string
// @returns
export method get_string_dict(multi_dict this, string key) =>
int index = -1
for i = 0 to array.size(this.s_registry.content) - 1
if this.s_registry.content.get(i).key == key
index := this.s_registry.content.get(i).val
(index >= 0 and index < array.size(this.s_dicts)) ? array.get(this.s_dicts,index) : na
// @function get_bool_dict
// @param this multi_dict
// @param key string
// @returns
export method get_bool_dict(multi_dict this, string key) =>
int index = -1
for i = 0 to array.size(this.b_registry.content) - 1
if this.b_registry.content.get(i).key == key
index := this.b_registry.content.get(i).val
(index >= 0 and index < array.size(this.b_dicts)) ? array.get(this.b_dicts,index) : na
// @function set_float
// @param this multi_dict
// @param key string
// @param val float
// @returns
export method set_float(multi_dict this, string key, float val) =>
int index = -1
for i = 0 to array.size(this.f_registry.content) - 1
if this.f_registry.content.get(i).key == key
index := this.f_registry.content.get(i).val
this.f_dicts.get(index).set(key,val)
break
// @function set_int
// @param this multi_dict
// @param key string
// @param val int
// @returns
export method set_int(multi_dict this, string key, int val) =>
int index = -1
for i = 0 to array.size(this.i_registry.content) - 1
if this.i_registry.content.get(i).key == key
index := this.i_registry.content.get(i).val
this.i_dicts.get(index).set(key,val)
break
// @function set_string
// @param this multi_dict
// @param key string
// @param val string
// @returns
export method set_string(multi_dict this, string key, string val) =>
int index = -1
for i = 0 to array.size(this.s_registry.content) - 1
if this.s_registry.content.get(i).key == key
index := this.s_registry.content.get(i).val
this.s_dicts.get(index).set(key,val)
break
// @function set_bool
// @param this multi_dict
// @param key string
// @param val bool
// @returns
export method set_bool(multi_dict this, string key, bool val) =>
int index = -1
for i = 0 to array.size(this.s_registry.content) - 1
if this.b_registry.content.get(i).key == key
index := this.b_registry.content.get(i).val
this.b_dicts.get(index).set(key,val)
break
|
Utilities | https://www.tradingview.com/script/IrBUGZaU-Utilities/ | boitoki | https://www.tradingview.com/u/boitoki/ | 13 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boitoki
//@version=5
// @description TODO: add library description here
library("Utilities")
import boitoki/Heikinashi/6 as heikinashi
// @function Convert price to pips.
// @param _v Price
// @returns Pips
export to_pips (float _v) => _v / (syminfo.mintick * 10)
export toPips (float _v) => _v / (syminfo.mintick * 10)
// @function Convert pips to price.
// @param _v Pips
// @returns Price
export to_price (float _p) => _p * (syminfo.mintick * 10)
export toPrice (float _p) => _p * (syminfo.mintick * 10)
export round (float _x, string _type = 'round') =>
switch _type
'ceil' => math.ceil(_x)
'floor' => math.floor(_x)
'round' => math.round(_x)
'int' => int(_x)
=> _x
// @function Round price
// @param _price Price
// @param _unit Number of Round
// @param _type Method type 'ceil' or 'floor'
// @param _index Index to get
export rounded_price (float _price, float _unit, string _type = 'ceil', bool is_up = true, int _index = 0) =>
index = math.max(_index, 0)
unit = _unit * syminfo.mintick
tick = _price / unit
price = round(tick, _type) * unit
if (_index > 0)
arr = array.new<float>()
for i = 0 to math.max(1, _index)
p = is_up ? (price + (unit * i)) : (price - (unit * i))
array.push(arr, p)
array.get(arr, _index)
else
price
// @function The difference will be returned.
// @param _a begin
// @param _b end
// @return Price as positive number
export price_range (float _a = open, float _b = close) => math.abs(_a - _b)
// @function Get the day of the week
// @param _n Number of day of week
// @param _lang en or ja
export get_day (int _n, string _lang = 'en') =>
_day = _lang == 'ja' ? _n + 10 : _n
switch _day
1 => 'Sun'
2 => 'Mon'
3 => 'Tue'
4 => 'Wed'
5 => 'Thu'
6 => 'Fri'
7 => 'Sat'
11 => '日'
12 => '月'
13 => '火'
14 => '水'
15 => '木'
16 => '金'
17 => '土'
// @function
// @return
export auto_htf () =>
timeframe.isintraday ? timeframe.multiplier <= 60 ? 'D' : timeframe.multiplier <= 240 ? 'W' : 'M' : timeframe.period == 'D' ? '6M' : '12M'
// @function TODO: add function description here
// @param x TODO: add parameter x description here
// @returns TODO: add what function returns
export source (string _name) =>
name = str.lower(_name)
hopen = 0.0, hclose = 0.0
if str.contains(name, 'heikinashi:')
[_hopen, _, _, _hclose] = heikinashi.calc(open, high, low, close)
hopen := _hopen
hclose := hclose
switch name
'open' => open
'high' => high
'low' => low
'close' => close
'oc2' => math.avg(open, close)
'hl2' => hl2
'hlc3' => hlc3
'ohlc4' => ohlc4
'hlcc4' => math.avg(high, low, close, close)
'volume' => volume
'heikinashi: open' => hopen
'heikinashi: close' => hclose
'heikinashi: oc2' => math.avg(hopen, hclose)
=> close
// @function Deletes the lines included in the array.
// @param _arr Array of lines
// @param _min Deletes the lines included in the array.
export clear_lines (line[] _arr, int _min = 0) =>
if array.size(_arr) > _min
for i = (1 + _min) to array.size(_arr)
line.delete(array.shift(_arr))
// @function Deletes the labels included in the array.
// @param _arr Array of labels
// @param _min Deletes the labels included in the array.
export clear_labels (label[] _arr, int _min = 0) =>
if array.size(_arr) > _min
for i = (1 + _min) to array.size(_arr)
label.delete(array.shift(_arr))
// @function Deletes the boxes included in the array.
// @param _arr Array of boxes
// @param _min Deletes the boxes included in the array.
export clear_boxes (box[] _arr, int _min = 0) =>
if array.size(_arr) > _min
for i = (1 + _min) to array.size(_arr)
box.delete(array.shift(_arr))
// @param _arr Array of line
// @param _max Max
// @param _start Start
// @param _step Step number
export remove_lines (line[] _arr, int _max, int _start, int _step) =>
if array.size(_arr) > (_max * _step)
for i = _start to array.size(_arr) - 1
line.delete(array.shift(_arr))
// @param _arr Array of linefill
// @param _max Max
// @param _start Start
// @param _step Step number
export remove_linefills (linefill[] _arr, int _max, int _start, int _step) =>
if array.size(_arr) > (_max * _step)
for i = _start to array.size(_arr) - 1
linefill.delete(array.shift(_arr))
// @param _arr Array of box
// @param _max Max
// @param _start Start
// @param _step Step number
export remove_boxes (box[] _arr, int _max, int _start, int _step) =>
if array.size(_arr) > (_max * _step)
for i = _start to array.size(_arr) - 1
box.delete(array.shift(_arr))
// @param _arr Array of label
// @param _max Max
// @param _start Start
// @param _step Step number
export remove_labels (label[] _arr, int _max, int _start, int _step) =>
if array.size(_arr) > (_max * _step)
for i = _start to array.size(_arr) - 1
label.delete(array.shift(_arr))
// @description QQE Library
// @param _src Source
// @param _period Period
// @param _s_factor Smoothing
// @param _f_factor Fast Factor
// @param _threshold Threshold
// @return [QQE, QQE MOD, QQE Line]
export qqe_func (float _src, simple int _period, simple int _s_factor, float _f_factor, float _threshold) =>
Wilders_Period = _period * 2 - 1
Rsi = ta.rsi(_src, _period)
RsiMa = ta.ema(Rsi , _s_factor)
AtrRsi = math.abs(RsiMa[1] - RsiMa)
MaAtrRsi = ta.ema(AtrRsi, Wilders_Period)
dar = ta.ema(MaAtrRsi, Wilders_Period) * _f_factor
longband = 0.0
shortband = 0.0
trend = 0
DeltaFastAtrRsi = dar
RSIndex = RsiMa
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1] , newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband
cross = ta.cross(longband[1], RSIndex)
trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// Zero cross
// QQExlong = 0
// QQExlong := nz(QQExlong[1])
// QQExshort = 0
// QQExshort := nz(QQExshort[1])
// QQExlong := FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0
// QQExshort := FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0
// qqeLong = QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na
// qqeShort = QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na
osc = RsiMa - 50
mod = (osc > _threshold) or (osc < 0 - _threshold) ? osc : 0
qqe = FastAtrRsiTL - 50
[osc, mod, qqe]
// @function qqe_func's sugar
export QQE (float _src, simple int _period, simple int _s_factor, float _f_factor, float _threshold) =>
qqe_func(_src, _period, _s_factor, _f_factor, _threshold)
////////////////
// Test suite //
var testTable = table.new(position = position.top_right, columns = 2, rows = 10, bgcolor = color.yellow, border_width = 1)
if barstate.islast
table.cell(table_id = testTable, column = 0, row = 0, text = "Open-Close is ")
table.cell(table_id = testTable, column = 1, row = 0, text = str.format('{0,number,#.#}', toPips(open - close)) + 'pips', bgcolor=color.white)
table.cell(table_id = testTable, column = 0, row = 1, text = "10pips is ")
table.cell(table_id = testTable, column = 1, row = 1, text = str.tostring(toPrice(10)) + ' ' + syminfo.currency, bgcolor=color.white)
table.cell(table_id = testTable, column = 0, row = 2, text = "Today is ")
table.cell(table_id = testTable, column = 1, row = 2, text = get_day(dayofweek), bgcolor=color.white)
table.cell(table_id = testTable, column = 0, row = 3, text = "今日は ")
table.cell(table_id = testTable, column = 1, row = 3, text = get_day(dayofweek, 'ja') + '曜日', bgcolor=color.white)
table.cell(table_id = testTable, column = 0, row = 4, text = "平均足 ")
table.cell(table_id = testTable, column = 1, row = 4, text = str.format('{0,number,#.##}', source('heikinashi-open')) + ', ' + str.format('{0,number,#.##}', source('heikinashi-close')), bgcolor=color.white)
table.cell(table_id = testTable, column = 0, row = 5, text = "HTF ")
table.cell(table_id = testTable, column = 1, row = 5, text = auto_htf(), bgcolor=color.white)
var a = array.new<label>()
var b = array.new<line>()
array.push(a, label.new(bar_index, na, str.tostring(dayofweek), yloc=yloc.abovebar, size=size.tiny))
array.push(b, line.new(bar_index, high + ta.sma(high - low, 10), bar_index, low - ta.sma(high - low, 10)))
clear_labels(a, 3)
clear_lines(b, 20) |
SH_Library | https://www.tradingview.com/script/3frYi8g7-SH-Library/ | sherwoodherben2 | https://www.tradingview.com/u/sherwoodherben2/ | 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/
// © sherwoodherben2
//@version=5
// original credit to:
// © jdehorty
// @description This library is a data provider for important Dates and Times from the Economic Calendar.
// Updates and additions by Sherwood
// v2 - [1/11/23] (published as revision 2.0)]
// added CPI calendar for 2023
// v3 -[1/11/23] (published as revision 5.0)]
// added PPI calendar for 2023
// v4 -[1/15/23] (published as revision 11.0)
// added ECI for 2022/23
library(title='SH_Library')
// @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(
"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
"ECI" // Employment Cost Index
)
// @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("9 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"), // 2022
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("12 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("11 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")
)
// @function Gets the ECI The Employment Cost Index (ECI) is a measure of the change in the cost of labor,
export eciReleases() =>
array.from(
timestamp("31 Jan 2022 8:30:00 EST"), // 2022
timestamp("29 Apr 2022 8:30:00 EST"),
timestamp("29 Jul 2022 8:30:00 EST"),
timestamp("31 oct 2022 8:30:00 EST"),
timestamp("31 Jan 2023 8:30:00 EST"), // 2023
timestamp("28 Apr 2023 8:30:00 EST"),
timestamp("28 Jul 2023 8:30:00 EST"),
timestamp("31 oct 2023 8:30:00 EST")
)
|
SessionInBoxesPro | https://www.tradingview.com/script/MEseTHmV-SessionInBoxesPro/ | theATR | https://www.tradingview.com/u/theATR/ | 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/
// © theATR
//@version=5
library("SessionInBoxesPro")
///////////////
// Functions
///////////////
export get_time_by_bar(int bar_count) => timeframe.multiplier * bar_count * 60 * 1000
export get_positions_func (int sessiontime_, int duration_) =>
int max = math.round(duration_ / timeframe.multiplier) // minutes to bar length
int begin_index = 0
for i = 1 to max
if (not na(sessiontime_[i]))
begin_index := begin_index + 1
int to_index = math.max(begin_index, 1)
int pR = bar_index
int pL = bar_index - begin_index
float pT = math.max(ta.highest(high[1], to_index), 0)
float pB = math.min(ta.lowest(low[1], to_index), high)
[pT, pB]
export get_period (int _session, int _start, int _lookback) =>
result = math.max(_start, 1)
for i = result to _lookback
if na(_session[i+1]) and _session[i]
result := i
break
result
export is_start (int _session) => na(_session[1]) and _session
export is_end (int _session) => na(_session) and _session[1]
f_get_day (n) =>
switch n
1 => 'Sun'
2 => 'Mon'
3 => 'Tue'
4 => 'Wed'
5 => 'Thu'
6 => 'Fri'
7 => 'Sat'
// ------------------------
// Drawing progress
// ------------------------
// [├, ┤, ∅, •]
export draw_progress (bool _show, int _session, bool _is_started, bool _is_ended, color _color, float _bottom, bool _delete_history) =>
var label my_label = na
// Variables
icon_closed = '⚀'
if _show
if _is_started
my_label := label.new(time, _bottom, '', textcolor=color.new(_color, 10), style=label.style_label_lower_right, color=color.new(color.black, 100), xloc=xloc.bar_time, size=size.small)
if _delete_history
label.delete(my_label[1])
if _session
label.set_y(my_label, _bottom)
label.set_x(my_label, time)
if _is_ended
label.set_text(my_label, icon_closed)
label.set_x(my_label, time)
// ------------------------
// Drawing labels
// ------------------------
export draw_label (bool _show, int _session, bool _is_started, color _color, float _top, float _bottom, string _text, bool _delete_history, string i_label_chg, string i_label_size, string i_label_position, string i_tz, bool i_label_format_day) =>
var label my_label = na
label_text = array.new_string(1, _text)
f_price = '{0,number,#.#####}'
f_pip = '{0,number,#.#}'
float pips = syminfo.mintick * 10
icon_separator = ' • '
var int start_time = na
if _is_started
start_time := time
chg = _top - _bottom
chg_text = i_label_chg == "YES"
? str.format(f_price, chg)
: str.format(f_pip, chg / pips)
if i_label_chg != "NO"
array.push(label_text, chg_text)
if i_label_format_day
array.push(label_text, f_get_day(dayofweek(start_time, i_tz)))
if _show
if _is_started
my_label := label.new(time, _top, array.join(label_text, icon_separator), textcolor=_color, color=color.new(color.black, 100), size=i_label_size, style=i_label_position, xloc=xloc.bar_time)
if _delete_history
label.delete(my_label[1])
if _session
label.set_y(my_label, _top)
label.set_text(my_label, array.join(label_text, icon_separator))
// ------------------------
// Drawing fibonacci lines
// ------------------------
export draw_fib (bool _show, int _session, bool _is_started, color _color, float _top, float _bottom, float _level, int _width, string _style, bool _is_extend, bool _delete_history) =>
var line my_line = na
y = (_top - _bottom) * _level + _bottom
if _show
if _is_started
my_line := line.new(time, y, time, y, width=_width, color=color.new(_color, 30), style=_style, xloc=xloc.bar_time)
if _is_extend
line.set_extend(my_line, extend.right)
if _delete_history
line.delete(my_line[1])
if _session
line.set_x2(my_line, time + get_time_by_bar(1))
line.set_y1(my_line, y)
line.set_y2(my_line, y)
// ------------------------
// Drawing Opening range
// ------------------------
export get_op_stricts(int _session, bool _is_started, float top, float bottom, int i_o_minutes)=>
var is_closeover = false
var is_closeunder = false
var int x1 = na
is_closeover := false
is_closeunder := false
if _is_started
x1 := time
if _session
is_op = x1 + (i_o_minutes * 60 * 1000)
if time >= is_op and time < is_op + get_time_by_bar(1)
is_closeover := false
is_closeunder := false
else
is_closeover := close>top
is_closeunder := close<bottom
[is_closeover,is_closeunder]
export draw_op (bool _show, int _session, bool _is_started, color _color, float top, float bottom, bool _is_extend, bool _delete_history, int i_o_minutes, int i_o_opacity) =>
var int x1 = na
var box my_box = na
// top = ta.highest(high, _max)
// bottom = ta.lowest(low, _max)
is_crossover = ta.crossover(close, box.get_top(my_box))
is_crossunder = ta.crossunder(close, box.get_bottom(my_box))
if _show
if _is_started
x1 := time
my_box := na
if _delete_history
box.delete(my_box[1])
my_box
if _session
is_op = x1 + (i_o_minutes * 60 * 1000)
if time >= is_op and time < is_op + get_time_by_bar(1)
my_box := box.new(x1, top, time, bottom, xloc=xloc.bar_time, border_width=0, bgcolor=color.new(_color, i_o_opacity))
if _is_extend
box.set_extend(my_box, extend.right)
my_box
else
box.set_right(my_box, time + get_time_by_bar(1))
if is_crossover
alert('Price crossed over the opening range', alert.freq_once_per_bar)
if is_crossunder
alert('Price crossed under the opening range', alert.freq_once_per_bar)
my_box
// ------------------------
// Drawing market
// ------------------------
export get_pm_stricts(bool _show, bool _show_pm, string tf, string ctf, bool _is_started)=>
var line pm_top = na
var line pm_bott = na
var label pm_top_lbl = na
var label pm_bott_lbl = na
var label err_lbl = na
a=0
top=0.0
bottom=10000000000000000.0
if _is_started and _show and _show_pm
if tf=="15m"
if ctf == "1" or ctf == "3" or ctf == "5"
lb = ctf == "1"?15:ctf == "3"?5:3
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
a:=1
else if tf=="30m"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10"
lb = ctf == "1"?30:ctf == "3"?10:ctf == "5"?6:3
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
a:=1
else if tf=="45m"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15"
lb = ctf == "1"?45:ctf == "3"?15:ctf == "5"?9:ctf == "10"?3:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
a:=1
else if tf=="1h"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15" or ctf == "30"
lb = ctf == "1"?60:ctf == "3"?20:ctf == "5"?12:ctf == "10"?6:ctf == "15"?4:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
a:=1
else if tf=="2h"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15" or ctf == "30" or ctf == "60"
lb = ctf == "1"?120:ctf == "3"?40:ctf == "5"?24:ctf == "10"?12:ctf == "15"?8:ctf == "30"?4:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
a:=1
else if tf=="4h"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15" or ctf == "30" or ctf == "60" or ctf == "120"
lb = ctf == "1"?240:ctf == "3"?80:ctf == "5"?48:ctf == "10"?24:ctf == "15"?16:ctf == "30"?8:ctf == "60"?4:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
a:=1
[top,bottom]
export draw_pm(bool _show, bool _show_pm, string tf, string ctf, bool _is_started, bool _is_ended, bool _delete_history, color _color)=>
var line pm_top = na
var line pm_bott = na
var label pm_top_lbl = na
var label pm_bott_lbl = na
var label err_lbl = na
var pm_start=false
pm_start:=_is_started
pm_start:=pm_start!=pm_start[1]?true:false
var pm_ends=false
pm_ends:=_is_ended
pm_ends:=pm_ends!=pm_ends[1]?true:false
a=0
top=0.0
bottom=10000000000000000.0
if _is_started and _show and _show_pm
if tf=="15m"
if ctf == "1" or ctf == "3" or ctf == "5"
lb = ctf == "1"?15:ctf == "3"?5:3
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
pm_top:=line.new(time[lb],top,time,top,xloc.bar_time,color=_color)
pm_top_lbl:=label.new(time[lb],top,"Pre Mkt H",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_down )
pm_bott:=line.new(time[lb],bottom,time,bottom,xloc.bar_time,color=_color)
pm_bott_lbl:=label.new(time[lb],bottom,"Pre Mkt L",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_up )
a:=1
else
err_lbl :=label.new(time,close,"Error:TF not matching.",xloc.bar_time,color=_color, textcolor=color.white)
a:=1
else if tf=="30m"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10"
lb = ctf == "1"?30:ctf == "3"?10:ctf == "5"?6:3
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
pm_top:=line.new(time[lb],top,time,top,xloc.bar_time,color=_color)
pm_top_lbl:=label.new(time[lb],top,"Pre Mkt H",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_down )
pm_bott:=line.new(time[lb],bottom,time,bottom,xloc.bar_time,color=_color)
pm_bott_lbl:=label.new(time[lb],bottom,"Pre Mkt L",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_up )
a:=1
else
err_lbl :=label.new(time,close,"Error:TF not matching.",xloc.bar_time,color=_color, textcolor=color.white)
a:=1
else if tf=="45m"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15"
lb = ctf == "1"?45:ctf == "3"?15:ctf == "5"?9:ctf == "10"?3:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
pm_top:=line.new(time[lb],top,time,top,xloc.bar_time,color=_color)
pm_top_lbl:=label.new(time[lb],top,"Pre Mkt H",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_down )
pm_bott:=line.new(time[lb],bottom,time,bottom,xloc.bar_time,color=_color)
pm_bott_lbl:=label.new(time[lb],bottom,"Pre Mkt L",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_up )
a:=1
else
err_lbl :=label.new(time,close,"Error:TF not matching.",xloc.bar_time,color=_color, textcolor=color.white)
a:=1
else if tf=="1h"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15" or ctf == "30"
lb = ctf == "1"?60:ctf == "3"?20:ctf == "5"?12:ctf == "10"?6:ctf == "15"?4:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
pm_top:=line.new(time[lb],top,time,top,xloc.bar_time,color=_color)
pm_top_lbl:=label.new(time[lb],top,"Pre Mkt H",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_down )
pm_bott:=line.new(time[lb],bottom,time,bottom,xloc.bar_time,color=_color)
pm_bott_lbl:=label.new(time[lb],bottom,"Pre Mkt L",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_up )
a:=1
else
err_lbl :=label.new(time,close,"Error:TF not matching.",xloc.bar_time,color=_color, textcolor=color.white)
a:=1
else if tf=="2h"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15" or ctf == "30" or ctf == "60"
lb = ctf == "1"?120:ctf == "3"?40:ctf == "5"?24:ctf == "10"?12:ctf == "15"?8:ctf == "30"?4:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
pm_top:=line.new(time[lb],top,time,top,xloc.bar_time,color=_color)
pm_top_lbl:=label.new(time[lb],top,"Pre Mkt H",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_down )
pm_bott:=line.new(time[lb],bottom,time,bottom,xloc.bar_time,color=_color)
pm_bott_lbl:=label.new(time[lb],bottom,"Pre Mkt L",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_up )
a:=1
else
err_lbl :=label.new(time,close,"Error:TF not matching.",xloc.bar_time,color=_color, textcolor=color.white)
a:=1
else if tf=="4h"
if ctf == "1" or ctf == "3" or ctf == "5" or ctf == "10" or ctf == "15" or ctf == "30" or ctf == "60" or ctf == "120"
lb = ctf == "1"?240:ctf == "3"?80:ctf == "5"?48:ctf == "10"?24:ctf == "15"?16:ctf == "30"?8:ctf == "60"?4:2
for i = 0 to lb
top:=high[i]>top?high[i]:top
for i = 0 to lb
bottom:=low[i]<bottom?low[i]:bottom
pm_top:=line.new(time[lb],top,time,top,xloc.bar_time,color=_color)
pm_top_lbl:=label.new(time[lb],top,"Pre Mkt H",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_down )
pm_bott:=line.new(time[lb],bottom,time,bottom,xloc.bar_time,color=_color)
pm_bott_lbl:=label.new(time[lb],bottom,"Pre Mkt L",xloc.bar_time, color=#00000000, textcolor=_color, style=label.style_label_up )
a:=1
else
err_lbl :=label.new(time,close,"Error:TF not matching.",xloc.bar_time,color=_color, textcolor=color.white)
a:=1
else if _is_ended and _delete_history and _show and _show_pm
line.delete(pm_top[1])
line.delete(pm_bott[1])
label.delete(pm_top_lbl[1])
label.delete(pm_bott_lbl[1])
label.delete(err_lbl[1])
a:=1
export draw_market (bool _show, int _session, bool _is_started, color _color, int btr, float _top, float _bottom, string _extend, bool _is_extend, bool _delete_history, string i_sess_border_style, int i_sess_border_width, int i_sess_bgopacity) =>
var box my_box = na
should_draw_endline = (not _is_extend) or (_extend == 'Extend + End line')
var box_x = 0
if _show
if _is_started
my_box := box.new(time, _top, time, _bottom, xloc=xloc.bar_time)
box.set_border_style(my_box, i_sess_border_style)
box.set_border_width(my_box, i_sess_border_width)
box.set_border_color(my_box, color.new(_color, btr))
box.set_bgcolor(my_box, color.new(_color, i_sess_bgopacity))
if _is_extend
box.set_extend(my_box, extend.right)
if _delete_history
box.delete(my_box[1])
// Proccesing
if _session
box.set_top(my_box, _top)
box.set_bottom(my_box, _bottom)
if should_draw_endline
box.set_right(my_box, time + get_time_by_bar(1))
// ------------------------
// Drawing
// ------------------------
export draw (bool _show, bool _show_pm, string pm_tf, string ctf, int _session, color _color, int btr, string _label, string _extend, bool _show_fib, bool _show_op, string i_label_chg, string i_label_size, string i_label_position, int i_o_minutes, int i_o_opacity, string i_sess_border_style, int i_sess_border_width, int i_sess_bgopacity, bool i_show_history, bool i_show_closed, bool i_label_show, int i_f_linewidth, string i_f_linestyle, float top, float bottom, string i_tz, bool i_label_format_day) =>
// max_bars_back(_session, 750)
// max = get_period(_session, 1, _lookback)
// top = ta.highest(high, max)
// bottom = ta.lowest(low, max)
is_started = is_start(_session)
is_ended = is_end(_session)
is_extend = _extend != "NO"
delete_history = (not i_show_history) or is_extend
draw_market(_show, _session, is_started, _color, btr, top, bottom, _extend, is_extend, delete_history, i_sess_border_style, i_sess_border_width, i_sess_bgopacity)
if _show_pm
draw_pm(_show,_show_pm, pm_tf, ctf, is_started, is_ended, delete_history, _color)
if i_show_closed
draw_progress(_show, _session, is_started, is_ended, _color, bottom, delete_history)
if i_label_show
draw_label(_show, _session, is_started, _color, top, bottom, _label, delete_history, i_label_chg, i_label_size, i_label_position, i_tz, i_label_format_day)
if _show_op
draw_op(_show, _session, is_started, _color, top, bottom, is_extend, delete_history, i_o_minutes, i_o_opacity)
if _show_fib
draw_fib(_show, _session, is_started, _color, top, bottom, 0.500, 2, line.style_solid, is_extend, delete_history)
draw_fib(_show, _session, is_started, _color, top, bottom, 0.628, i_f_linewidth, i_f_linestyle, is_extend, delete_history)
draw_fib(_show, _session, is_started, _color, top, bottom, 0.382, i_f_linewidth, i_f_linestyle, is_extend, delete_history)
_session
|
Antares | https://www.tradingview.com/script/7ZiMySqD-Antares/ | px2raj | https://www.tradingview.com/u/px2raj/ | 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/
// © px2raj
//@version=5
// @description this library contains some utility functions that I use in my open source scripts including moving average helpers, candlstick helpers, money management, formatters, convertors, webhook integration, analysis, filters and drawing helpers
library("Antares", true)
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// TRADINGVIEW OVERWRITTEN ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function Overwrites `ta.rma` duo to limitations of simple int length. Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
// @param length Number of bars (length).
// @param source Series of values to process.
// @returns Simple moving average of `source` for `length` bars back.
rma(int length = 14, float source = close) =>
sma = ta.sma(source, length)
alpha = 1/length
sum = 0.0
sum := na(sum[1]) ? sma : alpha * source + (1 - alpha) * nz(sum[1])
// @function Overwrites `ta.ema` duo to limitations of simple int length. The ema function returns the exponentially weighted moving average. In ema weighting factors decrease exponentially. It calculates by using a formula: EMA = alpha * source + (1 - alpha) * EMA[1], where alpha = 2 / (length + 1).
// @param length Number of bars (length).
// @param source Series of values to process.
// @returns Exponential moving average of `source` with alpha = 2 / (length + 1).
ema(int length = 14, float source = close) =>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ? source : alpha * source + (1 - alpha) * nz(sum[1])
// @function Wraps all ma functions
// @param type Either SMA or EMA or RMA or WMA or VWMA
// @param length Number of bars (length).
// @param source Series of values to process.
// @returns Moving average of `source` for `length` bars back by the of MA.
export ma(string type = 'SMA', int length = 14, float source = close) =>
if type != 'SMA' and type != 'EMA' and type != 'RMA' and type != 'WMA' and type != 'VWMA'
runtime.error(type + ' is invalid. Accepted types are: ' + 'SMA, EMA, RMA, WMA, VWMA')
_sma = ta.sma(source, length)
_ema = ema(length, source)
_rma = rma(length, source)
_wma = ta.wma(source, length)
_vwma = ta.vwma(source, length)
switch type
"SMA" => _sma
"EMA" => _ema
"RMA" => _rma
"WMA" => _wma
"VWMA" => _vwma
// @function Overwrites `ta.bb` duo to limitations of simple int.float mult. Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price, but can be adjusted to user preferences.
// @param ma Either SMA or EMA or RMA or WMA or VWMA
// @param length Number of bars (length).
// @param mult Standard deviation factor.
// @param source Series of values to process.
// @returns Bollinger Bands.
export bb(string ma = 'SMA', int length = 14, float mult = 2, float source = close) =>
float basis = ma(ma, length, source)
float dev = mult * ta.stdev(source, length)
[basis, basis + dev, basis - dev]
// @function Overwrites `ta.atr` duo to limitations of simple int length. Function atr (average true range) returns the RMA of true range. True range is max(high - low, abs(high - close[1]), abs(low - close[1])).
// @param length Number of bars (length).
// @param h High price high price.
// @param l low price.
// @param c Close price close price.
// @returns Average true range.
export atr(int length = 14, float h = high, float l = low, float c = close) =>
true_range = na(h[1]) ? h-l : math.max(math.max(h - l, math.abs(h - c[1])), math.abs(l - c[1]))
rma(length, true_range)
// @function Overwrites `ta.rsi` duo to limitations of simple int length. Relative strength index. It is calculated using the `ta.rma()` of upward and downward changes of `source` over the last `length` bars.
// @param length Number of bars (length).
// @param source Series of values to process.
// @returns Relative strength index.
export rsi(int length = 14, float source = close) =>
up = rma(length, math.max(ta.change(source), 0))
down = rma(length, -math.min(ta.change(source), 0))
down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
// @function Lowest value for a given number of bars back.
// @param length Number of bars (length).
// @param source Series of values to process.
// @param start Series number of bars that should be skipped before process.
// @returns Lowest value in the series.
export lowest(int length = 14, float source = low, int start = 0) =>
result = source[start]
for i = start to length + start - 1 by 1
if source[i] < result
result := source[i]
result
// @function Highest value for a given number of bars back.
// @param length Number of bars (length).
// @param source Series of values to process.
// @param start Series number of bars that should be skipped before process.
// @returns Highest value in the series.
export highest(int length = 14, float source = high, int start = 0) =>
result = source[start]
for i = start to length + start - 1 by 1
if source[i] > result
result := source[i]
result
// @function Turns source to a value between 0 and 100.
// @param source Series of values to process.
// @param length Number of bars (length).
// @returns A value between 0 and 100
export percentify(float source, int length = 200) =>
highest = highest(length, source)
lowest = lowest(length, source)
(source - lowest) * 100 / (highest - lowest)
// @function Dynamic atr multiplier calculated by RSI.
// @param rsi Relative strength index.
// @param atr_min_multiplier The minimum multiplier of atr
// @param atr_max_multiplier The maximum multiplier of atr
// @returns Dynamic multiplier of ATR
export atr_multiplier(float rsi, float atr_min_multiplier = 1, float atr_max_multiplier = 3) =>
if atr_min_multiplier > atr_max_multiplier
runtime.error('atr_min_multiplier can not be greater than atr_max_multiplier')
if atr_min_multiplier < 0
runtime.error('atr_min_multiplier can not be negative')
if atr_max_multiplier < 0
runtime.error('atr_max_multiplier can not be negative')
step = (atr_max_multiplier - atr_min_multiplier) / 20
math.min(atr_min_multiplier + math.abs(50 - rsi) * step, atr_max_multiplier)
// @function Safe dynamic offset you need to use in your stoploss, stop buy/sell, etc.
// @param atr Average true range.
// @param atr_multiplier ATR multiplier got from `atr_multiplier(rsi, atr_max_multiplier)`
// @returns Dynamic offset
export offset(float atr, float atr_multiplier = 3) =>
atr * atr_multiplier
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// SIGNALS ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
export type signal
float score
float max_score
string status
string name
array<signal> subsignals
// @function Checks all required signals and calculates cumulative score and max score.
// @param signals Array of signals to be checked.
// @param status Either "REQUIRED" or "OPTIONAL" or "IGNORE".
// @param name Name of the signal
// @param side Either 1 or -1. 1 means "Long", -1 means "Short". If it was na, then side is in the same direct of first signal
// @returns A single signal calculated by all the signals passed to
export signals(array<signal> signals, string status = "Required", string name = "Final Signal", int side = na) =>
first_signal = array.get(signals, 0)
first_signal_score = na(first_signal) ? na : first_signal.score
float _side = na(side) and not na(first_signal_score) ? first_signal_score : na
_side := _side / math.abs(_side)
if _side == 0
runtime.error("arg side should be either 1 or -1 but got 0")
int required = 0
int passed_required = 0
float score = 0
float max_score = 0
for i = 0 to array.size(signals) - 1 by 1
s = array.get(signals, i)
if na(s)
continue
same_direct = _side > 0 and s.score > 0 or _side < 0 and s.score < 0
if str.upper(s.status) == "REQUIRED"
required := required + 1
if same_direct
passed_required := passed_required + 1
if str.upper(s.status) != "IGNORE"
max_score := max_score + math.abs(s.max_score)
if same_direct
score := score + s.score
if passed_required != required
score := 0
signal.new(score, max_score, status, name, signals)
// @function Checks usd dominance, total2btc, btcusdt, altusdt and altbtc to see if all of them are verifying the trend.
// @param symbol Ticker ID.
// @param usd Signal of USD dominance in crypto
// @param total2btc Signal of TOTAL2/BTC in crypto
// @param btcusd Signal of BTC/USD in crypto
// @param altusd Signal of XXX/USD in crypto
// @param altbtc Signal of XXX/BTC in crypto
// @returns Single trend signal
export multi_trend_signal(string symbol, signal usd, signal total2btc, signal btcusd, signal altusd, signal altbtc, float multiplier = 1) =>
ticker = syminfo.ticker(symbol)
is_btc = str.startswith(ticker, "BTC") and str.contains(ticker, "USD")
is_alt = not str.startswith(ticker, "BTC") and str.contains(ticker, "USD")
usd_score = na(usd) ? na : usd.score
total2btc_score = na(total2btc) ? na : total2btc.score
btcusd_score = na(btcusd) ? na : btcusd.score
altusd_score = na(altusd) ? na : altusd.score
altbtc_score = na(altbtc) ? na : altbtc.score
score =
is_btc and btcusd_score > 0 and total2btc_score < 0 and usd_score < 0 ? 3 :
not is_alt ? 0 :
btcusd_score > 0 and altusd_score > 0 and altbtc_score > 0 and total2btc_score > 0 ? 4 :
btcusd_score > 0 and altusd_score > 0 and altbtc_score > 0 ? 3 :
btcusd_score == 0 and altusd_score > 0 and altbtc_score > 0 and total2btc_score > 0 ? 2 :
btcusd_score == 0 and altusd_score > 0 and altbtc_score > 0 ? 1 :
btcusd_score < 0 and altusd_score < 0 and altbtc_score < 0 and total2btc_score < 0 ? -4 :
btcusd_score < 0 and altusd_score < 0 and altbtc_score < 0 ? -3 :
btcusd_score == 0 and altusd_score < 0 and altbtc_score < 0 and total2btc_score < 0 ? -2 :
btcusd_score == 0 and altusd_score < 0 and altbtc_score < 0 ? -1 :
0
signal.new(score * multiplier, 4 * multiplier, "Required", "Multi Trend Signal")
// @function Tells you if RSI is in emotional zone.
// @param rsi Relative Strength Index
// @param bottom The zone that below it market reacts emotionally
// @param top The zone that above it market reacts emotionally
// @returns false if RSI was between `bottom` and `top` otherwise true
export rsi_emotional(float rsi, float bottom = 30, float top = 70) => rsi < bottom or top < rsi
// @function Tells you if RSI is in good point to check your other strategy conditions.
// @param rsi Relative Strength Index
// @param bottom The zone that below it market reacts emotionally
// @param top The zone that above it market reacts emotionally
// @returns 1 if RSI crossed out 30, 50 or 70. -1 if RSI crossed under 70, 50, 30. otherwise is 0
export rsi_score(float rsi, float bottom = 30, float top = 70) =>
middle = (bottom + top) / 2
rsi[1] < bottom and rsi > bottom or rsi[1] < middle and rsi > middle or rsi[1] < top and rsi > top ? 1 :
rsi[1] > bottom and rsi < bottom or rsi[1] > middle and rsi < middle or rsi[1] > top and rsi < top ? -1 :
0
// @function Tells you if slope of RSI is either ascending or descending
// @param rsi Relative Strength Index
// @param min_offset When RSI is either 0 or 100, offset is min_offset
// @param max_offset When RSI is 50, offset is max_offset
// @param offset_check Number of last candles that their offsets should be checked. It should be between 1 and 3
export slope_score(float rsi, float min_offset = 0.01, float max_offset = 5, int offset_check = 3) =>
if offset_check < 1 or offset_check > 3
runtime.error("offset_check should be either 1, 2 or 3")
float step = (max_offset - min_offset) / 50
float offset = math.max(max_offset - math.abs(50 - rsi) * step, min_offset)
int offset_signal = rsi > rsi[1] + offset ? 1 : rsi < rsi[1] - offset ? -1 : 0
switch offset_check
1 => offset_signal
2 => offset_signal > 0 and offset_signal[1] > 0 ? 1 :
offset_signal < 0 and offset_signal[1] < 0 ? -1 : 0
3 => offset_signal > 0 and offset_signal[1] > 0 and offset_signal[2] > 0 ? 1 :
offset_signal < 0 and offset_signal[1] < 0 and offset_signal[2] < 0 ? -1 : 0
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// CANDLESTICK PATTERNS ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function
// @param o Open price
// @param c Close price
// @returns
export body_high(float o = open, float c = close) => c >= o ? c : o
// @function
// @param o Open price
// @param c Close price
// @returns
export body_low(float o = open, float c = close) => c <= o ? c : o
// @function
// @param o Open price
// @param c Close price
// @returns
export is_green(float o = open, float c = close) => o < c
// @function
// @param o Open price
// @param c Close price
// @returns
export is_red(float o = open, float c = close) => o > c
// @function
// @param o Open price
// @param c Close price
// @param mintick Min tick value for the symbol.
// @returns
export body_size(float o = open, float c = close, float mintick = syminfo.mintick) => math.abs(c - o) / mintick
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @returns
export body_percent(float o = open, float h = high, float l = low, float c = close) => math.abs(c - o) / (h - l)
// @function
// @param o Open price
// @param h High price
// @param c Close price
// @param mintick Min tick value for the symbol.
// @returns
export top_wick_size(float o = open, float h = high, float c = close, float mintick = syminfo.mintick) => math.abs(h - body_high(o, c)) / mintick
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @returns
export top_wick_percent(float o = open, float h = high, float l = low, float c = close) => (h - body_high(o, c)) / (h - l)
// @function
// @param o Open price
// @param l Low price
// @param c Close price
// @param mintick Min tick value for the symbol.
// @returns
export bottom_wick_size(float o = open, float l = low, float c = close, float mintick = syminfo.mintick) => math.abs(l - body_low(o, c)) / mintick
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @returns
export bottom_wick_percent(float o = open, float h = high, float l = low, float c = close) => (body_low(o, c) - l) / (h - l)
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @returns
export wick_percent(float o = open, float h = high, float l = low, float c = close) => (top_wick_percent(o, h, l, c) + bottom_wick_percent(o, h, l, c)) / (h - l)
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @param fib Fibonachi level
// @param c Close price
// @param color_match If true then the color of the candle will be checked
// @returns
export is_hammer(float o = open, float h = high, float l = low, float c = close, float fib = 0.382, bool color_match = false) =>
bull_fib = (l - h) * fib + h
body_low(o, c) >= bull_fib and (not color_match or is_green(o, c))
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @param fib Fibonachi level
// @param color_match If true then the color of the candle will be checked
// @returns
export is_shooting_star(float o = open, float h = high, float l = low, float c = close, float fib = 0.382, bool color_match = false) =>
bear_fib = (h - l) * fib + l
body_high(o, c) <= bear_fib and (not color_match or is_red(o, c))
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @param max_body_percent Max percentage of candle body
// @param wick_size Size of wick
// @returns
export is_doji(float o = open, float h = high, float l = low, float c = close, float max_body_percent = 0.05, float wick_size = 2.0) =>
top_wick_percent(o, h, l, c) <= bottom_wick_percent(o, h, l, c) * wick_size
and bottom_wick_percent(o, h, l, c) <= top_wick_percent(o, h, l, c) * wick_size
and body_percent(o, h, l, c) <= max_body_percent
// @function
// @param offset Safe dynamic offset you need to use in your stoploss, stop buy/sell, etc.
// @param o Open price
// @param c Close price
// @returns
export is_whalish(float offset, float o = open, float c = close) => offset < math.abs(o - c)
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @param allowed_gap How much gap is allowed
// @param allowed_rejection_wick Max ratio of top wick size on body size
// @param engulf_wick Should it engulf wick of previous candle?
// @returns
export is_bullish_engulfing(float o = open, float h = high, float l = low, float c = close, float allowed_gap = 0, float allowed_rejection_wick = 0, bool engulf_wick = false) =>
c[1] <= o[1]
and c >= o[1]
and o <= c[1] + allowed_gap
and (not engulf_wick or c >= h[1])
and (allowed_rejection_wick == 0 or top_wick_percent(o, h, l, c) / body_percent(o, h, l, c) <= allowed_rejection_wick)
// @function
// @param o Open price
// @param h High price
// @param l Low price
// @param c Close price
// @param allowed_gap How much gap is allowed
// @param allowed_rejection_wick Max ratio of bottom wick size on body size
// @param engulf_wick Should it engulf wick of previous candle?
// @returns
export is_bearish_engulfing(float o = open, float h = high, float l = low, float c = close, float allowed_gap = 0, float allowed_rejection_wick = 0, bool engulf_wick = false) =>
c[1] >= o[1]
and c <= o[1]
and o >= c[1] - allowed_gap
and (not engulf_wick or c <= l[1])
and (allowed_rejection_wick == 0 or bottom_wick_percent(o, h, l, c) / body_percent(o, h, l, c) <= allowed_rejection_wick)
// @function
// @param length Number of bars (length).
// @param o Open price
// @param c Close price
// @param start Series number of bars that should be skipped before process.
// @returns
export bullish_bars(int length, float o = open, float c = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if o[i] < c[i]
counter := counter + 1
counter
// @function
// @param length Number of bars (length).
// @param o Open price
// @param c Close price
// @param start Series number of bars that should be skipped before process.
// @returns
export bearish_bars(int length, float o = open, float c = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if o[i] > c[i]
counter := counter + 1
counter
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// MOVING AVERAGE HELPERS ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function
// @param light_source MA with shorter length
// @param heavy_source MA with longer length
// @param reverse If true then downtrend chart means the price is bullish
// @returns 1 if light_source crossed over heavy_source, -1 if crossed under heavy_source, otherwise 0
export trend(float light_source, float heavy_source, bool reverse = false) => (reverse ? 1 : -1) * (light_source > heavy_source ? 1 : light_source < heavy_source ? -1 : 0)
// @function
// @param length Number of bars (length).
// @param l Low price
// @param h High price
// @returns
export donchian(int length = 14, float l = low, float h = high) => math.avg(lowest(length, l), highest(length, h))
// @function
// @param l Low price
// @param h High price
// @param length Number of bars (length).
// @returns
export tenkansen(float l = low, float h = high, int length = 9) => donchian(length, l, h)
// @function
// @param l Low price
// @param h High price
// @param length Number of bars (length).
// @returns
export kijunsen(float l = low, float h = high, int length = 26) => donchian(length, l, h)
// @function
// @param tenkansen Conversion Line, is the mid-point of the highest and lowest prices of an asset over the last nine periods.
// @param kijunsen Base line, is an indicator and important component of the Ichimoku Kinko Hyo method of technical analysis
// @returns
export senkou_a(float tenkansen, float kijunsen) => math.avg(tenkansen, kijunsen)
// @function
// @param l Low price
// @param h High price
// @param length Number of bars (length).
// @returns
export senkou_b(float l = low, float h = high, int length = 52) => donchian(length, l, h)
// @function
// @param heavy_source MA with longer length
// @param light_source MA with shorter length
// @param full_enter False means that previous source can be equal or lower than current one, otherwise should be lower
// @param full_cross False means that current source can be equal or greater than previous one, otherwise should be greater
// @returns
export crossover(float heavy_source, float light_source = close, bool full_enter = true, bool full_cross = true) =>
(full_enter ? light_source[1] < heavy_source[1] : light_source[1] <= heavy_source[1])
and (full_cross ? light_source > heavy_source : light_source >= heavy_source)
// @function
// @param heavy_source MA with longer length
// @param light_source MA with shorter length
// @param full_enter False means that previous source can be equal or lower than current one, otherwise should be lower
// @param full_cross False means that current source can be equal or greater than previous one, otherwise should be greater
// @returns
export crossunder(float heavy_source, float light_source = close, bool full_enter = true, bool full_cross = true) =>
(full_enter ? light_source[1] > heavy_source[1] : light_source[1] >= heavy_source[1])
and (full_cross ? light_source < heavy_source : light_source <= heavy_source)
// @function
// @param heavy_source MA with longer length
// @param light_source MA with shorter length
// @param full_enter False means that previous source can be equal or lower than current one, otherwise should be lower
// @param full_cross False means that current source can be equal or greater than previous one, otherwise should be greater
// @returns
export cross(float heavy_source, float light_source = close, bool full_enter = true, bool full_cross = true) =>
crossover(heavy_source, light_source, full_enter, full_cross)
or crossunder(heavy_source, light_source, full_enter, full_cross)
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param source Series of values to process
// @param start Series number of bars that should be skipped before process.
// @returns
export above_line(float line, int length = 14, float source = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if source[i] > line
counter := counter + 1
counter
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param source Series of values to process
// @param start Series number of bars that should be skipped before process.
// @returns
export below_line(float line, int length = 14, float source = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if source[i] < line
counter := counter + 1
counter
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param source Series of values to process
// @param start Series number of bars that should be skipped before process.
// @returns
export crossover_line(float line, int length = 14, float source = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if source[i + 1] < line and source[i] > line
counter := counter + 1
counter
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param source Series of values to process
// @param start Series number of bars that should be skipped before process.
// @returns
export crossunder_line(float line, int length = 14, float source = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if source[i + 1] > line and source[i] < line
counter := counter + 1
counter
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param source Series of values to process
// @param start Series number of bars that should be skipped before process.
// @returns
export cross_line(float line, int length = 14, float source = close, int start = 0) => crossover_line(line, length, source, start) + crossunder_line(line, length, source, start)
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param o Open price
// @param c Close price
// @param start Series number of bars that should be skipped before process.
// @returns
export bars_crossover_line(float line, int length = 14, float o = open, float c = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if o[i] < line and c[i] > line
counter := counter + 1
counter
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param o Open price
// @param c Close price
// @param start Series number of bars that should be skipped before process.
// @returns
export bars_crossunder_line(float line, int length = 14, float o = open, float c = close, int start = 0) =>
counter = 0
for i = start to length + start - 1 by 1
if o[i] > line and c[i] < line
counter := counter + 1
counter
// @function
// @param line Horizontal line that source will be checked with
// @param length Number of bars (length).
// @param o Open price
// @param c Close price
// @param start Series number of bars that should be skipped before process.
// @returns
export bars_cross_line(float line, int length = 14, float o = open, float c = close, int start = 0) => bars_crossover_line(line, length, o, c, start) + bars_crossunder_line(line, length, o, c, start)
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// ANALAYSIS ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function
// @param source_start The value of the source in the beginning of the change
// @param source_end The value of the source in the end of the change
// @returns pecent of change
export size_percent(float source_start, float source_end) => (source_end / source_start) - 1
// @function
// @param amount The size of the asset/coin (not in base currency) for a position.
// @param leverage The proportion of your trade that will be paid for with borrowed funds. If you are using 2x leverage, you will be funding half of the trade. If you are using 25x leverage you will be funding 1/25 of the trade.
// @returns
export margin(float amount, int leverage = 1) => amount / leverage
// @function
// @param exit The price at which you exit your trade. Can be referred to as your take profit or "TP".
// @param base_qty The size, or quantity, of the asset/coin (not currency) for this position.
// @param short A selling position that enables a trader to profit if the price of an asset decreases.
// @param entry The price at which you enter the trade.
// @returns
export pnl(float exit, float base_qty, bool short, float entry = close) => base_qty * (short ? (entry - exit) : (exit - entry))
// @function
// @param risked_capital What you stand to lose if given stoploss is reached.
// @param pnl Profit and Loss. Shows what you stand to gain or lose with the inputs provided.
// @returns
export risk_reward(float risked_capital, float pnl) => pnl / risked_capital
// @function
// @param pnl Profit and Loss. Shows what you stand to gain or lose with the inputs provided.
// @param margin Margin is the portion of your own funds that you put into a trade. Keep in mind that depending on what margin mode you are using, your losses may not be limited to this margin.
// @returns
export roe(float pnl, float margin) => (pnl / margin) * 100
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// MONEY MANAGEMENT ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
export type mm
float entry
float sl
float max_risk_percent
float risked_capital
float risked_percent
float sl_size
float sl_size_percent
float margin
float margin_percent
float base_qty
float quote_qty
export type tp
float ror
float limit
float base_qty
// @function the value of `number` percentified to with precision 2 by default
// @param number The value to be percentified.
// @param precision Optional argument. Decimal places to which `number` will be rounded. When no argument is supplied, rounding is to the nearest integer.
// @returns The value of `number` percentified according to precision.
export percent(float number, int precision = 2) => math.round(number * 100, precision)
// @function
// @param sl_size Comes dynamically from offset(atr, atr_multiplier). But you can use any offset algorithm you want.
// @param o Open price
// @param c Close price
// @returns
export sl(float sl_size, float o = open, float c = close) => is_green(o, c) ? c - sl_size : c + sl_size
// @function
// @param sl A price level you can set on a position which will, once reached, close the position and prevent any further loss.
// @param entry The price at which you enter the trade.
// @returns SL size in minticks
export sl_size(float sl, float entry) => math.abs(sl - entry)
// @function
// @param risked_capital What you stand to lose if given stoploss is reached.
// @param sl_size Comes dynamically from offset(atr, atr_multiplier). But you can use any offset algorithm you want.
// @returns
export base_qty(float risked_capital, float sl_size) => math.abs(risked_capital / sl_size)
// @function
// @param base_qty The size, or quantity, of the asset/coin (not in quote currency) for a position.
// @param entry The price at which you enter the trade.
// @returns
export quote_qty(float base_qty, float entry = close) => base_qty * entry
// @function
// @param sl_size Comes dynamically from offset(atr, atr_multiplier). But you can use any offset algorithm you want.
// @param capital The total amount of capital in your trading account.
// @param leverage The proportion of your trade that will be paid for with borrowed funds. If you are using 2x leverage, you will be funding half of the trade. If you are using 25x leverage you will be funding 1/25 of the trade.
// @param max_risk_percent Max margin
// @param entry The price at which you enter the trade.
// @returns
export max_risk_percent(float sl_size, float capital, int leverage = 1, float max_risk_percent = 0.99, float entry = close) => math.abs(capital * max_risk_percent * leverage * sl_size) / (entry * capital)
// @function
// @param risk The percentage of your total capital you are willing to risk in this trade.
// @param max_risk_percent The maximum risk that your margin allows you to do.
// @param capital The total amount of capital in your trading account.
// @param dynamic If true, reduces risked capital based on max risk
// @returns
export risked_capital(float risk_percent, float max_risk_percent, float capital, bool dynamic = false) => capital * (risk_percent <= max_risk_percent ? risk_percent : dynamic ? max_risk_percent : 0)
// @function
// @param risked_capital What you stand to lose if given stoploss is reached.
// @param capital The total amount of capital in your trading account.
// @returns
export risked_percent(float risked_capital, float capital) => risked_capital / capital
// @function Calculates everything related to money management
// @param sl A price level you can set on a position which will, once reached, close the position and prevent any further loss.
// @param capital The total amount of capital in your trading account.
// @param risk_percent The percentage of your total capital you are willing to risk in this trade.
// @param entry The price at which you enter the trade.
// @param leverage The proportion of your trade that will be paid for with borrowed funds. If you are using 2x leverage, you will be funding half of the trade. If you are using 25x leverage you will be funding 1/25 of the trade.
// @param max_margin Max margin percentage
// @returns mm object
export money_management(float sl, float capital, float risk_percent, float entry = close, int leverage = 20, float max_margin = 1) =>
float sl_size = entry - sl
float max_risk_percent = max_risk_percent(sl_size, capital, leverage, max_margin, entry)
float risked_capital = risked_capital(risk_percent, max_risk_percent, capital, true)
float risked_percent = risked_percent(risked_capital, capital)
float base_qty = base_qty(risked_capital, sl_size)
float quote_qty = quote_qty(base_qty, entry)
float margin = margin(quote_qty, leverage)
float margin_percent = margin / capital
mm.new(entry = entry,
sl = sl,
max_risk_percent = max_risk_percent,
risked_capital = risked_capital,
risked_percent = risked_percent,
sl_size = sl_size,
sl_size_percent = size_percent(entry, sl),
margin = margin,
margin_percent = margin_percent,
base_qty = base_qty,
quote_qty = quote_qty)
// @function
// @param mm Money Management onject
// @param limit The price that position should be closed at.
// @param percent The percentage of quantity you're going to take as profit, when the target ROR was reached.
// @param enabled True when you dont want set tp
// @returns tp object
export tp_by_limit(mm mm, float limit, float percent = 1, bool enabled = true) =>
float tp_base_qty = enabled and not na(limit) ? percent * mm.base_qty : na
float ror = not na(tp_base_qty) ? (limit - mm.entry) / mm.sl_size : na
tp.new(ror = ror,
limit = limit,
base_qty = tp_base_qty)
// @function
// @param mm Money Management onject
// @param ror The ratio of potential profit of the trade to its potential loss.
// @param percent The percentage of quantity you're going to take as profit, when the target ROR was reached.
// @param enabled True when you dont want set tp
// @returns tp object
export tp_by_ror(mm mm, float ror, float percent = 1, bool enabled = true) =>
float tp_limit = ror > 0 ? mm.entry + mm.sl_size * ror : na
tp_limit := enabled and tp_limit > 0 ? tp_limit : na
tp_by_limit(mm, tp_limit, percent, enabled)
// @function Handles risk management for your strategies
// @param signal Signal object
// @param full_risk_percent What should be risk percent at it's maximum value?
// @param full_risk_min_ratio What should be minimum of signal score ratio to use full_risk_percent
// @param half_risk_min_ratio What should be minimum of signal score ratio to use half_risk_percent
// @param quarter_risk_min_ratio What should be minimum of signal score ratio to use quarter_risk_percent
// @param one_eight_risk_min_ratio What should be minimum of signal score ratio to use one_eight_risk_percent
// @returns risk_percent arg of money_mangament function
export risk(signal signal, float full_risk_percent, float full_risk_min_ratio = 0.9, float half_risk_min_ratio = 0.7, float quarter_risk_min_ratio = 0.5, float one_eight_risk_min_ratio = 0.3) =>
float ratio = math.abs(signal.score / signal.max_score)
if ratio >= full_risk_min_ratio
full_risk_percent
else if ratio >= half_risk_min_ratio
full_risk_percent / 2
else if ratio >= quarter_risk_min_ratio
full_risk_percent / 4
else if ratio >= one_eight_risk_min_ratio
full_risk_percent / 8
else
0
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// FORMATTERS ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function
// @param number Number
// @param fallback Fallback, if the value was na
// @returns
export format_percent(float number, string fallback = '') => na(number) ? fallback : (str.tostring(percent(number)) + '%')
// @function
// @param main_value The first value
// @param second_value The second value
// @param title The title
// @param one_line_value If true wraps second value with parenthesis and concats it with the main value, otherwise moves it to another line
// @param one_line_pair If true divides the pairs with `:`, otherwise moves the values to another line
// @returns
export format_pairs(string main_value, string second_value = '', string title = '', bool one_line_value = true, bool one_line_pair = true) =>
value = one_line_value ? main_value + ' (' + second_value + ')' : main_value + '\n' + second_value
value := str.endswith(value, '\n') ? str.replace(value, ' \n', '') : str.replace(value, ' ()', '')
pair = title == '' ? value : one_line_value and one_line_pair ? title + ': ' + value : title + '\n' + value
// @function
// @param signal Signal
// @param with_name If true prints name of the signal as well
// @param with_sign If true prints negative sign for short signals
// @returns
export format_signal(signal signal, bool with_name = false, bool with_sign = false) => (with_name ? signal.name + ": " : "") + str.tostring(with_sign ? signal.score : math.abs(signal.score)) + "/" + str.tostring(signal.max_score)
// @function
// @param signals Signals
// @returns
export format_signals(array<signal> signals) =>
result = ""
for i = 0 to array.size(signals) - 1 by 1
s = array.get(signals, i)
if na(s)
continue
result := result + (i == 0 ? "" : "\n") + format_signal(s, true, true)
result
// @function
// @param source Series of values to process
// @param fallback Fallback, if the value was na
// @returns
export _format_quote(float source, string fallback = '') => na(source) ? fallback : (str.tostring(math.round_to_mintick(source)) + ' ' + syminfo.currency)
// @function
// @param source Series of values to process
// @param fallback Fallback, if the value was na
// @returns
export _format_base(float source = close, string fallback = '') => na(source) ? fallback : (str.tostring(source) + ' ' + syminfo.basecurrency)
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// FILTERS ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function
// @param start_time Start time
// @param end_time End time
// @param ignore Ignores filtering and retunrs true
// @param c Close priceurrent_time
// @returns
export is_in_period(int start_time, int end_time, bool ignore = false, int current_time = time) => ignore or start_time <= current_time and current_time <= end_time
// @function
// @param source Source string
// @param substring The substring to search fo
// @param case_sensitive Is it case sensitive? default is false
// @returns true if source contains substring
export str_contains(string source, string substring, bool case_sensitive = false) =>
str.replace_all(substring, " ", "") == "" or str.contains(case_sensitive ? source : str.upper(source), case_sensitive ? substring : str.upper(substring))
////////////////////////////////////////////
////////////////////////////////////////////
//// ////
//// EXCHANGE ////
//// ////
////////////////////////////////////////////
////////////////////////////////////////////
// @function returns btc pair of the current chart
// @param symbol Tickerid
// @returns symbol
export get_btc_pair_symbol(simple string basecurrency) =>
switch basecurrency
// "BINANCE:1000LUNCUSDT.P" => "OKX:LUNCBTC"
// "BINANCE:1000SHIBUSDT.P" => "OKX:SHIBBTC"
// "BINANCE:1000XECUSDT.P" => "BITFINEX:XECBTC"
// "BINANCE:BLUEBIRDUSDT.P" => ""
// "BINANCE:BTCDOMUSDT.P" => ""
// "BINANCE:BTCUSDT.P" => ""
// "BINANCE:DEFIUSDT.P" => ""
// "BINANCE:FOOTBALLUSDT.P" => ""
// "BINANCE:SPELLUSDT.P" => ""
// "BINANCE:USDCUSDT.P" => "BINANCE:USDCBTC"
"CKB" => "COINEX:CKBBTC"
"COCOS" => "MEXC:COCOSBTC"
"DENT" => "KUCOIN:DENTBTC"
"HNT" => "COINEX:HNTBTC"
"HOT" => "COINEX:HOTBTC"
"LUNA2" => "BITFINEX:LUNA2BTC"
"MASK" => "UPBIT:MASKBTC"
"REEF" => "KUCOIN:REEFBTC"
"RSR" => "KUCOIN:RSRBTC"
"T" => "UPBIT:TBTC"
"XEM" => "COINEX:XEMBTC"
"1INCH" => "BINANCE:1INCHBTC"
"AAVE" => "BINANCE:AAVEBTC"
"ACH" => "BINANCE:ACHBTC"
"ADA" => "BINANCE:ADABTC"
"AGIX" => "BINANCE:AGIXBTC"
"ALGO" => "BINANCE:ALGOBTC"
"ALICE" => "BINANCE:ALICEBTC"
"ALPHA" => "BINANCE:ALPHABTC"
"ANKR" => "BINANCE:ANKRBTC"
"ANT" => "BINANCE:ANTBTC"
"APE" => "BINANCE:APEBTC"
"API3" => "BINANCE:API3BTC"
"APT" => "BINANCE:APTBTC"
"ARB" => "BINANCE:ARBBTC"
"ARPA" => "BINANCE:ARPABTC"
"AR" => "BINANCE:ARBTC"
"ASTR" => "BINANCE:ASTRBTC"
"ATA" => "BINANCE:ATABTC"
"ATOM" => "BINANCE:ATOMBTC"
"AUDIO" => "BINANCE:AUDIOBTC"
"AVAX" => "BINANCE:AVAXBTC"
"AXS" => "BINANCE:AXSBTC"
"BAKE" => "BINANCE:BAKEBTC"
"BAL" => "BINANCE:BALBTC"
"BAND" => "BINANCE:BANDBTC"
"BAT" => "BINANCE:BATBTC"
"BCH" => "BINANCE:BCHBTC"
"BEL" => "BINANCE:BELBTC"
"BLZ" => "BINANCE:BLZBTC"
"BNB" => "BINANCE:BNBBTC"
"BNX" => "BINANCE:BNXBTC"
"C98" => "BINANCE:C98BTC"
"CELO" => "BINANCE:CELOBTC"
"CELR" => "BINANCE:CELRBTC"
"CFX" => "BINANCE:CFXBTC"
"CHR" => "BINANCE:CHRBTC"
"CHZ" => "BINANCE:CHZBTC"
"COMP" => "BINANCE:COMPBTC"
"COTI" => "BINANCE:COTIBTC"
"CRV" => "BINANCE:CRVBTC"
"CTK" => "BINANCE:CTKBTC"
"CTSI" => "BINANCE:CTSIBTC"
"CVX" => "BINANCE:CVXBTC"
"DAR" => "BINANCE:DARBTC"
"DASH" => "BINANCE:DASHBTC"
"DGB" => "BINANCE:DGBBTC"
"DOGE" => "BINANCE:DOGEBTC"
"DOT" => "BINANCE:DOTBTC"
"DUSK" => "BINANCE:DUSKBTC"
"DYDX" => "BINANCE:DYDXBTC"
"EGLD" => "BINANCE:EGLDBTC"
"ENJ" => "BINANCE:ENJBTC"
"ENS" => "BINANCE:ENSBTC"
"EOS" => "BINANCE:EOSBTC"
"ETC" => "BINANCE:ETCBTC"
"ETH" => "BINANCE:ETHBTC"
"FET" => "BINANCE:FETBTC"
"FIL" => "BINANCE:FILBTC"
"FLM" => "BINANCE:FLMBTC"
"FLOW" => "BINANCE:FLOWBTC"
"FTM" => "BINANCE:FTMBTC"
"FXS" => "BINANCE:FXSBTC"
"GALA" => "BINANCE:GALABTC"
"GAL" => "BINANCE:GALBTC"
"GMT" => "BINANCE:GMTBTC"
"GMX" => "BINANCE:GMXBTC"
"GRT" => "BINANCE:GRTBTC"
"GTC" => "BINANCE:GTCBTC"
"HBAR" => "BINANCE:HBARBTC"
"HIGH" => "BINANCE:HIGHBTC"
"HOOK" => "BINANCE:HOOKBTC"
"ICP" => "BINANCE:ICPBTC"
"ICX" => "BINANCE:ICXBTC"
"ID" => "BINANCE:IDBTC"
"IMX" => "BINANCE:IMXBTC"
"INJ" => "BINANCE:INJBTC"
"IOST" => "BINANCE:IOSTBTC"
"IOTA" => "BINANCE:IOTABTC"
"IOTX" => "BINANCE:IOTXBTC"
"JASMY" => "BINANCE:JASMYBTC"
"KAVA" => "BINANCE:KAVABTC"
"KLAY" => "BINANCE:KLAYBTC"
"KNC" => "BINANCE:KNCBTC"
"KSM" => "BINANCE:KSMBTC"
"LDO" => "BINANCE:LDOBTC"
"LINA" => "BINANCE:LINABTC"
"LINK" => "BINANCE:LINKBTC"
"LIT" => "BINANCE:LITBTC"
"LPT" => "BINANCE:LPTBTC"
"LQTY" => "BINANCE:LQTYBTC"
"LRC" => "BINANCE:LRCBTC"
"LTC" => "BINANCE:LTCBTC"
"MAGIC" => "BINANCE:MAGICBTC"
"MANA" => "BINANCE:MANABTC"
"MATIC" => "BINANCE:MATICBTC"
"MINA" => "BINANCE:MINABTC"
"MKR" => "BINANCE:MKRBTC"
"MTL" => "BINANCE:MTLBTC"
"NEAR" => "BINANCE:NEARBTC"
"NEO" => "BINANCE:NEOBTC"
"NKN" => "BINANCE:NKNBTC"
"OCEAN" => "BINANCE:OCEANBTC"
"OGN" => "BINANCE:OGNBTC"
"OMG" => "BINANCE:OMGBTC"
"ONE" => "BINANCE:ONEBTC"
"ONT" => "BINANCE:ONTBTC"
"OP" => "BINANCE:OPBTC"
"PEOPLE" => "BINANCE:PEOPLEBTC"
"PERP" => "BINANCE:PERPBTC"
"PHB" => "BINANCE:PHBBTC"
"QNT" => "BINANCE:QNTBTC"
"QTUM" => "BINANCE:QTUMBTC"
"REN" => "BINANCE:RENBTC"
"RLC" => "BINANCE:RLCBTC"
"RNDR" => "BINANCE:RNDRBTC"
"ROSE" => "BINANCE:ROSEBTC"
"RUNE" => "BINANCE:RUNEBTC"
"RVN" => "BINANCE:RVNBTC"
"SAND" => "BINANCE:SANDBTC"
"SFP" => "BINANCE:SFPBTC"
"SKL" => "BINANCE:SKLBTC"
"SNX" => "BINANCE:SNXBTC"
"SOL" => "BINANCE:SOLBTC"
"SSV" => "BINANCE:SSVBTC"
"STG" => "BINANCE:STGBTC"
"STMX" => "BINANCE:STMXBTC"
"STORJ" => "BINANCE:STORJBTC"
"STX" => "BINANCE:STXBTC"
"SUSHI" => "BINANCE:SUSHIBTC"
"SXP" => "BINANCE:SXPBTC"
"THETA" => "BINANCE:THETABTC"
"TOMO" => "BINANCE:TOMOBTC"
"TRB" => "BINANCE:TRBBTC"
"TRU" => "BINANCE:TRUBTC"
"TRX" => "BINANCE:TRXBTC"
"UNFI" => "BINANCE:UNFIBTC"
"UNI" => "BINANCE:UNIBTC"
"VET" => "BINANCE:VETBTC"
"WAVES" => "BINANCE:WAVESBTC"
"WOO" => "BINANCE:WOOBTC"
"XLM" => "BINANCE:XLMBTC"
"XMR" => "BINANCE:XMRBTC"
"XRP" => "BINANCE:XRPBTC"
"XTZ" => "BINANCE:XTZBTC"
"YFI" => "BINANCE:YFIBTC"
"ZEC" => "BINANCE:ZECBTC"
"ZEN" => "BINANCE:ZENBTC"
"ZIL" => "BINANCE:ZILBTC"
"ZRX" => "BINANCE:ZRXBTC"
"RDNT" => "BINANCE:RDNTBTC"
"HFT" => "BINANCE:HFTBTC"
"AMB" => "BINANCE:AMBBTC"
"LUNC" => "OKX:LUNCBTC"
"SHIB" => "OKX:SHIBBTC"
"XEC" => "BITFINEX:XECBTC"
"TLM" => "BINANCE:TLMBTC"
"JOE" => "BINANCE:JOEBTC"
=> na
// @function pagination for binance perpetual symbols.
// @param group Group
// @param item Item in each group
// @param group_items Length of group
// @returns symbol
export get_alt_coin_symbol(simple int group, simple int item, simple int group_items = 30) =>
switch (group - 1) * group_items + item
// => ["BINANCE:1000LUNCUSDT.P", get_brc_pair_symbol("LUNC")]
// => ["BINANCE:1000SHIBUSDT.P", get_brc_pair_symbol("SHIB")]
// => ["BINANCE:1000XECUSDT.P", get_brc_pair_symbol("XEC")]
// => ["BINANCE:BLUEBIRDUSDT.P", get_brc_pair_symbol("BLUEBIRD")] // not exist
// => ["BINANCE:BTCDOMUSDT.P", get_brc_pair_symbol("BTCDOM")] // not exist
// => ["BINANCE:BTCUSDT.P", get_brc_pair_symbol("BTC")] // not exist
// => ["BINANCE:DEFIUSDT.P", get_brc_pair_symbol("DEFI")] // not exist
// => ["BINANCE:FOOTBALLUSDT.P", get_brc_pair_symbol("FOOTBALL")] // not exist
// => ["BINANCE:SPELLUSDT.P", get_brc_pair_symbol("SPELL")] // not exist
// => ["BINANCE:LEVERUSDT.P", get_btc_pair_symbol("LEVER")] // not exist
// => ["BINANCE:USDCUSDT.P", na]
1 => ["BINANCE:CKBUSDT.P", get_btc_pair_symbol("CKB")]
2 => ["BINANCE:COCOSUSDT.P", get_btc_pair_symbol("COCOS")]
3 => ["BINANCE:DENTUSDT.P", get_btc_pair_symbol("DENT")]
4 => ["BINANCE:HNTUSDT.P", get_btc_pair_symbol("HNT")]
5 => ["BINANCE:HOTUSDT.P", get_btc_pair_symbol("HOT")]
6 => ["BINANCE:LUNA2USDT.P", get_btc_pair_symbol("LUNA2")]
7 => ["BINANCE:MASKUSDT.P", get_btc_pair_symbol("MASK")]
8 => ["BINANCE:REEFUSDT.P", get_btc_pair_symbol("REEF")]
9 => ["BINANCE:RSRUSDT.P", get_btc_pair_symbol("RSR")]
10 => ["BINANCE:TUSDT.P", get_btc_pair_symbol("T")]
11 => ["BINANCE:XEMUSDT.P", get_btc_pair_symbol("XEM")]
12 => ["BINANCE:1INCHUSDT.P", get_btc_pair_symbol("1INCH")]
13 => ["BINANCE:AAVEUSDT.P", get_btc_pair_symbol("AAVE")]
14 => ["BINANCE:ACHUSDT.P", get_btc_pair_symbol("ACH")]
15 => ["BINANCE:ADAUSDT.P", get_btc_pair_symbol("ADA")]
16 => ["BINANCE:AGIXUSDT.P", get_btc_pair_symbol("AGIX")]
17 => ["BINANCE:ALGOUSDT.P", get_btc_pair_symbol("ALGO")]
18 => ["BINANCE:ALICEUSDT.P", get_btc_pair_symbol("ALICE")]
19 => ["BINANCE:ALPHAUSDT.P", get_btc_pair_symbol("ALPHA")]
20 => ["BINANCE:ANKRUSDT.P", get_btc_pair_symbol("ANKR")]
21 => ["BINANCE:ANTUSDT.P", get_btc_pair_symbol("ANT")]
22 => ["BINANCE:APEUSDT.P", get_btc_pair_symbol("APE")]
23 => ["BINANCE:API3USDT.P", get_btc_pair_symbol("API3")]
24 => ["BINANCE:APTUSDT.P", get_btc_pair_symbol("APT")]
25 => ["BINANCE:ARBUSDT.P", get_btc_pair_symbol("ARB")]
26 => ["BINANCE:ARPAUSDT.P", get_btc_pair_symbol("ARPA")]
27 => ["BINANCE:ARUSDT.P", get_btc_pair_symbol("AR")]
28 => ["BINANCE:ASTRUSDT.P", get_btc_pair_symbol("ASTR")]
29 => ["BINANCE:ATAUSDT.P", get_btc_pair_symbol("ATA")]
30 => ["BINANCE:ATOMUSDT.P", get_btc_pair_symbol("ATOM")]
31 => ["BINANCE:AUDIOUSDT.P", get_btc_pair_symbol("AUDIO")]
32 => ["BINANCE:AVAXUSDT.P", get_btc_pair_symbol("AVAX")]
33 => ["BINANCE:AXSUSDT.P", get_btc_pair_symbol("AXS")]
34 => ["BINANCE:BAKEUSDT.P", get_btc_pair_symbol("BAKE")]
35 => ["BINANCE:BALUSDT.P", get_btc_pair_symbol("BAL")]
36 => ["BINANCE:BANDUSDT.P", get_btc_pair_symbol("BAND")]
37 => ["BINANCE:BATUSDT.P", get_btc_pair_symbol("BAT")]
38 => ["BINANCE:BCHUSDT.P", get_btc_pair_symbol("BCH")]
39 => ["BINANCE:BELUSDT.P", get_btc_pair_symbol("BEL")]
40 => ["BINANCE:BLZUSDT.P", get_btc_pair_symbol("BLZ")]
41 => ["BINANCE:BNBUSDT.P", get_btc_pair_symbol("BNB")]
42 => ["BINANCE:BNXUSDT.P", get_btc_pair_symbol("BNX")]
43 => ["BINANCE:C98USDT.P", get_btc_pair_symbol("C98")]
44 => ["BINANCE:CELOUSDT.P", get_btc_pair_symbol("CELO")]
45 => ["BINANCE:CELRUSDT.P", get_btc_pair_symbol("CELR")]
46 => ["BINANCE:CFXUSDT.P", get_btc_pair_symbol("CFX")]
47 => ["BINANCE:CHRUSDT.P", get_btc_pair_symbol("CHR")]
48 => ["BINANCE:CHZUSDT.P", get_btc_pair_symbol("CHZ")]
49 => ["BINANCE:COMPUSDT.P", get_btc_pair_symbol("COMP")]
50 => ["BINANCE:COTIUSDT.P", get_btc_pair_symbol("COTI")]
51 => ["BINANCE:CRVUSDT.P", get_btc_pair_symbol("CRV")]
52 => ["BINANCE:CTKUSDT.P", get_btc_pair_symbol("CTK")]
53 => ["BINANCE:CTSIUSDT.P", get_btc_pair_symbol("CTSI")]
54 => ["BINANCE:CVXUSDT.P", get_btc_pair_symbol("CVX")]
55 => ["BINANCE:DARUSDT.P", get_btc_pair_symbol("DAR")]
56 => ["BINANCE:DASHUSDT.P", get_btc_pair_symbol("DASH")]
57 => ["BINANCE:DGBUSDT.P", get_btc_pair_symbol("DGB")]
58 => ["BINANCE:DOGEUSDT.P", get_btc_pair_symbol("DOGE")]
59 => ["BINANCE:DOTUSDT.P", get_btc_pair_symbol("DOT")]
60 => ["BINANCE:DUSKUSDT.P", get_btc_pair_symbol("DUSK")]
61 => ["BINANCE:DYDXUSDT.P", get_btc_pair_symbol("DYDX")]
62 => ["BINANCE:EGLDUSDT.P", get_btc_pair_symbol("EGLD")]
63 => ["BINANCE:ENJUSDT.P", get_btc_pair_symbol("ENJ")]
64 => ["BINANCE:ENSUSDT.P", get_btc_pair_symbol("ENS")]
65 => ["BINANCE:EOSUSDT.P", get_btc_pair_symbol("EOS")]
66 => ["BINANCE:ETCUSDT.P", get_btc_pair_symbol("ETC")]
67 => ["BINANCE:ETHUSDT.P", get_btc_pair_symbol("ETH")]
68 => ["BINANCE:FETUSDT.P", get_btc_pair_symbol("FET")]
69 => ["BINANCE:FILUSDT.P", get_btc_pair_symbol("FIL")]
70 => ["BINANCE:FLMUSDT.P", get_btc_pair_symbol("FLM")]
71 => ["BINANCE:FLOWUSDT.P", get_btc_pair_symbol("FLOW")]
72 => ["BINANCE:FTMUSDT.P", get_btc_pair_symbol("FTM")]
73 => ["BINANCE:FXSUSDT.P", get_btc_pair_symbol("FXS")]
74 => ["BINANCE:GALAUSDT.P", get_btc_pair_symbol("GALA")]
75 => ["BINANCE:GALUSDT.P", get_btc_pair_symbol("GAL")]
76 => ["BINANCE:GMTUSDT.P", get_btc_pair_symbol("GMT")]
77 => ["BINANCE:GMXUSDT.P", get_btc_pair_symbol("GMX")]
78 => ["BINANCE:GRTUSDT.P", get_btc_pair_symbol("GRT")]
79 => ["BINANCE:GTCUSDT.P", get_btc_pair_symbol("GTC")]
80 => ["BINANCE:HBARUSDT.P", get_btc_pair_symbol("HBAR")]
81 => ["BINANCE:HIGHUSDT.P", get_btc_pair_symbol("HIGH")]
82 => ["BINANCE:HOOKUSDT.P", get_btc_pair_symbol("HOOK")]
83 => ["BINANCE:ICPUSDT.P", get_btc_pair_symbol("ICP")]
84 => ["BINANCE:ICXUSDT.P", get_btc_pair_symbol("ICX")]
85 => ["BINANCE:IDUSDT.P", get_btc_pair_symbol("ID")]
86 => ["BINANCE:IMXUSDT.P", get_btc_pair_symbol("IMX")]
87 => ["BINANCE:INJUSDT.P", get_btc_pair_symbol("INJ")]
88 => ["BINANCE:IOSTUSDT.P", get_btc_pair_symbol("IOST")]
89 => ["BINANCE:IOTAUSDT.P", get_btc_pair_symbol("IOTA")]
90 => ["BINANCE:IOTXUSDT.P", get_btc_pair_symbol("IOTX")]
91 => ["BINANCE:JASMYUSDT.P", get_btc_pair_symbol("JASMY")]
92 => ["BINANCE:KAVAUSDT.P", get_btc_pair_symbol("KAVA")]
93 => ["BINANCE:KLAYUSDT.P", get_btc_pair_symbol("KLAY")]
94 => ["BINANCE:KNCUSDT.P", get_btc_pair_symbol("KNC")]
95 => ["BINANCE:KSMUSDT.P", get_btc_pair_symbol("KSM")]
96 => ["BINANCE:LDOUSDT.P", get_btc_pair_symbol("LDO")]
97 => ["BINANCE:LINAUSDT.P", get_btc_pair_symbol("LINA")]
98 => ["BINANCE:LINKUSDT.P", get_btc_pair_symbol("LINK")]
99 => ["BINANCE:LITUSDT.P", get_btc_pair_symbol("LIT")]
100 => ["BINANCE:LPTUSDT.P", get_btc_pair_symbol("LPT")]
101 => ["BINANCE:LQTYUSDT.P", get_btc_pair_symbol("LQTY")]
102 => ["BINANCE:LRCUSDT.P", get_btc_pair_symbol("LRC")]
103 => ["BINANCE:LTCUSDT.P", get_btc_pair_symbol("LTC")]
104 => ["BINANCE:MAGICUSDT.P", get_btc_pair_symbol("MAGIC")]
105 => ["BINANCE:MANAUSDT.P", get_btc_pair_symbol("MANA")]
106 => ["BINANCE:MATICUSDT.P", get_btc_pair_symbol("MATIC")]
107 => ["BINANCE:MINAUSDT.P", get_btc_pair_symbol("MINA")]
108 => ["BINANCE:MKRUSDT.P", get_btc_pair_symbol("MKR")]
109 => ["BINANCE:MTLUSDT.P", get_btc_pair_symbol("MTL")]
110 => ["BINANCE:NEARUSDT.P", get_btc_pair_symbol("NEAR")]
111 => ["BINANCE:NEOUSDT.P", get_btc_pair_symbol("NEO")]
112 => ["BINANCE:NKNUSDT.P", get_btc_pair_symbol("NKN")]
113 => ["BINANCE:OCEANUSDT.P", get_btc_pair_symbol("OCEAN")]
114 => ["BINANCE:OGNUSDT.P", get_btc_pair_symbol("OGN")]
115 => ["BINANCE:OMGUSDT.P", get_btc_pair_symbol("OMG")]
116 => ["BINANCE:ONEUSDT.P", get_btc_pair_symbol("ONE")]
117 => ["BINANCE:ONTUSDT.P", get_btc_pair_symbol("ONT")]
118 => ["BINANCE:OPUSDT.P", get_btc_pair_symbol("OP")]
119 => ["BINANCE:PEOPLEUSDT.P", get_btc_pair_symbol("PEOPLE")]
120 => ["BINANCE:PERPUSDT.P", get_btc_pair_symbol("PERP")]
121 => ["BINANCE:PHBUSDT.P", get_btc_pair_symbol("PHB")]
122 => ["BINANCE:QNTUSDT.P", get_btc_pair_symbol("QNT")]
123 => ["BINANCE:QTUMUSDT.P", get_btc_pair_symbol("QTUM")]
124 => ["BINANCE:RENUSDT.P", get_btc_pair_symbol("REN")]
125 => ["BINANCE:RLCUSDT.P", get_btc_pair_symbol("RLC")]
126 => ["BINANCE:RNDRUSDT.P", get_btc_pair_symbol("RNDR")]
127 => ["BINANCE:ROSEUSDT.P", get_btc_pair_symbol("ROSE")]
128 => ["BINANCE:RUNEUSDT.P", get_btc_pair_symbol("RUNE")]
129 => ["BINANCE:RVNUSDT.P", get_btc_pair_symbol("RVN")]
130 => ["BINANCE:SANDUSDT.P", get_btc_pair_symbol("SAND")]
131 => ["BINANCE:SFPUSDT.P", get_btc_pair_symbol("SFP")]
132 => ["BINANCE:SKLUSDT.P", get_btc_pair_symbol("SKL")]
133 => ["BINANCE:SNXUSDT.P", get_btc_pair_symbol("SNX")]
134 => ["BINANCE:SOLUSDT.P", get_btc_pair_symbol("SOL")]
135 => ["BINANCE:SSVUSDT.P", get_btc_pair_symbol("SSV")]
136 => ["BINANCE:STGUSDT.P", get_btc_pair_symbol("STG")]
137 => ["BINANCE:STMXUSDT.P", get_btc_pair_symbol("STMX")]
138 => ["BINANCE:STORJUSDT.P", get_btc_pair_symbol("STORJ")]
139 => ["BINANCE:STXUSDT.P", get_btc_pair_symbol("STX")]
140 => ["BINANCE:SUSHIUSDT.P", get_btc_pair_symbol("SUSHI")]
141 => ["BINANCE:SXPUSDT.P", get_btc_pair_symbol("SXP")]
142 => ["BINANCE:THETAUSDT.P", get_btc_pair_symbol("THETA")]
143 => ["BINANCE:TOMOUSDT.P", get_btc_pair_symbol("TOMO")]
144 => ["BINANCE:TRBUSDT.P", get_btc_pair_symbol("TRB")]
145 => ["BINANCE:TRUUSDT.P", get_btc_pair_symbol("TRU")]
146 => ["BINANCE:TRXUSDT.P", get_btc_pair_symbol("TRX")]
147 => ["BINANCE:UNFIUSDT.P", get_btc_pair_symbol("UNFI")]
148 => ["BINANCE:UNIUSDT.P", get_btc_pair_symbol("UNI")]
149 => ["BINANCE:VETUSDT.P", get_btc_pair_symbol("VET")]
150 => ["BINANCE:WAVESUSDT.P", get_btc_pair_symbol("WAVES")]
151 => ["BINANCE:WOOUSDT.P", get_btc_pair_symbol("WOO")]
152 => ["BINANCE:XLMUSDT.P", get_btc_pair_symbol("XLM")]
153 => ["BINANCE:XMRUSDT.P", get_btc_pair_symbol("XMR")]
154 => ["BINANCE:XRPUSDT.P", get_btc_pair_symbol("XRP")]
155 => ["BINANCE:XTZUSDT.P", get_btc_pair_symbol("XTZ")]
156 => ["BINANCE:YFIUSDT.P", get_btc_pair_symbol("YFI")]
157 => ["BINANCE:ZECUSDT.P", get_btc_pair_symbol("ZEC")]
158 => ["BINANCE:ZENUSDT.P", get_btc_pair_symbol("ZEN")]
159 => ["BINANCE:ZILUSDT.P", get_btc_pair_symbol("ZIL")]
160 => ["BINANCE:ZRXUSDT.P", get_btc_pair_symbol("ZRX")]
161 => ["BINANCE:RDNTUSDT.P", get_btc_pair_symbol("RDNT")]
162 => ["BINANCE:HFTUSDT.P", get_btc_pair_symbol("HFT")]
163 => ["BINANCE:AMBUSDT.P", get_btc_pair_symbol("AMB")]
164 => ["BINANCE:TLMUSDT.P", get_btc_pair_symbol("TLM")]
165 => ["BINANCE:JOEUSDT.P", get_btc_pair_symbol("JOE")]
=> [na, na]
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// WEHBOOK INTEGRATION ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function
// @param fields Other properties
// @param api_key ApiKey
// @param chart_id Chart ID. You can find it in URL: www.tradingview.com/chart/{{chartId}}
// @param trade_type Type of the current symbol. Possible values are stock, futures, index, forex, crypto, fund, dr.
// @param symbol Symbol name without exchange prefix, e.g. 'MSFT'.
// @param exchange Prefix of current symbol name (i.e. for 'CME_EOD:TICKER' prefix is 'CME_EOD').
// @param base Base currency for the symbol. For the symbol 'BTCUSD' returns 'BTC'.
// @param currency Currency for the current symbol. Returns currency code: 'USD', 'EUR', etc.
// @param timeframe A string representation of the chart's timeframe. The returned string's format is "[<quantity>][<units>]", where <quantity> and <units> are in some cases absent. <quantity> is the number of units, but it is absent if that number is 1. <unit> is "S" for seconds, "D" for days, "W" for weeks, "M" for months, but it is absent for minutes. No <unit> exists for hours. The variable will return: "10S" for 10 seconds, "60" for 60 minutes, "D" for one day, "2W" for two weeks, "3M" for one quarter. Can be used as an argument with any function containing a `timeframe` parameter.
// @returns
export json(string fields, string api_key, string chart_id = '', string trade_type = syminfo.type, string tickerid = syminfo.tickerid, string exchange = syminfo.prefix, string base = syminfo.basecurrency, string currency = syminfo.currency, string timeframe = timeframe.period) => '{' +
'"exchange":"' + exchange + '",' +
'"base":"' + base + '",' +
'"quote":"' + currency + '",' +
'"tickerid":"' + tickerid + '",' +
'"timeframe":"' + timeframe + '",' +
'"type":"' + trade_type + '",' +
'"apiKey":"' + api_key + '",' +
(chart_id != "" ? '"chartUrl":"https://www.tradingview.com/chart/' + chart_id + '/?symbol=' + tickerid + '",' : '') +
fields +
'}'
///////////////////////////////////////////
///////////////////////////////////////////
//// ////
//// PLOT HELPERS ////
//// ////
///////////////////////////////////////////
///////////////////////////////////////////
// @function
// @param tbl The ID of a table object that can be passed to other table.*() functions.
// @param row The index of the cell's row. Numbering starts at 0.
// @param col The index of the cell's column. Numbering starts at 0.
// @param txt The text to be displayed inside the cell. Optional. The default is empty string.
// @param bgcolor The background color of the text. Optional. The default is color.white
// @param txtcolor The color of the text. Optional. The default is color.gray
// @param tooltip The tooltip to be displayed inside the cell. Optional.
// @param haligh The horizontal alignment of the cell's text. Optional. The default value is text.align_center. Possible values: text.align_left, text.align_center, text.align_right
// @param valign The vertical alignment of the cell's text. Optional. The default value is text.align_center. Possible values: text.align_top, text.align_center, text.align_bottom
// @param size Size of texts
// @returns
export _table_cel(table tbl, int row, int col, string txt, color bgcolor = na, color txtcolor = na, string tooltip = na, string halign = text.align_center, string valign = text.align_center, string size = size.small) =>
table.cell(tbl, col, row, txt,
text_color=na(txtcolor) ? color.white : txtcolor,
bgcolor=na(bgcolor) ? color.gray : bgcolor,
text_halign=halign,
text_valign=valign,
text_size=size,
tooltip=tooltip)
// @function
// @param signal 1 is bullish, greater than 1 is strongly bullish, -1 is bearish, lower than -1 is strongly bearish, 0 is neutral
// @param ncolor Neutral color.
// @returns
export _signal_color(int signal = 0, color ncolor = na) =>
signal == 1 ? color.new(color.green, 50) :
signal > 1 ? color.green :
signal == -1 ? color.new(color.red, 50) :
signal < -1 ? color.red :
ncolor
// @function Creates new label object for easier debug
// @param debug_bar_index Debug bar index
// @param tooltip Hover to see tooltip label.
// @returns new label object
export _debug(int debug_bar_index, string title, string tooltip = na) =>
if debug_bar_index == bar_index
label.new(
debug_bar_index,
high + high/5,
text=title,
color=color.gray,
textcolor=color.white,
yloc=yloc.abovebar,
style=label.style_label_down,
textalign=text.align_left,
tooltip=tooltip)
|
Candle Color Ratio | https://www.tradingview.com/script/UPJWyFDS-Candle-Color-Ratio/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 36 | 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/
// © LeafAlgo
//@version=5
indicator("Candle Color Ratio", overlay=false)
//Scoring Syntax
float greenScore1 = 0
float greenScore2 = 0
float greenScore3 = 0
float greenScore4 = 0
float greenScore5 = 0
float greenScore6 = 0
float greenScore7 = 0
float greenScore8 = 0
float greenScore9 = 0
float greenScore10 = 0
float redScore1 = 0
float redScore2 = 0
float redScore3 = 0
float redScore4 = 0
float redScore5 = 0
float redScore6 = 0
float redScore7 = 0
float redScore8 = 0
float redScore9 = 0
float redScore10 = 0
if close[1] > open[1]
greenScore1 := 1
redScore1 := 0
if close[1] < open[1]
greenScore1 := 0
redScore1 := 1
if close[2] > open[2]
greenScore2 := 1
redScore2 := 0
if close[2] < open[2]
greenScore2 := 0
redScore2 := 0
if close[3] > open[3]
greenScore3 := 1
redScore3 := 0
if close[3] < open[3]
greenScore3 := 0
redScore3 := 1
if close[4] > open[4]
greenScore4 := 1
redScore4 := 0
if close[4] < open[4]
greenScore4 := 0
redScore4 := 1
if close[5] > open[5]
greenScore5 := 1
redScore5 := 0
if close[5] < open[5]
greenScore5 := 0
redScore5 := 1
if close[6] > open[6]
greenScore6 := 1
redScore6 := 0
if close[6] < open[6]
greenScore6 := 0
redScore6 := 1
if close[7] > open[7]
greenScore7 := 1
redScore7 := 0
if close[7] < open[7]
greenScore7 := 0
redScore7 := 1
if close[8] > open[8]
greenScore8 := 1
redScore8 := 0
if close[8] < open[8]
greenScore8 := 0
redScore8 := 1
if close[9] > open[9]
greenScore9 := 1
redScore9 := 0
if close[9] < open[9]
greenScore9 := 0
redScore9 := 1
if close[10] > open[10]
greenScore10 := 1
redScore10 := 0
if close[10] < open[10]
greenScore10 := 0
redScore10 := 1
greenScore = greenScore1 + greenScore2 + greenScore3 + greenScore4 + greenScore5 + greenScore6 + greenScore7 + greenScore8 + greenScore9 + greenScore10
redScore = redScore1 + redScore2 + redScore3 + redScore4 + redScore5 + redScore6 + redScore7 + redScore8 + redScore9 + redScore10
GRratioScore = greenScore / redScore
RGratioScore = redScore / greenScore
//Plotting
threshold = input.int(2, title='Ratio Threshold')
plot(greenScore, color = color.new(color.green, 50), style=plot.style_histogram, title='Number of Green')
plot(redScore, color=color.new(color.red, 50), style=plot.style_histogram, title='Number of Red')
plot(GRratioScore, color=color.lime, linewidth=3, title='Green to Red Ratio')
plot(RGratioScore, color=color.fuchsia, linewidth=3, title='Red to Green Ratio')
plot(threshold, linewidth=3, color=color.white, title='Ratio Threshold')
|
Debugging_console | https://www.tradingview.com/script/kuxI1i8G-Debugging-console/ | plutustraining | https://www.tradingview.com/u/plutustraining/ | 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/
// © plutustraining
//@version=5
library(title = "Debugging_console", overlay = false)
var string[] console = array.new_string(25, na)
export print(string[] console , string input) =>
array.push(console, str.tostring(year(time))+'-' +str.tostring(month(time))+'-' +str.tostring(dayofmonth(time))+' '+input)
array.shift(console)
var table console_table = table.new(position.bottom_left, 1, 1,frame_color = color.white,frame_width =1)
string console_content = na
for i = 0 to array.size(console)-1
array_content = na(array.get(console, i))? '' :array.get(console, i)
console_content += array_content + '\n'
table.cell(console_table, 0, 0, console_content, bgcolor = color.black,text_halign=text.align_left,text_color=color.white)
console
//library testing
if barstate.islast
console :=print(console, "Debug testing")
|
BasicVisibleChart | https://www.tradingview.com/script/jCW9QKj0-BasicVisibleChart/ | twingall | https://www.tradingview.com/u/twingall/ | 18 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//Thanks to code from @PineCoders Visible Chart library (PineCoders/VisibleChart/4), which is a much more comprehensive library than this, but does not include the some functions which i find useful:
//Added the following exportable functions: highest/lowest body, highest/lowest close, highest/lowest open. These allow one to anchor fibs from bodies rather than wicks
//Added a Fib Box function in the example code
//@twingall
library("BasicVisibleChart", true)
//Functions to export:
export barIsVisible() =>
bool result = time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
// highest close, highest open, highest body (for cases of price gapping at the high, the highest of the two)
export highestClose() =>
var float result = na
if barIsVisible() and close >= nz(result, close)
result := close
result
export highestOpen() =>
var float result = na
if barIsVisible() and open >= nz(result, open)
result := open
result
export highestBody() =>
math.max(highestOpen(), highestClose())
// lowest close, lowest open, lowest body (for cases of price gapping at the low, the lowest of the two)
export lowestClose() =>
var float result = na
if barIsVisible() and close <= nz(result, close)
result := close
result
export lowestOpen() =>
var float result = na
if barIsVisible() and open <= nz(result, open)
result := open
result
export lowestBody() =>
math.min(lowestOpen(), lowestClose())
//thanks to @PineCoders' VisibleChart library for the remainder of the export functions
export high() =>
var float result = na
if barIsVisible() and high >= nz(result, high)
result := high
result
export highBarTime() =>
var float chartHigh = na
var int highTime = na
if barIsVisible() and high >= nz(chartHigh, high)
highTime := time
chartHigh := high
int result = highTime
export low() =>
var float result = na
if barIsVisible() and low <= nz(result, low)
result := low
result
export lowBarTime() =>
var float chartLow = na
var int lowTime = na
if barIsVisible() and low <= nz(chartLow, low)
lowTime := time
chartLow := low
int result = lowTime
export open() =>
var float result = na
if time == chart.left_visible_bar_time
result := open
result
export close() =>
var float result = na
if barIsVisible()
result := close
result
//////// Example Code ////////////////
// declare variables
//note: when pasting this into your own seperate indicator; you need to include the library name when declaring variables, i.e: // float highestBody = BasicVisibleChart.highestBody()
float highestBody = highestBody()
float lowestBody = lowestBody()
int highTime = highBarTime()
int lowTime = lowBarTime()
int leftTime = math.min(highTime, lowTime)
int rightTime = math.max(highTime, lowTime)
bool isBull = lowTime < highTime
//Function for Fib lines
fibLine(series color fibColor, series float fibLevel) =>
float fibRatio = 1-(fibLevel / 100)
float fibPrice = isBull ? lowestBody + ((highestBody - lowestBody) * fibRatio) :
highestBody - ((highestBody - lowestBody) * fibRatio)
var line fibLine = line.new(na, na, na, na, xloc.bar_time, extend.right, fibColor, line.style_dotted, 2)
line.set_xy1(fibLine, leftTime, fibPrice)
line.set_xy2(fibLine, rightTime, fibPrice)
// Function for Fib box: the zone of retracement
fibBox(series color fibColor, series float fibLevel_1, series float fibLevel_2) =>
float fibRatio_1 = 1-(fibLevel_1 / 100)
float fibPrice_1 = isBull ? lowestBody + ((highestBody - lowestBody) * fibRatio_1) :highestBody - ((highestBody - lowestBody) * fibRatio_1)
float fibRatio_2 = 1-(fibLevel_2 / 100)
float fibPrice_2 = isBull ? lowestBody + ((highestBody - lowestBody) * fibRatio_2) : highestBody - ((highestBody - lowestBody) * fibRatio_2)
var b = box.new(na, na, na, na, xloc=xloc.bar_time, border_style=line.style_dashed, extend = extend.right, border_color=color.new(color.white,100), text_color=color.new(color.gray,70), text_halign=text.align_right)
box.set_lefttop(b, leftTime, fibPrice_1)
box.set_rightbottom(b, rightTime,fibPrice_2)
box.set_bgcolor(b, fibColor)
// Display code that only runs on the last bar but displays visuals on visible bars, wherever they might be in the dataset.
if barstate.islast
//declare/define Fib lines and decalare/define Fib Box
fibLine(color.new(color.blue, 30), 0)
fibLine(color.new(color.blue, 30), 100)
//fibLine(color.new(color.blue, 30), 50) //midline
fibBox(color.new(color.orange,80), 61.8, 78.6) //draws fib box showing 61.8% - 78.6% retracement |
HSupertrend | https://www.tradingview.com/script/LvAtHaha-HSupertrend/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 133 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
import HeWhoMustNotBeNamed/rzigzag/10 as zg
import HeWhoMustNotBeNamed/eHarmonicpatternsLogScale/2 as hp
// @description Supertrend implementation based on harmonic patterns
library("HSupertrend", overlay = true)
// @type ZigzagProperties contains values required for zigzag calculation
// @field length Zigzag length
// @field source Array containing custom OHLC. If not set, array.from(high, low) is used
export type ZigzagProperties
int length
array<float> source
// @type PatternProperties are essential pattern parameters used for calculation of bullish and bearish zones
// @field base Base for calculating entry and stop of pattern. Can be CD, minmax or correction. Default is CD
// @field entryPercent Distance from D in terms of percent of Base in the direction of pattern
// @field stopPercent Distance from D in terms of percent of Base in the opposite direction of pattern
// @field useClosePrices When set uses close price for calculation of supertrend breakout
export type PatternProperties
string base='CD'
int entryPercent = 30
int stopPercent = 5
bool useClosePrices = true
bool useLogScale = false
// @function derives supertrend based on harmonic patterns
// @param zProperties ZigzagProperties containing Zigzag length and source array
// @param pProperties PatternProperties used for calculation
// @param errorPercent Error threshold for scanning patterns
// @param showPatterns Draw identified patterns structure on chart
// @param patternColor Color of the pattern lines to be drawn
// @returns [direction, supertrend]
export hsupertrend(ZigzagProperties zProperties, PatternProperties pProperties, simple int errorPercent = 8,
simple bool showPatterns = true, simple color patternColor = color.blue) =>
startIndex = 1
depth = 6
var float shortStop = na
var float longStop = na
var int dir = na
zigzagSource = na(zProperties.source)? array.from(high, low) : zProperties.source
var useLogScale = pProperties.useLogScale
[zigzagmatrix, zgFlags] = zg.zigzag(zProperties.length, zigzagSource, depth)
newPivot = array.get(zgFlags, 1)
if(matrix.rows(zigzagmatrix) >= startIndex+5 and newPivot and not newPivot[1])
x = matrix.get(zigzagmatrix, startIndex+4, 0)
a = matrix.get(zigzagmatrix, startIndex+3, 0)
b = matrix.get(zigzagmatrix, startIndex+2, 0)
c = matrix.get(zigzagmatrix, startIndex+1, 0)
d = matrix.get(zigzagmatrix, startIndex, 0)
patterns = hp.isHarmonicPattern(x, a, b, c, d, array.new<bool>(), true, errorPercent, useLogScale)
if(array.includes(patterns, true))
xBar = matrix.get(zigzagmatrix, startIndex+4, 1)
aBar = matrix.get(zigzagmatrix, startIndex+3, 1)
bBar = matrix.get(zigzagmatrix, startIndex+2, 1)
cBar = matrix.get(zigzagmatrix, startIndex+1, 1)
dBar = matrix.get(zigzagmatrix, startIndex, 1)
if showPatterns
line.new(int(xBar), x, int(aBar), a, color=patternColor, style = line.style_dotted, width = 0)
line.new(int(aBar), a, int(bBar), b, color=patternColor, style = line.style_dotted, width = 0)
line.new(int(bBar), b, int(cBar), c, color=patternColor, style = line.style_dotted, width = 0)
line.new(int(cBar), c, int(dBar), d, color=patternColor, style = line.style_dotted, width = 0)
line.new(int(bBar), b, int(dBar), d, color=patternColor, style = line.style_dotted, width = 0)
line.new(int(xBar), x, int(bBar), b, color=patternColor, style = line.style_dotted, width = 0)
lastDir = matrix.get(zigzagmatrix, startIndex, 3)
baseValue = pProperties.base == 'minmax' ? math.max(x,a,b,c,d) - math.min(x,a,b,c,d) : pProperties.base == 'correction'? math.abs((dir > 0? math.max(a, c) : math.min(a, c)) - d) : math.abs(c-d)
entryRange = d - math.sign(lastDir)*baseValue*(pProperties.entryPercent/100)
stopRange = d + math.sign(lastDir)*baseValue*(pProperties.stopPercent/100)
newBullishRange = math.max(entryRange, stopRange)
newBearishRange = math.min(entryRange, stopRange)
shortStop := dir < 0? math.min(shortStop, newBullishRange) : newBullishRange
longStop := dir > 0? math.max(longStop, newBearishRange) : newBearishRange
highPrice = pProperties.useClosePrices? close : high
lowPrice = pProperties.useClosePrices ? close : low
dir := highPrice >= shortStop? 1 : lowPrice <=longStop? -1 : dir
supertrend = dir > 0? longStop : shortStop
[dir, supertrend]
// @function derives supertrend based on harmonic patterns
// @param zProperties ZigzagProperties containing Zigzag length and source array
// @param pProperties PatternProperties used for calculation
// @param errorPercent Error threshold for scanning patterns
// @param showPatterns Draw identified patterns structure on chart
// @param patternColor Color of the pattern lines to be drawn
// @returns [direction, supertrend]
export hsupertrendplain(int length, array<float> source = na, string base='CD', int entryPercent = 30, int stopPercent = 5, bool useClosePrices = true, simple int errorPercent = 8) =>
startIndex = 1
depth = 6
var float shortStop = na
var float longStop = na
var int dir = na
zigzagSource = na(source)? array.from(high, low) : source
[zigzagmatrix, zgFlags] = zg.zigzag(length, zigzagSource, depth)
newPivot = array.get(zgFlags, 1)
if(matrix.rows(zigzagmatrix) >= startIndex+5 and newPivot and not newPivot[1])
x = matrix.get(zigzagmatrix, startIndex+4, 0)
a = matrix.get(zigzagmatrix, startIndex+3, 0)
b = matrix.get(zigzagmatrix, startIndex+2, 0)
c = matrix.get(zigzagmatrix, startIndex+1, 0)
d = matrix.get(zigzagmatrix, startIndex, 0)
patterns = hp.isHarmonicPattern(x, a, b, c, d, array.new<bool>(), true, errorPercent)
if(array.includes(patterns, true))
xBar = matrix.get(zigzagmatrix, startIndex+4, 1)
aBar = matrix.get(zigzagmatrix, startIndex+3, 1)
bBar = matrix.get(zigzagmatrix, startIndex+2, 1)
cBar = matrix.get(zigzagmatrix, startIndex+1, 1)
dBar = matrix.get(zigzagmatrix, startIndex, 1)
lastDir = matrix.get(zigzagmatrix, startIndex, 3)
baseValue = base == 'minmax' ? math.max(x,a,b,c,d) - math.min(x,a,b,c,d) : base == 'correction'? math.abs((dir > 0? math.max(a, c) : math.min(a, c)) - d) : math.abs(c-d)
entryRange = d - math.sign(lastDir)*baseValue*(entryPercent/100)
stopRange = d + math.sign(lastDir)*baseValue*(stopPercent/100)
newBullishRange = math.max(entryRange, stopRange)
newBearishRange = math.min(entryRange, stopRange)
shortStop := dir < 0? math.min(shortStop, newBullishRange) : newBullishRange
longStop := dir > 0? math.max(longStop, newBearishRange) : newBearishRange
highPrice = useClosePrices? close : high
lowPrice = useClosePrices ? close : low
dir := highPrice >= shortStop? 1 : lowPrice <=longStop? -1 : dir
supertrend = dir > 0? longStop : shortStop
[dir, supertrend, longStop, shortStop]
// Example
// [dir, supertrend] = hsupertrend(ZigzagProperties.new(8, na), PatternProperties.new())
// plot(supertrend, "hSupertrend", dir>0? color.green:color.red) |
Pattern | https://www.tradingview.com/script/5QPBNT1x-Pattern/ | reees | https://www.tradingview.com/u/reees/ | 131 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
// @description Pattern object definitions and functions. Easily draw and keep track of patterns, legs, and points.
//
// Supported pattern types:
// Type Leg validation # legs
// "xabcd" Direction 3 or 4 (point D not required)
// "zigzag" Direction >= 2
// "free" None >= 2
//
// Summary of exported types and associated methods/functions:
//
// type point A point on the chart (x,y)
// draw_label() Draw a point label
// erase_label() Erase a point label
//
// type leg A pattern leg (i.e. point A to point B)
// leg_init() Initialize/instantiate a leg
// draw() Draw a leg
// erase() Erase a leg
// leg_getLineTerms() Get the slope and y-intercept of a leg
// leg_getPrice() Get price (Y) at a given bar index (X) within a leg
//
// type pattern A pattern (set of at least 2 connected legs)
// pattern_init() Initialize/instantiate a pattern
// draw() Draw a pattern
// erase() Erase a pattern
//
// *See bottom of the script for example usage*
library("Pattern",overlay=true)
import reees/Draw/26 as draw
import reees/Algebra/4 as alg
import reees/Utilities/5 as u
// @type A point on the chart (x,y)
// @field x Bar index (x coordinate)
// @field y Price level (y coordinate)
// @field lbl Point label
export type point
int x
float y
label label
// @function Delete the point label
// @param this Point
// @returns Void
export erase_label(point this) =>
label.delete(this.label)
// @function Draw the point label
// @param this Point
// @returns line
export draw_label(point this, string position="bottom", color clr=color.gray, float transp=50.0, color txt_clr=color.white, string txt=na, string tooltip=na, string size="small") =>
erase_label(this)
lbstyle = draw.label_style(position)
lbsize = draw.size(size)
t = not na(txt) ? txt : str.tostring(this.y,"#.#####")
this.label := label.new(this.x, this.y, text=t, textcolor=txt_clr, size=lbsize, style=lbstyle, tooltip=tooltip, color=color.new(clr,transp))
// @type A pattern leg (point A to point B)
// @field a Point A
// @field b Point B
// @field deltaX ΔX (length)
// @field deltaY ΔY (height)
// @field prev Previous leg
// @field next Next leg
// @field retrace Retracement ratio (of previous leg)
// @field line Line
export type leg
point a
point b
int deltaX
float deltaY
leg prev
leg next
float retrace
line line
// @function Determine if two legs are valid (consecutive) pattern legs
validPatternLegs(leg1, leg2) =>
switch
leg1.b.x != leg2.a.x => false // leg must be connected
leg1.b.y != leg2.a.y => false
=> true
// @function Initialize a pattern leg
// @param a Point A (required)
// @param b Point B (required)
// @param prev Previous leg
// @param next Next leg
// @param line Line
// @returns New instance of leg object
export leg_init(point a, point b, leg prev=na, leg next=na, line line=na) =>
this = leg.new(a,b)
this.deltaX := b.x - a.x
this.deltaY := b.y - a.y
if not na(prev)
if validPatternLegs(prev,this)
this.prev := prev
this.retrace := (this.deltaY/prev.deltaY)*-1
prev.next := this
if not na(next)
if validPatternLegs(this,next)
this.next := next
this.line := line
this
// @function Delete the pattern leg
// @param this Leg
// @returns Void
export erase(leg this) =>
line.delete(this.line)
// @function Draw the pattern leg
// @param this Leg
// @param clr Color
// @param style Style ("solid", "dotted", "dashed", "arrowleft", "arrowright")
// @param transp Transparency
// @param width Width
// @returns line
export draw(leg this, color clr=color.gray, string style="solid", float transp=20.0, int width=1) =>
erase(this)
lstyle = draw.line_style(style)
this.line := line.new(this.a.x, this.a.y, this.b.x, this.b.y, color=color.new(clr,transp), width=width, style=lstyle)
// @function Get the slope and y-intercept of a leg
// @param this Leg
// @returns [slope, y-intercept]
export leg_getLineTerms(leg this) =>
alg.line_fromXy(this.a.x, this.a.y, this.b.x, this.b.y)
// @function Get the price (Y) at a given bar index (X) within the leg
// @param this Leg
// @param index Bar index
// @returns Price (float)
export leg_getPrice(leg this, int index) =>
if index >= this.a.x and index <= this.b.x
[slope, yint] = leg_getLineTerms(this)
alg.line_getPrice(index, slope, yint)
// @type A pattern (set of at least 2 connected legs)
// @field legs Array of pattern legs
// @field type Pattern type (dft = "free")
// @field subType Pattern subtype
// @field name Pattern name
// @field pid Pattern Identifier string
export type pattern
leg[] legs
string type = "free"
string subType
string name
string pid
// @function Determine if pattern legs are valid for the given pattern type
validForType(tp, leg[] legs) =>
valid = true
n = array.size(legs)
// check size
if n < 2
valid := false
else if tp == "xabcd"
if n != 3 and n != 4
valid := false
// check legs
else
if tp == "zigzag" or tp == "xabcd"
for i=1 to n-1
leg = array.get(legs,i)
prev = array.get(legs,i-1)
if prev.deltaY < 0 and leg.deltaY < 0 // leg must pivot in opposite direction
valid := false
break
else if prev.deltaY > 0 and leg.deltaY > 0
valid := false
break
valid
// @function Initialize a pattern object from a given set of legs
// @param legs Array of pattern legs (required)
// @param tp Pattern type ("zigzag", "xabcd", or "free". dft = "free")
// @param name Pattern name
// @param subType Pattern subtype
// @param pid Pattern Identifier string
// @returns New instance of pattern object, if one was successfully created
export pattern_init(leg[] legs, string tp="free", string name=na, string subType=na, string pid=na) =>
pattern this = na
if validForType(tp,legs)
this := pattern.new(legs,tp,subType,name,pid)
this
// @function Initialize a pattern object from a given set of points
// @param legs Array of pattern legs (required)
// @param tp Pattern type ("zigzag", "xabcd", or "free". dft = "free")
// @param name Pattern name
// @param subType Pattern subtype
// @param pid Pattern Identifier string
// @returns New instance of pattern object, if one was successfully created
export pattern_init(point[] points, string tp="free", string name=na, string subType=na, string pid=na) =>
leg[] legs = array.new<leg>()
n = array.size(points)
pattern this = na
if n >= 3
leg prevLeg = na
for i=1 to n-1
point = array.get(points,i)
prev = array.get(points,i-1)
leg = leg_init(prev,point,prevLeg)
if not na(leg)
array.push(legs,leg)
prevLeg := leg
this := pattern_init(legs,tp,name,subType,pid)
this
// @function Delete the pattern lines
// @param this Pattern
// @returns Void
export erase(pattern this) =>
for leg in this.legs
erase(leg)
// @function Draw the pattern
// @param this Pattern
// @param clr Color
// @param style Style ("solid", "dotted", "dashed", "arrowleft", "arrowright")
// @param transp Transparency
// @param width Width
// @returns line[]
export draw(pattern this, color clr=color.gray, string style="solid", float transp=20.0, int width=1) =>
erase(this)
line[] lines = array.new_line()
for leg in this.legs
array.push(lines, draw(leg, clr, style, transp, width))
lines
//********************************
// Example / Test code
//********************************
// Hard-coded coordinates for clarity and simplicity of example
// ADAUSD 4h gartley
var int xX = 10681
var float xY = .344
var x = point.new(xX,xY) // instantiate/initialize a point
var int aX = 10714
var float aY = .296
var a = point.new(aX,aY)
var xa = leg_init(x,a) // instantiate/initialize a leg
var int bX = 10743
var float bY = .322
var b = point.new(bX,bY)
var ab = leg_init(a,b,xa)
var int cX = 10752
var float cY = .3
var c = point.new(cX,cY)
var bc = leg_init(b,c,ab)
var int dX = 10796
var float dY = .329
var d = point.new(dX,dY)
var cd = leg_init(c,d)
var points = array.from(x, a, b, c, d)
var pattern = pattern_init(points,"xabcd") // instantiate/initialize a pattern
var legs = array.from(xa,ab,bc,cd)
if bar_index == 10796
// Draw point labels
draw_label(d, "top") // default text displays the price
draw_label(x, "top", txt="X")
draw_label(a, "bottom", txt="A")
draw_label(c, "bottom", txt="C")
// Draw the pattern
draw(pattern, color.red, width=2)
// Draw a leg
nextPoint = point.new(d.x+50, d.y*.8) // projecting a 20% drop in price from point D
nextLeg = leg_init(d, nextPoint)
draw(nextLeg,color.blue,"arrowright")
// Get details about a leg
abRetracement = ab.retrace
draw_label(b, "top", txt=("B\nRetracement\nAB/XA = " + str.tostring(abRetracement,"#.###"))) // get retracement ratio (from previous leg)
midX = d.x + 25
midPoint = point.new(midX, leg_getPrice(nextLeg,midX)) // get price at a given bar index of the leg
[slope, yint] = leg_getLineTerms(nextLeg)
draw_label(midPoint,"bottom",txt=("Slope = " + str.tostring(slope,"#.####") + "\ny-int = " + str.tostring(yint))) // get slope/y-intercept
|
String Extra Functions | https://www.tradingview.com/script/nsehLSIe-String-Extra-Functions/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// © kaigouthro
//@version=5
// @description Additional String shortcuts
library("string_extras")
// @function last char of a string
// @param _string String to process
// @returns last char of a string
export last (string _string ) =>
_l = str.length(_string), _l > 1 ? str.substring(_string,_l-1,_l) : ''
// @function string without first char
// @param _string String to process
// @returns string without first char
export shift (string _string ) =>
str.length(_string) > 1 ? str.substring(_string,1) : ''
// @function string without last char
// @param _string String to process
// @returns string without last char
export pop (string _string ) =>
_l = str.length(_string),_l>1?str.substring(_string,0,_l-1):_string
// @function get specific char of a string
// @param _string String to process
// @param _position int
// @returns string _string
export get (string _string, int _position ) =>
_position >=0 and _position < str.length(_string) ?
str.substring(_string,_position-1,_position) : _string
// @function push to end of a string
// @param _string String to process
// @param _char string
// @returns string _string
export push (string _string, string _char ) =>
_string + _char
// @function unshift char to prepend string
// @param _string String to process
// @param _char string
// @returns string _string
export unshift (string _string, string _char ) =>
_char + _string
// @function string from first char until input, if it exists, or itself, with option to cut off char
// @param _string String to process
// @param _char string
// @returns string up until/including the dsired character
export head (string _string, string _char, bool _include = false) =>
str.match(_string,'\[\^'+_char+'\]\+') + (_include ? _char : '' )
// @function string from last input char until end, if it exists, or itself with option to cut off char
// @param _string String to process
// @param _char string
// @returns string up until/including the dsired character
export tail (string _string, string _char, bool _include = false) =>
(_include ? _char : '' ) + str.match(_string,_char+'\(\?=\[\^'+_char+'\]\*\$\)\(\.\+\\n\*\)\+')
// @function returns the _occurabnce (1st, 2nd..) index of a character in a string if set , or last
// @param _string String to process
// @param _char string
// @returns int index of character
export index (string _string, string _char , int _occurance = na) =>
int _idx = na
occurance = 0
for i = 0 to str.length(_string)
_s = str.substring(_string, i, i+1)
if _s == _char
occurance += 1
if occurance == _occurance
break
_idx := i
else
_idx := i
|
Heikinashi | https://www.tradingview.com/script/Mn2i2gV4-Heikinashi/ | boitoki | https://www.tradingview.com/u/boitoki/ | 42 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boitoki
//@version=5
// @description This library calculates "Heikinashi".
library("Heikinashi", overlay=true)
export f_heikinashi_close (string _type, float _o, float _h, float _l, float _c) =>
switch _type
'close' => _c
'oc2' => math.avg(_o, _c)
'hl2' => math.avg(_l, _l)
'hlc3' => math.avg(_h, _l, _c)
'ohlc4' => math.avg(_o, _h, _l, _c)
'ohlc4-s2' => math.avg(_o, ta.sma(_h, 2), ta.sma(_l, 2), _c)
'ohlc4-s3' => math.avg(_o, ta.sma(_h, 3), ta.sma(_l, 3), _c)
'ohlc4-s4' => math.avg(_o, ta.sma(_h, 4), ta.sma(_l, 4), _c)
'ohlc4-s5' => math.avg(_o, ta.sma(_h, 5), ta.sma(_l, 5), _c)
'hlcc4' => math.avg(_h, _l, _c, _c)
'ohlcc5' => math.avg(_h, _l, _c, _c, _o)
=> math.avg(_o, _h, _l, _c)
heikinashi (float _o, float _h, float _l, float _c, string _close_type = 'ohlc4') =>
_hclose = f_heikinashi_close(_close_type, _o, _h, _l, _c)
// Day1
_hopen = ohlc4[1]
// Day2
if (not na(_hopen[1]))
_hopen := math.avg(nz(_hopen[1]), nz(_hclose[1]))
else if (not na(_hopen))
_hopen := ohlc4[1]
else
_hopen := open
[_hopen, _h, _l, _hclose]
heikinashi_for (float _o, float _h, float _l, float _c, string _close_type = 'ohlc4', int _times = 2) =>
times = math.max(_times, 2)
[_hopen, _, _, _hclose] = heikinashi(_o, _h, _l, _c, _close_type)
if (not na(open[times-1])) and times > 1
for i = 1 to times-1
_hclose := f_heikinashi_close(_close_type, _hopen, _h, _l, _hclose)
_hopen := math.avg(_hopen[1], _hclose[1])
[_hopen, _h, _l, _hclose]
heikinashi_for_v1 (float _o, float _h, float _l, float _c, string _close_type = 'ohlc4', int _times = 2) =>
times = math.min(math.max(_times, 1), 10)
[_open1 , _, _, _close1 ] = heikinashi(_o, _h, _l, _c, _close_type)
[_open2 , _, _, _close2 ] = heikinashi(_open1, _h, _l, _close1, _close_type)
[_open3 , _, _, _close3 ] = heikinashi(_open2, _h, _l, _close2, _close_type)
[_open4 , _, _, _close4 ] = heikinashi(_open3, _h, _l, _close3, _close_type)
[_open5 , _, _, _close5 ] = heikinashi(_open4, _h, _l, _close4, _close_type)
[_open6 , _, _, _close6 ] = heikinashi(_open5, _h, _l, _close5, _close_type)
[_open7 , _, _, _close7 ] = heikinashi(_open6, _h, _l, _close6, _close_type)
[_open8 , _, _, _close8 ] = heikinashi(_open7, _h, _l, _close7, _close_type)
[_open9 , _, _, _close9 ] = heikinashi(_open8, _h, _l, _close8, _close_type)
[_open10, _, _, _close10] = heikinashi(_open9, _h, _l, _close9, _close_type)
switch times
1 => [_open1, high, low, _close1]
2 => [_open2, high, low, _close2]
3 => [_open3, high, low, _close3]
4 => [_open4, high, low, _close4]
5 => [_open5, high, low, _close5]
6 => [_open6, high, low, _close6]
7 => [_open7, high, low, _close7]
8 => [_open8, high, low, _close8]
9 => [_open9, high, low, _close9]
10 => [_open10, high, low, _close10]
// @function This function calculates "Heikinashi".
// @param _o open
// @param _h high
// @param _l low
// @param _c close
// @param _close_type ['ohlc4', 'hlc3', 'oc2', 'hl2', 'close'] Sets the calculation method to be used for the closing price.
// @returns TODO: add what function returns
export calc (float _o, float _h, float _l, float _c, string _close_type = 'ohlc4') =>
heikinashi(_o, _h, _l, _c, _close_type)
// @function This function calculates "Heikinashi".
// @param _o open
// @param _h high
// @param _l low
// @param _c close
// @param _close_type ['ohlc4', 'hlc3', 'oc2', 'hl2', 'close'] Sets the calculation method to be used for the closing price.
// @param _times Sets how many times to average.(min:1, max:10)
// @returns TODO: add what function returns
export calcFor (float _o, float _h, float _l, float _c, string _close_type = 'ohlc4', int _times = 1) =>
heikinashi_for(_o, _h, _l, _c, _close_type, _times)
// @function This function calculates "Heikinashi".
// @param _o open
// @param _h high
// @param _l low
// @param _c close
// @param _close_type ['ohlc4', 'hlc3', 'oc2', 'hl2', 'close'] Sets the calculation method to be used for the closing price.
// @param _times Sets how many times to average.(min:1, max:10)
// @returns TODO: add what function returns
export calcFor_v1 (float _o, float _h, float _l, float _c, string _close_type = 'ohlc4', int _times = 1) =>
heikinashi_for_v1(_o, _h, _l, _c, _close_type, _times)
///////////////
// Test suit //
length = input.int(2, minval=1, maxval=10)
close_type = input.string('ohlc4', options=['close', 'oc2', 'hl2', 'hlc3', 'ohlc4', 'ohlc4-s2', 'ohlc4-s3', 'ohlc4-s4', 'ohlc4-s5', 'hlcc4', 'ohlcc5'])
i_algo = input.string('v1', options=['v1', 'for'])
i_ma_length = input.int(30, 'MA period')
[plot_open, _, _, plot_close] = switch i_algo
'v1' => heikinashi_for_v1(open, high, low, close, close_type, length)
'for' => heikinashi_for (open, high, low, close, close_type, length)
c = plot_open > plot_close ? color.red : color.green
plotcandle(plot_open, high, low, plot_close, 'Heikinashi 2', color=plot_open > plot_close ? c : color.new(color.black, 100), wickcolor=c, bordercolor=c)
plot(ta.ema(close, i_ma_length), display=display.none)
|
Replica of TradingView's Backtesting Engine with Arrays | https://www.tradingview.com/script/y4wMeSpt-Replica-of-TradingView-s-Backtesting-Engine-with-Arrays/ | OztheWoz | https://www.tradingview.com/u/OztheWoz/ | 39 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OztheWoz
//@version=5
library("OzzyBacktestEngine")
// quality of life user function that help when working with array data usage
_indexArray(_array, _index) =>
array.size(_array) > _index ? _index : na
_clearArray(_array, _oversize) =>
if array.size(_array) >= _oversize
array.pop(_array)
// _backtest() function
export _backtest(bool _enter, bool _exit, float _startQty, float _tradeQty) =>
var profit_array = array.new_float()
var percentProfit_array = array.new_float()
var entryPrice_array = array.new_float()
var entryQty_array = array.new_float()
var exitPrice_array = array.new_float()
var tradeReturn_array = array.new_float()
var trade = _tradeQty / close
var tradeAmt = 0
var tradeProfitable = 0
var grossProfit = 0.0
var grossLoss = 0.0
var netProfit = 0.0
var netPercentProfit = 0.0
var percentProfitable = 0.0
var profitFactor = 0.0
var entryPrice = 0.0
var entryQty = 0.0
var exitPrice = 0.0
var tradeOpen = 0
var maxDrawdown = 0.0
var maxPercentDrawdown= 0.0
var avgTrade = 0.0
var avgPercentTrade = 0.0
if barstate.isconfirmed
if barstate.isfirst
array.unshift(profit_array, 0)
if _enter[1] and (tradeOpen == 0)
tradeOpen := 1
array.unshift(entryPrice_array, open)
entryPrice := array.get(entryPrice_array, _indexArray(entryPrice_array, 0))
array.unshift(entryQty_array, _tradeQty/entryPrice)
entryQty := array.get(entryQty_array, _indexArray(entryQty_array, 0))
netProfit := netProfit
_clearArray(entryPrice_array, 3)
_clearArray(entryQty_array, 3)
if _exit[1] and (tradeOpen == 1)
tradeOpen := 0
tradeAmt += 1
array.unshift(exitPrice_array, open)
exitPrice := array.get(exitPrice_array, _indexArray(exitPrice_array, 0))
_clearArray(exitPrice_array, 3)
tradeReturn = ((entryQty * exitPrice) - (entryPrice * entryQty))
netProfit += tradeReturn
netPercentProfit := (((_startQty + netProfit) - _startQty) / _startQty) * 100
array.unshift(tradeReturn_array, tradeReturn)
array.unshift(profit_array, netProfit)
array.unshift(percentProfit_array, netPercentProfit)
curr_net = array.get(profit_array, _indexArray(profit_array, 0))
last_net = array.get(profit_array, _indexArray(profit_array, 1))
if curr_net > last_net
tradeProfitable += 1
grossProfit += math.abs(tradeReturn)
if curr_net <= last_net
grossLoss += math.abs(tradeReturn)
percentProfitable := (tradeProfitable / tradeAmt) * 100
profitFactor := grossProfit / grossLoss
// Max Drawdown
indexMaxProfit = array.indexof(profit_array, array.max(profit_array, 0))
var maxProfit = 0.0
maxProfit := array.size(profit_array) > 2 ? array.get(profit_array, indexMaxProfit > 0 ? indexMaxProfit : na) : array.get(profit_array, _indexArray(profit_array, 0))
drawdown = maxProfit - curr_net
var drawdown_array = array.new_float()
array.unshift(drawdown_array, drawdown)
indexMaxDrawdown = array.indexof(drawdown_array, array.max(drawdown_array, 0))
maxDrawdown := array.get(drawdown_array, indexMaxDrawdown >= 0 ? indexMaxDrawdown : na)
maxPercentDrawdown := (maxDrawdown / (_startQty + array.get(profit_array, indexMaxDrawdown))) * 100
// "THE PERCENTAGE AND ABBSOLUTE VALUES OF A DRAWDOWN ARE TWO DIFFERENT METRICS. THEY ARE TRICKED INDEPENDENTLY."
// This takes the percent of the current Max Drawdown, not the max percent drawdown
// Average Trade
avgTrade := array.avg(tradeReturn_array)
avgPercentTrade := (avgTrade / _startQty) * 100
[netProfit, netPercentProfit, tradeAmt, percentProfitable, profitFactor, maxDrawdown, maxPercentDrawdown, avgTrade, avgPercentTrade]
////////////////////////////////////////////
//// DEMO STRATEGY (PLOTTED ON CHART) ////
////////////////////////////////////////////
// //@version=5
// strategy("DEMO STRATEGY", overlay=true, default_qty_type = strategy.cash, default_qty_value = 1000, initial_capital = 10000)
// sma_fast = ta.sma(close, 9)
// sma_slow = ta.sma(close, 26)
// enterLong = ta.crossover(sma_fast, sma_slow)
// exitLong = ta.crossunder(sma_fast, sma_slow)
// if enterLong
// strategy.entry("Long", strategy.long)
// if exitLong
// strategy.close("Long")
sma_fast = ta.sma(close, 9)
sma_slow = ta.sma(close, 26)
enterLong = ta.crossover(sma_fast, sma_slow)
exitLong = ta.crossunder(sma_fast, sma_slow)
plot(sma_fast, color=color.lime)
plot(sma_slow, color=color.blue, linewidth=2)
// example of _backtest() function being used
[netProfit, netPercentProfit, tradeAmt, percentProfitable, profitFactor, maxDrawdown, maxPercentDrawdown, avgTrade, avgPercentTrade] = _backtest(enterLong, exitLong, 10000, 1000)
// table showing data
backtest_table = table.new(position.top_right, 7, 2, bgcolor=color.new(#CFCFCF, 80), border_color=na, border_width=1)
_addCell(_table) =>
table.cell(_table, 1, 0, text="Net Profit", text_color=color.white)
table.cell(_table, 2, 0, text="Total Trades", text_color=color.white)
table.cell(_table, 3, 0, text="Percent of Trades \nProfitable", text_color=color.white)
table.cell(_table, 4, 0, text="Profit Factor", text_color=color.white)
table.cell(_table, 5, 0, text="Max Drawdown", text_color=color.white)
table.cell(_table, 6, 0, text="Average Trade", text_color=color.white)
table.cell(_table, 1, 1, text="$" + str.tostring(math.round(netProfit, 2)) + "\n" + str.tostring(math.round(netPercentProfit, 2)) + "%", text_color=color.white)
table.cell(_table, 2, 1, text=str.tostring(math.round(tradeAmt)), text_color=color.white)
table.cell(_table, 3, 1, text=str.tostring(math.round(percentProfitable, 2)) + "%", text_color=color.white)
table.cell(_table, 4, 1, text=str.tostring(math.round(profitFactor, 3)), text_color=color.white)
table.cell(_table, 5, 1, text=str.tostring(math.round(maxDrawdown, 2)) + "\n" + str.tostring(math.round(maxPercentDrawdown, 2)) + "%", text_color=color.white)
table.cell(_table, 6, 1, text=str.tostring(math.round(avgTrade, 2)) + "\n" + str.tostring(math.round(avgPercentTrade, 2)) + "%", text_color=color.white)
_addCell(backtest_table)
|
Developing CPR & Camarilla L3 | https://www.tradingview.com/script/24aWCg5D-Developing-CPR-Camarilla-L3/ | F_Ozyuksel | https://www.tradingview.com/u/F_Ozyuksel/ | 6 | 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/
//@version=5
indicator("Developing CPR & Camarilla L3", shorttitle="DCPRC3", overlay=true)
computeDevCM3(isNewPeriod) =>
var float h = na
var float l = na
c = close
h := isNewPeriod or high > h ? high : h[1]
l := isNewPeriod or low < l ? low : l[1]
pr = h-l
h3 = c + pr*0.2750
l3 = c - pr*0.2750
pivot = (h + l + c) / 3.0
bc = (h + l) / 2.0
tc = pivot - bc + pivot
[h3, l3, pivot, bc, tc]
timeChange(timeframe) =>
ta.change(time(timeframe))
anchor = input.timeframe(defval="D", title="Time Frame")
TimeFrame = anchor
isNewPeriod = timeChange(TimeFrame)
[h3,l3, pivot, bc, tc] = computeDevCM3(isNewPeriod)
plot(h3, title="Developing CMH3", style=plot.style_line, color=color.new(#525eff, 0), linewidth=1)
plot(l3, title="Developing CML3", style=plot.style_line, color=color.new(#525eff, 0), linewidth=1)
plot(pivot, title="Developing Pivot", style=plot.style_line, color=color.new(#15b100, 0), linewidth=1)
plot(tc, title="Developing CPRH", style=plot.style_line, color=color.new(#15b100, 0), linewidth=1)
plot(bc, title="Developing CPRL", style=plot.style_line, color=color.new(#15b100, 0), linewidth=1)
|
Motion | https://www.tradingview.com/script/hk4bWDkH-Motion/ | cryptolinx | https://www.tradingview.com/u/cryptolinx/ | 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/
// © cryptolinx - jango_blockchained - open-source 💙
// https://www.tradingview.com/x/DiuimTu4/
// ———— Primary Functions {
//
// ▸ transition()
// ▸ iteration()
// }
// ———— Simplified Functions {
//
// ▸ marquee() ▸ slideInLeft() ▸ slideInRight()
// ▸ blink() ▸ slideOutLeft() ▸ slideOutRight()
// }
// ———— Secondary Functions
//
// ▸ start() ▸ reset() ▸ next()
// ▸ stop() ▸ reverse() ▸ prev()
// ▸ pause() ▸ toggle()
// }
// ———— Utility Functions
//
// ▸ _onFirst() ▸ _onOpen() ▸ _setupTransition() ▸ _controller()
// ▸ _onUpdate() ▸ _onClose() ▸ _setupTimer() ▸ nz()
// ▸ _onSetup() ▸ _onProcess() ▸ _updateKeyframe() ▸ __()
// }
// ———— Types {
//
// ▸ <keyframe>
// ▸ <transition>
// ▸ <timer>
// ▸ <brackets>
// }
//@version=5
library("Motion", overlay = true)
// ▪ TYPES ────
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ———— Type Transition {
//
// @type transition A transition object.
// @param seq Set the sequence.
// @param fx Set the effect.
// @param max_loops Set the maximum loops.
// @param ws Set the amount of trailing white spaces.
// @param sub_start Set the subsequence start.
// @param sub_length Set the subsequence length.
// @param refill Set the refill state.
// @param reset_on_every_bar Set the reset state.
// @param prefix Set the prefix.
// @param suffix Set the suffix.
// @param seq_arr Set the sequence array.
// @param action Stores the action.
// @param dir Stores the direction.
// @param side Stores the side.
// @param init_index Stores the initial index.
// @param length The sequence length.
// --
export type transition
// --
string seq = na
string fx = 'marquee'
int max_loops = 0
int ws = 0
int sub_start = 0
int sub_length = 0
bool refill = true
bool reset_on_every_bar = false
// --
string prefix
string suffix
array <string> seq_arr = na
//--
string action
string dir
string side
// --
int init_index = bar_index
int length = 0
// }
// ----------------------------------------------------------------------------------------------
// ———— Type Timer {
//
// @type timer A timer object.
// @param type Set the type `on_time` represents tick based and time filtered on_tick represents tick-based calc.
// @param mu Set the time unit.
// @param mode Set the mode.
// @param start Set the starting point value (timenow/bar_index).
// --
export type timer
// --
string type = 'on_tick' // represents tick based and time filtered calc. | on_tick represents tick-based calc.
float mu = 1000
string mode_start = 'now' // on_open | on_close
int mode_calc = 0 // 0 = relative, 1 = absolute < todo
// --
int start = 0
// }
// ----------------------------------------------------------------------------------------------
// ———— Type Keyframe {
//
// @type keyframe A keyframe object.
// @param intv Set the interval (Δt). [0;∞[
// @param step Set the steps per execution.
// @param ltr Set the direction.
// @param update_no Set the update number.
// @param frame_no Set the frame number.
// @param seq_no Set the sequence number.
// @param loop_no Set the loop number.
// @param pointer Set the pointer.
// @param offset Set the offset.
// @param setup Set the setup state.
// @param started Set the started state.
// @param execution Start/Stop motion effect.
// @param __transition Set the transition.
// @param __timer Set the timer.
// @param output Set the output.
// --
export type keyframe
// --
int intv = 0
int steps = 1
bool ltr = na
// --
int update_no = 0
int frame_no = 0
int seq_no = 0
int loop_no = 0
int pointer = 0
int offset = 0
// --
bool setup = na
bool started = na
bool execution = na
// --
transition __transition
timer __timer
// --
string state = na
int index = na
// --
string output
// }
// ----------------------------------------------------------------------------------------------
// ———— Type Brackets {
//
// @type brackets A brackets object.
// @param sws Set secured white spaces.
// @param us Set underscore.
// @param vd Set vertical divider.
// @param mu Set mu.
// @param empty Set empty.
// @param none Set none.
// --
type brackets
// --
string sws // needs to be initialized. WHite spaces in default arguments gets removed.
string us = '_' // underscore
string vd = '|' // vertical divider
string mu = 'µ' // mu
string empty = ''
string none = na
// }
// ▪ UTILITY FUNCTIONS ────
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ———— Shadowing Build-In Function nz() {
//
// @function nz Replace `na` with a default value.
// @param _src Set source value.
// @param _replacement Set replacement value.
// @returns string, transition, timer, keyframe, array <string>
// --
nz(string _src, string _replacement) => na(_src) or _src == string(na) ? _replacement : _src
nz(transition _src, transition _replacement) => na(_src) ? _replacement : _src
nz(timer _src, timer _replacement) => na(_src) ? _replacement : _src
nz(keyframe _src, keyframe _replacement) => na(_src) ? _replacement : _src
nz(array <string> _src, array <string> _replacement) => na(_src) ? _replacement : _src
// }
// ----------------------------------------------------------------------------------------------
// ———— Get Mono-Spaced String {
//
// @function _ws Get a mono-spaced string.
// @param _str Used string.
// @param _len Length of the string.
// @returns string
// --
__(int _len, string _str) =>
// >>
array.join(array.new<string>(_len, _str))
// }
// ----------------------------------------------------------------------------------------------
// ———— Set State {
//
// @function _setState Set the state. []
// @param this Main `<keyframe>` object.
// @param _len Length of the string.
// @returns string
// --
_setState(keyframe this, // *required
string state = na, int index = bar_index) =>
// >>
this.state := nz(state, this.state), this.index := nz(index, this.index)
// }
// ----------------------------------------------------------------------------------------------
// ———— On Setup { << [deprecated]
//
// @function _onSetup Executed only once, at start, per keyframe setup.
// @param this Main `<keyframe>` object.
// @returns bool
// --
_onSetup(keyframe this) =>
// >>
barstate.isnew and not this.setup
// }
// ———— On Process {
//
// @function _onProcess Executed on every bar update.
// @param this Main `<keyframe>` object.
// @returns bool
// --
_onProcess(keyframe this) =>
// >>
(this.intv == 0 or this.update_no % this.intv == 0) ? barstate.islast : false
// }
// ———— On Open {
//
// @function _onOpen Executed only once on bar open
// @param this Main `<keyframe>` object.
// @returns bool
// --
_onOpen() =>
// >>
barstate.islast and barstate.isnew // varip
// }
// ———— On Close {
//
// @function _onClose Executed only once on bar close.
// @param this Main `<keyframe>` object.
// @returns bool
// --
_onClose() =>
// >>
barstate.islast and barstate.isconfirmed // varip
// }
// ----------------------------------------------------------------------------------------------
// ———— On Start {
//
// @function _onStart Executed on event.
// @param this Main `<keyframe>` object.
// @param _event Set the event.
// @returns bool
// --
_onStart(keyframe this) =>
// >>
if barstate.islast and not this.started
// --
this.__timer.mode_start == 'on_open' ? _onOpen() : this.__timer.mode_start == 'on_close' ? _onClose() : true
// }
// ----------------------------------------------------------------------------------------------
// ———— On Index {
//
// @function _getIndex Returns the next `update_no` from an interval per bar.
// @param this Main `<keyframe>` object.
// @returns initial
// --
_getIndex(this) =>
// >>
bar_index - this.__timer.start
// }
// ———— On Time {
//
// @function _getTime Returns the next `update_no` from a tick based time interval.
// @param this Main `<keyframe>` object.
// @returns int
// --
_getTime(this) =>
// >>
int((timenow - this.__timer.start) / this.__timer.mu)
// }
// ———— On Time {
//
// @function _getTime Returns the next `update_no` from a tick based interval.
// @param this Main `<keyframe>` object.
// @returns int
// --
_getTick(this) =>
// >>
this.update_no + 1
// }
// ----------------------------------------------------------------------------------------------
// ———— Function Get Update No {
//
// @function _getUpdateNumber Get the update number.
// @param this Main `<keyframe>` object.
// @returns int
// --
_getUpdateNumber(keyframe this) =>
// >>
this.update_no := switch this.__timer.type
// --
'on_index' => _getIndex(this)
'on_time' => _getTime(this)
// --
=> _getTick(this)
// }
// ----------------------------------------------------------------------------------------------
// ———— Function Setup Timer {
//
// @function _setupTimer Setup the timer object.
// @param this Main `<keyframe>` object.
// @returns bool
// --
_setupTimer(keyframe this) =>
// >>
this.__timer.start := if this.__timer.mode_calc == 1
switch this.__timer.type
// >>
'on_time' => timenow
=> bar_index // 'on_index' and 'on_tick'
else
0
// }
// ———— Function Setup Keyframe {
//
// @function _setupTransition Setup the keyframe object.
// @param this Main `<keyframe>` object.
// @returns bool
// --
_setupTransition(keyframe this) =>
// --
var __ = brackets.new(' ')
// --
transition t = this.__transition // ref
array <string> transProp = str.split(t.fx, __.us)
t.action := array.get(transProp, 0)
t.dir := array.size(transProp) >= 2 ? array.get(transProp, 1) : t.dir
t.side := array.size(transProp) == 3 ? array.get(transProp, 2) : t.side
// --
t.sub_length := t.sub_length == 0 ? t.length : t.sub_length
// >>
this.setup := true
// }
// ----------------------------------------------------------------------------------------------
// ———— Function Update Keyframe {
//
// @function _updateKeyframe Setup the keyframe object.
// @param this Main `<keyframe>` object.
// @returns bool
// --
_updateKeyframe(keyframe this) =>
// --
transition t = this.__transition // ref
// --
this.frame_no := math.floor(this.update_no / this.intv)
this.loop_no := math.floor(this.frame_no / t.length)
// --
if _onOpen() and this.__transition.reset_on_every_bar
// --
this.update_no := 0, this.frame_no := 0, this.loop_no := 0, this.pointer := 0, t.init_index := bar_index
_setupTimer(this)
// --
this.setup and this.started and this.execution
// }
// ----------------------------------------------------------------------------------------------
// ———— Execution Controller {
//
// @function _controller Controller.
// @param this Main `<keyframe>` object.
// @returns bool
// --
_controller(keyframe this) => // *required
// --
_getUpdateNumber(this)
// --
switch
// --
_onSetup(this) => _setupTimer(this), _setupTransition(this), false
_onStart(this) => this.started := true, false
_onProcess(this) => _updateKeyframe(this)
=> false
// }
// ▪ PRIMARY FUNCTIONS ────
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ———— Function Start Execution {
//
// @function start Starts execution.
// @param this Main `<keyframe>` object.
// @returns bool
// --
export start(keyframe this) => this.execution := true, this.started := true
// }
// ———— Function Stop Execution {
//
// @function stop Stops execution.
// @param this Main `<keyframe>` object.
// @returns bool
// --
export stop(keyframe this) => this.execution := false
// }
// ———— Function Reset Metadata {
//
// @function stop executions/Starts execution.
// @param this Main `<keyframe>` object.
// @returns int
// --
export reset(keyframe this) =>
// --
this.__timer.start := 0, this.update_no := 0, this.frame_no := 0, this.loop_no := 0
this.pointer := 0, this.__transition.init_index := bar_index
// --
_setupTimer(this)
// }
// ----------------------------------------------------------------------------------------------
// ———— Function Transition Effect {
//
// @function marquee Generates a text effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _fx Optional effect name. If not set, the default marquee effect will be used.
// @param _ws wss between the input source.
// @param _maxLoops Optional maximum loops.
// @param _subLen Optional substring length.
// @param _subStart Optional substring start.
// @param _ltr Set the direction to left to right.
// @param _refill Optional refill.
// @param _resetOnEveryBar Optional reset on every bar.
// @param _autoplay Optional autoplay.
// @param _prefix Optional prefix.
// @param _suffix Optional suffix.
// @param _timerType Optional timer type.
// @param _timerMu Optional timer mu.
// @param _timerMode Optional timer calculation mode.
// @returns string
// --
export transition(keyframe this, // *required
string _seq = na, string _fx = 'marquee', int _ws = 0, int _maxLoops = 0, int _subLen = 0, int _subStart = 0,
bool _ltr = false, bool _refill = true, bool _resetOnEveryBar = false, bool _autoplay = true, string _prefix = na,
string _suffix = na, string _timerType = 'on_tick', float _timerMu = 1000, string _timerStart = 'now', int _timerMode = 1) =>
// --
var __ = brackets.new(' ')
// -- init once.
this.__timer := nz(this.__timer, timer.new(_timerType, _timerMu, _timerStart, _timerMode))
this.__transition := nz(this.__transition, transition.new(fx = _fx, max_loops = _maxLoops, ws = _ws,
sub_start = _subStart, sub_length = _subLen, refill = _refill, reset_on_every_bar = _resetOnEveryBar,
prefix = nz(_prefix, __.empty), suffix = nz(_suffix, __.empty)))
transition t = this.__transition // -- short-hand (object reference <3)
t.length := str.length(nz(_seq, t.seq)) + t.ws
this.ltr := nz(this.ltr, _ltr), this.execution := nz(this.execution, _autoplay) // -- keyframe first
// --
if _controller(this)
// --
this.ltr := t.fx == 'marquee' ? this.ltr
: t.action == 'slide' and ((t.dir == 'in' and t.side == 'left') or (t.dir == 'out' and t.side == 'right')) ? true
: t.action == 'blend' and ((t.dir == 'out' and t.side == 'left') or (t.dir == 'in' and t.side == 'right')) ? true
: false
this.pointer := math.abs((this.ltr ? t.length - 1 : 0)
- (((this.frame_no + this.offset) * this.steps) % t.length)) + (t.side == 'right' ? 1 : 0)
// >>
// this.output :=
t.prefix + str.substring(
// -- marquee effect
(t.action == 'marquee' ? str.substring(nz(_seq, t.seq) + __(t.ws, __.sws), this.pointer, t.length) + str.substring(nz(_seq, t.seq) + __(t.ws, __.sws), 0, this.pointer)
// -- slide effect without placeholder (dynamic string length)
: t.action == 'slide' and not t.refill ? str.substring(nz(_seq, t.seq) + __(t.ws, __.sws), t.side == 'left' ? this.pointer : 0, t.side == 'left' ? t.length : this.pointer)
// -- slide effect with placeholder (static string length)
: t.action == 'slide' and t.refill ? str.substring(__(t.side == 'right' ? t.length : 0, __.sws) + nz(_seq, t.seq) + __(t.ws, __.sws)
+ __(t.side == 'left' ? t.length : 0, __.sws), this.pointer, this.pointer + t.length)
// -- blend effect without placeholder (dynamic string length)
: t.action == 'blend' and not t.refill ? str.substring(nz(_seq, t.seq) + __(t.ws, __.sws), t.side == 'left' ? 0 : this.pointer, t.side == 'left' ? this.pointer : t.length)
// -- blend effect with placeholder (static string length)
: t.action == 'blend' and t.refill ? __(t.side == 'right' ? this.pointer : 0, __.sws) + str.substring(nz(_seq, t.seq)
+ __(t.ws, __.sws), t.side == 'left' ? 0 : this.pointer, t.side == 'left' ? this.pointer : t.length) + __(t.side == 'left' ? t.length - this.pointer : 0, __.sws)
// -- blink
: t.action == 'blink' ? str.substring(nz(_seq, t.seq) + __(t.ws, __.sws) + __(t.length, __.sws), this.pointer % 2 ? 0 : t.length, this.pointer % 2 ? t.length : t.length * 2)
// -- default
: nz(_seq, t.seq) + __(t.ws, __.sws)
), t.sub_start, t.sub_start + t.sub_length) + t.suffix
// }
// ----------------------------------------------------------------------------------------------
// ———— Function Iteration Effect {
//
// @function iteration Generates a text effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws wss between the input source.
// @param _maxLoops Optional maximum loops.
// @param _subLen Optional substring length.
// @param _subStart Optional substring start.
// @param _ltr Set the direction to left to right.
// @param _prefix Optional prefix.
// @param _suffix Optional suffix.
// @param _seqArr Optional sequence array.
// @param _autoplay Optional autoplay.
// @param _resetOnEveryBar Optional reset on every bar.
// @param _timerType Optional timer type.
// @param _timerMu Optional timer mu.
// @param _timerMode Optional timer mode.
// @param _delimiter Optional One or more characters that separates the seq string.
// @returns string
// --
export iteration(keyframe this, // * required
string _seq = na, int _ws = 0, int _maxLoops = 0, int _subLen = 0, int _subStart = 0, bool _refill = true, bool _ltr = false,
string _prefix = na, string _suffix = na, array <string> _seqArr = na, bool _autoplay = true, bool _resetOnEveryBar = false,
string _timerType = 'on_tick', float _timerMu = 1000, string _timerStart = 'now', int _timerMode = 1, string _delimiter = na) =>
// --
var __ = brackets.new(' '), int maxLength = 0
// -- init once
this.__timer := nz(this.__timer, timer.new(_timerType, _timerMu, _timerStart, _timerMode))
this.__transition := nz(this.__transition, transition.new(seq = _seq, seq_arr = _seqArr, max_loops = _maxLoops,
ws = _ws, sub_start = _subStart, sub_length = _subLen, refill = _refill, prefix = nz(_prefix, __.empty),
suffix = nz(_suffix, __.empty), reset_on_every_bar = _resetOnEveryBar, init_index = bar_index))
this.ltr := nz(this.ltr, _ltr), this.execution := nz(this.execution, _autoplay) // keyframe first
transition t = this.__transition
// --
t.seq_arr := nz(t.seq_arr, str.split(_seq, nz(_delimiter, __.empty)))
// --
for [idx_, content_] in t.seq_arr
maxLength := math.max(maxLength, str.length(content_))
t.length := array.size(t.seq_arr)
// --
if _controller(this)
// --
this.pointer := math.abs((this.ltr ? t.length - 1 : 0) - (((this.frame_no + this.offset) * this.steps) % t.length))
// --
int currentLength = str.length(array.get(t.seq_arr, this.pointer))
t.sub_length := _subLen > 0 ? _subLen : currentLength
// >> fix here
this.output := t.prefix + str.substring(array.get(t.seq_arr, this.pointer), t.sub_start, t.sub_start + t.sub_length)
+ __(t.refill ? maxLength - currentLength : 0, __.sws) + __(t.ws, __.sws) + t.suffix
// }
// ----------------------------------------------------------------------------------------------
// ———— Function Color Gradient Effect {
//
// @function color_gradient Generates a color gradient effect.
// @param this Main `<keyframe>` object.
// @param _from Set Color from.
// @param _to Set Color to.
// @param _steps Optional steps.
// @param _maxLoops Optional maximum loops.
// @param _resetOnEveryBar Optional reset on every bar.
// @param _autoplay Optional autoplay.
// @param _timerType Optional timer type.
// @param _timerMu Optional timer mu.
// @param _timerMode Optional timer calculation mode.
// @returns string
// --
export color_gradient(keyframe this, // *required
color _color_from, color _color_to, int _transp_from = 0, int _transp_to = 0,
int _steps = 6, int _maxLoops = 0, bool _resetOnEveryBar = false, bool _autoplay = true, bool _cycle = true,
string _timerType = 'on_tick', float _timerMu = 1000, string _timerStart = 'now', int _timerMode = 1) =>
// -- init once
this.__timer := nz(this.__timer, timer.new(_timerType, _timerMu, _timerStart, _timerMode))
this.__transition := nz(this.__transition, transition.new(fx = 'color', max_loops = _maxLoops, length = _steps,
reset_on_every_bar = _resetOnEveryBar))
this.execution := nz(this.execution, _autoplay) // -- keyframe first
// --
if _controller(this)
// --
this.ltr := _cycle and this.loop_no % 2 ? false : true // oscillating color
this.pointer := math.abs((this.ltr ? _steps : 0) - (((this.frame_no + this.offset) * this.steps) % _steps))
// >>
color.from_gradient(value = this.pointer, bottom_value = 0, top_value = _steps,
bottom_color = color.new(color = _color_from, transp = _transp_from), top_color = color.new(color = _color_to, transp = _transp_to))
// }
// ▪ SIMPLIFIED FUNCTIONS ────
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ———— Function String Marquee Effect {
//
// @function marquee Generates a marquee effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _ltr Set the direction to left to right.
// @returns string
// --
export marquee(keyframe this, string _seq, // *required
int _ws = 1, int _maxLoops = 0, bool _ltr = false, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'marquee', _ws = _ws, _maxLoops = _maxLoops,
_ltr = _ltr, _timerType = _timerType)
// }
// ----------------------------------------------------------------------------------------------
// ———— Function String Blink Effect {
//
// @function blink Generates a blink effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @returns string
// --
export blink(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'blink', _ws = _ws, _maxLoops = _maxLoops, _timerType = _timerType)
// }
// ----------------------------------------------------------------------------------------------
// ———— Function Color Fade In Effect {
//
// @function fadeIn Generates a fade in effect.
// @param this Main `<keyframe>` object.
// @param _color_from Set Color from.
// @param _color_to Set Color to.
// @param _steps Optional steps.
// @param _transp_from Optional transparency from.
// @param _transp_to Optional transparency to.
// @param _maxLoops Optional maximum loops.
// @param _timerType Optional timer type.
// @returns color
// --
export fadeIn(keyframe this, color _color_from, color _color_to, // *required
int _steps = 5, int _transp_from = 100, int _transp_to = 0, int _maxLoops = 0, string _timerType = 'on_tick') =>
// >>
// this.output_color :=
color_gradient(this, _color_from = _color_from, _color_to = _color_to, _steps = _steps,
_transp_from = _transp_from, _transp_to = _transp_to, _maxLoops = _maxLoops, _timerType = _timerType)
// }
// ———— Function Color Fade Out Effect {
//
// @function fadeOut Generates a fade out effect.
// @param this Main `<keyframe>` object.
// @param _color_from Set Color from.
// @param _color_to Set Color to.
// @param _steps Optional steps.
// @param _transp_from Optional transparency from.
// @param _transp_to Optional transparency to.
// @param _maxLoops Optional maximum loops.
// @param _timerType Optional timer type.
// @returns color
// --
export fadeOut(keyframe this, color _color_from, color _color_to, // *required
int _steps = 5, int _transp_from = 0, int _transp_to = 100, int _maxLoops = 0, string _timerType = 'on_tick') =>
// >>
// this.output_color :=
color_gradient(this, _steps = _steps, _color_from = _color_from, _color_to = _color_to,
_transp_from = _transp_from, _transp_to = _transp_to, _maxLoops = _maxLoops, _timerType = _timerType)
// }
// ----------------------------------------------------------------------------------------------
// ———— Function String SLide In Left Effect {
//
// @function slideInLeft Generates a slide in left effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _refill Optional refill.
// @returns string
// --
export slideInLeft(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'slide_in_left', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ———— Function String Slide Out Left Effect {
//
// @function slideOutLeft Generates a slide out left effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @returns string
// --
export slideOutLeft(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'slide_out_left', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ———— Function String Slide In Right Effect {
//
// @function slideInRight Generates a slide in right effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _refill Optional refill.
// @returns string
// --
export slideInRight(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'slide_in_right', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ———— Function String Slide Out Right Effect {
//
// @function slideOutRight Generates a slide out right effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _refill Optional refill.
// @returns string
// --
export slideOutRight(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'slide_out_right', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ----------------------------------------------------------------------------------------------
// ———— Function String Blend In Left Effect {
//
// @function blendInLeft Generates a blend in left effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _refill Optional refill.
// @returns string
// --
export blendInLeft(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'blend_in_left', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ———— Function String Blend Out Left Effect {
//
// @function blendInLeft Generates a blend out left effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _refill Optional refill.
// @returns string
// --
export blendOutLeft(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'blend_out_left', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ———— Function String Blend In Right Effect {
//
// @function blendInRight Generates a blend in right effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _refill Optional refill.
// @returns string
// --
export blendInRight(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'blend_in_right', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ———— Function String Blend Out Right Effect {
//
// @function blendInLeft Generates a blend out right effect.
// @param this Main `<keyframe>` object.
// @param _seq Optional sequence.
// @param _ws White space between the input source.
// @param _maxLoops Optional maximum loops.
// @param _refill Optional refill.
// @returns string
// --
export blendOutRight(keyframe this, string _seq, // *required
int _ws = 0, int _maxLoops = 0, bool _refill = true, string _timerType = 'on_tick') =>
// >>
this.output := transition(this, _seq = _seq, _fx = 'blend_out_right', _ws = _ws, _maxLoops = _maxLoops,
_refill = _refill, _timerType = _timerType)
// }
// ▪ EXAMPLE ────
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
/// ———— User Input {
//
// ⚠️ IMPORTANT: Example Type. NOT REQUIRED.
//
type user_input
// --
string fx
bool play
string timing
int intv
int mu
int step
bool reset
int max_loops
int sub_start
int sub_length
bool ltr
bool refill
string prefix
string txt
int ws
string suffix
int color_steps
bool color_cycle
color color_from
color color_to
string mode_start
int mode_calc
// --
var __settings = user_input.new(
fx = input.string('marquee', 'Transition', options = ['marquee', 'blink', 'blend_in_right', 'blend_out_right', 'blend_in_left', 'blend_out_left', 'slide_in_left', 'slide_in_right', 'slide_out_left', 'slide_out_right'], group = 'ACTION'),
play = input.bool(true, 'Play', group = 'ACTION'),
timing = input.string('on_time', 'Event Producer', options = ['on_tick', 'on_time', 'on_index'], group = 'TIMING'),
intv = input.int(1, title = 'Interval (Δt)', step = 1, minval = 1, maxval = 100, tooltip = 'Delta Time [1;∞[', group = 'TIMING'),
mu = input.int(1000, title = 'onTime - Fineness (μ)', step = 50, minval = 50, maxval = 2000, tooltip = '[50-2000] 1000 = default. lower value = higher freq.', group = 'TIMING'),
step = input.int(1, title = 'Steps Per Execution', step = 1, minval = 1, maxval = 20, group = 'PREFERENCES'),
reset = input.bool(false, title = 'Reset On Every Bar', group = 'PREFERENCES'),
max_loops = input.int(0, title = 'Max. Loops', step = 1, minval = 0, maxval = 100, tooltip = '0 = infinite', group = 'PREFERENCES'),
sub_start = input.int(0, title = 'Subsequence Start', step = 1, minval = 0, maxval = 20, tooltip = '[ABCDEF]GHI...\n| |\n0 5', group = 'PREFERENCES'),
sub_length = input.int(0, title = 'Subsequence Length', step = 1, minval = 0, maxval = 20, group = 'PREFERENCES'),
refill = input.bool(true, 'Placeholder String', group = 'PREFERENCES', tooltip = 'true = default; false = slide effect without placeholder (+/- string length)'),
ltr = input.bool(false, title = 'Left To Right', group = 'ONLY MARQUEE'),
prefix = input.string('', 'Prefix', group = 'CONTENT'),
txt = input.string('ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789', 'Text', group = 'CONTENT'),
ws = input.int(0, title = 'Trailing White Space', step = 1, minval = 0, maxval = 10, group = 'CONTENT'),
suffix = input.string('', 'Suffix', group = 'CONTENT'),
color_steps = input.int(6, title = 'Gradient Steps', step = 1, minval = 1, maxval = 20, group = 'COLOR'),
color_cycle = input.bool(true, title = 'Color Cycle', group = 'COLOR'),
color_from = input.color(color.rgb(0, 57, 212), 'Color From', group = 'COLOR'),
color_to = input.color(color.rgb(59, 209, 255), 'Color To', group = 'COLOR'),
mode_start = 'now', // input.string('now', 'Effect Start', options = ['now', 'on_open', 'on_close'], group = 'ADVANCED/DEVELOPMENT'),
mode_calc = 1) // input.int(1, 'Calculation Mode', minval = 0, maxval = 1, step = 1, tooltip = '0 = relative; 1 = absolute', group = 'ADVANCED/DEVELOPMENT'))
// }
// ———— Motion 🪄 {
//
// ⚠️ IMPORTANT: The keyframe object must be created by using the `varip` keyword.
//
varip transitionKf = keyframe.new(intv = __settings.intv, steps = __settings.step, execution = __settings.play) // create keyframe
string transitionString = transition(transitionKf, _seq = __settings.txt, _fx = __settings.fx, _ws = __settings.ws, _maxLoops = __settings.max_loops,
_subLen = __settings.sub_length, _subStart = __settings.sub_start, _ltr = __settings.ltr, _resetOnEveryBar = __settings.reset, _autoplay = __settings.play,
_refill = __settings.refill, _timerType = __settings.timing, _timerMu = __settings.mu, _timerMode = __settings.mode_calc, _prefix = __settings.prefix, _suffix = __settings.suffix)
// --
varip iterationKf = keyframe.new(intv = 3, steps = __settings.step, execution = __settings.play)
iteration(iterationKf, _seqArr = array.from('THIS','IS','AN','ITERATION','EFFECT!'), _ws = __settings.ws,
_subLen = __settings.sub_length, _subStart = __settings.sub_start, _ltr = __settings.ltr, _resetOnEveryBar = __settings.reset, _autoplay = false, //__settings.play,
_refill = __settings.refill, _timerType = __settings.timing, _timerMu = __settings.mu, _timerMode = __settings.mode_calc, _prefix = __settings.prefix, _suffix = __settings.suffix)
// --
varip colorKf = keyframe.new(intv = __settings.intv, steps = __settings.step, execution = __settings.play)
color gradient = fadeOut(colorKf, color.red, color.yellow)//color_gradient(colorKf, __settings.color_from, __settings.color_to, _steps = __settings.color_steps, _cycle = __settings.color_cycle, _timerType = __settings.timing)
// }
// ———— Label {
//
var select = label.new(bar_index, 750, text = 'Double click, to select a transition effect from input:', textcolor = color.white, color = #ffffff0b, size = size.normal, style = label.style_label_center)
var fx = label.new(bar_index, 700, text = __settings.fx, textcolor = #AAFF00, color = #ffffff0b, size = size.normal, style = label.style_label_center, textalign = text.align_center, text_font_family = font.family_default)
var openSource = label.new(bar_index, 300, text = 'open 💙 source', textcolor = color.white, color = #ffffff0b, size = size.normal, style = label.style_label_center)
var example = label.new(bar_index, 600, text = '', textcolor = color.white, color = #ffffff0b, size = size.huge, style = label.style_label_center, textalign = text.align_center, text_font_family = font.family_monospace)
var itr = label.new(bar_index, 450, text = '', textcolor = color.white, color = #ffffff0b, size = size.normal, style = label.style_label_center, textalign = text.align_center, text_font_family = font.family_monospace)
// --
label.set_x(select, bar_index), label.set_x(fx, bar_index), label.set_x(example, bar_index), label.set_x(openSource, bar_index), label.set_x(itr, bar_index),
label.set_text(fx, __settings.fx), label.set_text(example, transitionString), label.set_text(itr, iterationKf.output)
label.set_textcolor(itr, gradient)
// }
// } #EOF |
Library_Smoothers | https://www.tradingview.com/script/LUv54YeK-Library-Smoothers/ | Koalems | https://www.tradingview.com/u/Koalems/ | 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/
// © Koalems
// @version=5
// @description A library of smoothing algorithms.
//
// HOW TO USE: SAMPLE CODE:
//
// Group8240 = 'MA 1: Settings'
// ma1Corrected = input.bool(false, 'Corrected', group=Group8240)
// ma1Src = input.source(close, 'Source', group=Group8240, inline='MA1.1')
//
// ma1Type = input.string('SMMA', 'MA type', group=Group8240, inline='MA1.2', options=['None', 'Corrected', 'EHMA', 'EMA', 'FRAMA', 'HMA', 'Jurik', 'LINREG', 'RMA', 'SMA', 'SMMA', 'Super Smoother', 'SWMA', 'TMA', 'TSF', 'VAWMA', 'VIDYA', 'VWMA', 'WMA', 'WWMA', 'ZLEMA'])
// ma1Length = input.int(15, 'Length', group=Group8240, inline='MA1.2', minval=1, step=5)
// ma1Timeframe = input.timeframe('', 'Res', group=Group8240, inline='MA1.2')
//
// Group8242 = 'MA 1: Settings: Extra'
// ma1FramaFast = input.int(2, 'FRAMA: Fast', group=Group8242, inline='MA1.3', minval=1, step=1)
// ma1FramaSlow = input.int(200, 'Slow', group=Group8242, inline='MA1.3', minval=1, step=10)
// ma1JurikPhase = input.int(50, 'Jurik: Phase', group=Group8242, inline='MA1.4', minval=-100, maxval=100, step=5)
// ma1JurikPower = input.float(2, 'Power', group=Group8242, inline='MA1.4', minval=0, step=0.25)
// ma1LinRegOffset = input.int(0, 'Lin. Reg.: Offset', group=Group8242, inline='MA1.5', minval=0, step=1)
// ma1VwwmaStartingWeight = input.int(1, 'VAWMA: Starting weight', group=Group8242, inline='MA1.6', minval=0, step=1)
// ma1VwwmaVolumeDefault = input.int(0, 'Vol. default', group=Group8242, inline='MA1.6', minval=0, step=1)
//
// ma1 = MAs.MaTypes(ma1Type, ma1Src, ma1Length, ma1FramaFast, ma1FramaSlow, ma1LinRegOffset, ma1JurikPhase, ma1JurikPower, ma1VwwmaStartingWeight, ma1VwwmaVolumeDefault, ma1Corrected)
library("Library_Smoothers", overlay=false)
SQRT2 = math.sqrt(2.0)
IsLenInvalid(simple int len, simple string name = 'len') =>
if na(len)
runtime.error("The '" + name + "' param cannot be " + str.tostring(len))
true
else if len < 0
runtime.error("The '" + name + "' param cannot be negative.")
true
else if len == 0
true
else
false
// @function CorrectedMA The strengths of the corrected Average (CA) is that the current value of the time series must exceed a the current volatility-dependent threshold, so that the filter increases or falls, avoiding false signals when the trend is in a weak phase.
// @param src Source
// @param length Length
// @returns The Corrected source.
export CorrectedMA(float Src, int Len) =>
sma = ta.sma(Src, Len)
cma = sma
cma := nz(cma[1], cma)
v1 = ta.variance(Src, Len)
v2 = math.pow(cma - sma, 2)
k = v2 < v1 ? 0 : 1 - v1 / v2
cma := cma + k * (sma - cma)
cma
// Chande Momentum Oscillator
CmoF1(m) => m >= 0.0 ? m : 0.0
CmoF2(m) => m >= 0.0 ? 0.0 : -m
CmoPercent(nom, div) => 100 * nom / div
ChandeMomentumOscillator(float src, int length) =>
momm = ta.change(src, length)
m1 = CmoF1(momm)
m2 = CmoF2(momm)
sm1 = math.sum(m1, length)
sm2 = math.sum(m2, length)
out = nz(CmoPercent(sm1 - sm2, sm1 + sm2))
out
// @function EMA Exponential Moving Average.
// @param src Source to act upon
// @param length Length of moving average
// @returns EMA of source
export EHMA(float src, simple int len) => ta.ema(2 * ta.ema(src, len / 2) - ta.ema(src, len), math.round(math.sqrt(len)))
// @function FRAMA Fractal Adaptive Moving Average
// @param src Source to act upon
// @param len Length of moving average
// @param FC Fast moving average
// @param SC Slow moving average
// @returns FRAMA of source
export FRAMA(float src, int len, int FC, int SC) =>
len1 = len / 2
w = math.log(2 / (SC + 1)) / math.log(math.e) // Natural logarithm (ln(2 / (SC + 1))) workaround
H1 = ta.highest(high, len1)
L1 = ta.lowest(low, len1)
N1 = (H1 - L1) / len1
H2 = ta.highest(high, len1)[len1]
L2 = ta.lowest(low, len1)[len1]
N2 = (H2 - L2) / len1
H3 = ta.highest(high, len)
L3 = ta.lowest(low, len)
N3 = (H3 - L3) / len
dimen1 = (math.log(N1 + N2) - math.log(N3)) / math.log(2)
dimen = N1 > 0 and N2 > 0 and N3 > 0 ? dimen1 : nz(dimen1[1])
alpha1 = math.exp(w * (dimen - 1))
oldalpha = alpha1 > 1 ? 1 : (alpha1 < 0.01 ? 0.01 : alpha1)
oldN = (2 - oldalpha) / oldalpha
N = (((SC - FC) * (oldN - 1)) / (SC - 1)) + FC
alpha_ = 2 / (N + 1)
alpha = alpha_ < 2 / (SC + 1) ? 2 / (SC + 1) : (alpha_ > 1 ? 1 : alpha_)
out = 0.0
out := (1 - alpha) * nz(out[1]) + alpha * src
out
// @function Jurik A low lag filter
// @param src Source
// @param length Length for smoothing
// @param phase Phase range is ±100
// @param power Mathematical power to use. Doesn't need to be whole numbers
// @returns Jurik of source
export Jurik(float src, int length, int phase, float power)=>
jma = 0.0
e0 = 0.0
e1 = 0.0
e2 = 0.0
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
l1 = length - 1
beta = 0.45 * l1 / (0.45 * l1 + 2)
alpha = math.pow(beta, power)
e0 := (1 - alpha) * src + alpha * nz(e0[1])
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
jma
// @function SMMA Smoothed moving average. Think of the SMMA as a hybrid of its better-known siblings — the simple moving average (SMA) and the exponential moving average (EMA).
// @param src Source
// @param length Length for smoothing
// @returns SMMA of source
export SMMA(float src, int len) =>
sma = ta.sma(src, len)
smma = 0.
smma := na(smma[1]) ? sma : (smma[1] * (len - 1) + src) / len
smma
// @function SuperSmoother
// @param src Source to smooth
// @param length Length to use
// @returns SuperSmoother of the source
export SuperSmoother(float src, int len) =>
lambda = math.pi * SQRT2 / len
a1 = math.exp(-lambda)
coeff2 = 2.0 * a1 * math.cos(lambda)
coeff3 = -math.pow(a1, 2.0)
coeff1 = 1.0 - coeff2 - coeff3
filt1 = 0.0
filt1 := coeff1 * (src + nz(src[1])) * 0.5 + coeff2 * nz(filt1[1]) + coeff3 * nz(filt1[2])
filt1
// @function TMA Triangular Moving Average
// @param src Source
// @param length Length to use
// @returns TMA of source
export TMA(float src, int len) => ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1)
// @function TSF Time Series Forecast. Uses linear regression.
// @param src Source
// @param length Length to use
// @returns TSF of source
export TSF(float src, int len) =>
lrc = ta.linreg(src, len, 0)
lrc1 = ta.linreg(src, len, 1)
lrs = lrc - lrc1
TSF = ta.linreg(src, len, 0) + lrs
TSF
// @function VIDYA Chande's Variable Index Dynamic Average. See http://www.fxcorporate.com/help/MS/NOTFIFO/i_Vidya.html
// @param src Source
// @param length Length for CMO
// @returns VIDYA of source
export VIDYA(float src, simple int len) =>
k = math.abs(ChandeMomentumOscillator(src, len)) / 100
smoothingFactor = 2 / (len + 1)
vidya=0.0
vidya := nz(smoothingFactor * k * src) + (1 - smoothingFactor * k) * nz(vidya[1])
// @function VAWMA = VWMA and WMA combined. Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. Uses a triangular algorithm to taper off values in the past (same as WMA does).
// @param src Source
// @param len Length
// @param volumeDefault The default value to use when a chart has no volume.
// @returns The VAWMA of the source.
export VAWMA(
series float src,
simple int len,
simple int startingWeight=1,
simple float volumeDefault =na
) =>
var float notAvailable = na
if IsLenInvalid(len)
notAvailable
else
sum = 0.0
vol = 0.0
last = len - 1
for i = 0 to last
s = src[i]
v = volume[i]
if na(v) and not na(volumeDefault)
v := volumeDefault
if not na(s) and not na(v)
m = last - i + startingWeight
v *= m
vol += v
sum += s * v
ma = vol == 0 ? na : sum / vol
ma
// @function WWMA Welles Wilder Moving Average
// @param src Source
// @param length Length
// @returns The WWMA of the source
export WWMA(float src, int len) =>
wwalpha = 1 / len
WWMA = 0.0
WWMA := wwalpha * src + (1 - wwalpha) * nz(WWMA[1])
//
// @function ZLEMA Zero Lag Expotential Moving Average
// @param src Source
// @param length
// @param
// @returns The ZLEMA of the source
export ZLEMA(float src, int len) =>
lag = len / 2 == math.round(len / 2) ? len / 2 : (len - 1) / 2
EMAData = src + src - src[lag]
ZLEMA = ta.ema(EMAData, len)
ZLEMA
// @function Performs the specified moving average
// @param mode Name of moving average
// @param src the source to apply the MA type
// @param the length for the MA
// @param fastMA FRAMA fast moving average
// @param slowMA FRAMA slow moving average
// @param offset Linear regression offset
// @param phase Jurik phase
// @param power Jurik power
// @param startingWeight VAWMA starting weight
// @param volumeDefault VAWMA default volume
// @param Corrected
// @returns The MA smoothed source
export SmootherType(
simple string mode,
float src,
simple int len,
simple int fastMA = 0,
simple int slowMA = 0,
simple int offset = 0,
simple int phase = 0,
simple float power = 0,
simple int startingWeight = 1,
simple float volumeDefault = na,
simple bool Corrected = false
) =>
float smoother = switch mode
'Corrected' => CorrectedMA( src, len)
'EHMA' => EHMA( src, len)
'EMA' => ta.ema( src, len)
'FRAMA' => FRAMA( src, len, fastMA, slowMA)
'HMA' => ta.hma( src, len)
'Jurik' => Jurik( src, len, phase, power)
'LINREG' => ta.linreg( src, len, offset)
'None' => src // NONE !!!!!
'RMA' => ta.rma( src, len)
'SMA' => ta.sma( src, len)
'SMMA' => SMMA( src, len)
'Super Smoother' => SuperSmoother( src, len)
'SWMA' => ta.swma( src)
'TMA' => TMA( src, len)
'TSF' => TSF( src, len)
'VAWMA' => VAWMA( src, len, startingWeight, volumeDefault)
'VIDYA' => VIDYA( src, len)
'VWMA' => ta.vwma( src, len)
'WMA' => ta.wma( src, len)
'WWMA' => WWMA( src, len)
'ZLEMA' => ZLEMA( src, len)
=>
runtime.error("No matching smoother type found.")
float(na)
if Corrected
smoother := CorrectedMA(src, len)
smoother
|
[KVA]Keltner Channel Percentage | https://www.tradingview.com/script/n8bpUymU-KVA-Keltner-Channel-Percentage/ | Kamvia | https://www.tradingview.com/u/Kamvia/ | 5 | 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/
// © Kamvia
//@version=5
indicator("[KVA]Keltner Channel Percentage", shorttitle="KC%", overlay=false)
// User-defined input for the length and the source of the Keltner Channel
length = input(20, title="Length")
src = close
mult = input(2.0, title="Multiplier")
// Calculating the Keltner Channels
basis = ta.sma(src, length)
upper = basis + mult * ta.atr(length)
lower = basis - mult * ta.atr(length)
// Calculate Keltner Channel Percentage
kc_percent = 100 * (src - lower) / (upper - lower)
// Plotting the Keltner Channel Percentage
plot(kc_percent, title="KC%", color=color.blue, linewidth=2)
hline(0, "Lower Bound", color=color.red)
hline(100, "Upper Bound", color=color.green)
|
[PUZ] MACD MTB System MTF | https://www.tradingview.com/script/AlzGGtK1/ | PuzzlesAnalytik | https://www.tradingview.com/u/PuzzlesAnalytik/ | 6 | 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/
// © PuzzlesAnalytik
//@version=5
indicator("[PUZ] MACD MTB System MTF", overlay = false)
timeframe = input.timeframe("", "Timeframe Value", group = "Timeframe")
long_threshold_L1 = input.int( 0, title = "Crossover Thrshold Long L1", group = "Thresholds")
short_threshold_L1 = input.int( 0, title = "Crossunder Threshold Short L1", group = "Thresholds")
long_threshold_L2 = input.int( 0, title = "Risingcondition Thrshold Long L2", group = "Thresholds")
short_threshold_L2 = input.int( 0, title = "Falingcondition Threshold Short L2", group = "Thresholds")
long_threshold_L3 = input.int(-50, title = "Thrshold Long L3", group = "Thresholds")
short_threshold_L3 = input.int(100, title = "Threshold Short L3", group = "Thresholds")
bool showalerts_L1 = input.bool(true, 'Show alerts L1',group='Alerts', inline='1a')
bool showalerts_L2 = input.bool(true, 'Show alerts L2',group='Alerts', inline='1a')
bool showalerts_L3 = input.bool(true, 'Show alerts L3',group='Alerts', inline='1a')
risingcolor = input.color(color.green, "Rising Color", group = "Colors")
falingcolor = input.color(color.yellow, "Falin Color", group = "Colors")
defaultcolor = input.color(color.gray, "Default Color", group = "Colors")
SlowLineUpColor = input.color(color.blue, "Rising Signal Line Color", group = "Colors")
SlowLineDownColor = input.color(color.red, "Faling Signal Line Color", group = "Colors")
[macdLine, signalLine, histLine] = request.security(symbol = syminfo.tickerid, timeframe = timeframe, expression = ta.macd(close, 12, 26, 9))
histLine := ta.sma(histLine, 10)
//{ Color Condition
//MACD Line Color
risingcondition = macdLine > macdLine[1] and macdLine < signalLine
falingcondition = macdLine < macdLine[1] and macdLine > signalLine
colorCondition = risingcondition ? color.new(risingcolor, 0) :
(falingcondition ? color.new(falingcolor, 0) : defaultcolor)
//Signal Line Color
var color SignalLineColor = na
SignalLineColor := ta.crossover(macdLine, signalLine) ? SlowLineUpColor : ta.crossunder(macdLine, signalLine) ? SlowLineDownColor : SignalLineColor
//Hist Line Color
var color histcolor = na
a = color.rgb(76, 177, 79)
a_1 = color.rgb(181, 233, 183)
b = color.red
b_1 = color.rgb(250, 143, 143)
histcolor := histLine > histLine[1] and histLine < 0 ? b_1 : histLine < 0 ? b : histLine < histLine[1] and histLine > 0 ? a_1 : histLine > 0 ? a : histcolor
//}
// Creating the Alarms Start {
//************************************************************************************************************
bool a_L1_long = false
bool a_L1_short = false
bool a_L2_long = false
bool a_L2_short = false
bool a_L3_long = false
bool a_L3_short = false
// Long Condition
if macdLine < long_threshold_L1
a_L1_long := ta.crossover(macdLine, signalLine)
if macdLine < long_threshold_L2
a_L2_long := risingcondition ? true : false
if macdLine < long_threshold_L3
a_L3_long := histLine > histLine[1] and histLine[1] > histLine[2] and histLine < 0 ? true : false
// Short Condition
if macdLine > short_threshold_L1
a_L1_short := ta.crossunder(macdLine, signalLine)
if macdLine > short_threshold_L2
a_L2_short := falingcondition ? true : false
if macdLine > short_threshold_L3
a_L3_short := histLine < histLine[1] and histLine[1] < histLine[2] and histLine > 0 ? true : false
alertcondition(a_L3_long, 'MACDD -50 Crossover', 'MACDD -50 Crossover')
alertcondition(a_L2_long, 'MACDD -20 Crossover', 'MACDD -20 Crossover')
alertcondition(a_L1_long, 'MACDD 0 Crossover', 'MACDD 0 Crossover')
alertcondition(a_L1_short, 'MACDD 0 Crossunder', 'MACDD 0 Crossunder')
alertcondition(a_L3_short, 'MACDD 50 Crossunder', 'MACDD 50 Crossunder')
alertcondition(a_L3_short, 'MACDD 100 Crossunder', 'MACDD 100 Crossunder')
//}
plot(macdLine, color=colorCondition, linewidth = 2)
plot(signalLine, color=SignalLineColor, linewidth = 2)
plot(histLine, color=histcolor, linewidth = 4 ,style=plot.style_histogram)
// Plotting of Alarms {
plotshape(showalerts_L1? a_L1_long: na ,
style=shape.triangleup, location=location.bottom, color=color.new(#ebff00, 60), size=size.tiny)
plotshape(showalerts_L1? a_L1_short: na ,
style=shape.triangledown, location=location.top, color=color.new(#ebff00, 60), size=size.tiny)
plotshape(showalerts_L2? a_L2_long: na ,
style=shape.triangleup, location=location.bottom, color=color.new(#00ff20, 30), size=size.small)
plotshape(showalerts_L2? a_L2_short: na ,
style=shape.triangledown, location=location.top, color=color.new(#ff0000, 30), size=size.small)
plotshape(showalerts_L3? a_L3_long: na ,
style=shape.diamond, location=location.bottom, color=color.new(#00ff20, 0), size=size.small)
plotshape(showalerts_L3? a_L3_short: na ,
style=shape.diamond, location=location.top, color=color.new(#ff0000, 0), size=size.small)
//}
// SIGNAL Daisychain {
string inputtype = input.string('NoInput' , title='Signal Type', group='Multibit signal config', options=['MultiBit', 'MultiBit_pass', 'NoInput'], tooltip='Multibit Daisychain with and without infusing\nMutlibit is the Signal-Type used in my Backtestsystem',inline='3a')
float inputModule = input(title='Select L1 Indicator Signal', group='Multibit signal config', defval=close, inline='3a')
Signal_Channel_Line1= input.int(-1, 'L1 long channel', minval=-1, maxval=15,group='Multibit',inline='1a')
Signal_Channel_Line2= input.int(-1, 'L1 short channel', minval=-1, maxval=15,group='Multibit',inline='1a')
Signal_Channel_Line3= input.int(-1, 'L2 long channel', minval=-1, maxval=15,group='Multibit',inline='1b')
Signal_Channel_Line4= input.int(-1, 'L2 short channel', minval=-1, maxval=15,group='Multibit',inline='1b')
Signal_Channel_Line5= input.int(-1, 'L3 long channel', minval=-1, maxval=15,group='Multibit',inline='1c')
Signal_Channel_Line6= input.int(-1, 'L3 short channel', minval=-1, maxval=15,group='Multibit',inline='1c')
//*********** MULTIBIT Implementation
import djmad/Signal_transcoder_library/7 as transcode
bool [] Multibit = array.new<bool>(16,false)
if inputtype == 'MultiBit' or inputtype == 'MultiBit_pass'
Multibit := transcode._16bit_decode(inputModule)
if inputtype != 'MultiBit_pass'
transcode.f_infuse_signal(Signal_Channel_Line1, a_L1_long, Signal_Channel_Line2, a_L1_short, Signal_Channel_Line3, a_L2_long, Signal_Channel_Line4, a_L2_short, Signal_Channel_Line5, a_L3_long, Signal_Channel_Line6, a_L3_short, Multibit)
float plot_output = transcode._16bit_encode(Multibit)
plot(plot_output,title='MultiBit Signal',display=display.none)
|
PlurexSignalStrategy | https://www.tradingview.com/script/2niooM0e-PlurexSignalStrategy/ | plurex | https://www.tradingview.com/u/plurex/ | 13 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © plurex
//@version=5
// @description Provides functions that wrap the built in TradingView strategy functions so you can seemlessly integrate with Plurex Signal automation.
// NOTE: Be sure to:
// - set your strategy default_qty_value to the default entry percentage of your signal
// - set your strategy default_qty_type to strategy.percent_of_equity
// - set your strategy pyramiding to some value greater than 1 or something appropriate to your strategy in order to have multiple entries.
library("PlurexSignalStrategy")
import plurex/PlurexSignalCore/1 as psc
SHORT_SL_ID = "s-sl"
LONG_SL_ID = "l-sl"
// @function Open a new long entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param stop Optional, trigger price for the stop loss. See strategy.exit documentation
// @param takeProfit Optional, trigger price for the take profit. See strategy.exit documentation
// @param budgetPercentage Optional, The percentage of budget to use in the entry.
// @param priceLimit Optional, The worst price to accept for the entry.
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export long(string secret, float stop = na, float takeProfit = na, float budgetPercentage = na, float priceLimit = na, string marketOverride = na) =>
longID = str.format("l{0}", time(""))
message = psc.long(secret = secret, budgetPercentage = budgetPercentage, priceLimit = priceLimit, marketOverride = marketOverride)
strategy.cancel(SHORT_SL_ID)
strategy.entry(longID, strategy.long, qty=budgetPercentage, limit = priceLimit, alert_message=message)
if( not na(stop) or not na(takeProfit))
strategy.exit(LONG_SL_ID, stop = stop, limit = takeProfit, alert_message = psc.closeLongs(secret=secret, marketOverride=marketOverride))
// @function Open a new long entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
// @param secret The secret for your Signal on plurex
// @param trail_offset See strategy.exit documentation
// @param trail_price See strategy.exit documentation
// @param trail_points See strategy.exit documentation
// @param budgetPercentage Optional, The percentage of budget to use in the entry.
// @param priceLimit Optional, The worst price to accept for the entry.
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export longAndTrailingStopLoss(string secret, float trail_offset, float trail_price = na, float trail_points = na, float budgetPercentage = na, float priceLimit = na, string marketOverride = na) =>
longID = str.format("l{0}", time(""))
message = psc.long(secret = secret, budgetPercentage = budgetPercentage, priceLimit = priceLimit, marketOverride = marketOverride)
strategy.cancel(SHORT_SL_ID)
strategy.entry(longID, strategy.long, qty=budgetPercentage, limit = priceLimit, alert_message=message)
strategy.exit(LONG_SL_ID, trail_offset = trail_offset, trail_price = trail_price, trail_points = trail_points, alert_message = psc.closeLongs(secret=secret, marketOverride=marketOverride))
// @function Open a new short entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param stop Optional, trigger price for the stop loss. See strategy.exit documentation
// @param takeProfit Optional, trigger price for the take profit. See strategy.exit documentation
// @param budgetPercentage Optional, The percentage of budget to use in the entry.
// @param priceLimit Optional, The worst price to accept for the entry.
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export short(string secret, float stop = na, float takeProfit = na, float budgetPercentage = na, float priceLimit = na, string marketOverride = na) =>
shortID = str.format("s{0}", time(""))
message = psc.short(secret = secret, budgetPercentage = budgetPercentage, priceLimit = priceLimit, marketOverride = marketOverride)
strategy.cancel(LONG_SL_ID)
strategy.entry(shortID, strategy.short, qty=budgetPercentage, limit = priceLimit, alert_message=message)
if( not na(stop) or not na(takeProfit))
strategy.exit(SHORT_SL_ID, stop = stop, limit = takeProfit, alert_message = psc.closeShorts(secret=secret, marketOverride=marketOverride))
// @function Open a new short entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
// @param secret The secret for your Signal on plurex
// @param trail_offset See strategy.exit documentation
// @param trail_price See strategy.exit documentation
// @param trail_points See strategy.exit documentation
// @param budgetPercentage Optional, The percentage of budget to use in the entry.
// @param priceLimit Optional, The worst price to accept for the entry.
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export shortAndTrailingStopLoss(string secret, float trail_offset, float trail_price = na, float trail_points = na, float budgetPercentage = na, float priceLimit = na, string marketOverride = na) =>
shortID = str.format("s{0}", time(""))
message = psc.short(secret = secret, budgetPercentage = budgetPercentage, priceLimit = priceLimit, marketOverride = marketOverride)
strategy.cancel(LONG_SL_ID)
strategy.entry(shortID, strategy.short, qty=budgetPercentage, limit = priceLimit, alert_message=message)
strategy.exit(SHORT_SL_ID, trail_offset = trail_offset, trail_price = trail_price, trail_points = trail_points, alert_message = psc.closeShorts(secret=secret, marketOverride=marketOverride))
// @function Close all positions. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeAll(string secret, string marketOverride = na) =>
strategy.close_all(alert_message=psc.closeAll(secret=secret, marketOverride = marketOverride))
// @function close all longs. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeLongs(string secret, string marketOverride = na) =>
size = strategy.opentrades.size(strategy.opentrades-1)
if size > 0
strategy.close_all(alert_message=psc.closeLongs(secret=secret, marketOverride=marketOverride))
// @function close all shorts. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeShorts(string secret, string marketOverride = na) =>
size = strategy.opentrades.size(strategy.opentrades-1)
if size < 0
strategy.close_all(alert_message=psc.closeShorts(secret=secret, marketOverride=marketOverride))
// @function Close last long entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeLastLong(string secret, string marketOverride = na) =>
openTrades = strategy.opentrades
lastID = ""
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "l")
lastID := tradeID
lastID := tradeID
if lastID != ""
strategy.close(lastID, alert_message=psc.closeLastLong(secret=secret, marketOverride=marketOverride))
// @function Close last short entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeLastShort(string secret, string marketOverride = na) =>
openTrades = strategy.opentrades
lastID = ""
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "s")
lastID := tradeID
lastID := tradeID
if lastID != ""
strategy.close(lastID, alert_message=psc.closeLastShort(secret=secret, marketOverride=marketOverride))
// @function Close first long entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeFirstLong(string secret, string marketOverride = na) =>
openTrades = strategy.opentrades
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "l")
strategy.close(tradeID, alert_message=psc.closeFirstLong(secret=secret, marketOverride=marketOverride))
break
// @function Close first short entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeFirstShort(string secret, string marketOverride = na) =>
openTrades = strategy.opentrades
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "s")
strategy.close(tradeID, alert_message=psc.closeFirstShort(secret=secret, marketOverride=marketOverride))
break
// The secret unique to your Plurex Signal. needed for each message sent to the webhook
secret = "foo"
earliestBackTestMillis = 1663545605000 // Change this to suit your chart
if time > earliestBackTestMillis
indexDecimal = bar_index % 56
switch indexDecimal
0 => closeAll(secret)
2 => long(secret)
4 => long(secret)
6 => closeLastLong(secret)
8 => closeLastLong(secret)
10 => long(secret)
12 => long(secret)
14 => closeFirstLong(secret)
16 => closeFirstLong(secret)
18 => short(secret)
20 => short(secret)
22 => closeLastShort(secret)
24 => closeLastShort(secret)
26 => short(secret)
28 => short(secret)
30 => closeFirstShort(secret)
32 => closeFirstShort(secret)
34 => long(secret)
36 => long(secret)
38 => closeLongs(secret)
40 => short(secret)
42 => short(secret)
44 => closeShorts(secret)
46 => long(secret)
48 => long(secret)
50 => closeAll(secret)
52 => short(secret)
54 => short(secret)
plot(strategy.position_size) |
BinaryInsertionSort | https://www.tradingview.com/script/ZudhdK9O-BinaryInsertionSort/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 23 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
// @description Library containing functions which can help create sorted array based on binary insertion sort.
// This sorting will be quicker than array.sort function if the sorting needs to be done on every bar and the size of the array is comparatively big.
library("BinaryInsertionSort")
binary_sort(sortedArray, item, order)=>
startIndex = 0
endIndex = array.size(sortedArray)
while(startIndex < endIndex)
midIndex = int((startIndex+endIndex)/2)
if(item*order > array.get(sortedArray, midIndex)*order)
startIndex := midIndex+1
else
endIndex := midIndex
array.insert(sortedArray, startIndex, item)
startIndex
// @function binary insertion sort - inserts item into sorted array while maintaining sort order
// @param sortedArray array<float|int> which is assumed to be sorted in the requested order
// @param item float|int item which needs to be inserted into sorted array
// @param order Sort order - positive number means ascending order whereas negative number represents descending order
// @returns int index at which the item is inserted into sorted array
export binary_insertion_sort(array<float> sortedArray, float item, int order = 1)=>binary_sort(sortedArray, item, order)
export binary_insertion_sort(array<int> sortedArray, int item, int order = 1)=>binary_sort(sortedArray, item, order)
// @function adds the sort index of new item added to sorted array and also updates existing sort indices.
// @param sortIndices array<int> containing sort indices of an array.
// @param newItemIndex sort index of new item added to sorted array
// @returns void
export update_sort_indices(array<int> sortIndices, int newItemIndex)=>
for [index, sortItem] in sortIndices
if(sortItem >= newItemIndex)
array.set(sortIndices, index, sortItem+1)
array.push(sortIndices, newItemIndex)
array_of_series(sortedArray, valueArray, item, order)=>
array.push(valueArray, item)
sortIndex = binary_insertion_sort(sortedArray, item, order)
[valueArray, sortedArray, sortIndex]
// @function Converts series into array and sorted array.
// @param item float|int series
// @param order Sort order - positive number means ascending order whereas negative number represents descending order
// @returns [valueArray, sortedArray, sortIndex of last item]
export get_array_of_series(float item, int order = 1)=>
var array<float> sortedArray = array.new<float>()
var array<float> valueArray = array.new<float>()
array_of_series(sortedArray, valueArray, item, order)
export get_array_of_series(int item, int order = 1)=>
var array<int> sortedArray = array.new<int>()
var array<int> valueArray = array.new<int>()
array_of_series(sortedArray, valueArray, item, order)
sorted_arrays(item, order)=>
var array<int> sortIndices = array.new<int>()
[valueArray, sortedArray, sortIndex] = get_array_of_series(item, order)
update_sort_indices(sortIndices, sortIndex)
[valueArray, sortedArray, sortIndices]
// @function Converts series into array and sorted array. Also calculates the sort order of the value array
// @param item float|int series
// @param order Sort order - positive number means ascending order whereas negative number represents descending order
// @returns [valueArray, sortedArray, sortIndices]
export get_sorted_arrays(float item, int order = 1)=>sorted_arrays(item, order)
export get_sorted_arrays(int item, int order = 1)=>sorted_arrays(item, order)
|
ZigZag | https://www.tradingview.com/script/bzIRuGXC-ZigZag/ | TradingView | https://www.tradingview.com/u/TradingView/ | 301 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingView
//@version=5
library("ZigZag", overlay = true)
// ZigZag Library
// v7, 2023.10.26
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
//#region ———————————————————— Library types and functions
// @type Provides calculation and display properties to `ZigZag` objects.
// @field devThreshold The minimum percentage deviation from a point before the `ZigZag` changes direction.
// @field depth The number of bars required for pivot detection.
// @field lineColor The color of each line drawn by the `ZigZag`.
// @field extendLast A condition allowing a line to connect the most recent pivot with the current close.
// @field displayReversalPrice A condition to display the pivot price in the pivot label.
// @field displayCumulativeVolume A condition to display the cumulative volume for the pivot segment in the pivot label.
// @field displayReversalPriceChange A condition to display the change in price or percent from the previous pivot in each pivot label.
// @field differencePriceMode The reversal change display mode. Options are "Absolute" or "Percent".
// @field draw A condition to determine whether the `ZigZag` displays lines and labels.
// @field allowZigZagOnOneBar A condition to allow double pivots i.e., when a large bar makes both a pivot high and a pivot low.
export type Settings
float devThreshold = 5.0
int depth = 10
color lineColor = #2962FF
bool extendLast = true
bool displayReversalPrice = true
bool displayCumulativeVolume = true
bool displayReversalPriceChange = true
string differencePriceMode = "Absolute"
bool draw = true
bool allowZigZagOnOneBar = true
// @type Represents a significant level that indicates directional movement or potential support and resistance.
// @field ln A `line` object connecting the `start` and `end` chart points.
// @field lb A `label` object to display pivot values.
// @field isHigh A condition to determine whether the pivot is a pivot high.
// @field vol The cumulative volume for the pivot segment.
// @field start A `chart.point` object representing the coordinates of the previous point.
// @field end A `chart.point` object representing the coordinate of the current point.
export type Pivot
line ln
label lb
bool isHigh
float vol
chart.point start
chart.point end
// @type An object to maintain a Zig Zag's settings, pivots, and cumulative volume.
// @field settings A `Settings` object to provide calculation and display properties.
// @field pivots An array of `Pivot` objects.
// @field sumVol The volume sum for the current `Pivot` object's line segment.
// @field extend A `Pivot` object used to project a line from the last pivot point to the current bar.
export type ZigZag
Settings settings
array<Pivot> pivots
float sumVol = 0
Pivot extend = na
// @function Identifies a pivot point when the `src` has not reached beyond its value
// from `length` bars ago. Finds pivot highs when `isHigh` is `true`, and
// finds pivot lows otherwise.
// @param src (series float) The data series to calculate the pivot value from.
// @param length (series float) The length in bars required for pivot confirmation.
// @param isHigh (simple bool) Determines whether the pivot is a pivot high or pivot low.
// @returns (chart.point) A `chart.point` object when a pivot is found, `na` otherwise.
findPivotPoint(series float src, series float length, simple bool isHigh) =>
float pivotPrice = nz(src[length])
if length == 0
chart.point.new(time, bar_index, pivotPrice)
else if length * 2 <= bar_index
bool isFound = true
for i = 0 to math.abs(length - 1)
if (isHigh and src[i] > pivotPrice) or (not isHigh and src[i] < pivotPrice)
isFound := false
break
for i = length + 1 to 2 * length
if (isHigh and src[i] >= pivotPrice) or (not isHigh and src[i] <= pivotPrice)
isFound := false
break
if isFound
chart.point.new(time[length], bar_index[length], pivotPrice)
// @function Calculates the deviation percentage between the `price` and the `basePrice`.
// @param basePrice (series float) The start price.
// @param price (series float) The end price.
// @returns (float) The signed deviation percentage.
calcDev(series float basePrice, series float price) =>
float result = 100 * (price - basePrice) / math.abs(basePrice)
// @function Calculates the difference between the `start` and `end` point as a price or
// percentage difference and converts its value to a "string".
// @param start (series float) The start price.
// @param end (series float) The end price.
// @param settings (series Settings) A `Settings` object.
// @returns (string) A "string" representation of the difference between points.
priceRotationDiff(series float start, series float end, Settings settings) =>
float diff = end - start
string sign = math.sign(diff) > 0 ? "+" : ""
string diffStr = switch settings.differencePriceMode
"Absolute" => str.tostring(diff, format.mintick)
=> str.tostring(diff * 100 / start, format.percent)
string result = str.format("({0}{1})", sign, diffStr)
// @function Creates a "string" containing the price, cumulative volume, and change in price
// for the pivot.
// @param start (series float) The start price.
// @param end (series float) The end price.
// @param vol (series float) The pivot's cumulative volume.
// @param settings (series Settings) A `Settings` object.
// @returns (string) A "string" to display in pivot labels.
priceRotationAggregate(series float start, series float end, series float vol, Settings settings) =>
string str = ""
if settings.displayReversalPrice
str += str.tostring(end, format.mintick) + " "
if settings.displayReversalPriceChange
str += priceRotationDiff(start, end, settings) + " "
if settings.displayCumulativeVolume
str += "\n" + str.tostring(vol, format.volume)
str
// @function Creates a label with coordinates from the `point` if the `settings` display
// properties allow it.
// @param isHigh (series bool) The condition to determine the label's color and location.
// @param point (series chart.point) A `chart.point` object.
// @param settings (series Settings) A `Settings` object.
// @returns (void) The function does not return a value.
makePivotLabel(series bool isHigh, chart.point point, Settings settings) =>
if settings.displayReversalPrice or settings.displayReversalPriceChange or settings.displayCumulativeVolume
[yloc, txtColor] = switch
isHigh => [yloc.abovebar, color.green]
=> [yloc.belowbar, color.red]
label.new(point, style = label.style_none, xloc = xloc.bar_time, yloc = yloc, textcolor = txtColor)
// @function Updates a `Pivot` object's properties, including its `end` point,
// cumulative volume, label text, and label and line drawing locations.
// Can be used as a function or method.
// @param this (series Pivot) The `Pivot` object to update.
// @param end (series chart.point) A new `chart.point` for the `end` field of the `Pivot`.
// @param vol (series float) The cumulative volume of the `Pivot`.
// @param settings (series Settings) A `Settings` object.
// @returns (void) The function does not return a value.
method updatePivot(Pivot this, chart.point end, float vol, Settings settings) =>
this.end := end
this.vol := vol
if not na(this.lb)
this.lb.set_point(this.end)
this.lb.set_text(priceRotationAggregate(this.start.price, this.end.price, this.vol, settings))
this.ln.set_second_point(this.end)
// @function Creates a new `Pivot` object, and assigns a line and label if the `draw` field
// of the `settings` allows it.
// @param start (series chart.point) A `chart.point` for the `start` of the `Pivot`.
// @param end (series chart.point) A `chart.point` for the `end` of the `Pivot`.
// @param vol (series float) The cumulative volume of the `Pivot`.
// @param isHigh (series bool) Specifies whether the `Pivot` represents a pivot high or pivot low.
// @param settings (series settings) A `Settings` object.
// @returns (Pivot) The new `Pivot` object.
newPivot(
series chart.point start, series chart.point end, series float vol, series bool isHigh, series Settings settings
) =>
Pivot p = Pivot.new(na, na, isHigh, vol, start, end)
if settings.draw
p.ln := line.new(start, end, xloc = xloc.bar_time, color = settings.lineColor, width = 2)
p.lb := makePivotLabel(isHigh, end, settings)
p.updatePivot(end, vol, settings)
p
// @function Deletes the `line` and `label` objects assigned to the `ln` and `lb` fields in
// a `Pivot` object.
// Can be used as a function or method.
// @param this (series Pivot) The `Pivot` object to modify.
// @returns (void) The function does not return a value.
method delete(series Pivot this) =>
if not na(this.ln)
this.ln.delete()
if not na(this.lb)
this.lb.delete()
// @function Determines whether the `price` of the `point` reaches past the `price` of the
// `end` chart point of a `Pivot` object.
// Can be used as a function or method.
// @param this (series Pivot) A `Pivot` object.
// @param point (series chart.point) A `chart.point` object.
// @returns (bool) `true` if the `price` of the `point` reaches past that of the `end`
// in the `Pivot` object, `false` otherwise.
method isMorePrice(series Pivot this, series chart.point point) =>
int m = this.isHigh ? 1 : -1
bool result = point.price * m > this.end.price * m
// @function Returns the last `Pivot` object from a `ZigZag` instance if it contains at
// least one `Pivot`, and `na` otherwise.
// Can be used as a function or method.
// @param this (series ZigZag) A `ZigZag` object.
// @returns (Pivot) The last `Pivot` object in the `ZigZag`.
export method lastPivot(series ZigZag this) =>
int numberOfPivots = this.pivots.size()
Pivot result = numberOfPivots > 0 ? this.pivots.get(numberOfPivots - 1) : na
// @function Updates the fields of the last `Pivot` in a `ZigZag` object and sets the
// `sumVol` of the `ZigZag` to 0.
// Can be used as a function or method.
// @param this (series ZigZag) A `ZigZag` object.
// @param point (series chart.point) The `chart.point` for the `start` of the last `Pivot`.
// @returns (void) The function does not return a value.
method updateLastPivot(series ZigZag this, series chart.point point) =>
Pivot lastPivot = this.lastPivot()
if this.pivots.size() == 1
lastPivot.start := point
if this.settings.draw
lastPivot.ln.set_first_point(point)
lastPivot.updatePivot(point, lastPivot.vol + this.sumVol, this.settings)
this.sumVol := 0
// @function Pushes a new `Pivot` object into the `pivots` array of a `ZigZag` instance.
// Can be used as a function or method.
// @param this (series ZigZag) A `ZigZag` object.
// @param new (series Pivot) The new `Pivot` to add to the ZigZag.
// @returns (void) The function does not return a value.
method newPivotFound(series ZigZag this, series Pivot new) =>
this.pivots.push(new)
this.sumVol := 0
// @function Determines if a new pivot point is detected or if the properties of the
// last `Pivot` in the `ZigZag` need to be updated by comparing the `end` of the
// last `Pivot` to a new `point`. Updates the `ZigZag` and returns `true` if
// either condition occurs.
// Can be used as a function or method.
// @param this (series ZigZag) A `ZigZag` object.
// @param isHigh (series bool) Determines whether it checks for a pivot high or pivot low.
// @param point (chart.point) A `chart.point` to compare to the `end` of the last
// `Pivot` in the `ZigZag`.
// @returns (bool) `true` if it updates the last `Pivot` or adds a new `Pivot` to
// the `ZigZag`, `false` otherwise.
method newPivotPointFound(series ZigZag this, simple bool isHigh, series chart.point point) =>
bool result = false
Pivot lastPivot = this.lastPivot()
if not na(lastPivot)
if lastPivot.isHigh == isHigh
if lastPivot.isMorePrice(point)
this.updateLastPivot(point)
result := true
else
float dev = calcDev(lastPivot.end.price, point.price)
if (not lastPivot.isHigh and dev >= this.settings.devThreshold) or
(lastPivot.isHigh and dev <= -1 * this.settings.devThreshold)
newPivotFound(this, newPivot(lastPivot.end, point, this.sumVol, isHigh, this.settings))
result := true
else
this.newPivotFound(newPivot(point, point, this.sumVol, isHigh, this.settings))
result := true
result
// @function Tries to find a new pivot point for the `ZigZag` instance. Updates the
// `ZigZag` and returns `true` when it registers a detected pivot.
// Can be used as a function or method.
// @param this (series ZigZag) A `ZigZag` object.
// @param src (series float) The data series to calculate the pivot value from.
// @param isHigh (simple bool) Determines whether it checks for a pivot high or pivot low.
// @param depth (series int) The number of bars to search for new pivots.
// @param registerPivot (series bool) A condition that determines whether or not to register a pivot.
// @returns (bool) `true` when a new pivot point is registered and the `ZigZag` is updated,
// `false` otherwise.
method tryFindPivot(
series ZigZag this, series float src, simple bool isHigh, series int depth, series bool registerPivot = true
) =>
chart.point point = findPivotPoint(src, depth, isHigh)
bool result = not na(point) and registerPivot ? this.newPivotPointFound(isHigh, point) : false
// @function Updates a `ZigZag` objects with new pivots, volume, lines, and labels.
// NOTE: This function must be called on every bar for accurate calculations.
// Can be used as a function or method.
// @param this (series ZigZag) A `ZigZag` object.
// @returns (bool) `true` when a new pivot point is registered and the `ZigZag` is updated,
// `false` otherwise.
export method update(series ZigZag this) =>
int depth = math.max(2, math.floor(this.settings.depth / 2))
this.sumVol += nz(volume[depth])
bool somethingChanged = this.tryFindPivot(high, true, depth)
somethingChanged := this.tryFindPivot(
low, false, depth, this.settings.allowZigZagOnOneBar or not somethingChanged
) or somethingChanged
Pivot lastPivot = this.lastPivot()
float remVol = math.sum(volume, math.max(depth, 1))
if this.settings.extendLast and barstate.islast and not na(lastPivot)
bool isHigh = not lastPivot.isHigh
float curSeries = isHigh ? high : low
chart.point end = chart.point.new(time, bar_index, curSeries)
if na(this.extend) or somethingChanged
if not na(this.extend)
this.extend.delete()
this.extend := newPivot(lastPivot.end, end, this.sumVol, isHigh, this.settings)
this.extend.updatePivot(end, this.sumVol + remVol, this.settings)
somethingChanged
// @function Instantiates a new `ZigZag` object with optional `settings`.
// If no `settings` are provided, creates a `ZigZag` object with default settings.
// @param settings (series Settings) A `Settings` object.
// @returns (ZigZag) A new `ZigZag` instance.
export newInstance(series Settings settings = na) =>
ZigZag result = ZigZag.new(na(settings) ? Settings.new() : settings, array.new<Pivot>())
//#endregion
//#region ———————————————————— Example Code
// @variable The deviation percentage from the last local high or low required to form a new Zig Zag point.
float deviationInput = input.float(5.0, "Deviation (%)", minval = 0.00001, maxval = 100.0)
// @variable The number of bars in the pivot calculation.
int depthInput = input.int(10, "Depth", minval = 1)
// @variable The color of the Zig Zag's lines.
color lineColorInput = input.color(#2962FF, "Line Color")
// @variable If `true`, the Zig Zag will also display a line connecting the last known pivot to the current `close`.
bool extendInput = input.bool(true, "Extend to Last Bar")
// @variable If `true`, the pivot labels will display their price values.
bool showPriceInput = input.bool(true, "Display Reversal Price")
// @variable If `true`, each pivot label will display the volume accumulated since the previous pivot.
bool showVolInput = input.bool(true, "Display Cumulative Volume")
// @variable If `true`, each pivot label will display the change in price from the previous pivot.
bool showChgInput = input.bool(true, "Display Reversal Price Change", inline = "Price Rev")
// @variable Controls whether the labels show price changes as raw values or percentages when `showChgInput` is `true`.
string priceDiffInput = input.string("Absolute", "", options = ["Absolute", "Percent"], inline = "Price Rev")
// @variable A `Settings` instance for `ZigZag` creation.
var Settings settings =
Settings.new(
deviationInput, depthInput,
lineColorInput, extendInput,
showPriceInput, showVolInput,
showChgInput, priceDiffInput
)
// @variable A `ZigZag` object created using the `settings`.
var ZigZag zigZag = newInstance(settings)
// Update the `zigZag` on every bar.
zigZag.update()
//#endregion
|
WelcomeUDT | https://www.tradingview.com/script/xKa2uR6d-WelcomeUDT/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description Library for Welcome UDT
library('WelcomeUDT')
//#region ———————————————————— Library functions
// @type Initialize type values
// @field bar X position for label
// @field price Y position for label
// @field phrase Text for label
// @field bg Color for label
// @field variable Boolean for enable new line and delete line
export type Settings
int bar
float price
string phrase
color bg = color.blue
bool variable = true
// @function Print out label
// @param Settings types
// @returns Label object
export printLabel(Settings setup) =>
if setup.variable
var label lab = na
label.delete(lab)
lab := label.new(setup.bar, setup.price, setup.phrase, color = setup.bg)
else
label.new(setup.bar, setup.price, setup.phrase, color = setup.bg)
//#endregion
//#region ———————————————————— Example Code
// Inputs for Settings
priceInput = input.float( 0, minval = 0)
phraseInput = input.text_area('Welcome UDT')
colorInput = input.color( color.blue)
variableInput = input.bool( true)
// Types for Settings
Settings setup = Settings.new(bar_index[0], priceInput, phraseInput, colorInput, variableInput)
// Alternative way to write types
// Settings setup = Settings.new(
// bar = bar_index[0],
// price = priceInput,
// phrase = phraseInput,
// bg = colorInput,
// variable = variableInput)
printLabel(setup)
//#endregion |
json | https://www.tradingview.com/script/q1UyKVar-json/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 23 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kaigouthro
//@version=5
//============================================
// @description Json dictionary functions, create, format, and write.
library("json")
// new (name , kind ) -> object
// defines a new obj. each obbj can be :
// - _OBJECT to contain sub obj's
// - _ARRAY for json array (can contain obbjs or items)
// - unspecified: automatic int/float/bool/srting
// set (_item , _obj , _key ) -> set item to parent obj
// add (_obj , _key , _item ) -> from object, add an item
// set (_child , _Guardians ) -> set child object to a parent
// add (_Guardians , _child ) -> to _parentt object, add a child
// write (object ) -> convert any obbject at any level tto json
//============================================
//============================================
// Imports, User Defined Type
// Helpers, Formatters
//#region
//============================================
import kaigouthro/into/2
import kaigouthro/font/5
import kaigouthro/catchChecks/1 as chk
// @type obj Object storage container/item
// @field key (string ) item name
// @field kind (string ) item's type(for writing)
// @field item (string ) item (converted to string)
// @field keys (string[] ) keys of all sub-items and objects
// @field items (obj[] ) nested obj off individual subitems (for later...)
export type obj
string key = ''
string kind = ''
string item = ''
string[] keys
obj [] items
bool flag
// @function create multitype object
// @pparam _name (string) Name off object
// @pparam _kind (string) Preset Type (_OBJECT if a container item)
// @returns object container/item 2-in-1
export new(string _name, string _kind = '') =>
var key = _name
var kind = _kind
var item = ''
var keys = array.new <string> ( 0 )
var items = array.new <obj> ( 0 )
obj = obj.new ( key,kind,item,keys,items)
obj
// @variable Type/Kind key for storage/writing
var _OBJECT = 'object'
// @variable Type/Kind key for storage/writing
var _STRING = 'string'
// @variable Type/Kind key for storage/writing
var _BOOL = 'bool'
// @variable Type/Kind key for storage/writing
var _INT = 'integer'
// @variable Type/Kind key for storage/writing
var _FLOAT = 'float'
// @variable Type/Kind key for storage/writing
var _ARRAY = 'array'
// @variable Type/Kind key for storage/writing
var _TOPLEVEL= 'parentOBJ'
//@helper shortcuts
f(x) => into.f ( x )
i(x) => into.i ( x )
b(x) => into.b ( x )
s(x) => into.s ( x )
//@helpers for index / adding / setting / compacted
_pushnew ( obj _o ,_k,_sz ) => array.push(_o.keys , _k ), array.push(_o.items , new(_k)),_sz
_getkey ( obj _o ,_k ) => _sz= array.size(_o.keys),_idx = array.includes(_o.keys,_k) ? (array.indexof ( _o.keys , _k )) : na, na(_idx) ? _pushnew(_o,_k,_sz): _idx
_doadd ( obj _o , string _k , obj _i ,string _t) => _id = _getkey (_o,_k) ,_i.kind:=_t,array.set ( _o.items , _id , _i )
_doadd ( obj _o , string _k , _i ) => _id = _getkey (_o,_k),_obj = array.get ( _o.items , _id ) ,_obj.item := s(_i),_obj.kind := chk.typeIs(_i,false),array.set ( _o.items , _id , _obj ) ,_obj
_rem (obj _o,_idx) => array.remove (_o.keys, _idx), array.remove(_o.items,_idx)
_array ( obj _o ,_k,string[] _keys, obj[] _items ) =>
_id = _getkey (_o,_k) ,_obj = array.get ( _o.items , _id )
_arraysize = array.size(_obj.items)
_keysize = math.min(array.size ( _keys),_arraysize)
if _arraysize >0
for _n = 0 to array.size (_obj.keys )
_oldkey = array.shift(_obj.keys)
_olditem = array.shift(_obj.items)
if array.includes(_keys,_oldkey)
array.push(_obj.keys, _oldkey)
array.push(_obj.items, _olditem)
for [_n, item] in _items
key = array.get(_keys,_n)
_doadd(_obj,key,item,item.kind)
array.set ( _o.items , _id , _obj)
_array ( obj _o ,_k,string[] _keys, _items, string _type ) =>
_id = _getkey (_o,_k) ,_obj = array.get ( _o.items , _id )
_arraysize = array.size(_obj.items)
_keysize = math.min(array.size ( _keys),_arraysize)
_obj.kind :=_type != _ARRAY ? _ARRAY : _OBJECT
if _arraysize >0
for _n = 0 to array.size (_obj.keys )
_oldkey = array.shift(_obj.keys)
_olditem = array.shift(_obj.items)
if array.includes(_keys,_oldkey)
array.push(_obj.keys, _oldkey)
array.push(_obj.items, _olditem)
for [_n, item] in _items
key = array.get(_keys,_n)
_itm = _doadd(_obj,key,item)
_itm.key := key
array.set ( _o.items , _id , _obj)
//============================================
//#endregion
//#region
//============================================
// @function Formats JSON for presentable output
// @param _input (string) json string
// @returns cleaned string
export format (string _input) =>
data = _input
for _char in array.from('\n','\t')
data := str.replace_all(data ,_char,'')
_str = '', inc = 0, gu = false
_length = str.length(data)
for i = 0 to _length -1
s = str.substring(data,i,i+1)
_str += switch
not gu and str.contains(',' ,s) => s + font.indent(inc)
not gu and str.contains('{[' ,s) => inc += 1 ,s + font.indent(inc)
not gu and str.contains('}]' ,s) => inc -= 1, font.indent(inc) + s
str.contains ('\'"',s) => gu := gu ? false : true , s
=> s
_str
// // @function Write object to string Object
// // @param _object (obj)
// // @param _key (array<(string/int)> )/(string)
// // @param _itemname (string)
export write ( obj _item ) =>
item = obj.copy(_item)
item.flag := true
stack = array.new<obj>(1, item )
out = "{"
while array.size ( stack ) > 0
current = array.get(stack, 0)
_type = current.kind
_l = _type == _OBJECT ? '{' : _type == _ARRAY ? '[' : ''
_r = _type == _OBJECT ? '}' : _type == _ARRAY ? ']' : ''
size = array.size(current.items)
strlen = str.length(out)
if size == 0 and current.flag
comma = str.contains('{[',str.substring(out,strlen-1)) ? '' : ','
out += comma + '"'+current.key+'":'+ (_type == _STRING ? '"'+current.item+'"': current.item)
current.flag := false
array.shift(stack)
else
if current.flag
if size > 0
comma = str.contains('{[',str.substring(out,strlen-1)) ? '' : ','
out += comma + '"' + current.key +'":'+ (current.kind == _OBJECT ? '{' : _type == _ARRAY ? '[' : '' )
for i = size- 1 to 0
itm = array.get(current.items,i)
itm.flag := true
array.unshift(stack, itm)
current.flag := false
else
out += '' + _r
array.shift(stack)
out += '}'
// @function Remove an object (Wipes it and all children out)
// @param obj ( obj multi-type-item object)
// @param key ( string/int)
export remove (obj obj, string key ) => array.includes(obj.keys,key)?_rem(obj,array.indexof(obj.keys,key)):na
export remove (obj obj, int key ) => array.includes(obj.keys,s(key))?_rem(obj,array.indexof(obj.keys,s(key))):na
// @function Add any or array of any => int/float/string/bool/object
// @param _obj ( obj multi-type-item object)
// @param _key ( string/int)
// @param _item ( int / float / bool / string )
// @param _items array of ( int / float / bool / string )
export add ( obj _obj , int _key , int _item ) => _doadd ( _obj ,s(_key) , _item )
export add ( obj _obj , int _key , float _item ) => _doadd ( _obj ,s(_key) , _item )
export add ( obj _obj , int _key , bool _item ) => _doadd ( _obj ,s(_key) , _item )
export add ( obj _obj , int _key , string _item ) => _doadd ( _obj ,s(_key) , _item )
export add ( obj _obj , string _key , int _item ) => _doadd ( _obj , _key , _item )
export add ( obj _obj , string _key , float _item ) => _doadd ( _obj , _key , _item )
export add ( obj _obj , string _key , bool _item ) => _doadd ( _obj , _key , _item )
export add ( obj _obj , string _key , string _item ) => _doadd ( _obj , _key , _item )
export add ( obj _obj , string _key , string[] _keys, obj [] _items ) => _array ( _obj , _key, _keys, _items)
export add ( obj _obj , string _key , string[] _keys, string [] _items ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export add ( obj _obj , string _key , string[] _keys, int [] _items ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export add ( obj _obj , string _key , string[] _keys, bool [] _items ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export add ( obj _obj , string _key , string[] _keys, float [] _items ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export add ( obj _obj , int _key , string[] _keys, obj [] _items ) => _array ( _obj , s(_key), _keys, _items)
export add ( obj _obj , int _key , string[] _keys, string [] _items ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
export add ( obj _obj , int _key , string[] _keys, int [] _items ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
export add ( obj _obj , int _key , string[] _keys, bool [] _items ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
export add ( obj _obj , int _key , string[] _keys, float [] _items ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
// @function Add a object as a subobject to storage
// @param _Guardians to insert obj into
// @param _child to be inserted
export add ( obj _Guardians , obj _child ) => _doadd ( _Guardians , _child.key , _child,_child.kind)
// @function Set item to an object (here in preparation for future Pine methods)
// @param _obj ( obj multi-type-item object)
// @param _key ( string/int)
// @param _item ( int / float / bool / string )
// @param _items array of ( int / float / bool / string )
export set ( int _item , obj _obj , int _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( float _item , obj _obj , int _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( bool _item , obj _obj , int _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( string _item , obj _obj , int _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( int _item , obj _obj , string _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( float _item , obj _obj , string _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( bool _item , obj _obj , string _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( string _item , obj _obj , string _key ) => _doadd ( _obj ,s(_key) , _item )
export set ( obj [] _items, string[] _keys, obj _obj , string _key ) => _array ( _obj , _key, _keys, _items)
export set ( string [] _items, string[] _keys, obj _obj , string _key ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export set ( int [] _items, string[] _keys, obj _obj , string _key ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export set ( bool [] _items, string[] _keys, obj _obj , string _key ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export set ( float [] _items, string[] _keys, obj _obj , string _key ) => _array ( _obj , _key, _keys, _items,chk.typeIs(_items,false))
export set ( obj [] _items, string[] _keys, obj _obj , int _key ) => _array ( _obj , s(_key), _keys, _items)
export set ( string [] _items, string[] _keys, obj _obj , int _key ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
export set ( int [] _items, string[] _keys, obj _obj , int _key ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
export set ( bool [] _items, string[] _keys, obj _obj , int _key ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
export set ( float [] _items, string[] _keys, obj _obj , int _key ) => _array ( _obj , s(_key), _keys, _items,chk.typeIs(_items,false))
// @function Add a solitary object as a subobject to storage
// @param _child to be inserted
// @param _Guardians to insert obj into
export set ( obj _child , obj _Guardians ) => _doadd ( _Guardians , _child.key , _child, _child.kind)
//============================================
//#endregion
//============================================
// testing / demo
var _GrandParent = new ( 'GrandParent' , _OBJECT )
var _Guardians = new ( 'Childcare' , _OBJECT )
var _child = new ( 'Sibling' , _OBJECT )
var _stepparent = new ( 'StepParent' , _OBJECT )
var _child2 = new ( 'StepSibling' , _OBJECT )
var _floatkeys = array.from('capricious','abaft','pizzas','borrow','cause','fuel','hallowed','abrupt','finger','rely','head','valuable')
var _floatarr = array.from(3.96,9.63,9.06,7.47,4.38,7.91,3.29,2.86,9.11,7.20,4.01,4.34)
// test label
var label[] lbls = array.new<label>(4)
refresh(_s,i)=>array.set(lbls,i,label.new(last_bar_index - 10*i , 0, font.uni(_s,16),
xloc.bar_index, yloc.price,#a4e5e8e7, label.style_label_upper_left,
textcolor = #0d0227, textalign = text.align_left, size=size.normal))
if barstate.islast
// Generic Example for Alerts, Create your owm!
// set items, using strings as keys, these are just examples.
// (for a future method, add/set are same/swapped order)
add ( _GrandParent , 'Mom' , 'Susan' )
add ( _GrandParent , 'Dad' , 'John' )
add ( _Guardians , 'Babysitter' , 'Bianca' )
add ( _child , 'Daughter' , 'Suzie' )
add ( _child , 'Son' , 'Johnny' )
// family assembled
add ( _GrandParent , _Guardians )
add ( _Guardians , _child )
refresh( ' _Guardian \n\n' + format(write (_Guardians )), 2)
// some assorted testing.. and overwwrite on add
add ( _GrandParent , 'parent level item1' , 'an item' )
add ( _GrandParent , 'parent level item2' , 'an item' )
add ( _GrandParent , 'Overwrwite test' , "true" )
add ( _GrandParent , 'Overwrwite test' , 2 )
add ( _GrandParent , 'Overwrwite test' , 3 )
add ( _GrandParent , 'Overwrwite test' , 4 )
add ( _GrandParent , 'Overwrwite test' , 1234 )
refresh( '_GrandParent \n\n ' + format(write (_GrandParent )), 3)
// Susan Didn't Invest wisely..
remove ( _Guardians , 'Babysitter')
add ( _GrandParent , _stepparent )
add ( _stepparent , _child2 )
add ( _child2 , 'StepBrother', 'Jonathon' )
refresh( '_GrandParent \n\n' + format(write (_GrandParent )), 1)
add ( _GrandParent , 'Mom' , 'Bianca' )
// check that it adds after the fast and still works
add ( _child2 , 'All the Toys??', _floatkeys , _floatarr )
refresh( '_GrandParent \n\n' + format(write (_GrandParent )), 0) |
Color | https://www.tradingview.com/script/h81hHWm5-Color/ | Electrified | https://www.tradingview.com/u/Electrified/ | 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/
// © Electrified (electrifiedtrading)
// @version=5
// @description Utility for working with colors.
library('Color', true)
//////////////////////////////////////////////////
// @function Determines if two colors are equal.
// @param a The first color to compare.
// @param b The second color to compare.
// @returns True if both colors are equal, false otherwise.
export method equals(color a, color b) =>
isAna = na(a)
isBna = na(b)
if isAna
isBna
else if isBna
false
else if color.r(a) != color.r(b)
false
else if color.g(a) != color.g(b)
false
else if color.b(a) != color.b(b)
false
else
color.t(a) == color.t(b)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Calculates the luminosity of a color using the given red, green, and blue values.
// @param r The red value of the color, from 0 to 255.
// @param g The green value of the color, from 0 to 255.
// @param b The blue value of the color, from 0 to 255.
// @returns The luminosity of the color, a float between 0 and 1.
export luminosity(float r, float g, float b) =>
(0.299 * r + 0.587 * g + 0.114 * b) / 255
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Calculates the luminosity of a color using its red, green, and blue values.
// @param c The color to calculate the luminosity for.
// @returns The luminosity of the color, a float between 0 and 1.
export method luminosity(color c) =>
na(c) ? na : luminosity(color.r(c), color.g(c), color.b(c))
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Returns a color that is either black or white depending on the luminosity of the given background color. If the background color is na, returns gray.
// @param bgColor The background color to determine the contrast color for.
// @param keepNa When true and the value of bgColor is na the return value will be na; otherwise the if bgColor is na the return will be gray.
// @returns A color that provides high contrast with the given background color.
export method getContrastColor(color bgColor, bool keepNa = false) =>
(na(bgColor) ? true : color.t(bgColor)==100) ? (keepNa ? na : color.rgb(128, 128, 128)) :
luminosity(bgColor) > 0.5 ? color.rgb(0, 0, 0) : color.rgb(255, 255, 255)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Converts a color value to a string in the "rgbt(r,g,b,t)" format.
// @param color The color to convert.
// @returns The color value as a string.
export method tostringRGBT(color color) =>
na(color) ? "na" : (
"rgbt("+
str.tostring(color.r(color))+","+
str.tostring(color.g(color))+","+
str.tostring(color.b(color))+","+
str.tostring(color.t(color))+")")
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Converts an integer between 0 and 15 to its hex equivalent character.
// @param n The integer value to convert.
export toHexChar(int n) =>
if na(n)
runtime.error("Cannot convert na to hex.")
if n < 0
runtime.error("Value of (n) must be at least zero. Actual: "+str.tostring(n))
if n > 15
runtime.error("Value of (n) must be less than 16. Actual: "+str.tostring(n))
// Convert the integer to a hex character
switch n
10 => 'A'
11 => 'B'
12 => 'C'
13 => 'D'
14 => 'E'
15 => 'F'
=> str.tostring(n)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Converts an integer from 0 to 255 to a 2-character hex string.
// @param n The integer value to convert.
export byteToHex(float n) =>
if na(n)
runtime.error("Cannot convert na to hex.")
if n < 0
runtime.error("Value of (n) must be at least zero. Actual: "+str.tostring(n))
if n > 255
runtime.error("Value of (n) must be less than 255. Actual: "+str.tostring(n))
// Calculate the hex value for the tens place
tens = math.floor(n / 16)
// Calculate the hex value for the ones place
ones = math.floor(n % 16)
// Convert the tens and ones values to hex characters
tens_char = toHexChar(tens)
ones_char = toHexChar(ones)
// Return the hex string
tens_char + ones_char
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Converts a color to its hex string (#FFFFFF).
// @param n The color to convert.
// @returns The six digit hex string.
export method toHex(color color) =>
na(color) ? "na" : "#" + byteToHex(color.r(color)) + byteToHex(color.r(color)) + byteToHex(color.r(color))
//////////////////////////////////////////////////
//////////////////////////////////////////////////
brighten(float c, float ratio) =>
ratio > 0 ?
c + (255 - c) * ratio :
c * (1 + ratio)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Proportionally adjusts the RGB values of a color. A value of positive (+) 100 will result in white. A value of negative (-) 100 will result in black.
// @param c The color to adjust.
// @param value The percent amount (-100 to +100) to adjust the color by. Values less than -100 or greater than +100 will be clamped.
// @returns The resultant color.
export method brighten(color c, float value) =>
if na(c) or nz(value, 0) == 0
c
else
t = color.t(c)
if value >= 100
color.rgb(255, 255, 255, t)
else if value <= -100
color.rgb(0, 0, 0, t)
else
ratio = value / 100
r = brighten(color.r(c), ratio)
g = brighten(color.g(c), ratio)
b = brighten(color.b(c), ratio)
color.rgb(r,g,b,t)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Proportionally adjusts the RGB values of a color. A value of positive (+) 100 will result in black. A value of negative (-) 100 will result in white.
// @param c The color to adjust.
// @param value The percent amount (-100 to +100) to adjust the color by. Values less than -100 or greater than +100 will be clamped.
// @returns The resultant color.
export method darken(color c, float value) =>
brighten(c, -nz(value))
////////////////////////////////////////////////// |
TableBuilder | https://www.tradingview.com/script/D8RKHenM-TableBuilder/ | Electrified | https://www.tradingview.com/u/Electrified/ | 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/
// © Electrified (electrifiedtrading)
// @version=5
// @description Utility for creating tables.
library('TableBuilder', true)
import Electrified/Color/8
//// Color Utility ///////////////////////////////
getFgColor(color fgColor, color bgColor) =>
na(fgColor) ? Color.getContrastColor(bgColor) : fgColor
//////////////////////////////////////////////////
//// types ///////////////////////////////////////
//////////////////////////////////////////////////
// Represents the font properties of a text element in the table.
export type TextStyle
color color // The color of the font.
string size // The size of the font.
string family // The font family.
// Represents the border or frame properties of a line element in the table.
export type LineStyle
color color // The color of the line.
int width // The width of the line.
// Represents the alignment properties of a cell in the table.
export type CellAlign
string horizontal // The horizontal alignment of the cell contents.
string vertical // The vertical alignment of the cell contents.
// Represents the style properties of a cell in the table.
export type CellStyle
color bgColor // The background color of the cell.
int width // The width of the cell.
int height // The height of the cell.
// Represents text displayed by a cell.
export type Cell
string contents // The cell contents.
string tooltip // The cell tooltip.
// Represents the style properties of the table.
export type TableStyle
string position // The position of the table on the chart.
color bgColor // The background color of the table.
LineStyle border // The border style of the table.
LineStyle frame // The frame style of the table.
// Represents the resultant size of a PineScript table.
export type TableSize
int columns // The number of columns.
int rows // The number of rows.
// Represents a row of data in the table.
export type Row
Cell[] cells // An array of strings representing the contents of the cells in the row.
int height // The desired height of the row.
string tooltip // The default tooltip for the row.
// The result of initializing a table.
export type Table
table table // The PineScript table created.
TableSize size // The size of the table.
//////////////////////////////////////////////////
// @function Creates a new row with an empty array of cells.
// @param height The height of the row.
// @param tooltip The tooltip of the row.
// @returns A new Row object.
export createRow(int height = na, string tooltip = na) =>
cells = array.new<Cell>()
Row.new(cells, height, tooltip)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Creates a new row with an array of cells containing the given contents.
// @param contents An array of strings representing the cell contents.
// @param height The height of the row.
// @param tooltip The tooltip of the row.
// @returns A new Row object.
export createRow(string[] contents, int height = na, string tooltip = na) =>
width = array.size(contents)
cells = array.new<Cell>(width)
for i = 0 to width==0 ? na : width - 1
c = array.get(contents, i)
array.set(cells, i, Cell.new(c, tooltip))
Row.new(cells, height, tooltip)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Adds a new cell with the given contents to the array of cells.
// @param cells An array of cells.
// @param contents The contents of the new cell.
// @param tooltip The tooltip of the new cell.
// @returns The new Cell object.
export addCell(Cell[] cells, string contents, string tooltip = na) =>
c = Cell.new(contents, tooltip)
array.push(cells, c)
c
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Adds a new cell with the given contents to the row.
// @param row The row to add the cell to.
// @param contents The contents of the new cell.
// @param tooltip The tooltip of the new cell.
// @returns The new Cell object.
export addCell(Row row, string contents, string tooltip = na) =>
addCell(row.cells, contents, tooltip)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Adds a new cell with the given floating point number contents to the array of cells.
// @param cells An array of cells.
// @param contents The contents of the new cell, a floating point number.
// @param format The format string for the floating point number.
// @param tooltip The tooltip of the new cell.
// @returns The new Cell object.
export addCell(Cell[] cells, float contents, string format = na, string tooltip = na) =>
c = Cell.new(na(contents) ? na : str.tostring(contents, format), tooltip)
array.push(cells, c)
c
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Adds a new cell with the given floating point number contents to the row.
// @param row The row to add the cell to.
// @param contents The contents of the new cell, a floating point number.
// @param format The format string for the floating point number.
// @param tooltip The tooltip of the new cell.
// @returns The new Cell object.
export addCell(Row row, float contents, string format = na, string tooltip = na) =>
addCell(row.cells, contents, format, tooltip)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Adds a new cell with the given integer contents to the array of cells.
// @param cells An array of cells.
// @param contents The contents of the new cell, an integer.
// @param format The format string for the integer.
// @param tooltip The tooltip of the new cell.
// @returns The new Cell object.
export addCell(Cell[] cells, int contents, string format = na, string tooltip = na) =>
c = Cell.new(na(contents) ? na : str.tostring(contents, format), tooltip)
array.push(cells, c)
c
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Adds a new cell with the given integer contents to the row.
// @param row The row to add the cell to.
// @param contents The contents of the new cell, an integer.
// @param format The format string for the integer.
// @param tooltip The tooltip of the new cell.
// @returns The new Cell object.
export addCell(Row row, int contents, string format = na, string tooltip = na) =>
addCell(row.cells, contents, format, tooltip)
//////////////////////////////////////////////////
// @function Adds a new row to the array of rows using the given array of cells.
// @param rows An array of rows.
// @param cells The array of cells to use for the new row.
// @param height The height of the new row.
// @param tooltip The tooltip of the new row.
// @returns The new Row object.
export addRow(Row[] rows, Cell[] cells = na, int height = na, string tooltip = na) =>
c = na(cells) ? array.new<Cell>() : cells
r = Row.new(c, height, tooltip)
array.push(rows, r)
r
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Adds a new row to the array of rows using the given array of cell contents.
// @param rows An array of rows.
// @param contents The array of cell contents to use for the new row.
// @param height The height of the new row.
// @param tooltip The tooltip of the new row.
// @returns The new Row object.
export addRow(Row[] rows, string[] contents, int height = na, string tooltip = na) =>
r = createRow(contents, height, tooltip)
array.push(rows, r)
r
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Updates a PineScript table with the style properties of the given TableStyle.
// @param t The PineScript table to update.
// @param style The TableStyle containing the style properties to apply.
export updateStyle(table t, TableStyle style) =>
if not na(style)
// Set the background color of the table.
if not na(style.bgColor)
table.set_bgcolor(t, style.bgColor)
// Set the border properties of the table.
if not na(style.border)
if not na(style.border.color)
table.set_border_color(t, style.border.color)
if not na(style.border.width)
table.set_border_width(t, style.border.width)
// Set the frame properties of the table.
if not na(style.frame)
if not na(style.frame.color)
table.set_frame_color(t, style.frame.color)
if not na(style.frame.width)
table.set_frame_width(t, style.frame.width)
// Set the position of the table.
if not na(style.position)
table.set_position(t, style.position)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Updates a row of cells in a table with the given cell content.
// @param t The table to update.
// @param row The index of the row to update.
// @param cells The array of cells to set in the row.
// @param tooltip The optional default tooltip to use if the cell's value is na.
export updateRow(table t, int row, Cell[] cells, string tooltip = na) =>
cellCount = array.size(cells)
for c = 0 to cellCount==0 ? na : cellCount - 1
cell = array.get(cells, c)
if not na(cell)
if not na(cell.contents)
table.cell_set_text(t, c, row, cell.contents)
tt = na(cell.tooltip) ? tooltip : cell.tooltip
if not na(tt)
table.cell_set_tooltip(t, c, row, tt)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Updates a row of cells in a table with the given cell content.
// @param t The table to update.
// @param row The index of the row to update.
// @param cells The array of cell content to set in the row.
// @param tooltip The optional default tooltip to use if the cell's value is na.
export updateRow(table t, int row, string[] cells, string tooltip = na) =>
cellCount = array.size(cells)
for c = 0 to cellCount==0 ? na : cellCount - 1
cell = array.get(cells, c)
if not na(cell)
table.cell_set_text(t, c, row, cell)
if not na(tooltip)
table.cell_set_tooltip(t, c, row, tooltip)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Initializes a new PineScript table with the given data rows and table style.
// @param rows An array of DataRows to populate the table with.
// @param style The TableStyle to apply to the table.
// @returns The new PineScript table.
export initialize(Row[] rows, TableStyle style) =>
// Calculate the number of rows and columns in the table
numRows = array.size(rows)
numColumns = 0
for row in rows
numColumns := math.max(numColumns, array.size(row.cells))
// Create the table
t = table.new(style.position, math.max(numColumns, 1), math.max(numRows, 1))
// Apply the table style
updateStyle(t, style)
color fgColor = na(style.bgColor) ? color.gray : Color.getContrastColor(style.bgColor)
// Iterate through the rows and cells and set their styles
for r = 0 to numRows == 0 ? na : numRows - 1
row = array.get(rows, r)
cells = row.cells
cellCount = array.size(cells)
for c = 0 to cellCount == 0 ? na : cellCount - 1
cell = array.get(cells, c)
// Set the cell text and tooltips
if not na(cell.contents)
table.cell_set_text(t, c, r, cell.contents)
tooltip = na(cell.tooltip) ? row.tooltip : cell.tooltip
if not na(tooltip)
table.cell_set_tooltip(t, c, r, tooltip)
// Set the cell text color based on the table background color
table.cell_set_text_color(t, c, r, fgColor)
Table.new(t, TableSize.new(numColumns, numRows))
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Initializes a new PineScript table with the given data rows and table style.
// @param rows An array of Rows to populate the table with.
// @param position The position of the table within the chart.
// @param bgColor The optional background color for the table.
// @param border The optional border style for the table.
// @param frame The optional frame style for the table.
// @returns The new PineScript table.
export initialize(Row[] rows, string position, color bgColor, LineStyle border = na, LineStyle frame = na) =>
initialize(rows, TableStyle.new(position, bgColor, border, frame))
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Initializes a new PineScript table with the given data rows and table style.
// @param rows An array of Rows to populate the table with.
// @param position The position of the table within the chart.
// @param border The optional border style for the table.
// @param frame The optional frame style for the table.
// @returns The new PineScript table.
export initialize(Row[] rows, string position, LineStyle border = na, LineStyle frame = na) =>
initialize(rows, TableStyle.new(position, na, border, frame))
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of the table with the given cell and text styles, and cell alignment.
// @param t The table to style.
// @param firstCol The index of the first column in the range.
// @param lastCol The index of the last column in the range.
// @param firstRow The index of the first row in the range.
// @param lastRow The index of the last row in the range.
// @param cellStyle The cell style to apply.
// @param textStyle The text style to apply.
// @param align The cell alignment to apply.
export style(table t, int firstCol, int lastCol, int firstRow, int lastRow, CellStyle cellStyle = na, TextStyle textStyle = na, CellAlign align = na) =>
// capture the colors
color bgColor = na(cellStyle) ? na : (na(cellStyle.bgColor) ? na : cellStyle.bgColor)
color fgColor = getFgColor(na(textStyle) ? na : (na(textStyle.color) ? na : textStyle.color), bgColor)
if firstCol >= 0 and lastCol >= 0 and firstRow >= 0 and lastRow >= 0
// set all the values
for r = firstRow to lastRow
for c = firstCol to lastCol
if not na(bgColor)
table.cell_set_bgcolor(t, c, r, bgColor)
if not na(fgColor)
table.cell_set_text_color(t, c, r, fgColor)
if not na(textStyle)
if not na(textStyle.size)
table.cell_set_text_size(t, c, r, textStyle.size)
if not na(textStyle.family)
table.cell_set_text_font_family(t, c, r, textStyle.family)
if not na(align)
if not na(align.horizontal)
table.cell_set_text_halign(t, c, r, align.horizontal)
if not na(align.vertical)
table.cell_set_text_valign(t, c, r, align.vertical)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles all the cells in the table.
// @param t The Table to style.
// @param cellStyle The cell style to apply.
// @param textStyle The text style to apply.
// @param align The cell alignment to apply.
export style(Table t, CellStyle cellStyle = na, TextStyle textStyle = na, CellAlign align = na) =>
style(t.table, 0, t.size.columns-1, 0, t.size.rows-1, cellStyle, textStyle, align)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of the table with the given background color and foreground color.
// @param t The table to style.
// @param firstCol The index of the first column in the range.
// @param lastCol The index of the last column in the range.
// @param firstRow The index of the first row in the range.
// @param lastRow The index of the last row in the range.
// @param bgColor The background color to apply.
export style(table t, int firstCol, int lastCol, int firstRow, int lastRow, color bgColor, color fgColor) =>
fgc = getFgColor(fgColor, bgColor)
for r = firstRow to lastRow
for c = firstCol to lastCol
if not na(bgColor)
table.cell_set_bgcolor(t, c, r, bgColor)
if not na(fgc)
table.cell_set_text_color(t, c, r, fgc)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of the table with the given background color while automatically chosing a foreground color.
// @param t The table to style.
// @param firstCol The index of the first column in the range.
// @param lastCol The index of the last column in the range.
// @param firstRow The index of the first row in the range.
// @param lastRow The index of the last row in the range.
// @param bgColor The background color to apply.
export style(table t, int firstCol, int lastCol, int firstRow, int lastRow, color bgColor) =>
style(t, firstCol, lastCol, firstRow, lastRow, bgColor, na)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of columns of the table with the given cell and text styles, and cell alignment.
// @param t The table to style.
// @param first The index of the first column in the range.
// @param last The index of the last column in the range.
// @param cellStyle The cell style to apply.
// @param textStyle The text style to apply.
// @param align The cell alignment to apply.
export styleColumns(Table t, int first, int last, CellStyle cellStyle = na, TextStyle textStyle = na, CellAlign align = na) =>
style(t.table, first, last, 0, t.size.rows-1, cellStyle, textStyle, align)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given column of the table with the given cell and text styles, and cell alignment.
// @param t The table to style.
// @param col The index of the column.
// @param cellStyle The cell style to apply.
// @param textStyle The text style to apply.
// @param align The cell alignment to apply.
export styleColumn(Table t, int col, CellStyle cellStyle = na, TextStyle textStyle = na, CellAlign align = na) =>
styleColumns(t, col, col, cellStyle, textStyle, align)
//////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// @function Styles the cells in the given range of rows of the table with the given cell and text styles, and cell alignment.
// @param t The table to style.
// @param first The index of the first row in the range.
// @param last The index of the last row in the range.
// @param cellStyle The cell style to apply.
// @param textStyle The text style to apply.
// @param align The cell alignment to apply.
export styleRows(Table t, int first, int last, CellStyle cellStyle = na, TextStyle textStyle = na, CellAlign align = na) =>
style(t.table, 0, t.size.columns-1, first, last, cellStyle, textStyle, align)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given row of the table with the given cell and text styles, and cell alignment
// @param t The table to style.
// @param col The index of the row.
// @param cellStyle The cell style to apply.
// @param textStyle The text style to apply.
// @param align The cell alignment to apply.
export styleRow(Table t, int col, CellStyle cellStyle = na, TextStyle textStyle = na, CellAlign align = na) =>
styleRows(t, col, col, cellStyle, textStyle, align)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of columns of the table with the given background color and foreground color.
// @param t The table to style.
// @param first The index of the first column in the range.
// @param last The index of the last column in the range.
// @param bgColor The background color to apply.
// @param fgColor The foreground color to apply.
export styleColumns(Table t, int first, int last, color bgColor, color fgColor) =>
style(t.table, first, last, 0, t.size.rows-1, bgColor, fgColor)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given column of the table with the given background color and foreground color.
// @param t The table to style.
// @param col The index of the column.
// @param bgColor The background color to apply.
// @param fgColor The foreground color to apply.
export styleColumn(Table t, int col, color bgColor, color fgColor) =>
styleColumns(t, col, col, bgColor, fgColor)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of rows of the table with the given background color and foreground color.
// @param t The table to style.
// @param first The index of the first row in the range.
// @param last The index of the last row in the range.
// @param bgColor The background color to apply.
// @param fgColor The foreground color to apply.
export styleRows(Table t, int first, int last, color bgColor, color fgColor) =>
style(t.table, 0, t.size.columns-1, first, last, bgColor, fgColor)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given row of the table with the given background color and foreground color.
// @param t The table to style.
// @param col The index of the row.
// @param bgColor The background color to apply.
// @param fgColor The foreground color to apply.
export styleRow(Table t, int col, color bgColor, color fgColor) =>
styleRows(t, col, col, bgColor, fgColor)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of columns of the table with the given background color while automatically chosing a foreground color.
// @param t The table to style.
// @param first The index of the first column in the range.
// @param last The index of the last column in the range.
// @param bgColor The background color to apply.
export styleColumns(Table t, int first, int last, color bgColor) =>
style(t.table, first, last, 0, t.size.rows-1, bgColor, na)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given column of the table with the given background color while automatically chosing a foreground color.
// @param t The table to style.
// @param col The index of the column.
// @param bgColor The background color to apply.
export styleColumn(Table t, int col, color bgColor) =>
styleColumns(t, col, col, bgColor)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of rows of the table with the given background color while automatically chosing a foreground color.
// @param t The table to style.
// @param first The index of the first row in the range.
// @param last The index of the last row in the range.
// @param bgColor The background color to apply.
export styleRows(Table t, int first, int last, color bgColor) =>
style(t.table, 0, t.size.columns-1, first, last, bgColor, na)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given row of the table with the given background color while automatically chosing a foreground color.
// @param t The table to style.
// @param col The index of the row.
// @param bgColor The background color to apply.
export styleRow(Table t, int col, color bgColor) =>
styleRows(t, col, col, bgColor)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @function Styles the cells in the given range of rows of the table with the given background color while automatically chosing a foreground color.
// @param t The table to style.
// @param first The index of the first row in the range.
// @param last The index of the last row in the range.
// @param bgColor The background color to apply.
export styleRows(Table t, color[] rowColors) =>
last = array.size(rowColors) - 1
for row = 0 to last==-1 ? na : last
c = array.get(rowColors, row)
styleRow(t, row, c)
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//// Demo ////////////////////////////////////////
//////////////////////////////////////////////////
// Setup the rows.
rows = array.new<Row>()
// Add the header
header = addRow(rows)
addCell(header, "Index")
addCell(header, "Value")
addCell(header, "Percent")
// First create the data.
for i = 1 to 10
row = addRow(rows, tooltip = "Row " + str.tostring(i))
addCell(row, i)
addCell(row, i*2000)
addCell(row, i*10, format.percent)
tbl = initialize(rows, position.top_right,
frame = LineStyle.new(color.white, 1))
// Align the cells to the right.
style(tbl, align = CellAlign.new(text.align_right))
// Style the columnS.
styleColumn(tbl, 1, color.blue)
styleColumn(tbl, 2, #0022AA, #FF22AA)
// Style the header row.
styleRow(tbl, 0, color.white)
|
FrizBug | https://www.tradingview.com/script/wqHOinCt-FrizBug/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 30 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FFriZz
//@version=5
// .--. .--.
// _ ` \ / ` _
// ██████╗ ███████╗ `\.===. \.^./ .===./`
// ███████╗███████╗███████ ██ ███████ ███████╗ ██╔══██╗██╔════╝ \/`"`\/
// ██╔════▒██╔════▒██╔══██╗██░╚════██░╚════██░ ██║ ██║█████╗ , | | ,
// █████╗ ░█████╗ ░██████╔╝██░ ███╔═╝ ███╔═╝ ██║ ██║██╔══╝ / `\|;-.-'|/` \
// ██╔══╝ ░██╔══╝ ░██╔══██╗██░██╔══╝ ██╔══╝ ██████╔╝███████╗ / |::\ | \
// ██░░ ░██░░ ░██░░ ██░██░███████╗███████╗ ╚═════╝ ╚══════╝ .-' ,-'`|:::; |`'-, '-.
// ╚═╝░ ░╚═╝░ ░╚═╝░ ╚═╝╚═╝╚══════╝╚══════╝ | |::::\| |
// --- All in One --- | |::::;| |
// -- Debugger -- | \::::// |
// | `.://' | ███████╗██████╗
// .' `. ██╔════╝██╔══██╗
// _,' `,_ █████╗ ██████╔╝
// ██╔══╝ ██╔══██╗
// By @FFriZz | @frizlabz ███████╗██║ ██║
// ╚══════╝╚═╝ ╚═╝
export type any // for docstrings
string any
// @function
//
//![FrizLabz](https://cdn.discordapp.com/attachments/993257747430772841/1086326365499949076/546666666.gif)
//---
//# **FrizBug Docs**
//---
//```
//method str(any input) => string
//```
// Converts all types to respective `string` form
// **Parameters**
// - `input` - (any) required
//>
//**`Returns`**
//string of the input
//***
//```
//method init(string console='table', int UTC=na) => array<string>
//```
// init console array
// **Parameters**
// - `UTC` - (integer) representing the time zone offset from UTC in hours. A positive value means the time zone is ahead of UTC (e.g. UTC+3),
// while a negative value means the time zone is behind UTC (e.g. UTC-5). The default value is -6.
// - `console` - (string) indicating the type of console to output data to. Valid options are 'table', 'label', 'box', and 'tool'.
// The default value is 'table'.
// - `type` - (string) indicating the type of data to output. Valid options are 'tick' and 'bar'. The default value is 'bar'.
//>
//**`Returns`**
//Console stirng[]
//---
//```
// update(array<string> console1=na,array<string> console2=na,array<string> console3=na
//| color bg_color=#0000007d,color text_color=#00ff00,color border_color=#00ff00) => Void
//```
// The update function updates the given consoles with the latest input in their respective buffers.
// It also checks for the type of console and updates the label, table, box, or tooltip accordingly.
// If a console is not provided or is empty, it is skipped.
// **Parameters**
// - `console1` - (string) An array of strings representing the console to be updated.
// - `console2` - (string) An array of strings representing the console to be updated.
// - `console3` - (string) An array of strings representing the console to be updated.
// - `bg_color` - (color) Color of the bg of the console
// - `text_color` - (color) Color of the text of the console
// - `border_color` - (color) Color of the border of the console
//>
//**`Returns`**
//(void)
//---
//```
// method log(array<string> console,any inp,string data_label="",bool off=false,
//| int loop=na,bool tick=false) => inp param (unchanged)
//```
// log and keep records of log events
// **Parameters**
// - `console` - (array<string>) The console to output the message to.
// - `inp` - (all) The input value to be printed.
// - `data_label` - (string) An optional label to be printed before the input value.
// - `off` - (bool) An optional flag to turn off printing. Default is false.
// - `tick` - (bool) An optional flag to turn off printing. Default is false.
// - `loop` - (int) for the index inside a loop will display the index on the console.
// - `m_rows` - (int) An optional parameter for printing a matrix with a specified number of rows.
// - `m_cols` - (int) An optional parameter for printing a matrix with a specified number of columns.
// - `a_index` - (int) An optional parameter for printing an array with a specified number of indexs.
//>
//**`Returns`**
//the 'inp' param of the function
//---
//```
// method print(any input, string data_label='',bool tick=false, string pos=na,
//| bool off=false, int loop=na, int size=20, string text_size=size.small,
//| color bg_color=#0000007d, color text_color=#00ff00) => input param (unchanged)
//```
// print single variable per bar data to print more than 1 data the data must be called together
// **Parameters**
// - `input` - (all) The input to be printed in the console
// - `data_label` - (string) A label to be printed before each input in the console. Default value is an empty string.
// - `tick` - (bool) A flag indicating whether to print the input immediately [true] or store it in a buffer to be printe
// Default value is false.
// - `pos` - (string) The position of the console on the chart. Valid values are "1", "2", "3", "4", "5", "6", "7", "8", a
// corresponding to the positions in a 3x3 grid. If set to na, the console will be placed in the bott
// Default value is na.
// - `off` - (bool) A flag indicating whether to disable printing [true] or enable it [false]. Default value is false.
// - `size` - (int) The maximum number of lines that can be displayed in the console. Default value is 20.
// - `loop` - (int) for the index inside a loop will display the index on the console.
// - `text_size` - (string) The size of the text in the console. Default value is size.small.
// - `bg_color` - (color) The background color of the console. Default value is #0000007d.
// - `text_color` - (color) The color of the text in the console. Default value is #00ff00.
// - `UTC` - (int) The time zone offset to use when displaying timestamps in the console. Default value is -6.
// - `m_rows` - (int) An optional parameter for printing a matrix with a specified number of rows.
// - `m_cols` - (int) An optional parameter for printing a matrix with a specified number of columns.
// - `a_index` - (int) An optional parameter for printing an array with a specified number of indexs.
//>
//**`Returns`**
//the 'inp' param of the function
export docs() =>
'\n
"Import the Library and call this function as done below
"Use the hover over and hover over the function to see the docs from text editor!
import FFriZz/FrizBug/xx as bug
bug.docs()
'
// Credits:
// @kaigouthro - for the font library
// @RicardoSantos - for the Debugging Concept that I used to make this
// Everything should be pretty simple just use bug.print([tick or console], val, (label if you want)) bug.console([tick or console], val, (label if you want))
// @description Debug Tools | The Pinescript Debugging Tool Kit
library("FrizBug",overlay = true)
import FFriZz/BoxLine_Lib/10 as BL
import FFriZz/FrizLabz_Time_Utility_Methods/4 as TUM
//=================================================================================================================//
// function: str(input)
// - input <type> all - converted to string
// return: string
//=================================================================================================================//
//=================================================================================================================//
// function: init(UTC,console,type)
// - UTC <type> int - representing the time zone offset from UTC in hours. A positive value means the time zone is ahead of UTC e.g. UTC+3),
// while a negative value means the time zone is behind UTC (e.g. UTC-5). The default value is -6.
// - console <type> string - indicating the type of console to output data to. Valid options are 'table', 'label', 'box', and 'tool'.
// The default value is 'table'.
// - type <type> string - indicating the type of data to output. Valid options are 'tick' and 'bar'. The default value is 'bar'.
// return: array<string> out - string array for logging debug data.
//=================================================================================================================//
//=================================================================================================================//
// function: update(console1,console2,console3)
// - console1 <type> array<string> - An array of strings representing the console to be updated.
// - console2 <type> array<string> - An array of strings representing the console to be updated.
// - console3 <type> array<string> - An array of strings representing the console to be updated.
// - bg_color <type> color - An optional paramater for the bg_color. Default is #000000
// - text_color <type> color - An optional paramter for the text_color. Default is #00ff00
// - border_color <type> color - An optional paramter for the border_color. Default is #00ff00
// returns: (void)
//=================================================================================================================//
//=================================================================================================================//
// function log(console,inp,data_label,off,m_rows,a_index_m_cols)
// - console <type> array<string> - The console to output the message to.
// - inp <type> all - The input value to be printed.
// - data_label <type> string - An optional label to be printed before the input value.
// - loop <type> int - Paramater for use within a loop input the index for paramater
// - off <type> bool - An optional flag to turn off printing. Default is false.
// - a_index <type> int - An optional parameter for printing a array with a specified number of indexs.
// - m_rows <type> int - An optional parameter for printing a matrix with a specified number of rows.
// - m_cols <type> int - An optional parameter for printing a matrix with a specified number of columns.
// returns: <all> inp - as when input infto functions (can be used as wrapper function)
//=================================================================================================================//
//=================================================================================================================//
// function print(input,data_label,tick,pos,off,size,text_size,bg_color,text_color,border_color,UTC)
// - input <type> all
// - data_label <type> string - A label to be printed before each input in the console. Default value is an empty string.
// - tick <type> bool - A flag indicating whether to print the input immediately [true] or store
// it in a buffer to be printed later [false]. Default value is false.
// - pos <type> string - The position of the console on the chart. Valid values
// are "1", "2", "3", "4", "5", "6", "7", "8", and "9",
// - loop <type> int - Paramater for use within a loop input the index for paramater
// - off <type> bool - A flag indicating whether to disable printing [true] or enable it [false].
// Default value is false.
// - size <type> int - The maximum number of lines that can be displayed in the console. Default value is 20.
// - text_size <type> string - The size of the text in the console. Default value is size.small.
// - bg_color <type> color - The background color of the console. Default value is #00000075.
// - fg_color <type> color - The color of the text in the console. Default value is #00ff00.
// - UTC <type> int - The time zone offset to use when displaying timestamps in the console. Default value is -6.
// returns: <all> inp - as when input infto functions (can be used as wrapper function)
//=================================================================================================================//
// @function print_check
//-
// **Usage**
// ```
// array<string> inputArray = array.new("1","2","3",.......)
// array<string> result = print_check(inputArray)
// console.log(result) // Output: ["1","2","3",.......]
// ```
// **Info**
// - Check the length of the input array of strings. If its length is greater than 4000 characters, shorten the array by removing elements from the beginning of the array until the length is less than or equal to 4000 characters.\
//
// @param a_bug - (array<string>) Array of strings to be checked for length.
// @returns a_bug - (array<string>) Array of strings that has been shortened if its length is greater than 4000 characters.
//***
print_check(a_bug) =>
if not na(a_bug)
a_size = array.size(a_bug)
str_len = str.length(array.join(a_bug))
while str_len > 4000 and a_size
if str_len < 4000
break
else
array.shift(a_bug)
str_len := str.length(array.join(a_bug))
a_bug
// @function **`init()` - Console init Function**
//**Usage**
//```
//console = init()// init(console,UTC) => console = "table" | UTC = -6
//console.log(close,"close price")
//console.log(time,"bar open time")
//console.update()// Output: will print close price and bar open time to console on chart
//```
//***
//**Params**
// - **console** - (`string`) `Optional` | default = `"table"`, `"label"`, `"box"`, and `"tool"`.
// - **UTC** - (`int`) `Optional` | default = `-6`, UTC timezone offset `(Can find at bottom right of chart)`.
//***
//**Info**
// - Initializes a debug console for logging debug data based on the specified console type and UTC offset.
//
// @param console - (string) Optional. Indicates the type of console to output data to. Valid options are 'table', 'label', 'box', and 'tool'.
// @param UTC - (int) Optional. Represents the time zone offset from UTC in hours. A positive value means the time zone is ahead of UTC (e.g. UTC+3), while a negative value means the time zone is behind UTC (e.g. UTC-5).
// @returns
//- **out** - `(array<string>)` Console for logging debug data.
export method init(string console = 'table') =>
array<string> out = na
varip aip =array.new<string>()
var a = array.new<string>()
str = ''
if str.contains(console,'ool')
out := aip
str := '\nlog.console '
array.unshift(out,str+'[Tooltip] ----------- ')
if str.contains(console,'able')
out := aip
str := '\nlog.console '
array.unshift(out,str+'[Table] -------------------------------------------------------- ')
if str.contains(console,'abel')
out := aip
str := '\nlog.console '
array.unshift(out,str+'[Label] --------------------------------------------------------')
if str.contains(console,'ox')
out := aip
str := '\nlog.console '
array.unshift(out,str+'[Box] -------------------------------------------------------- ')
out
// @function **`str(`function)** | **method`.str()`** - Converts all types to respective `string` form
// \
// **Usage**
// ```
//| num = 1212
//| num2 = 1212
//| out = if str(num2) == num.str()
//| true
//| else
//| false
//|
//| // returns out = true
// ```
// **Params**
// - **input** - (`any type`) `required` | The input matrix of lines to be converted to a string
// ***
// **Info**
// - Will turn **box**, **line**, **label**, **linefill** `(type/array/matrix)` into string representations of their location parameters,
// including text for `labels`
// - Will turn **all other types** `(type/array/matrix)` to the respective string version.
// ***
// @param input - ('any type') required
// @returns `string` of the input
export method str(float input) => str.tostring(input)
export method str(int input) => str.tostring(input)
export method str(bool input) => str.tostring(input)
export method str(string input) => str.tostring(input)
// export method str(any input) => string = any.new(), input
export method str(linefill input) =>
_1 = linefill.get_line1(input)
_2 = linefill.get_line2(input)
[X,Y,XX,YY] = BL.LineXY(_1)
[x,y,xx,yy] = BL.LineXY(_2)
str = str.format('line1 -\nx1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}',
X,Y,XX,YY)
str += str.format('\nline2 -\nx1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}',
x,y,xx,yy)
str
export method str(line input) =>
[x,y,xx,yy] = BL.LineXY(input)
str = str.format('x1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}',
x,y,xx,yy)
str
export method str(box input) =>
[L,T,R,B] = BL.BoxXY(input)
str = str.format('left = {0}\ntop = {1}\nright = {2}\nbottom = {3}',
L,T,R,B)
str
export method str(label input) =>
[x,y,t] = BL.LabelXY(input)
str = str.format('x = {0}\ny = {1}\ntext = {2}',
x,y,t)
str
export method str(array<float> input) => str.tostring(input)
export method str(array<int> input) => str.tostring(input)
export method str(array<bool> input) => str.tostring(input)
export method str(array<string> input) => str.tostring(input)
export method str(linefill[] input) =>
a_str = array.new<string>()
m_str = matrix.new<string>()
a_size = array.size(input)
for i = 0 to a_size > 0 ? a_size-1 : na
lf = array.get(input,i)
_1 = linefill.get_line1(lf)
_2 = linefill.get_line2(lf)
[X,Y,XX,YY] = BL.LineXY(_1)
[x,y,xx,yy] = BL.LineXY(_2)
array.push(a_str,str.format('line1 -\nx1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}',
X,Y,XX,YY) +
str.format('\nline2 -\nx1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}\n <i{4}>',
x,y,xx,yy,i))
matrix.add_col(m_str,0,a_str)
str.tostring(m_str)
export method str(array<line> input) =>
a_str = array.new<string>()
m_str = matrix.new<string>()
a_size = array.size(input)
for i = 0 to a_size > 0 ? a_size-1 : na
line = array.get(input,i)
[x,y,xx,yy] = BL.LineXY(line)
array.push(a_str,str.format('x1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}\n <i{4}>',
x,y,xx,yy,i))
matrix.add_col(m_str,0,a_str)
str.tostring(m_str)
export method str(array<box> input) =>
a_str = array.new<string>()
m_str = matrix.new<string>()
a_size = array.size(input)
for i = 0 to a_size > 0 ? a_size-1 : na
box = array.get(input,i)
[L,T,R,B] = BL.BoxXY(box)
array.push(a_str,str.format('left = {0}\ntop = {1}\nright = {2}\nbottom = {3}\n <i{4}>',
L,T,R,B,i))
matrix.add_col(m_str,0,a_str)
str.tostring(m_str)
export method str(array<label> input) =>
a_str = array.new<string>()
m_str = matrix.new<string>()
a_size = array.size(input)
for i = 0 to a_size > 0 ? a_size-1 : na
label = array.get(input,i)
[x,y,t] = BL.LabelXY(label)
array.push(a_str,str.format('x = {0}\ny = {1}\ntext = {2}\n <i{4}>',
x,y,t,i))
matrix.add_col(m_str,0,a_str)
str.tostring(m_str)
export method str(matrix<float> input) => str.tostring(input,'0.00')
export method str(matrix<int> input) => str.tostring(input,'00')
export method str(matrix<bool> input) => str.tostring(input)
export method str(matrix<string> input) => str.tostring(input)
export method str(matrix<linefill> input) =>
str = ''
m_str = matrix.new<string>()
m_rows = matrix.rows(input)
m_cols = matrix.columns(input)
for r = 0 to m_rows > 0 ? m_rows-1 : na
a_str = array.new<string>()
for c = 0 to m_cols > 0 ? m_cols-1 : na
lf = matrix.get(input,r,c)
_1 = linefill.get_line1(lf)
_2 = linefill.get_line2(lf)
[X,Y,XX,YY] = BL.LineXY(_1)
[x,y,xx,yy] = BL.LineXY(_2)
str += str.format('line 1 -\nx1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}',
X,Y,XX,YY) +
str.format('\nline 2-\nx1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}\n <r{4}|c{5}>',
x,y,xx,yy,r,c)
array.set(a_str,c,str)
matrix.add_row(m_str,r,a_str)
str.tostring(m_str)
export method str(matrix<line> input) =>
str = ''
m_str = matrix.new<string>()
m_rows = matrix.rows(input)
m_cols = matrix.columns(input)
for r = 0 to m_rows > 0 ? m_rows-1 : na
a_str = array.new<string>()
for c = 0 to m_cols > 0 ? m_cols-1 : na
line = matrix.get(input,r,c)
[x,y,xx,yy] = BL.LineXY(line)
str += str.format('x1 = {0}\ny1 = {1}\nx2 = {2}\ny2 = {3}\n <r{4}|c{5}>',
x,y,xx,yy,r,c)
array.set(a_str,c,str)
str := ''
matrix.add_row(m_str,r,a_str)
str.tostring(m_str)
export method str(matrix<box> input) =>
str = ''
m_str = matrix.new<string>()
m_rows = matrix.rows(input)
m_cols = matrix.columns(input)
for r = 0 to m_rows > 0 ? m_rows-1 : na
a_str = array.new<string>()
for c = 0 to m_cols > 0 ? m_cols-1 : na
box = matrix.get(input,r,c)
[L,T,R,B] = BL.BoxXY(box)
str += str.format('left = {0}\ntop = {1}\nright = {2}\nbottom = {3}\n <r{4}|c{5}>',
L,T,R,B,r,c)
array.set(a_str,c,str)
str := ''
matrix.add_row(m_str,r,a_str)
str.tostring(m_str)
export method str(matrix<label> input) =>
str = ''
m_str = matrix.new<string>()
m_rows = matrix.rows(input)
m_cols = matrix.columns(input)
for r = 0 to m_rows > 0 ? m_rows-1 : na
a_str = array.new<string>()
for c = 0 to m_cols > 0 ? m_cols-1 : na
label = matrix.get(input,r,c)
[x,y,t] = BL.LabelXY(label)
str += str.format('x = {0}\ny = {1}\ntext = {2}\n <r{4}|c{5}>',
x,y,t,r,c)
array.set(a_str,c,str)
str := ''
matrix.add_col(m_str,r,a_str)
str.tostring(m_str)
str_check(str) =>
if not na(str)
str_len = str.length(str)
a = str.split(str,' ')
a_size = array.size(a)
while str_len > 4000 and a_size
if str_len < 4000
break
else
array.shift(a)
str_len := str.length(array.join(a))
array.join(a,' ')
LTB(console,C,bg_color=#0000007d,text_color=#00ff00,border_color=#00ff00) =>
var box Box = na,
var label Label = na,
var table Table = na
if C == 'Label'
if na(Label)
Label := TUM.Label(
x = time,
y = high,
txt = array.join(console),
color = bg_color, textcolor = text_color,
style = label.style_label_down, textalign = text.align_left, size = 'normal'
)
else
label.set_text(Label,array.join(console))
label.set_x(Label,time)
if C == 'Box'
if na(Box)
Box := TUM.Box(
left = TUM.bars_back_to_time(-50),
top = high * 100,
right= TUM.bars_back_to_time(-350),
bottom = high,
border_width = 1, border_style = line.style_solid,
bgcolor = bg_color, text_color = text_color, border_color = border_color,
txt = array.join(console), text_halign = text.align_left, text_valign = text.align_bottom, text_size = 'auto'
)
else
box.set_text(Box,array.join(console))
box.set_right(Box,TUM.bars_back_to_time(-50))
box.set_left(Box,TUM.bars_back_to_time(-350))
if C == 'Table' or C == 'Tooltip'
Table := table.new(
position = C == 'Tooltip' ? position.top_right : position.bottom_center,
columns = 1, rows = 1, frame_width = 1,border_width = 1,
bgcolor = bg_color, frame_color = border_color, border_color = border_color
)
if C == 'Tooltip'
array.reverse(console)
table.cell(
Table,
column = 0, row = 0, width = 0,height = 0,
text = C == "Table" ? array.join(console) : 'Debug',
text_color = text_color, bgcolor = bg_color,
text_halign = text.align_left, text_valign = text.align_bottom, text_size = 'small',
tooltip = C == 'Tooltip' ? array.join(console) : na
)
if C == 'Tooltip'
array.reverse(console)
// @function **update(console1, console2, console3, bg_color, text_color, border_color)**
//\
//**Usage**
// ```
//| update(console1, console2)
//| // or
//| console1.update()
//| console2.update()
// ```
// **Info*
// The update() function updates the given consoles with the latest input in their respective buffers. It also checks for
// the type of console and updates the label, table, box, or tooltip accordingly. If a console is not provided or is empty,
// it is skipped.
//
// **Params**
// - **console1** (array<string>) optional - An array of strings representing the console to be updated.
// - **console2** (array<string>) optional - An array of strings representing the console to be updated.
// - **console3** (array<string>) optional - An array of strings representing the console to be updated.
// - **bg_color** (color) optional - Color of the background of the consoles.
// - **text_color** (color) optional - Color of the text of the consoles.
// - **border_color** (color) optional - Color of the border of the consoles.
//
// @param console1 array<string> - An array of strings representing the console to be updated.
// @param console2 array<string> - An array of strings representing the console to be updated.
// @param console3 array<string> - An array of strings representing the console to be updated.
// @param bg_color color - Color of the bg of the consoles
// @param text_color color - Color of the text of the consoles
// @param border_color color - Color of the border of the consoles
// **Returns**
// (void) - This function does not return anything. It updates the given consoles with the latest input in their respective buffers.
export method update(array<string> console1 = na,array<string> console2 = na, array<string> console3 = na,
color bg_color = #0000007d, color text_color = #00ff00, color border_color = #00ff00) =>
if barstate.islast
C1 = ''
C2 = ''
C3 = ''
a_size1 = not na(console1) ? array.size(console1) : na
a_size2 = not na(console2) ? array.size(console2) : na
a_size3 = not na(console3) ? array.size(console3) : na
a_g1 = not na(a_size1) ? array.get(console1,array.size(console1)-1) : na
a_g2 = not na(a_size2) ? array.get(console2,array.size(console2)-1) : na
a_g3 = not na(a_size3) ? array.get(console3,array.size(console3)-1) : na
if not na(console1) and a_size1
if str.contains(a_g1,'Label')
C1 := 'Label'
if str.contains(a_g1,'Table')
C1 := 'Table'
if str.contains(a_g1,'Box')
C1 := 'Box'
if str.contains(a_g1,'Tooltip')
C1 := 'Tooltip'
print_check(console1)
if not na(console2) and a_size2
if str.contains(a_g2,'Label')
C2 := 'Label'
if str.contains(a_g2,'Table')
C2 := 'Table'
if str.contains(a_g2,'Box')
C2 := 'Box'
if str.contains(a_g2,'Tooltip')
C2 := 'Tooltip'
print_check(console2)
if not na(console3) and a_size3
if str.contains(a_g3,'Label')
C3 := 'Label'
if str.contains(a_g3,'Table')
C3 := 'Table'
if str.contains(a_g3,'Box')
C3 := 'Box'
if str.contains(a_g3,'Tooltip')
C3 := 'Tooltip'
print_check(console3)
LTB(console1,C1,bg_color,text_color,border_color)
LTB(console2,C2,bg_color,text_color,border_color)
LTB(console3,C3,bg_color,text_color,border_color)
export method shorten(string str, int a_index=0, int m_rows=0, int m_cols=0) =>
out = ''
if str.startswith(str,'[') and str.endswith(str,']')
if (m_rows or m_cols)
m = str
m := str.replace_all(m,'[','')
m := str.replace_all(m,'\n','')
m := str.replace_all(m,'[]','')
s_s = str.split(m,']')
a_g = array.size(s_s) > 0 ? array.get(s_s,0) : na
s_ss = str.split(a_g,', ')
m_out = ''
// matrix shorten logic
if array.size(s_s) > 0 and array.size(s_ss) > 0
if array.size(s_s) >= m_rows*2 or array.size(s_ss) >= m_cols*2
pop_shift = str.tonumber(str.tostring(m_rows,'0.'))
m_strbot = array.new<string>()
// array shorten pop then unshift
c_ = array.copy(s_s)
for i = 0 to pop_shift
a_pop = ''
if array.size(c_) > 0
a_pop := array.pop(c_)
s_s_s = str.split(a_pop,', ')
a_size = array.size(s_s_s)
// if m_cols/a_rows are < setting skip array shorten put first to not waste the time on iteration
if a_size <= m_cols*2
array.unshift(m_strbot,('[') + array.pop(s_s)+']')
else
a_pop_shift = str.tonumber(str.tostring(m_cols,'0.'))
// array shorten pop to unshift
a_strbot = array.new<string>()
for ii = 1 to a_pop_shift
array.unshift(a_strbot,array.pop(s_s_s))
array.unshift(a_strbot,'|')
// array shorten unshift to push for top
a_strtop = array.new<string>()
for ii = 1 to a_pop_shift
array.push(a_strtop,array.shift(s_s_s))
array.unshift(m_strbot,'['+array.join(array.concat(a_strtop,a_strbot),', ')+']')
len = str.length(array.get(m_strbot,0))
_len = len*0.6
_len := int(_len/2)
sep = ''
for s = 0 to int(len)
if s < int(_len) or int(s*0.7) > len-int(_len*2)
sep += ' '
else
sep += '—'
array.unshift(m_strbot,sep)
m_strtop = array.new<string>()
// array shorten shift to push
for i = 1 to pop_shift
a_shift = ''
if array.size(c_) > 0
a_shift := array.shift(c_)
s_s_s = str.split(a_shift,', ')
a_size = array.size(s_s_s)
// if m_cols/a_rows are < setting skip array shorten put first to not waste the time on iteration
if a_size <= m_cols*2
array.push(m_strtop,'['+array.shift(s_s)+']')
else
a_pop_shift = str.tonumber(str.tostring(m_cols,'0.'))
// array shorten pop to unshift
a_strbot = array.new<string>()
for ii = 1 to a_pop_shift
array.unshift(a_strbot,array.pop(s_s_s))
array.unshift(a_strbot,'|')
// array shorten pop to unshift
a_strtop = array.new<string>()
for ii = 1 to a_pop_shift
array.push(a_strtop,array.shift(s_s_s))
array.push(m_strtop,'['+array.join(array.concat(a_strtop,a_strbot),', ')+']')
// array.push(m_strtop,'\n')
out := str.replace_all(str.replace_all(array.join(array.concat(m_strtop,m_strbot),'\n'),'[]',''),', |,', ' | ')
else
out := str
if a_index
a = str
a := str.replace_all(a,'[','')
a := str.replace_all(a,']','')
s_s = str.split(a,', ')
a_size = array.size(s_s)
if a_size > a_index*2 and a_size > 0
pop_shift = str.tonumber(str.tostring(a_index,'0.'))
a_strbot = array.new<string>()
for i = 0 to pop_shift
array.unshift(a_strbot,array.pop(s_s))
array.unshift(a_strbot,'|')
a_strtop = array.new<string>()
for i = 0 to pop_shift
array.push(a_strtop,array.shift(s_s))
out := array.join(array.concat(a_strtop,a_strbot),', ')
out := '['+str.replace_all(out,', |,', ' | ')+']'
else
out := str
'\n' + out
// @function ● This function is a utility function for logging information to a console-like output.
// ● It takes in a string array console, a string inp, a string data_label, a string type,
// a string a_or_m, an integer m_rows, and an integer a_index_m_cols.
// ● The function first checks if the console array exists and if the current bar is the last bar.
// ● If either of these conditions is not met, the function ends.
// ● If both conditions are met, the function checks if the console array has more than 100 elements.
// ● If it does, it removes the first element in the array using the array.shift() function.
// ● Next, the function checks if the console array has any elements.
// ● If it does, it creates a string a_join by concatenating all the elements in the console array with a space character.
// ● The function then checks if the a_join string contains the string "_Console" using the str.contains() function. If it does,
// it gets the last element in the console array, a_g, and splits it on the { and } characters. It then gets the second
// element of this split and assigns it to the utc variable. If a_join does not contain "_Console", utc is set to an empty string.
// ● Next, the function converts the inp variable to a string and assigns the result to the str variable.
// ● If the a_or_m variable is not an empty string, the function calls the shorten() function on str,
// passing in a_or_m, m_rows, and a_index_m_cols as arguments.
// ● The function then appends a string to str, which includes the type and data_label variables.
// ● The function then sets the tick and bar variables to false,
// gets the last element in the console array, ap, and checks if ap contains the string "_Console" or "_Bar".
// ● If it contains "_Console", tick is set to true. If it contains "_Bar", bar is set to true.
// ● The function then pushes ap back onto the console array.If tick is true,
// the function creates a string time_str that includes the current time and bar index.
// ● It then checks if time_str is already in the console array. If it is not, it removes the last element from the console array,
// pushes time_str onto the array, and then pushes the removed element back onto the array.
// ● The function then checks if str is already in the console array. If it is not,
// it removes the last element from the console array, pushes str onto the array, and then pushes the removed element back onto the array.
// ● If bar is true, the function creates a string time_str that includes the current time and bar index.
// ● It then checks if time_str is in the array. If not it adds it to the array by poping the array, adding time_str, adding popped item.
// ● It doesnt check first it pops item from the array and add str and adds popped item to the array.
// @param console string - The console array to update.
// @param inp string - The input data to add to the console.
// @param data_label string - A label for the input data.
// @param type string - The type of input data.
// @returns void
_console(array<string> console = na, string inp, string data_label = '', int buffer = 0, bool tick = false, string _type = '') =>
_Console = 'log.console'
_data_label = data_label
str_sep_start = ' '
str_sep_end = ' '
// check for console array and last bar
if not na(console) and (last_bar_index - bar_index) >= buffer
a_size = array.size(console)
if a_size > 40
array.shift(console)
a_size := array.size(console)
if a_size
a_join = array.join(console,' ')
str_i = str(inp)
str = str_i
str := '\n'+_type+_data_label+'\n '+str
time_str =
str_sep_start
+ '\n> Time | ' + str(time)
+ ' | Bar_index - '
+ str.tostring(bar_index)
+ ' —————————————————————————————————————————\n'
+ str_sep_end
s_c_time = str.contains(a_join,' Bar_index - ' + str.tostring(bar_index))
if not s_c_time
apopbar = array.pop(console)
array.push(console,time_str)
array.push(console,apopbar)
if a_size
apoptick = array.pop(console)
a_pop_hold = ''
push = false
for i = console.size()-1 to 0
if console.size() > 0
g = console.get(i)
if str.contains(g,'\n> Time |')
if push == false
push := true
break
if str.contains(g,_type+_data_label)
push := false
if tick
s_g = str.split(g,'\n')
s_g1 = str.split(array.get(s_g,1),' »')
s_s_sg0 = if s_g1.size() > 0
s_s_sg0 = array.get(s_g1,0)
if str.contains(s_s_sg0,str_i)
break
else
if array.size(s_g1) > 10
array.pop(s_g1)
array.unshift(s_g1,str_i)
join = array.join(s_g1, ' »')
to_set = str.format('\n{0}{1}\n {2}\n',_type,_data_label,join)
console.set(i,to_set)
break
if not tick
console.set(i,str+'\n')
break
else
push := true
if push
console.push(str+'\n')
console.push(apoptick)
p_helper(inp, int a_index=0, int m_rows=0, int m_cols=0) =>
string str = str(inp)
if a_index or m_rows or m_cols
str := shorten(str,a_index=a_index, m_rows=m_rows, m_cols=m_cols)
if str.length(str) > 4000
str := str_check(str)
[inp,str]
// @function log
// @param inp (all) - The input value to be printed.
// @param data_label (string) - An optional label to be printed before the input value.
// @param console (array<string>) - The console to output the message to.
// @param off (bool) - An optional flag to turn off printing. Default is false.
// @param tick (bool) - An optional flag to turn off printing. Default is false.
// @param loop (int) - for the index inside a loop will display the index on the console.
// @param m_rows (int) - An optional parameter for printing a matrix with a specified number of rows.
// @param m_cols (int) - An optional parameter for printing a matrix with a specified number of columns.
// @param a_index (int) - An optional parameter for printing an array with a specified number of indexs.
// @returns out (all) - The input value.
export method log(array<string> console, string inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type string) ', tick=tick)
out
export method log(array<string> console,
string inp1=na, string inp2=na, string inp3=na, string inp4=na,
string inp5=na, string inp6=na, string inp7=na, string inp8=na,
string inp9=na, string inp10=na, string inp11=na, string inp12=na,
string inp13=na, string inp14=na, string inp15=na, string inp16=na,
string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
build = ""
switch
not na(inp1) => build += "\n1 = {0}"
not na(inp2) => build += "\n2 = {1}"
not na(inp3) => build += "\n3 = {2}"
not na(inp4) => build += "\n4 = {3}"
not na(inp5) => build += "\n5 = {4}"
not na(inp6) => build += "\n6 = {5}"
not na(inp7) => build += "\n7 = {6}"
not na(inp8) => build += "\n8 = {7}"
not na(inp9) => build += "\n9 = {8}"
not na(inp10) => build += "\n10 = {9}"
not na(inp11) => build += "\n11 = {10}"
not na(inp12) => build += "\n12 = {11}"
not na(inp13) => build += "\n13 = {12}"
not na(inp14) => build += "\n14 = {13}"
not na(inp15) => build += "\n15 = {14}"
not na(inp16) => build += "\n16 = {15}"
str = str.format(build,inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9,inp10,inp11,inp12,inp13,inp14,inp15,inp16)
console.log(str, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(array<string> console, int inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console = console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type int) ',tick=tick)
out
export method log(array<string> console, float inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type float) ', tick=tick)
out
export method log(array<string> console, bool inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type bool) ', tick=tick)
out
export method log(array<string> console, line inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type line) ', tick=tick)
out
export method log(array<string> console, box inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type box) ', tick=tick)
out
export method log(array<string> console, label inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type label) ', tick=tick)
out
export method log(array<string> console, linefill inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
[out, _str] = p_helper(inp=inp)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str,data_label=data_label,buffer=buffer, _type=_loop+'(type linefill) ', tick=tick)
out
export method log(array<string> console, array<string> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [string]) ', tick=tick)
out
export method log(array<string> console, array<int> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [int]) ', tick=tick)
out
export method log(array<string> console, array<float> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [float]) ', tick=tick)
out
export method log(array<string> console, array<bool> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [bool]) ', tick=tick)
out
export method log(array<string> console, array<line> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [line]) ', tick=tick)
out
export method log(array<string> console, array<box> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [box]) ', tick=tick)
out
export method log(array<string> console, array<label> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [label]) ', tick=tick)
out
export method log(array<string> console, array<linefill> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
[out,_str] = p_helper(inp=inp,a_index=a_index)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type [linefill]) ', tick=tick)
out
export method log(array<string> console, matrix<string> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <string>) ', tick=tick)
out
export method log(array<string> console, matrix<int> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <int>) ', tick=tick)
out
export method log(array<string> console, matrix<float> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console,inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <float>) ', tick=tick)
out
export method log(array<string> console, matrix<bool> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <bool>) ', tick=tick)
out
export method log(array<string> console, matrix<line> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <line>) ', tick=tick)
out
export method log(array<string> console, matrix<box> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <box>) ', tick=tick)
out
export method log(array<string> console, matrix<label> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <label>) ', tick=tick)
out
export method log(array<string> console, matrix<linefill> inp, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
[out,_str] = p_helper(inp=inp,m_rows=m_rows,m_cols=m_cols)
if not off
_loop = (not na(loop) ? '↻'+str(loop): '')
_console(console=console, inp=_str, data_label=data_label,buffer=buffer, _type=_loop+'(type <linefill>) ', tick=tick)
out
export method log(string inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(int inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(float inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(bool inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(line inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(box inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(label inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(linefill inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick)
export method log(array<int> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, a_index = a_index)
export method log(array<float> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, a_index = a_index)
export method log(array<bool> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, a_index = a_index)
export method log(array<line> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, a_index = a_index)
export method log(array<box> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, a_index = a_index)
export method log(array<label> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, a_index = a_index)
export method log(array<linefill> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int a_index = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, a_index = a_index)
export method log(matrix<string> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
export method log(matrix<int> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
export method log(matrix<float> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
export method log(matrix<bool> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
export method log(matrix<line> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
export method log(matrix<box> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
export method log(matrix<label> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
export method log(matrix<linefill> inp, array<string> console, string data_label = "", bool off = false, int buffer = 0, int loop = na, bool tick = false,
int m_rows = 0, int m_cols = 0) =>
console.log(inp, data_label = data_label,off = off, buffer = buffer, loop = loop, tick = tick, m_rows=m_rows, m_cols=m_cols)
//#region print main()
// @function console
// @param input all - The input string to be printed in the console.
// @param tick bool - A flag indicating whether to print the input immediately (true) or store it in a buffer to be printed later (false).
// Default value is false.
// @param position string - The position of the console on the chart.
// Valid values are "1", "2", "3", "4", "5", "6", "7", "8", and "9", corresponding to the positions in a 3x3 grid.
// If set to `na`, the console will be placed in the bottom left corner. Default value is na.
// @param size int - The maximum number of lines that can be displayed in the console. Default value is 20.
// @param text_size string - The size of the text in the console. Default value is size.small.
// @param bg_color color - The background color of the console. Default value is #00000075.
// @param fg_color color - The color of the text in the console. Default value is #00ff00.
// @param UTC int - The time zone offset to use when displaying timestamps in the console. Default value is -6.
// @param data_label string - A label to be printed before each input in the console. Default value is an empty string.
// @returns table - The table object representing the console.
// @description - This function is used to print a string in a console on the chart.
// The console is a table object with a single column and two rows.
// The first row displays the current timestamp, and the second row displays the input string.
// The console can be positioned at any of the nine locations in a 3x3 grid on the chart,
// or in the bottom left corner if the position parameter is set to na. The maximum number of lines that can be displayed
// in the console can be set using the size parameter, and the size of the text in the console can be set using the text_size parameter.
// The background color, text color, and border color of the console can be set using the bg_color, text_color,
// and border_color parameters, respectively. The time zone offset to use when displaying timestamps in the console can be set using the UTC parameter.
// Additionally, a label can be printed before each input string using the data_label parameter.
// The function returns the table object representing the console.
console(string input, string data_label = '', int buffer = 0, bool tick = false, string position = na, int size = 20,
string text_size = size.small, string _type = 'string',
color text_color = #00ff00, color bg_color = #0000007d) =>
var table table = na
_data_label = data_label
TIME = str(tick ? timenow : time) + ' | Bar_index~' + str.tostring(bar_index)
t_loc = position.bottom_left
if not na(position)
pos = array.size(table.all)
if pos > 9
pos -= 9
if _data_label == ''
_data_label := str.tostring(pos)
if str.length(position) == 1
pos := int(str.tonumber(position))
t_loc := switch pos
1 => position.bottom_left
2 => position.bottom_center
3 => position.bottom_right
4 => position.middle_left
5 => position.middle_center
6 => position.middle_right
7 => position.top_left
8 => position.top_center
9 => position.top_right
table := table.new(
position = t_loc, columns = 1, rows = 2,
bgcolor = bg_color, frame_color = text_color, frame_width=1,
border_color = text_color, border_width = 1
)
if (last_bar_index - bar_index) >= buffer
var a_ = array.new<string>()
string = TIME+'\n'+_type+" "+_data_label+'\n'+input+'\n'
if not tick
var array<string> a_console = array.new<string>()
array.push(a_console,string)
if array.size(a_console) > size
array.shift(a_console)
print_check(a_console)
a_ := a_console
if tick
varip array<string> a_consoleip = array.new<string>()
array.push(a_consoleip,string)
if array.size(a_consoleip) > size
array.shift(a_consoleip)
print_check(a_consoleip)
a_ := a_consoleip
table.cell(
table_id = table, column = 0, row = 1, width = 30,
text = not na(a_) ? array.join(a_, '\n') : na,
text_color = text_color, bgcolor = bg_color,
text_halign = text.align_left, text_valign = text.align_bottom, text_size = text_size
)
time_str = 'Time~'+ str(time) +' | Bar_index~' +
str.tostring(bar_index)+ '| str.len~' + str(str.length(array.join(a_)))
table.cell(
table_id = table, column = 0, row = 0, width = 30,
text = time_str,
text_color = text_color,bgcolor = bg_color,
text_halign = text.align_center, text_valign = text.align_bottom, text_size = text_size
)
//#endregion
//#region print overloads()
// @function print
// @param input (all) - The input to be printed in the console
// @param data_label (string) - A label to be printed before each input in the console. Default value is an empty string.
// @param tick (bool) - A flag indicating whether to print the input immediately [true] or store it in a buffer to be printed later [false].
// Default value is false.
// @param pos (string) - The position of the console on the chart. Valid values are "1", "2", "3", "4", "5", "6", "7", "8", and "9",
// corresponding to the positions in a 3x3 grid. If set to na, the console will be placed in the bottom left corner.
// Default value is na.
// @param off (bool) - A flag indicating whether to disable printing [true] or enable it [false]. Default value is false.
// @param size (int) - The maximum number of lines that can be displayed in the console. Default value is 20.
// @param loop (int) - for the index inside a loop will display the index on the console.
// @param text_size (string) - The size of the text in the console. Default value is size.small.
// @param bg_color (color) - The background color of the console. Default value is #0000007d.
// @param text_color (color) - The color of the text in the console. Default value is #00ff00.
// @param UTC (int) - The time zone offset to use when displaying timestamps in the console. Default value is -6.
// @param m_rows (int) - An optional parameter for printing a matrix with a specified number of rows.
// @param m_cols (int) - An optional parameter for printing a matrix with a specified number of columns.
// @param a_index (int) - An optional parameter for printing an array with a specified number of indexs.
// @returns out (all) - The input value.
// @description - The print function is used to display a message in a console on a chart.
// The input value to be printed, inp, can be of any data type [e.g. string, int, float, array, matrix].
// The data_label parameter is an optional string that can be used to label the input value.
// The tick parameter is a boolean flag that determines whether the input value should be printed immediately [true] or
// stored in a buffer to be printed later [false]. The off parameter is a boolean flag that can be used to
// disable printing [true] or enable it [false]. The size parameter sets the maximum number of lines that can be displayed in the console.
// The text_size parameter sets the size of the text in the console. The bg_color parameter sets the background color of the console.
// The text_color parameter sets the color of the text in the console. The border_color parameter sets the color of the border around the console.
// The position parameter sets the position of the console on the chart. The UTC parameter sets the time zone offset to use when
// displaying timestamps in the console. The function returns the input value inp.
export method print(string input, string data_label='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type str)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(int input, string data_label ='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type int)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(float input, string data_label='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type float)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(bool input, string data_label='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type bool)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(line input, string data_label='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type line)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(box input, string data_label='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type box)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(label input, string data_label='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type label)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(linefill input, string data_label='',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out, _str] = p_helper(inp=input)
if not off
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
_type= '(type linefill)\n'
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(array<string> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [string])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(array<int> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [int])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(array<float> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [float])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(array<bool> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [bool])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(array<line> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [line])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(array<box> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [box])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(array<label> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [label])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(linefill[] input, string data_label = '',bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int a_index = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,a_index=a_index)
if not off
_type= '(type [linefill])'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<string> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
a_or_m = 'matrix'
if not off
_type= '(type <string>)'
_loop= (not na(loop) ? '↻'+str(loop) +'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<int> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
if not off
_type= '(type <int>)'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<float> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
if not off
_type= '(type <float>)'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<bool> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
if not off
_type= '(type <bool>)'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<line> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
if not off
_type= '(type <line>)'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<box> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
if not off
_type= '(type <box>)'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<label> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
if not off
_type= '(type <label>)'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
export method print(matrix<linefill> input, string data_label = '', bool tick = false, string pos = na,
int buffer = 0, bool off = false, int loop = na, int m_rows = 0, int m_cols = 0,
int size = 20, string text_size = size.small,
color bg_color = #0000007d, color text_color = #00ff00) =>
[out,_str] = p_helper(inp=input,m_rows=m_rows,m_cols=m_cols)
if not off
_type= '(type <linefill>)'
_loop= (not na(loop) ? '↻'+str(loop)+'\n': '')
console(input= _str,tick=tick, size=size, text_size=text_size, buffer=buffer,
position=pos, data_label=data_label, _type=_loop+_type,
bg_color=bg_color, text_color=text_color)
out
//#endregion
// __ __ __ ________ ___
// /\ \/\ \ / // \ \ ____\ /\_ \
// \ \ \ \ \ ____ __ __ __ / // \ \ ____ __ _ __ ___ ___ _____\//\ \ __ ____
// \ \ \ \ \ /',__\ /'__`\ /'_ `\ /'__`\ / // \ \ ____\ /\ \/'\ /'__`\ /' __` __`\/\ '__`\\ \ \ /'__`\ /',__\
// \ \ \_\ \/\__, `\/\ \L\.\_/\ \L\ \/\ __/ / // \ \ \____ \/> <//\ \L\.\_/\ \/\ \/\ \ \ \L\ \\_\ \_/\ __//\__, `\
// \ \_____\/\____/\ \__/.\_\ \____ \ \____\ / // \ \______//\_/\_\ \__/.\_\ \_\ \_\ \_\ \ ,__//\____\ \____\/\____/
// \/_____/\/___/ \/__/\/_/\/___L\ \/____/ /_// \/_____/ \//\/_/\/__/\/_/\/_/\/_/\/_/\ \ \/ \/____/\/____/\/___/
// /\____/ \ \_\
// \_/__/ \/_/
// // instructions
// // import FFriZz/FrizBug/<version> as bug
// //Put at start of code after import
table = init()
// tooltip = init(UTC = -6,'tool','bar')
// for the print function there is no need to init and database or to update at the end of script
// the only draw back is that you can only view 1 var at a time unless an array is used
// Examples
a_string = array.from('2','1','5','7','3','2','1','6','7','4')
mf = matrix.new<float>(10,10,5.5)
matrix.add_row(mf,matrix.rows(mf),array.from(1,1,1,1,1,1,1,1,1,1))
matrix.add_row(mf,0,array.from(9,9,9,9,9,9,9,9,9,9))
print(mf,'Matrix',pos = '1',m_rows=4,m_cols=4)
log(table,'letter I','I = i{tick = true non changing value} ',tick=true)
log(table,close,'Close {with tick = true}',tick = true)
log(table,close,'Close {with tick = false}')
// Put at end of code
update(table)
// } =====================================================================================
|
TechnicalRating | https://www.tradingview.com/script/jDWyb5PG-TechnicalRating/ | TradingView | https://www.tradingview.com/u/TradingView/ | 231 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingView
//@version=5
library("TechnicalRating")
// TechnicalRating Library
// v1, 2022.12.30
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import TradingView/ta/5
//#region ———————————————————— Library functions
// @function General MA rating (+1/0/-1) calculated using position of `src` price with regards to `ma`.
// @param ma (series int/float) The moving average to check against the `src`.
// @param src (series int/float) The `src` to check against the moving average.
// @returns (int) A rating integer (+1/0/-1).
calcRatingMA(series float ma, series float src) =>
float result = math.sign(src - ma)
// @function Converts bull/bear conditions into a +1/0/-1 value corresponding to a bull/neutral/bear bias.
// @param src (<type>) The source to monitor for an `na` condition.
// @param bullCond (series bool) The bullish condition to convert to a rating.
// @param bearCond (series bool) The bearish condition to convert to a rating.
// @returns (int) A rating integer (+1/0/-1), or `na` if `src` to be evaluated is `na`.
calcRating(src, series bool bullCond, series bool bearCond) =>
int result = na(src) ? na : bullCond ? 1 : bearCond ? -1 : 0
// @function Calculates 3 ratings (ratings total, MA ratings, indicator ratings) using the aggregate biases of 26 different technical indicators.
// @returns A 3-element tuple: ([(float) ratingTotal, (float) ratingOther, (float) ratingMA].
export calcRatingAll() =>
[con, base, lead1, lead2, _] = ta.ichimoku()
[kStoch, dStoch] = ta.stochFull(14, 3, 3)
[kStochRsi, dStochRsi] = ta.stochRsi(14, 14, 3, 3)
[diP, diN, adx] = ta.dmi(14, 14)
[macd, signal, _] = ta.macd(close, 12, 26, 9)
float bullPower = high - ta.ema(close, 13)
float bearPower = low - ta.ema(close, 13)
float rsi = ta.rsi(close, 14)
float cci = ta.cci(close, 20)
float mom = ta.mom(close, 10)
float priceAvg = ta.ema(close, 50)
bool downTrend = close < priceAvg
bool upTrend = close > priceAvg
float uo = ta.uo(7, 14, 28)
float wr = ta.wpr(14)
float ao = ta.ao()
var array<float> indRatings = array.new<float>()
array.clear(indRatings)
array.push(indRatings, calcRatingMA(ta.sma(close , 10), close))
array.push(indRatings, calcRatingMA(ta.sma(close , 20), close))
array.push(indRatings, calcRatingMA(ta.sma(close , 30), close))
array.push(indRatings, calcRatingMA(ta.sma(close , 50), close))
array.push(indRatings, calcRatingMA(ta.sma(close , 100), close))
array.push(indRatings, calcRatingMA(ta.sma(close , 200), close))
array.push(indRatings, calcRatingMA(ta.ema(close , 10), close))
array.push(indRatings, calcRatingMA(ta.ema(close , 20), close))
array.push(indRatings, calcRatingMA(ta.ema(close , 30), close))
array.push(indRatings, calcRatingMA(ta.ema(close , 50), close))
array.push(indRatings, calcRatingMA(ta.ema(close , 100), close))
array.push(indRatings, calcRatingMA(ta.ema(close , 200), close))
array.push(indRatings, calcRatingMA(ta.hma(close , 9), close))
array.push(indRatings, calcRatingMA(ta.vwma(close, 20), close))
array.push(indRatings, calcRating(lead2,
lead1[26] > lead2[26] and close > lead1[26] and close < base and close[1] < con and close > con,
lead2[26] > lead1[26] and close < lead2[26] and close > base and close[1] > con and close < con))
float ratingMA = array.avg(indRatings)
array.clear(indRatings)
array.push(indRatings, calcRating(rsi[1],
rsi < 30 and rsi[1] < rsi,
rsi > 70 and rsi[1] > rsi))
array.push(indRatings, calcRating(dStoch[1],
kStoch < 20 and dStoch < 20 and kStoch > dStoch and kStoch[1] < dStoch[1],
kStoch > 80 and dStoch > 80 and kStoch < dStoch and kStoch[1] > dStoch[1]))
array.push(indRatings, calcRating(cci[1],
cci < -100 and cci > cci[1],
cci > 100 and cci < cci[1]))
array.push(indRatings, calcRating(adx,
adx > 20 and diP[1] < diN[1] and diP > diN,
adx > 20 and diP[1] > diN[1] and diP < diN))
array.push(indRatings, calcRating(ao[1],
ta.crossover(ao, 0) or (ao > 0 and ao[1] > 0 and ao > ao[1] and ao[2] > ao[1]),
ta.crossunder(ao,0) or (ao < 0 and ao[1] < 0 and ao < ao[1] and ao[2] < ao[1])))
array.push(indRatings, calcRating(mom[1], mom > mom[1], mom < mom[1]))
array.push(indRatings, calcRating(signal,
macd > signal,
macd < signal))
array.push(indRatings, calcRating(upTrend,
downTrend and kStochRsi < 20 and dStochRsi < 20 and kStochRsi > dStochRsi and kStochRsi[1] < dStochRsi[1],
upTrend and kStochRsi > 80 and dStochRsi > 80 and kStochRsi < dStochRsi and kStochRsi[1] > dStochRsi[1]))
array.push(indRatings, calcRating(wr[1],
wr < -80 and wr > wr[1],
wr > -20 and wr < wr[1]))
array.push(indRatings, calcRating(upTrend,
upTrend and bearPower < 0 and bearPower > bearPower[1],
downTrend and bullPower > 0 and bullPower < bullPower[1]))
array.push(indRatings, calcRating(uo, uo > 70, uo < 30))
float ratingOther = array.avg(indRatings)
float total = nz(ratingMA, 0) + nz(ratingOther, 0)
float ratingTotal = switch
not na(ratingMA) and not na(ratingOther) => total / 2
not na(ratingMA) or not na(ratingOther) => total
=> na
[ratingTotal, ratingOther, ratingMA]
// @function Calculates the number of times the values in the given series increase in value up to a maximum count of 5.
// @param plot (series float) The series of values to check for rising values.
// @returns (int) The number of times the values in the series increased in value.
export countRising(series float plot) =>
float vPlot = math.abs(plot)
var int result = 0
result := switch
vPlot == 0 => 0
vPlot >= vPlot[1] => math.min(5, result + 1)
vPlot < vPlot[1] => math.max(1, result - 1)
result
// @function Determines the rating status of a given series based on its values and defined bounds.
// @param ratingValue (series float) The series of values to determine the rating status for.
// @param strongBound (series float) The upper bound for a "strong" rating.
// @param weakBound (series float) The upper bound for a "weak" rating.
// @returns (string) The rating status of the given series ("Strong Buy", "Buy", "Neutral", "Sell", or "Strong Sell").
export ratingStatus(series float ratingValue, series float strongBound = 0.5, series float weakBound = 0.1) =>
string result = switch
na(ratingValue) => "-"
ratingValue < -strongBound => "Strong\nSell"
ratingValue < -weakBound => "Sell"
ratingValue > strongBound => "Strong\nBuy "
ratingValue > weakBound => "Buy"
=> "Neutral"
//#endregion
//#region ———————————————————— Example Code
// Find indicator ratings.
[ratingTotal, ratingOther, ratingMa] = calcRatingAll()
// Colors.
color SOFT = #5b9cf6
color ROYAL = #2962ff
color MISCHKA = #a8adbc
color PINK = #ef9a9a
color RED = #f44336
// Constants.
float STRONG_BOUND = 0.5
float WEAK_BOUND = 0.1
float BAND = 0.2
float ZERO = 0.0
// Calculate color gradient.
color buyColor = color.from_gradient(ratingTotal, ZERO, BAND, MISCHKA, ROYAL)
color sellColor = color.from_gradient(ratingTotal, -BAND, ZERO, RED, MISCHKA)
color gradColor = color.from_gradient(ratingTotal, -BAND, BAND, sellColor, buyColor)
// Determine values and conditions for the positive and negative ratings series.
bool posCond = ratingTotal > WEAK_BOUND
bool negCond = ratingTotal < -WEAK_BOUND
float posSeries = posCond ? ratingTotal : ZERO
float negSeries = negCond ? ratingTotal : ZERO
// Count the number of bars with increasing positive or negative ratings to determine the transparency of the color.
int posCount = countRising(posSeries)
int negCount = countRising(negSeries)
int perc = posCond ? posCount : negCond ? negCount : 0
color curColor = color.new(gradColor, 50 - perc * 10)
// Plot the rating as columns.
plot(ratingTotal, "Rating", curColor, 1, plot.style_columns)
// Draw a label on the last bar displaying the ratings status.
if barstate.islast
var label signal = label.new(bar_index, 0, "", textcolor = chart.fg_color, style = label.style_label_left)
label.set_xy(signal, bar_index + 1, ratingTotal)
label.set_text(signal, ratingStatus(ratingTotal, STRONG_BOUND, WEAK_BOUND))
label.set_color(signal, curColor)
//#endregion
|
Obj_XABCD_Harmonic | https://www.tradingview.com/script/bu99tQZF-Obj-XABCD-Harmonic/ | reees | https://www.tradingview.com/u/reees/ | 248 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
// @description Harmonic XABCD Pattern object and associated methods. Easily validate, draw, and get information about harmonic patterns. See example code at the end of the script for details.
library("Obj_XABCD_Harmonic",true)
import reees/TA/76 as t
import reees/Draw/26 as draw
import reees/Utilities/5 as u
import reees/Pattern/1 as p
// @type Validation and scoring parameters for a Harmonic Pattern object (xabcd_harmonic)
// @field pct_error Allowed % error of leg retracement ratio versus the defined harmonic ratio
// @field pct_asym Allowed leg length/period asymmetry % (a leg is considered invalid if it is this % longer or shorter than the average length of the other legs)
// @field types Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
// @field w_e Weight of ratio % error (used in score calculation, dft = 1)
// @field w_p Weight of PRZ confluence (used in score calculation, dft = 1)
// @field w_d Weight of Point D / PRZ confluence (used in score calculation, dft = 1)
export type harmonic_params
float pct_error = 15.0
float pct_asym = 250.0
int[] types
float w_e = 1.0
float w_p = 1.0
float w_d = 1.0
// @function Create a harmonic parameters object (used by xabcd_harmonic object for pattern validation and scoring).
// @param pct_error Allowed % error of leg retracement ratio versus the defined harmonic ratio
// @param pct_asym Allowed leg length/period asymmetry % (a leg is considered invalid if it is this % longer or shorter than the average length of the other legs)
// @param types Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
// @param w_e Weight of ratio % error (used in score calculation, dft = 1)
// @param w_p Weight of PRZ confluence (used in score calculation, dft = 1)
// @param w_d Weight of Point D / PRZ confluence (used in score calculation, dft = 1)
// @returns harmonic_params object instance. It is recommended to store and reuse this object for multiple xabcd_harmonic objects rather than creating new params objects unnecessarily.
export init_params(float pct_error=15.0, float pct_asym=250.0, int[] types=na, float w_e=1, float w_p=1, float w_d=1) =>
harmonic_params.new(pct_error,
pct_asym,
na(types)?array.from(1,2,3,4,5,6):types,
w_e,
w_p,
w_d)
// @type Harmonic Pattern object
// @field bull Bullish pattern flag
// @field tp Pattern type (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
// @field x Point X
// @field a Point A
// @field b Point B
// @field c Point C
// @field d Point D
// @field r_xb XAB ratio
// @field re_xb XAB ratio % error
// @field r_ac ABC ratio
// @field re_ac ABC ratio % error
// @field r_bd BCD ratio
// @field re_bd BCD ratio % error
// @field r_xd XAD or XCD ratio, depending on pattern type
// @field re_xd XAD ratio % error
// @field score Total score
// @field score_eAvg Avg % error
// @field score_prz PRZ score
// @field score_eD Point D/PRZ confluence score
// @field prz_bN BCD retracement near
// @field prz_bF BCD retracement far
// @field prz_xN XAD/XCD retracement near
// @field prz_xF XAD/XCD retracement far
// @field t1Hit Target 1 flag
// @field t1 Target 1 level
// @field t2Hit Target 2 flag
// @field t2 Target 2 level
// @field sHit Stop flag
// @field stop Stop level
// @field entry Entry level
// @field eHit Entry flag
// @field eX Entry bar index
// @field eY Enty price/level
// @field invalid_d TRUE if point D is an invalid or unconfirmed pivot
// @field pLines Pattern lines
// @field pLabel Pattern label
// @field pid Pattern ID
// @field params harmonic_params for validating and scoring the pattern
export type xabcd_harmonic
// *** Type ***
bool bull // Bullish flag
int tp // Type (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
// *** Points ***
p.point x
p.point a
p.point b
p.point c
p.point d
// *** Values ***
float r_xb // XAB ratio
float re_xb // XAB ratio % error
float r_ac // etc...
float re_ac
float r_bd
float re_bd
float r_xd // XAD or XCD, depending on pattern type
float re_xd
// Score
float score // total score
float score_eAvg // avg % error
// float sym // leg length symmetry
float score_prz // PRZ score
float score_eD // Point D/PRZ confluence score
// PRZ
float prz_bN // BCD retracement near
float prz_bF // BCD retracement far
float prz_xN // XAD/XCD retracement near
float prz_xF // XAD/XCD retracement far
// State flags/values
bool t1Hit // target 1 flag
float t1 // target 1 level
bool t2Hit // target 2 flag
float t2 // target 2 level
bool sHit // stop-loss flag
float stop // stop-loss level
float entry // entry level
bool eHit // entry flag
p.point e // entry point
bool invalid_d // TRUE if point D is an invalid or unconfirmed pivot
// *** Drawings ***
line[] pLines
label pLabel
//
string pid // Pattern ID
harmonic_params params // Validation parameters
//*******************************************************************
// Object functions/methods
//*******************************************************************
// (private) Pattern ID
pid(p) =>
str.tostring(p.tp) + "_"
+ str.tostring(p.x.x) + "_"
+ str.tostring(p.a.x) + "_"
+ str.tostring(p.b.x) + "_"
+ str.tostring(p.c.x) + "_"
+ str.tostring(p.d.x)
// (private) Set pattern ID
set_pid(p) =>
p.pid := pid(p)
// (private) Get the highest scoring pattern type. It's unlikely that a complete pattern will be valid for more than one harmonic,
// but it's possible (especially if your validation parameters are more inclusive).
highestScoringType(tps,params,x,a,b,c,d) =>
int hst = na
float hs=0.0, float hs1=0.0, float hs2=0.0, float hs3=0.0
for tp in tps
[eavg,asym,eD,prz,_,_,_] = t.harmonic_xabcd_score(tp+1,x.x,x.y,a.x,a.y,b.x,b.y,c.x,c.y,d.x,d.y)
s = t.harmonic_xabcd_scoreTot(asym,eavg,prz,eD,tp+1,0.0,params.w_e,params.w_p,params.w_d)
if s>hs
hst := tp+1
hs := s
hs1 := eavg
hs2 := eD
hs3 := prz
[hst,hs,hs1,hs2,hs3]
// (private) Validate ABCD
validAbcd(bull,a,b,c,d) =>
if bull
a.y > b.y and c.y> b.y and (na(d.y) ? true : c.y > d.y)
else
a.y < b.y and c.y < b.y and (na(d.y) ? true : c.y < d.y)
delete_lines(p) =>
for l in p.pLines
line.delete(l)
delete_label(p) =>
if not na(p.pLabel)
label.delete(p.pLabel)
delete_drawings(p) =>
delete_lines(p)
delete_label(p)
p
// @function Initialize an xabcd_harmonic object instance from a given set of points
// If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
// own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
// Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
// and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
// to re-initialize it (e.g. for re-validation and/or re-scoring).
// @param x Point X
// @param a Point A
// @param b Point B
// @param c Point C
// @param d Point D
// @param params harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
// @param tp Pattern type
// @param p xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
// @returns xabcd_harmonic object instance if a valid harmonic, else na
export init(p.point x, p.point a, p.point b, p.point c, p.point d=na,
harmonic_params params=na, int tp=na, xabcd_harmonic p=na) =>
xabcd_harmonic obj = p
int validType = tp>0 and tp<7 ? tp : na
float[] scores = array.new_float()
par = na(params) ? init_params() : params
p.point ptD = na(d) ? p.point.new() : d
// Validate XABCD pattern
bull = x.y < a.y
if validAbcd(bull,a,b,c,ptD) == false
validType := na
// Validate Harmonic pattern
else if na(validType)
tps = u.intToBoolArr(par.types,7)
int[] intTps = na
if not na(ptD.x)
[f,h1,h2,h3,h4,h5,h6] =
t.harmonic_xabcd_validate(x.x,x.y,a.x,a.y,b.x,b.y,c.x,c.y,ptD.x,ptD.y,par.pct_error,par.pct_asym,
array.get(tps,1),array.get(tps,2),array.get(tps,3),array.get(tps,4),array.get(tps,5),array.get(tps,6))
intTps := u.boolToIntArr(array.from(h1,h2,h3,h4,h5,h6))
else
[f,h1,h2,h3,h4,h5,h6] =
t.harmonic_xabcd_validateIncomplete(x.x,x.y,a.x,a.y,b.x,b.y,c.x,c.y,par.pct_error,par.pct_asym,
array.get(tps,1),array.get(tps,2),array.get(tps,3),array.get(tps,4),array.get(tps,5),array.get(tps,6))
intTps := u.boolToIntArr(array.from(h1,h2,h3,h4,h5,h6))
if array.size(intTps) == 1
validType := array.pop(intTps)+1
else if array.size(intTps) > 1
[hst,s,s1,s2,s3] = highestScoringType(intTps,par,x,a,b,c,ptD)
scores := array.from(s,s1,s2,s3)
validType := hst
else
validType := na
// Create object if we have a valid type (or type was explicitly passed)
if not na(validType)
obj := na(p) ? xabcd_harmonic.new() : delete_drawings(p)
[xbr,xbre] = t.harmonic_xabcd_rAndE(validType,"xab",a.y-b.y,a.y-x.y)
[acr,acre] = t.harmonic_xabcd_rAndE(validType,"abc",c.y-b.y,a.y-b.y)
[bdr,bdre] = t.harmonic_xabcd_rAndE(validType,"bcd",c.y-ptD.y,c.y-b.y)
[xdr,xdre] = t.harmonic_xabcd_rAndE(validType,"xad",a.y-ptD.y,a.y-x.y)
if array.size(scores) == 0
[eavg,asym,eD,przscore,_,cpl1,cpl2] = t.harmonic_xabcd_score(validType,x.x,x.y,a.x,a.y,b.x,b.y,c.x,c.y,ptD.x,ptD.y)
s = t.harmonic_xabcd_scoreTot(asym,eavg,przscore,eD,validType,0.0,par.w_e,par.w_p,par.w_d)
scores := array.from(s,eavg,eD,przscore)
[bcN,bcF,xaN,xaF] = t.harmonic_xabcd_prz(validType,x.y,a.y,b.y,c.y)
obj.bull := bull
obj.tp := validType
obj.x := x
obj.a := a
obj.b := b
obj.c := c
obj.d := ptD
obj.r_xb := xbr
obj.re_xb := xbre
obj.r_ac := acr
obj.re_ac := acre
obj.r_bd := obj.invalid_d ? na : bdr
obj.re_bd := obj.invalid_d ? na : bdre
obj.r_xd := obj.invalid_d ? na : xdr
obj.re_xd := obj.invalid_d ? na : xdre
obj.score := array.get(scores,0)
obj.score_eAvg := array.get(scores,1)
obj.score_prz := array.get(scores,3)
obj.score_eD := obj.invalid_d ? na : array.get(scores,2)
obj.prz_bN := bcN
obj.prz_bF := bcF
obj.prz_xN := xaN
obj.prz_xF := xaF
obj.e := na(p) ? p.point.new() : p.e
obj.pLines := array.new_line()
set_pid(obj)
obj
// @function Initialize an xabcd_harmonic object instance from a given set of x and y coordinate values.
// If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
// own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
// Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
// and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
// to re-initialize it (e.g. for re-validation and/or re-scoring).
// @param xX Point X bar index (required)
// @param xY Point X price/level (required)
// @param aX Point A bar index (required)
// @param aY Point A price/level (required)
// @param bX Point B bar index (required)
// @param bY Point B price/level (required)
// @param cX Point C bar index (required)
// @param cY Point C price/level (required)
// @param dX Point D bar index
// @param dY Point D price/level
// @param params harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
// @param tp Pattern type
// @param p xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
// @returns xabcd_harmonic object instance if a valid harmonic, else na
export init(int xX, float xY, int aX, float aY, int bX, float bY, int cX, float cY,int dX=na,float dY=na,
harmonic_params params=na, int tp=na, xabcd_harmonic p=na) =>
init(p.point.new(xX,xY), p.point.new(aX,aY), p.point.new(bX,bY), p.point.new(cX,cY), p.point.new(dX,dY), params, tp, p)
// @function Initialize an xabcd_harmonic object instance from a given pattern
// If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
// own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
// Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
// and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
// to re-initialize it (e.g. for re-validation and/or re-scoring).
// @param pattern Pattern
// @param params harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
// @param tp Pattern type
// @param p xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
// @returns xabcd_harmonic object instance if a valid harmonic, else na
export init(p.pattern pattern, harmonic_params params=na, int tp=na, xabcd_harmonic p=na) =>
if array.size(pattern.legs) == 4
xa = array.get(pattern.legs,0)
bc = array.get(pattern.legs,2)
cd = array.get(pattern.legs,3)
init(xa.a, xa.b, bc.a, bc.b, cd.b, params, tp, p)
else if array.size(pattern.legs) == 3
xa = array.get(pattern.legs,0)
bc = array.get(pattern.legs,2)
init(xa.a, xa.b, bc.a, bc.b, na, params, tp, p)
else
na
// *** Get/Set ***
// @function Get the pattern name
// @param p Instance of xabcd_harmonic object
// @returns Pattern name (string)
export method get_name(xabcd_harmonic p) =>
a = p.bull ? "Bullish" : "Bearish"
b = switch p.tp
1 => "Gartley"
2 => "Bat"
3 => "Butterfly"
4 => "Crab"
5 => "Shark"
6 => "Cypher"
=> "Undefined harmonic"
a + " " + b
// @function Get the pattern symbol
// @param p Instance of xabcd_harmonic object
// @returns Pattern symbol (1 byte string)
export method get_symbol(xabcd_harmonic p) =>
t.harmonic_xabcd_symbol(p.tp)
// @function Get the Pattern ID. Patterns of the same type with the same coordinates will have the same Pattern ID.
// @param p Instance of xabcd_harmonic object
// @returns Pattern ID (string)
export method get_pid(xabcd_harmonic p) =>
if na(p.pid)
set_pid(p)
p.pid
// @function Set value for a target. Use the calc_target parameter to automatically calculate the target for a specific harmonic ratio.
// @param p Instance of xabcd_harmonic object
// @param target Target (1 or 2)
// @param target_lvl Target price/level (required if calc_target is not specified)
// @param calc_target Target to auto calculate (required if target is not specified)
// Options: [".382 AD", ".5 AD", ".618 AD", "1.272 AD", "1.618 AD"
// ".382 XA", ".5 XA" ,".618 XA", "1.272 XA", "1.618 XA",
// ".382 CD", ".5 CD", ".618 CD", "1.272 CD", "1.618 CD",
// "A", "B", "C"]
// @returns Target price/level (float)
export method set_target(xabcd_harmonic p, int target=1, float target_lvl=na, string calc_target=".618 AD") =>
if na(target_lvl)
[t,_,_] = t.harmonic_xabcd_targets(p.x.y,p.a.y,p.b.y,p.c.y,p.d.y,calc_target)
if target==1
p.t1 := t
else
p.t2 := t
else
if target==1
p.t1 := target_lvl
else
p.t2 := target_lvl
// *** Functions ***
// @function Erase the pattern
// @param p Instance of xabcd_harmonic object
// @returns p
export method erase_pattern(xabcd_harmonic p) =>
delete_lines(p)
p.pLines := array.new_line()
p
// @function Draw the pattern
// @param p Instance of xabcd_harmonic object
// @returns Pattern lines
// [l1,l2,l3,l4,l5,l6]
export method draw_pattern(xabcd_harmonic p, color clr) =>
erase_pattern(p)
[lower,higher] = t.harmonic_xabcd_przClosest(p.prz_bN,p.prz_bF,p.prz_xN,p.prz_xF)
float iE = na(p.d.x) ? (p.bull?higher:lower) : na // potential point D for incomplete pattern
[l1,l2,l3,l4,l5,l6] = draw.xabcd(p.x.x,p.x.y,p.a.x,p.a.y,p.b.x,p.b.y,p.c.x,p.c.y,p.d.x,p.d.y,iE,p.bull,color.new(clr,20),color.new(clr,20))
p.pLines := array.from(l1,l2,l3,l4,l5,l6)
[l1,l2,l3,l4,l5,l6]
// @function Erase the pattern label
// @param p Instance of xabcd_harmonic object
// @returns p
export method erase_label(xabcd_harmonic p) =>
delete_label(p)
p
// @function Draw the pattern label. Default text is the pattern name.
// @param p Instance of xabcd_harmonic object
// @param txt Label text
// @param tooltip Tooltip text
// @param clr Label color
// @param txt_clr Text color
// @returns Label
export method draw_label(xabcd_harmonic p, color clr=color.gray, color txt_clr=color.white, string txt=na, string tooltip=na) =>
erase_label(p)
lbstyle = p.bull ? label.style_label_up : label.style_label_down
incLbstyle = p.bull ? label.style_label_down : label.style_label_up
t = not na(txt) ? txt : get_name(p)
lbl =
if not na(p.d.x) // Completed pattern
label.new(p.d.x,p.d.y,text=t,textcolor=txt_clr,size=size.small,style=lbstyle,tooltip=tooltip,color=clr)
else // Incomplete pattern
if array.size(p.pLines)>0
l4 = array.get(p.pLines,3)
not na(l4) ? label.new(line.get_x2(l4),line.get_y2(l4),text=t,tooltip=tooltip,textcolor=txt_clr,size=size.small,style=lbstyle,color=clr)
: label.new(p.c.x,p.c.y,text=t,tooltip=tooltip,textcolor=txt_clr,size=size.small,style=lbstyle,color=clr)
else
label.new(p.c.x,p.c.y,text=t,tooltip=tooltip,textcolor=txt_clr,size=size.small,style=lbstyle,color=clr)
p.pLabel := lbl
//********************************
// Example / Test code
//********************************
// Use your preferred zig-zag method to get the XABCD pattern coordinates.
// Coordinates are hard-coded here for simplicity of the example.
// ADA 4h gartley
var int xX = 10681
var float xY = .344
var x = p.point.new(xX,xY)
var int aX = 10714
var float aY = .296
var a = p.point.new(aX,aY)
var xa = p.leg_init(x,a)
var int bX = 10743
var float bY = .322
var b = p.point.new(bX,bY)
var ab = p.leg_init(a,b)
var int cX = 10752
var float cY = .3
var c = p.point.new(cX,cY)
var bc = p.leg_init(b,c)
var int dX = 10796
var float dY = .329
var d = p.point.new(dX,dY)
var cd = p.leg_init(c,d)
var points = array.from(x, a, b, c, d)
var pattern = p.pattern_init(points,"xabcd")
var legs = array.from(xa,ab,bc,cd)
if bar_index == 10796
// *** Instantiate the xabcd_harmonic ***
// [0] Simply pass in the pattern coordinates and the pattern will be automatically validated.
// If the pattern is valid, an xabcd_harmonic object instance is returned. If you prefer to do
// your own validation, you can skip it by explicitly passing a type (tp) to the init() function.
// Or, if you want to specify the validation and scoring parameters, you can do so by passing a
// harmonic_params object to the init() function.
// pat = init(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY)
// pat = init(xX, xY, aX, aY, bX, bY, cX, cY) // pattern can be incomplete, i.e. point D not yet established
// pat = init(pattern) // can also be initialized from a pattern object
// pat = init(legs) // or from an array of leg objects
pat = init(x,a,b,c,d) // or from an array of point objects
if not na(pat)
// *** When a valid xabcd_harmonic is initialized... ***
// [1] We know what type of harmonic pattern we have (pat.tp field)
name = pat.get_name() + " (" + pat.get_symbol() + ")" // get pattern name and symbol with exported functions
u.print(name)
// [2] PRZ levels are automatically calculated
// e.g. pat.prz_bN, pat.prz_xN, pat.prz_bF, pat.prz_xF
draw.level(pat.prz_bN,na(pat.d)?pat.c.x:pat.d.x,length=100,padding=.5,txt="Near BC PRZ level") // illustrate near BC PRZ retracement level
draw.level(pat.prz_xN,na(pat.d)?pat.c.x:pat.d.x,length=100,padding=.5,txt="Near XA PRZ level") // illustrate near XA PRZ retracement level
// [3] Scores are calculated to represent the quality of the harmonic pattern
// e.g. pat.score, pat.score_prz, pat.score_eAvg, pat.score_eD
u.print(("Leg avg retracement % error: " + str.tostring(pat.score_eAvg*100,"#.#") + "%"),position.bottom_left) // illustrate avg leg retracement % error score
// [4] Easily draw the pattern and a label
pat.draw_pattern(color.red)
pat.draw_label(color.new(color.red,70))
// [5] Set targets. You can specify a specific target level, or have the target automatically calculated for a specific
// harmonic retracement ratio of a pattern leg
// e.g. ".618 AD" or "1.272 XA"
pat.set_target(1, calc_target=".618 AD")
pat.set_target(2, calc_target="1.272 XA")
draw.level(pat.t1,na(pat.d)?pat.c.x:pat.d.x,length=100,padding=.5,txt="Target 1") // illustrate target 1
draw.level(pat.t2,na(pat.d)?pat.c.x:pat.d.x,length=100,padding=.5,txt="Target 2") // illustrate target 2
//erase_pattern(pat)
//erase_label(pat)
// [6] Set stop/entry values, and track trades with state flags
// e.g. pat.stop, pat.entry, pat.sHit, pat.eHit, pat.t1Hit, pat.t2Hit
|
ISODateTime | https://www.tradingview.com/script/UruWuNYe-ISODateTime/ | thomastthai | https://www.tradingview.com/u/thomastthai/ | 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/
// © thomastthai
// @version=5
// @description Library functions to work with ISO 8601 date and time string. It's especially helpful on a daily timeframe when working with timestamp() for a time that occurs after the bar's open time (but same day), and the label or drawing is printed on the next day instead being drawn on the day in the date string.
library(title='ISODateTime')
// @function Get year, month, day from date string.
// @param dateStr <string> : ISO 8601 format, i.e. "2022-05-04T14:00:00.001000-04:00" or "2022-05-04T14:00:00Z"
// @returns int [YYYY, MM, DD]
export getDateParts(string dateStr) =>
var _year = int(na)
var _month = int(na)
var _day = int(na)
var dateStrUpper = str.upper(dateStr)
datePart = str.match(dateStrUpper, "[\\d]{4}-[\\d]{2}-[\\d]{2}")
// get date parts
if str.length(datePart) > 0
_year := math.round(str.tonumber(array.get(str.split(datePart, "-"), 0)))
_month := math.round(str.tonumber(array.get(str.split(datePart, "-"), 1)))
_day := math.round(str.tonumber(array.get(str.split(datePart, "-"), 2)))
[_year, _month, _day]
// @function Get hour, minute, seconds from date string.
// @param dateStr <string> : ISO 8601 format, i.e. "2022-05-04T14:00:00.001000-04:00" or "2022-05-04T14:00:00Z"
// @returns int [HH, MM, SS, MS]
export getTimeParts(string dateStr) =>
var _hour = int(na)
var _minute = int(na)
var _second = int(na)
var _millisecond = 0
var dateStrUpper = str.upper(dateStr)
timePart = str.match(dateStrUpper, "[\\d]+:[\\d]+:[\\d]+")
// get military time
if str.length(timePart) > 0
_hour := math.round(str.tonumber(array.get(str.split(timePart, ":"), 0)))
_minute := math.round(str.tonumber(array.get(str.split(timePart, ":"), 1)))
_second := math.round(str.tonumber(array.get(str.split(timePart, ":"), 2)))
// get milliseconds
if str.length(str.match(dateStrUpper, "\.[\\d]+")) > 0
_millisecond := math.round(str.tonumber(str.match(dateStrUpper, "\.[\\d]+")) * 1000)
[_hour, _minute, _second, _millisecond]
// @function Get UTC timezone.
// @param dateStr <string> : ISO 8601 format, i.e. "2022-05-04T14:00:00.001000-04:00" or "2022-05-04T14:00:00Z"
// @returns string UTC timezone
export getUTCTimezone(string dateStr) =>
var dateStrUpper = str.upper(dateStr)
var _timezone = string(na)
// get timezone
if str.endswith(dateStrUpper, "Z")
_timezone := "UTC" + "+00::00"
else
_timezone := "UTC" + str.match(dateStrUpper, "[+-][\\d]+:[\\d]+$") |
fraction | https://www.tradingview.com/script/bhYERiBH-fraction/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
//@version=5
// © kaigouthro
import kaigouthro/calc/5
//@description Fraction Creation and Basic Operations, To/From Decimal(float), Comparison ( < / == / >), Add / Sub / Mult / Div, Invert polarity +/-, and String output with 2 formats ..
library("fraction")
// function Helpers
// @function Greatet Common Denominator
_gcd(_numerator, _denominator)=>
_greatestCommon = _numerator
_den = _denominator
_swap = _den
while _den != 0
_greatestCommon %= _den
_swap := _den
_den := _greatestCommon
_greatestCommon := _swap
math.abs(_greatestCommon)
// @function array Get wrap for readability
_num (_array) => array.get(_array,0)
// @function array Get wrap for readability
_den (_array) => array.get(_array,1)
//@function Fraction Making and growing if desired to a multiple.
normTo(int _numerator, int _denominator, int _val = na) =>
_arr = array.new<int>(2)
if _denominator != 0
if na(_val)
_arr := array.from(_numerator, _denominator)
else
_arr := array.from(_numerator * _val, _denominator * _val)
// @param _numerator (int) above the line integer ie: ____ of (___ / bottom )
// @param _denominator (int) below the line integer ie: ____ of (top / ______ )
// @param _val (int) OPTIONAL (for no real reason including it) integer to multiply
// @returns array<int> where index 0 is Numerator, 1 is Denominator
export make ( int _numerator, int _denominator, int _val = na) =>
switch
_denominator == 1 => normTo( _numerator , 1)
_numerator == 0 => normTo( 0 , 1)
_denominator == 0 => normTo( 1 , 1)
=>
_d = _gcd( _numerator , _denominator )
switch _d
1 => normTo( _numerator , _denominator , _val )
=> normTo( _numerator / _d, _denominator / _d , _val )
// @function Perform add operation (left adds right onto )
// @param _fraction (array<int>) left side Fraction Object
// @param _fraction2 (array<int>) right side Fraction Object
// @returns array<int> where index 0 is Numerator, 1 is Denominator
export add ( array<int> _fraction , array<int> _fraction2 ) => make ( _num(_fraction) * _den(_fraction2) + _den(_fraction) * _num(_fraction2), _den(_fraction) * _den(_fraction2))
// @function Perform subtract operation (left subtracts right from )
// @param _fraction (array<int>) left side Fraction Object
// @param _fraction2 (array<int>) right side Fraction Object
// @returns array<int> where index 0 is Numerator, 1 is Denominator
export subtract ( array<int> _fraction , array<int> _fraction2 ) => make ( _num(_fraction) * _den(_fraction2) - _den(_fraction) * _num(_fraction2), _den(_fraction) * _den(_fraction2))
// @function Perform multiply operation (left multiplies by right )
// @param _fraction (array<int>) left side Fraction Object
// @param _fraction2 (array<int>) right side Fraction Object
// @returns array<int> where index 0 is Numerator, 1 is Denominator
export multiply ( array<int> _fraction , array<int> _fraction2 ) => make ( _num(_fraction) * _num(_fraction2) , _den(_fraction) * _den(_fraction2))
// @function Perform divide operation (left divides by right )
// @param _fraction (array<int>) left side Fraction Object
// @param _fraction2 (array<int>) right side Fraction Object
// @returns array<int> where index 0 is Numerator, 1 is Denominator
export divide ( array<int> _fraction , array<int> _fraction2 ) => make ( _num(_fraction) * _den(_fraction2) , _den(_fraction) * _num(_fraction2))
// @function Perform Negative number inversion ie: (-1/2 => 1/2) or (3/5 => -3/5)
// @param _fraction (array<int>) Fraction Object to invert to/from negative
// @returns array<int> where index 0 is Numerator, 1 is Denominator
export negative ( array<int> _fraction ) => make (-_num(_fraction) , _den(_fraction))
// @function Check if first fraction is smaller
// @param _fraction (array<int>) left side Fraction Object
// @param _fraction2 (array<int>) right side Fraction Object
// @returns True if smaller, false if bigger
export isSmaller ( array<int> _fraction , array<int> _fraction2 ) => _num(_fraction) *_den(_fraction2) < _num(_fraction2) *_den(_fraction)
// @function Check if first fraction is larger
// @param _fraction (array<int>) left side Fraction Object
// @param _fraction2 (array<int>) right side Fraction Object
// @returns True if smaller, false if bigger
export isLarger ( array<int> _fraction , array<int> _fraction2 ) => _num(_fraction) *_den(_fraction2) > _num(_fraction2) *_den(_fraction)
// @function Check if first fraction is equal
// @param _fraction (array<int>) left side Fraction Object
// @param _fraction2 (array<int>) right side Fraction Object
// @returns True if smaller, false if bigger
export isEqual ( array<int> _fraction , array<int> _fraction2 ) => _num(_fraction) *_den(_fraction2) == _num(_fraction2) *_den(_fraction)
// @function Convert Decimal to Fractioin array
// note : this is my own Negative Number Capable (tiny speed loss)
// adaptation of the fastest algo out there
// Exclusive for Tradingview.
// @param _input (float) Decimal Input
// @param _epsilon (int) (OPTIONAL) to precision 0's after dec 0.0000 -> epsilon 0's
// @param _iterations (int) (OPTIONAL) Maximum iterations Till give up
// @returns array<int> where index 0 is Numerator, 1 is Denominator
export fromDec ( float _source, int _epsilon = 9, int _iterations = 20) =>
switch
int (_source) == _source => make(int(_source), 1)
na (_source) => make(0 , 1)
=>
_num = _source
_pol = math.sign(_num)
_z = math.abs(_num), _n = 1, _t = 1
_d = array.new<int>(_iterations+2,0)
array.set(_d,1,1)
while _t < _iterations and calc.gapSize(_n/array.get(_d,_t), _num) > math.pow(10, -_epsilon)
_t += 1
_z := math.sign(_z)/calc.gapSize(_z,int(_z))
array.set(_d,_t , array.get(_d,_t-1) * math.abs(int(_z)) + array.get(_d,_t-2))
_n := int(_num * array.get(_d,_t ) + _pol/2)
make (_n,array.get(_d,_t))
// @function Convert Fraction to Decimal Output
// @returns Float of fration
export toDec ( array<int> _fraction) =>
_num(_fraction) / _den(_fraction)
// @function Create "A/B" or "A and B/C" String Value of Fraction.
// @param _fraction (array<int>) Fraction Object to invert to/from negative
// @returns String as (-)? A and B/C format
export toString ( array<int> _fraction , bool _wholenum = false) =>
_num = _num ( _fraction )
_den = _den ( _fraction )
switch _den
0 => str.format ('{0} / {1}', 1 , 0 )
1 => str.format ('{0}' , _num )
=>
if _wholenum
_dec = _num / _den
_whole = int ( na )
if math.abs(_dec) > 1
_whole := int ( _num / _den )
_f = fromDec( _dec - _whole )
_num := math.abs(_num ( _f ) )
_den := math.abs(_den ( _f ) )
(na(_whole) ? '' : str.tostring(_whole) + ' and ') + str.format ('{0} / {1}', _num , _den )
else
str.format ('{0} / {1}', _num , _den )
// frac from ints
a = make ( input ( 20 ) , input (11) )
// frac from dec
b = fromDec( input ( 5 ) / input (14) )
// check all and string
_str = " Fractions => op \/ A XXX B \n" +
"\n A ="+toString(a) + " || B =" + toString (b ) +
"\n\n\n A add B ||| => " + toString (add ( a ,b)) +
"\n A subtract B ||| => " + toString (subtract ( a ,b)) +
"\n A multiply B ||| => " + toString (multiply ( a ,b), true) +
"\n A divide B ||| => " + toString (divide ( a ,b), true) +
"\n A negative ||| => " + toString (negative ( a )) +
"\n A is Smaller than B " + str.tostring(isSmaller ( a ,b)) +
"\n A is Larger than B " + str.tostring(isLarger ( a ,b)) +
"\n A is Equal to B " + str.tostring(isEqual ( a ,b))
if barstate.islastconfirmedhistory
label.new(last_bar_index, 0, _str , size = size.huge, color = color.white)
|
TurntLibrary | https://www.tradingview.com/script/39SP8HxB-TurntLibrary/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 10 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EsIstTurnt
//@version=5
// @description Collection of functions created for simplification/easy referencing. Includes variations of moving averages, length value oscillators, and a few other simple functions based upon HH/LL values.
library("TurntLibrary")
// @function Apply a moving average to a float value
// @param source Value to be used
// @param length Number of bars to include in calculation
// @param type Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
// @returns Smoothed value of initial float value
export ma(float source,simple int length,string type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"RMA" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWAP"=> ta.vwap(source)
"SWMA"=> ta.swma(source)
"LRC" => ta.linreg(source,length,0)
// @function Exaggerates curves of a float value designed for use as an exit signal.
// @param src Initial value to curve
// @param len Number of bars to include in calculation
// @param lb1 (Default = 1) First lookback length
// @param lb2 (Default = 2) Second lookback length
// @returns Curvey Average
export curve(float src,int len,int lb1 = 1,int lb2 = 2)=>
x=ta.linreg((ta.highest(src[len],len)-ta.lowest(src[len],len) > ta.highest(src,len)-ta.lowest(src,len))?
ta.sma(math.avg(open,open[lb1],open[lb2])<math.avg(close,close[lb1],close[lb2])?ta.highest(src,math.round(math.avg(lb1,lb2))):ta.lowest(src,math.round(math.avg(lb1,lb2))),len)
:ta.linreg(src,len ,0),len,0)
avg=math.avg(x,ta.ema(src,math.round(len/2)))
avg
// @function Average of a moving average and the previous value of the moving average
// @param src Initial float value to use
// @param len Number of bars to include in calculation
// @param space Lookback integer for second half of average
// @param str Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
// @returns Fragmented Average
export fragma(float src,simple int len,int space,string str)=>
ma1=ma(src,len,str)
ma2=ma(src[space],len,str)
avg=ma(math.avg(ma1,ma2),len,str)
avg
// @function Difference of 2 float values, subtracting the lowest from the highest
// @param x Value 1
// @param y Value 2
// @returns The +Difference between 2 float values
export maxmin(float x,float y)=>
var float dif = 0.0
dif := math.max(x,y)-math.min(x,y)
dif
// @function Variable Length using a oscillator value and a corresponding slope shape ("Incline",Decline","Peak","Trough")
// @param val Oscillator Value to use
// @param type Slope of length curve ("Incline",Decline","Peak","Trough")
// @returns Variable Length Integer
export oscLen(float val, string type)=>
v=ta.min(val) >= 0 ? 100*val/ta.max(val):100*((0-ta.min(val))+val)/(ta.max(0-ta.min(val)+val))
switch type
"Incline" => v>98?98:v>96?96:v>94?94:v>92?92:v>90?90:
v>88?88:v>86?86:v>84?84:v>82?82:v>80?80:
v>78?78:v>76?76:v> 74?74:v>72?72:v>70?70:
v>68?68:v>66?66:v>64?64:v>62?62:v>60?60:
v>58?58:v>56?56:v>54?74:v>52?72:v>50?50:
v>48?48:v>46?46:v>44?44:v>42?42:v>40?40:
v>38?38:v>36?36:v>34?34:v>32?32:v>30?30:
v>28?28:v>26?26:v>24?24:v>22?22:v>20?20:
v>18?18:v>16?16:v>14?14:v>12?12:v>10?10:
v>8?8:v>6?6:4
"Decline" => v>98?2:v>96?4:v>94?6:v>92?8:v>90?10:
v>88?12:v>86?14:v>84?16:v>82?18:v>80?20:
v>78?22:v>76?24:v>74?26:v>72?28:v>70?30:
v>68?32:v>66?34:v>64?36:v>62?38:v>60?40:
v>58?42:v>56?44:v>54?46:v>52?48:v>50?50:
v>48?48:v>46?46:v>44?44:v>42?42:v>40?40:
v>38?38:v>36?36:v>34?34:v>32?32:v>30?30:
v>28?28:v>26?26:v>24?24:v>22?22:v>20?20:
v>18?18:v>16?16:v>14?14:v>12?12:v>10?10:
v>8?8:v>6?4:2
"Peak" => v>98?32:v>96?36:v>94?40:v>92?44:v>90?48:
v>88?52:v>86?56:v>84?60:v>82?64:v>80?68:
v>78?72:v>76?76:v>74?80:v>72?84:v>70?88:
v>68?92:v>66?96:v>64?100:v>62?104:v>60?108:
v>58?112:v>56?116:v>54?120:v>52?124:v>50?128:
v>48?124:v>46?120:v>44?116:v>42?112:v>40?108:
v>38?104:v>36?100:v>34?96:v>32?92:v>30?88:
v>28?84:v>26?80:v>24?76:v>22?72:v>20?68:
v>18?64:v>16?60:v>14?56:v>12?52:v>10?48:
v>8?44:v>6?40:v>4?36:32
"Trough"=> v>98?98:v>96?96:v>94?94:v>92?92:v>90?90:
v>88?88:v>86?86:v>84?84:v>82?82:v>80?80:
v>78?78:v>76?76:v> 74?74:v>72?72:v>70?70:
v>68?68:v>66?66:v>64?64:v>62?62:v>60?60:
v>58?58:v>56?56:v>54?74:v>52?72:v>50?50:
v>48?52:v>46?54:v>44?56:v>42?58:v>40?60:
v>38?62:v>36?64:v>34?66:v>32?68:v>30?70:
v>28?72:v>26?74:v>24?76:v>22?78:v>20?80:
v>18?82:v>16?84:v>14?86:v>12?88:v>10?90:
v>8?92:v>6?94:v>4?96:98
// @function Average of HH,LL with variable lengths based on the slope shape ("Incline","Decline","Trough") value relative to highest and lowest
// @param val Source Value to use
// @param Highest Length value to use
// @param Lowest Length value to use
// @param Shape of length curve ("Incline","Decline","Trough")
// @param include Add "val" to the averaging process, instead of more weight to highest or lowest value
// @returns Variable Length Average of Highest Lowest "val"
export hlAverage(float val, int smooth, int max,int min, string type,bool include = false)=>
minmax= (max-min)/20
lengthH= min
lengthL= min
x1 =type == "Incline"? 1 :type == "Decline"?20:type == "Trough"?10*2:na//type == "Peak"?1 *1.5
x2 =type == "Incline"? 2 :type == "Decline"?19:type == "Trough"?9 *2:na//type == "Peak"?2 *1.5
x3 =type == "Incline"? 3 :type == "Decline"?18:type == "Trough"?8 *2:na//type == "Peak"?3 *1.5
x4 =type == "Incline"? 4 :type == "Decline"?17:type == "Trough"?7 *2:na//type == "Peak"?4 *1.5
x5 =type == "Incline"? 5 :type == "Decline"?16:type == "Trough"?6 *2:na//type == "Peak"?5 *1.5
x6 =type == "Incline"? 6 :type == "Decline"?15:type == "Trough"?5 *2:na//type == "Peak"?6 *1.5
x7 =type == "Incline"? 7 :type == "Decline"?14:type == "Trough"?4 *2:na//type == "Peak"?7 *1.5
x8 =type == "Incline"? 8 :type == "Decline"?13:type == "Trough"?3 *2:na//type == "Peak"?8 *1.5
x9 =type == "Incline"? 9 :type == "Decline"?12:type == "Trough"?2 *2:na//type == "Peak"?9 *1.5
x10 =type == "Incline"? 10 :type == "Decline"?11:type == "Trough"?1 *2:na//type == "Peak"?10*1.5
x11 =type == "Incline"? 11 :type == "Decline"?10:type == "Trough"?1 *2:na//type == "Peak"?10*1.5
x12 =type == "Incline"? 12 :type == "Decline"? 9:type == "Trough"?2 *2:na//type == "Peak"?9 *1.5
x13 =type == "Incline"? 13 :type == "Decline"? 8:type == "Trough"?3 *2:na//type == "Peak"?8 *1.5
x14 =type == "Incline"? 14 :type == "Decline"? 7:type == "Trough"?4 *2:na//type == "Peak"?7 *1.5
x15 =type == "Incline"? 15 :type == "Decline"? 6:type == "Trough"?5 *2:na//type == "Peak"?6 *1.5
x16 =type == "Incline"? 16 :type == "Decline"? 5:type == "Trough"?6 *2:na//type == "Peak"?5 *1.5
x17 =type == "Incline"? 17 :type == "Decline"? 4:type == "Trough"?7 *2:na//type == "Peak"?4 *1.5
x18 =type == "Incline"? 18 :type == "Decline"? 3:type == "Trough"?8 *2:na//type == "Peak"?3 *1.5
x19 =type == "Incline"? 19 :type == "Decline"? 2:type == "Trough"?9 *2:na//type == "Peak"?2 *1.5
x20 =type == "Incline"? 20 :type == "Decline"? 1:type == "Trough"?10*2:na//type == "Peak"?1 *1.5
dif_h=ta.highest(val,max) - val
dif_l=val - ta.lowest (val,max)
dif_hl=ta.highest(val,max)-ta.lowest(val,max)
ratio_h=(100*dif_h)/dif_hl
ratio_l=(100*dif_l)/dif_hl
lengthH:=math.round(math.max(ratio_h<=5?max-(x1*minmax)
:ratio_h<=10?min+ (x2 *minmax)
:ratio_h<=15?min+ (x3 *minmax)
:ratio_h<=20?min+ (x4 *minmax)
:ratio_h<=25?min+ (x5 *minmax)
:ratio_h<=30?min+ (x6 *minmax)
:ratio_h<=35?min+ (x7 *minmax)
:ratio_h<=40?min+ (x8 *minmax)
:ratio_h<=45?min+ (x9 *minmax)
:ratio_h<=50?min+ (x10*minmax)
:ratio_h<=55?min+ (x11*minmax)
:ratio_h<=60?min+ (x12*minmax)
:ratio_h<=65?min+ (x13*minmax)
:ratio_h<=70?min+ (x14*minmax)
:ratio_h<=75?min+ (x15*minmax)
:ratio_h<=80?min+ (x16*minmax)
:ratio_h<=85?min+ (x17*minmax)
:ratio_h<=90?min+ (x18*minmax)
:ratio_h<=95?min+ (x19*minmax)
:min+ (x20*minmax),min))
lengthL:=math.round(math.max(ratio_l<=5?max-(x1*minmax)
:ratio_l<=10?max-(x2 *minmax)
:ratio_l<=15?max-(x3 *minmax)
:ratio_l<=20?max-(x4 *minmax)
:ratio_l<=25?max-(x5 *minmax)
:ratio_l<=30?max-(x6 *minmax)
:ratio_l<=35?max-(x7 *minmax)
:ratio_l<=40?max-(x8 *minmax)
:ratio_l<=45?max-(x9 *minmax)
:ratio_l<=50?max-(x10*minmax)
:ratio_l<=55?max-(x11*minmax)
:ratio_l<=60?max-(x12*minmax)
:ratio_l<=65?max-(x13*minmax)
:ratio_l<=70?max-(x14*minmax)
:ratio_l<=75?max-(x15*minmax)
:ratio_l<=80?max-(x16*minmax)
:ratio_l<=85?max-(x17*minmax)
:ratio_l<=90?max-(x18*minmax)
:ratio_l<=95?max-(x19*minmax)
:max-(x20*minmax),min))
avglen=nz(math.round(ta.median(math.avg(lengthH,lengthL),max)),8)
average=ta.ema(ta.linreg(math.avg(ta.highest(close,lengthH),ta.lowest(close,lengthL),(include?close:close>ta.vwap(close)?ta.highest(high,min):ta.lowest(low,min))),smooth,0),smooth )
average
// @function Geometric average of midpoint and value with an additional modifier
// @param src = Value to use in calculation
// @param length # of bars to include in calculation
// @param offset LRC offset
// @param atr ATR length to use
// @returns a Geometric Average of a modified Geometric Average
export geoma(float src,simple int length,simple int offset, simple int atr = 4)=>
lrc=ta.linreg(src, length, offset)
avg=math.avg(ta.highest(high,length),ta.lowest(low,length))
sqrt=math.sqrt(lrc*avg)
hl=ta.ema(src,8)>sqrt?ta.linreg(high,length,0)+ta.atr(atr):ta.linreg(low,length,0)-ta.atr(atr)
sqrt:=ta.ema(math.sqrt(hl*sqrt),length/8)
sqrt
// @function Midpoint between Highest and Lowest using variable lookback
// @param src = Value to use in calculation
// @param length # of bars to include in calculation
// @param offset LRC offset
// @param up Slope of length curve to use ("Incline","Decline","Peak","Trough")
// @param dn Slope of length curve to use ("Incline","Decline","Peak","Trough")
// @returns Dynamic Relative Strength Average
export rsma(float src,simple int length,simple int offset,string up="Peak", string dn = "Trough")=>
lrc=ta.linreg(ta.vwap(src), length, offset)
rsi=ta.rsi(hl2,length)
rup=oscLen(rsi,up)
rdn=oscLen(rsi,dn)
avg=math.avg(ta.highest(high,math.round(rup)),ta.lowest(low,math.round(rdn)))
sqrt=math.sqrt(lrc*avg)
hl=ta.ema(avg,math.round(length/2))<lrc?ta.linreg(high+ta.atr(length),rup,0):ta.linreg(low-ta.atr(length),rdn,0)
sqrt:=ta.ema(math.sqrt(hl*sqrt),length/2)
sqrt
// @function Midpoint using dynamic lengths with Incline/Decline Slopes
// @param src = Value to use in calculation
// @param length # of bars to include in calculation
// @param offset LRC offset
// @returns Incline Decline MA
export yma(float src,simple int length,simple int offset)=>
hI=oscLen(ta.rsi(ta.barssince(ta.highest(src[1],length)==src[1] and ta.highest(src,length)!=src)*-1,length),'Incline')
hD=oscLen(ta.rsi(ta.barssince(ta.highest(src[1],length)==src[1] and ta.highest(src,length)!=src)*-1,length),'Decline')
lI=oscLen(ta.rsi(ta.barssince(ta.lowest(src[1],length)==src[1] and ta.lowest(src,length)!=src) ,length),'Incline')
lD=oscLen(ta.rsi(ta.barssince(ta.lowest(src[1],length)==src[1] and ta.lowest(src,length)!=src) ,length),'Decline')
avg=ta.rsi(ta.ema(math.avg(hI,lI,hD,lD),length*2),length)
hi=ta.highest(high,nz(math.max(math.round(length/2),math.round(avg)),1))
lo=ta.lowest(low,nz(math.max(math.round(length/2),math.round(avg)),1))
avghl=ta.linreg(math.avg(hi,lo),length*2,offset)
avghl
// @function Midpoint using dynamic lengths with Peak Trough Slopes
// @param src = Value to use in calculation
// @param length # of bars to include in calculation
// @param offset LRC offset
// @returns Peak Trough MA
export xma(float src,simple int length,simple int offset)=>
hP=oscLen(ta.rsi(ta.barssince(ta.highest(src[1],length)==src[1] and ta.highest(src,length)!=src)*-1,length),'Peak')
hT=oscLen(ta.rsi(ta.barssince(ta.highest(src[1],length)==src[1] and ta.highest(src,length)!=src)*-1,length),'Trough')
lP=oscLen(ta.rsi(ta.barssince(ta.lowest(src[1],length)==src[1] and ta.lowest(src,length)!=src) ,length),'Peak')
lT=oscLen(ta.rsi(ta.barssince(ta.lowest(src[1],length)==src[1] and ta.lowest(src,length)!=src) ,length),'Trough')
avg=ta.rsi(ta.ema(math.avg(hP,lP,hT,lT),length*2),length)
hi=ta.highest(high,nz(math.max(math.round(length/2),math.round(avg)),1))
lo=ta.lowest(low,nz(math.max(math.round(length/2),math.round(avg)),1))
avghl=ta.linreg(math.avg(hi,lo),length*2,offset)
avghl
// @function Gravitational Moving Average, Adds weight to lowest highest or center point based upon the current value in relation to the highest/lowest values.
// @param src = Value to use in calculation
// @param length # of bars to include in calculation
// @param offset LRC offset
// @returns Gravitational MA
export gma(float src,simple int length,simple int mult = 4, string type = "Trough")=>
h=ta.highest(src,length*mult)
hdif=ta.highest(src,length*mult)-src
l=ta.lowest(src,length*mult)
ldif=src-ta.lowest(src,length*mult)
dif=h-l
lgrav=ldif<0.1*dif?math.avg(l,src):ldif<0.2*dif?math.avg(l,l,src):ldif<0.3*dif?math.avg(l,l,l,src):math.avg(l,src+0.5*hdif,src-0.5*ldif)
hgrav=hdif<0.1*dif?math.avg(h,src):hdif<0.2*dif?math.avg(h,h,src):hdif<0.3*dif?math.avg(h,h,h,src):math.avg(h,src+0.5*hdif,src-0.5*ldif)
grav=ta.ema(ta.linreg((ldif<0.4*dif?lgrav:ldif>0.4*dif and hdif > 0.4*dif? math.avg(hgrav,lgrav):hgrav),oscLen((ta.rsi(math.min(ldif,hdif)/math.max(ldif,hdif),length)),type),0),length)
grav
// @function Convert a positive float / price to a percentage of it's highest value on record
// @param val Value To convert to a percentage of it's highest value ever
// @returns Percentage
export pct(float val)=>
percent=100*val/ta.max(val)
percent
// @function Difference between Highest High and Lowest Low of float value
// @param x Value to use in calculation
// @param len Number of bars to include in calculation
// @returns Difference
export hlrange(float x, int len)=>
span=ta.highest(x,len)-ta.lowest(x,len)
span
// @function The average value of the float's Highest High and Lowest Low in a number of bars
// @param x Value to use in calculation
// @param l Number of bars to include in calculation
// @param smooth (Default=na) Optional smoothing type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
// @returns Midpoint
export midpoint(float x,simple int len,string smooth = na)=>
h=ta.highest(x,len)
l=ta.lowest(x,len)
avg=math.avg(h,l)
switch smooth
"SMA" => ta.sma(avg,len)
"EMA" => ta.ema(avg,len)
"RMA" => ta.rma(avg,len)
"WMA" => ta.wma(avg,len)
"VWAP"=> ta.vwap(avg)
"SWMA"=> ta.swma(avg)
"LRC" => ta.linreg(avg,len,0)
=>avg
// @function RSI based momentum oscillator
// @param src Source value to use
// @param len Length value to use throughout calculation
// @param lookback (Default = 1) Lookback value
// @param pow (Default = 2) Power to use on counters
// @returns A curvey rsi based momentum oscillator
export wave(float src,simple int len,int lookback = 1,float pow = 2)=>
rsi=ta.rsi(src,len)
h=ta.rsi(math.pow(ta.barssince(ta.highest(src[lookback],len*4)==src[lookback] and rsi>70 and ta.highest(src,len*4)!=src),pow)*-1,len)
l=ta.rsi(math.pow(ta.barssince(ta.lowest(src[lookback],len*4)==src[lookback] and rsi<30 and ta.lowest(src,len*4)!=src),pow),len)
avg=ta.ema(math.avg(h,l),len*2)
avg
//////////////////PLOTS
//plot(hlAverage(close,32,128,32,"Incline"),color=#ff0000)
//plot(hlAverage(close,8,64,12,"Trough"),color=#ee6600)
plot(curve(close,16))
//plot(hlAverage(close,32,128,32,"Decline"),color=#acfb00)
line1=geoma(close,24,0)
line2=rsma(close,24,0)
line3=yma(close,24,0)
line4=xma(close,24,0)
line5=gma(close,16)
avg=ta.linreg(math.avg(line1,line2,line3,line4,line5),16,0)
//plot(line1,color=#00ee33)
//plot(line2,color=#ee6600)
//plot(line3,color=#ff0000)
//plot(line4,color=#fff000)
//plot(line5,color=#a619c9)
plot(avg,color=#ff0000) |
TrapCar | https://www.tradingview.com/script/sMStzTWK-TrapCar/ | poppip | https://www.tradingview.com/u/poppip/ | 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/
// © Maestro37
//@version=5
indicator("Trap Car" , overlay = true , precision = 3 , max_labels_count = 500)
smoothK = input.int(3, 'K', minval=1)
smoothD = input.int(3, 'D', minval=1)
lengthRSI = input.int(14, 'RSI Length', minval=1)
lengthStoch = input.int(14, 'Stochastic Length', minval=1)
src = input(close, title='RSI Source')
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
cond = k == 0
cond2 = k == 100
symbol = input.string("🚘" , title = "Symbol for Stochastic Above 95 " , tooltip = "Only the first character is displayed")
symbol2 = input.string("🚖" , title = "Symbol for Stochastic Between 5 - 95 " , tooltip = "Only the first character is displayed")
symbol3 = input.string("🚔" , title = "Symbol for Stochastic below 5 " , tooltip = "Only the first character is displayed")
symsize = input.string("Auto" , title = "Symbol Size" , options = ["Tiny" , "Small" , "Normal" , "Large" , "Huge" , "Auto"])
Locating = input.string("Above Bar" , title = "Location" , options = ["Above Bar" , "Below Bar", "Top" , "Bottom"])
colorSym = input.color(color.red , title = "Color of Symbol" , tooltip = "This Works only for Symbols with no default colors , emoji have default colors so it wont work on them ")
textCol = input.color(color.red , title = "Color of Text")
candleSize(sizes) =>
sizing = switch sizes
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
sizing
location(locating) =>
location = switch Locating
"Above Bar" => location.abovebar
"Below Bar" => location.belowbar
"Top" => location.top
"Bottom" => location.bottom
location
sizeofsymbol = candleSize(symsize)
plotchar((close > 0 or close < 0) and symsize == "Tiny" and k > 95, title = "Something" , char = symbol , location = location(Locating) , size = size.tiny , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Small" and k > 95, title = "Something" , char = symbol , location = location(Locating) , size = size.small , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Normal" and k > 95, title = "Something" , char = symbol , location = location(Locating) , size = size.normal , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Large" and k > 95, title = "Something" , char = symbol , location = location(Locating) , size = size.large , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Huge" and k > 95, title = "Something" , char = symbol , location = location(Locating) , size = size.huge , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Auto" and k > 95, title = "Something" , char = symbol , location = location(Locating) , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Tiny" and k >=5 and k <= 95, title = "Something" , char = symbol2 , location = location(Locating) , size = size.tiny , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Small" and k >=5 and k <= 95, title = "Something" , char = symbol2 , location = location(Locating) , size = size.small , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Normal" and k >=5 and k <= 95, title = "Something" , char = symbol2 , location = location(Locating) , size = size.normal , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Large" and k >=5 and k <= 95, title = "Something" , char = symbol2 , location = location(Locating) , size = size.large , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Huge" and k >=5 and k <= 95, title = "Something" , char = symbol2 , location = location(Locating) , size = size.huge , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Auto" and k >=5 and k <= 95, title = "Something" , char = symbol2 , location = location(Locating) , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Tiny" and k < 5, title = "Something" , char = symbol3 , location = location(Locating) , size = size.tiny , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Small" and k < 5, title = "Something" , char = symbol3 , location = location(Locating) , size = size.small , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Normal" and k < 5, title = "Something" , char = symbol3 , location = location(Locating) , size = size.normal , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Large" and k < 5, title = "Something" , char = symbol3 , location = location(Locating) , size = size.large , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Huge" and k < 5, title = "Something" , char = symbol3 , location = location(Locating) , size = size.huge , display = display.pane , color = colorSym)
plotchar((close > 0 or close < 0) and symsize == "Auto" and k < 5, title = "Something" , char = symbol3 , location = location(Locating) , display = display.pane , color = colorSym)
label.new(x = bar_index , y =low , text = cond ? "Buy" : cond2 ? "Sell" : str.tostring(k , "#.##") , style = label.style_diamond , color = color.rgb(255, 82, 82, 100) , textcolor = textCol , yloc = yloc.belowbar , size = size.auto)
alertcondition(cond, "Buy Alert" , "This is a Buy Signal Alert")
alertcondition(cond2, "Sell Alert" , "This is a Sell Signal Alert") |
Slope_TK | https://www.tradingview.com/script/yNDmge51-Slope-TK/ | mentalRock19315 | https://www.tradingview.com/u/mentalRock19315/ | 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/
// © mentalRock19315
//@version=5
// @description This library calculate the slope of a serie between two points
library("Slope_TK")
// @function Return the slope between the actual bar and the older bar in the 'size' position
// @param serie = serie from which you want calculate the slope
// @param size = the number of bars between the two bars on which the slope is calculated
// @returns The slope of the line beween the two values : ( serie[size], bar_index[size] ) and ( serie, bar_index )
export slope(float serie, int size) =>
// Slope value
// a = (y2 - y1) / (x2 - x1)
slope = (serie[0]-serie[size])
slope |
CAPM Model with Returns Table | https://www.tradingview.com/script/h6mg2CwM-CAPM-Model-with-Returns-Table/ | Mishari_Alr | https://www.tradingview.com/u/Mishari_Alr/ | 4 | 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/
// © Mishari_Algos
//@version=5
indicator("CAPM Model with Returns Table", shorttitle = "CAPM MODEL", overlay=false, precision = 3)
// User inputs
benchmarkSymbol = input.symbol ("CRYPTOCAP:TOTAL")
riskFreeRate = input.float(0.01, "Risk-free Rate (e.g., 0.01 for 1%)",group = "Plot Settings ")
assetSymbol = syminfo.tickerid
Benchmark_Asset_Length = input.int(30, "Benchmark Period", tooltip = "This setting is only used for the plot and not included in the calculations displayed on the table",group = "Plot Settings ")
period1 = input.int(30, "First Period (days)",group = "Periods Settings ",tooltip = "All Periods below are for table calulcations only!")
period2 = input.int(60, "Second Period (days)",group = "Periods Settings ")
period3 = input.int(90, "Third Period (days)",group = "Periods Settings ")
period4 = input.int(120, "Fourth Period (days)",group = "Periods Settings ")
// Retrieve the close prices for the benchmark and the asset
benchmarkClose = request.security(benchmarkSymbol, timeframe.period, close)
assetClose = request.security(assetSymbol, timeframe.period, close)
// Calculate daily returns for benchmark and asset
benchmarkReturn = ta.change(benchmarkClose) / benchmarkClose[1]
assetReturn = ta.change(assetClose) / assetClose[1]
// Helper function to calculate beta for a given period
calcBeta(period) =>
benchmarkMeanReturnPeriod = ta.sma(benchmarkReturn, period)
assetMeanReturnPeriod = ta.sma(assetReturn, period)
covXYPeriod = ta.sma((benchmarkReturn - benchmarkMeanReturnPeriod) * (assetReturn - assetMeanReturnPeriod), period)
varXPeriod = ta.sma(math.pow(benchmarkReturn - benchmarkMeanReturnPeriod, 2), period)
covXYPeriod / varXPeriod
// Calculate expected returns for each user-specified period
expectedReturnPeriod1 = riskFreeRate + calcBeta(period1) * (ta.sma(benchmarkReturn, period1) - riskFreeRate)
expectedReturnPeriod2 = riskFreeRate + calcBeta(period2) * (ta.sma(benchmarkReturn, period2) - riskFreeRate)
expectedReturnPeriod3 = riskFreeRate + calcBeta(period3) * (ta.sma(benchmarkReturn, period3) - riskFreeRate)
expectedReturnPeriod4 = riskFreeRate + calcBeta(period4) * (ta.sma(benchmarkReturn, period4) - riskFreeRate)
// Calculate mean returns for benchmark and asset
benchmarkMeanReturn = ta.sma(benchmarkReturn, Benchmark_Asset_Length)
assetMeanReturn = ta.sma(assetReturn, Benchmark_Asset_Length)
// Calculate the asset's mean return for each user-specified period
assetMeanReturnPeriod1 = ta.sma(assetReturn, period1)
assetMeanReturnPeriod2 = ta.sma(assetReturn, period2)
assetMeanReturnPeriod3 = ta.sma(assetReturn, period3)
assetMeanReturnPeriod4 = ta.sma(assetReturn, period4)
// Calculate covariance and variance
covXY = ta.sma((benchmarkReturn - benchmarkMeanReturn) * (assetReturn - assetMeanReturn), Benchmark_Asset_Length)
varX = ta.sma(math.pow(benchmarkReturn - benchmarkMeanReturn, 2), Benchmark_Asset_Length)
// Calculate beta
beta = covXY / varX
// Using CAPM to estimate expected return
expectedReturn = riskFreeRate + beta * (benchmarkMeanReturn - riskFreeRate)
// Average of the expected returns
avgExpectedReturn = (expectedReturnPeriod1 + expectedReturnPeriod2 + expectedReturnPeriod3 + expectedReturnPeriod4) / 4.0
// Average of the asset's mean returns
avgAssetMeanReturn = (assetMeanReturnPeriod1 + assetMeanReturnPeriod2 + assetMeanReturnPeriod3 + assetMeanReturnPeriod4) / 4.0
// Display results in a table
var table returnsTable = table.new(position.middle_left, 6, 3,frame_width = 1,frame_color = color.black,border_width = 1)
table.cell(returnsTable, 0, 0, "Period", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 0, 1, "Expected Return", bgcolor=color.gray, text_color=color.rgb(14, 145, 42))
table.cell(returnsTable, 1, 0, str.tostring(period1) + " Days", bgcolor=color.silver)
table.cell(returnsTable, 1, 1, str.tostring(math.round(expectedReturnPeriod1 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 2, 0, str.tostring(period2) + " Days", bgcolor=color.silver)
table.cell(returnsTable, 2, 1, str.tostring(math.round(expectedReturnPeriod2 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 3, 0, str.tostring(period3) + " Days", bgcolor=color.silver)
table.cell(returnsTable, 3, 1, str.tostring(math.round(expectedReturnPeriod3 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 4, 0, str.tostring(period4) + " Days", bgcolor=color.silver)
table.cell(returnsTable, 4, 1, str.tostring(math.round(expectedReturnPeriod4 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 5, 0, "Average", bgcolor=color.gray, text_color=color.white)
table.cell(returnsTable, 5, 1, str.tostring(math.round(avgExpectedReturn * 100, 2)) + "%", bgcolor=color.gray, text_color=color.white)
// Add asset's mean returns to the table
table.cell(returnsTable, 0, 2, "Asset's Mean Return", bgcolor=color.gray, text_color=color.rgb(25, 69, 158))
table.cell(returnsTable, 1, 2, str.tostring(math.round(assetMeanReturnPeriod1 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 2, 2, str.tostring(math.round(assetMeanReturnPeriod2 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 3, 2, str.tostring(math.round(assetMeanReturnPeriod3 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 4, 2, str.tostring(math.round(assetMeanReturnPeriod4 * 100, 2)) + "%", bgcolor=color.silver)
table.cell(returnsTable, 5, 2, str.tostring(math.round(avgAssetMeanReturn * 100, 2)) + "%", bgcolor=color.gray, text_color=color.white)
// ========== Start of Implication Code ==========
// Determine implication based on comparison
implication() =>
er = avgExpectedReturn
mr = avgAssetMeanReturn
if er > 0 and mr > er
"Historical performance of the asset has been better than what the model currently predicts.\n The asset might be experiencing a slowdown or the model might be conservative."
else if er > 0 and er > mr
"The model is more optimistic about the asset's future performance than its recent history suggests.\n Possible signs of a turnaround or an upcoming positive trend."
else if er > 0 and mr == 0
"The model suggests positive returns, but the asset's historical performance has been neutral.\n This might indicate changing conditions or new factors influencing the asset."
else if er > 0 and mr < 0
"The model suggests positive returns, but historically the asset has performed poorly. \nThis could indicate potential turnaround, or it might suggest that the model's assumptions or inputs need review."
else if er == 0 and mr > 0
"The model suggests neutral returns while the asset has had positive historical returns.\n This might indicate a potential slowdown or stagnation."
else if er == 0 and mr == 0
"Both the model and historical data suggest neutral returns. \nThe asset may be seen as stable or stagnant."
else if er == 0 and mr < 0
"The model expects no change, but the asset has historically lost value. \nThis might indicate potential stabilization after a downturn."
else if er < 0 and mr < er
"Both the model and historical data suggest negative returns, but the model is more pessimistic than the asset's history. \nThe situation might be worsening, or the model might be overly pessimistic."
else if er < 0 and er < mr
"Both suggest negative returns, but historical data is more pessimistic than the model's prediction.\n This could indicate potential stabilization or a slight recovery."
else if er < 0 and mr == 0
"The model suggests negative returns, while the asset's historical performance has been neutral.\n This might indicate potential challenges ahead."
else
"No specific implication detected." // Default message in case no conditions are met
// Create a mutable label variable
var label impLabel = na
// Update the label
// Offset for label placement
labelOffset = 300
// Update the label
if (na(impLabel))
impLabel := label.new(x=bar_index - labelOffset, y=0, text=implication(), color=color.gray )
else
label.set_xy(impLabel, bar_index - labelOffset, 0)
label.set_text(impLabel, implication())
// ========== End of Implication Code ==========
// Determine implication based on comparison
// Plot expected return and asset's mean return
plot(expectedReturn * 100, title="Expected Return (%)", color=color.green)
plot(assetMeanReturn * 100, title="Asset's Mean Return (%)", color=color.blue)
hline(0, "Zero Return", color=color.gray)
|
MarketStructure | https://www.tradingview.com/script/0c17A7v9-MarketStructure/ | SimpleCryptoLife | https://www.tradingview.com/u/SimpleCryptoLife/ | 93 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SimpleCryptoLife
//@version=5
// @description This library contains functions for identifying Lows and Highs in a rule-based way, and deriving useful information from them.
library("MarketStructure", overlay=true)
string in_showFunction = input.string(title="Show Function", defval="f_localLowHigh", options=["f_simpleLowHigh","f_localLowHigh","f_enhancedSimpleLowHigh", "f_trueLowHigh"])
// Variables derived entirely from inputs
var bool showSimple = in_showFunction == "f_simpleLowHigh"
var bool showLocal = in_showFunction == "f_localLowHigh"
var bool showEnhanced = in_showFunction == "f_enhancedSimpleLowHigh"
var bool showTrue = in_showFunction == "f_trueLowHigh"
import SimpleCryptoLife/Labels/2 as SCL_Label
color labelColour = color.new(color.white,50)
// 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦 FUNCTION 1 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦
// @function _simpleLowHigh() // This function finds Local Lows and Highs, but NOT in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
// The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
// It doesn't have to be "the" high, so don't be confused.
// By the rules, Local Lows and Highs must alternate. In this function they do not, so I'm calling them Simple Lows and Highs.
// Simple Highs and Lows, by the above definition, can be useful for entries and stops. Because I intend to use them for stops, I want them all, not just the ones that alternate in strict order.
// @param - there are no parameters. The function uses the chart OHLC.
// @returns boolean values for whether this bar confirms a Simple Low/High, and ints for the bar_index of that Low/High.
export f_simpleLowHigh() =>
var float _trailingLow = na, var float _trailingHigh = na // Trail for the low (which is used to confirm Highs), and the high (used to confirm Lows).
var int _simpleHighIndex = na, var int _simpleLowIndex = na // The bar index of the Simple High/Low when confirmed.
var int _trailingLowIndex = na, var int _trailingHighIndex = na // The bar index of the last low that changed the trailing low, or high for trailing high.
// Setup for Highs
if low > _trailingLow or (na(_trailingLow) and (low > low[1]))
_trailingLow := low // Trail the lows up. If higher, reset, otherwise persist.
_trailingLowIndex := bar_index // When you change the trailing low, store the bar index.
// Setup for Lows
if high < _trailingHigh or (na(_trailingHigh) and (high < high[1]))
_trailingHigh := high // Trail the highs down. If lower, reset, otherwise persist.
_trailingHighIndex := bar_index // When you change the trailing high, store the bar index.
// Confirm Highs, Lows
bool _isSimpleHigh = close < _trailingLow // Confirm a High on close below the trailing low.
bool _isSimpleLow = close > _trailingHigh // Confirm a Low on close above the trailing high.
// Cleanup
if _isSimpleHigh
_trailingLow := na // When a High is confirmed, unset the trailing low line.
_simpleHighIndex := _trailingLowIndex // And store the bar index of the High.
if _isSimpleLow
_trailingHigh := na // When a Low is confirmed, unset the trailing high line.
_simpleLowIndex := _trailingHighIndex // And store the bar index of the Low.
[_isSimpleHigh, _isSimpleLow, _simpleHighIndex, _simpleLowIndex]
// Example usage
[isSimpleHigh, isSimpleLow, simpleHighIndex, simpleLowIndex] = f_simpleLowHigh()
plotshape(showSimple ? isSimpleHigh : na, title="Simple High Confirmed", style=shape.arrowdown, color=color.red, location=location.abovebar, size=size.small)
plotshape(showSimple ? isSimpleLow : na, title="Simple Low Confirmed", style=shape.arrowup, color=color.green, location=location.belowbar, size=size.small)
int offsetHighSimple = simpleHighIndex - bar_index, int offsetLowSimple = simpleLowIndex - bar_index // Offset for the label must be negative to offset to the left.
int historyHighSimple = bar_index - simpleHighIndex, int historyLowSimple = bar_index - simpleLowIndex // Offset for the historical operator must be the other way round.
// We have to use a label because plotshape and plotchar don't work for some reason with series offsets even though they're supposed to.
if showSimple and isSimpleLow
SCL_Label.labelLast(_text="Simple\nLow", _keepLast = false, _offset=offsetLowSimple, _y=low[historyLowSimple], _textAlign=text.align_left, _style=label.style_label_up, _color=labelColour)
if showSimple and isSimpleHigh
SCL_Label.labelLast(_text="Simple\nHigh", _keepLast = false, _offset=offsetHighSimple, _y=high[historyHighSimple], _textAlign=text.align_left, _style=label.style_label_down, _color=labelColour)
// 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦 FUNCTION 2 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦
// @function f_localLowHigh() // This function finds Local Lows and Highs, in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
// The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
// By the rules, Local Lows and Highs must alternate, and in this function they do.
// @param - there are no parameters. The function uses the chart OHLC.
// @returns boolean values for whether this bar confirms a Local Low/High, and ints for the bar_index of that Low/High.
export f_localLowHigh() =>
var float _trailingLow = na, var float _trailingHigh = na // Trail for the low (which is used to confirm Highs), and the high (used to confirm Lows).
var int _simpleHighIndex = na, var int _simpleLowIndex = na // The bar index of the Simple High/Low when confirmed.
var int _trailingLowIndex = na, var int _trailingHighIndex = na // The bar index of the last low that changed the trailing low, or high for trailing high.
var string _lastPivot = na // Store whether the most recent pivot was a High or Low.
var bool _isStrictLocalHigh = na, var bool _isStrictLocalLow = na // Whether the Local High/Low counts, because it's in order.
// Setup for Highs
if low > _trailingLow or (na(_trailingLow) and (low > low[1]))
_trailingLow := low // Trail the lows up. If higher, reset, otherwise persist.
_trailingLowIndex := bar_index // When you change the trailing low, store the bar index.
// Setup for Lows
if high < _trailingHigh or (na(_trailingHigh) and (high < high[1]))
_trailingHigh := high // Trail the highs down. If lower, reset, otherwise persist.
_trailingHighIndex := bar_index // When you change the trailing high, store the bar index.
// Confirm Highs, Lows
bool _isLocalHigh = (close < _trailingLow) // Confirm a High on close below the trailing low.
bool _isLocalLow = (close > _trailingHigh) // Confirm a Low on close above the trailing high.
// Cleanup
if _isLocalHigh
_trailingLow := na // When a High is confirmed, unset the trailing low line.
_simpleHighIndex := _trailingLowIndex // And store the bar index of the High.
if _isLocalLow
_trailingHigh := na // When a Low is confirmed, unset the trailing high line.
_simpleLowIndex := _trailingHighIndex // And store the bar index of the Low.
// Promote Highs, Lows only in strict order
if _isLocalHigh and _lastPivot != "High"
_isStrictLocalHigh := true
_lastPivot := "High"
else
_isStrictLocalHigh := false
if _isLocalLow and _lastPivot != "Low"
_isStrictLocalLow := true
_lastPivot := "Low"
else
_isStrictLocalLow := false
[_isStrictLocalHigh, _isStrictLocalLow, _simpleHighIndex, _simpleLowIndex, _trailingHigh, _trailingLow]
// Example usage
[isLocalHigh, isLocalLow, localHighIndex, localLowIndex, trailingHigh, trailingLow] = f_localLowHigh()
plotshape(showLocal ? isLocalHigh : na, title="Local High Confirmed", style=shape.arrowdown, color=color.red, location=location.abovebar, size=size.small)
plotshape(showLocal ? isLocalLow : na, title="Local Low Confirmed", style=shape.arrowup, color=color.green, location=location.belowbar, size=size.small)
int offsetHighLocal = localHighIndex - bar_index, int offsetLowLocal = localLowIndex - bar_index // Offset for the label must be negative to offset to the left.
int historyHighLocal = bar_index - localHighIndex, int historyLowLocal = bar_index - localLowIndex // Offset for the historical operator must be the other way round.
if showLocal and isLocalLow
SCL_Label.labelLast(_text="Local\nLow", _keepLast = false, _offset=offsetLowLocal, _y=low[historyLowLocal], _textAlign=text.align_left, _style=label.style_label_up, _color=labelColour)
if showLocal and isLocalHigh
SCL_Label.labelLast(_text="Local\nHigh", _keepLast = false, _offset=offsetHighLocal, _y=high[historyHighLocal], _textAlign=text.align_left, _style=label.style_label_down, _color=labelColour)
// 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦 FUNCTION 3 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦
// @function f_enhancedSimpleLowHigh() // This function finds Local Lows and Highs, but NOT in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
// The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
// By the rules, Local Lows and Highs must alternate. In this function they do not, so I'm calling them Simple Lows and Highs.
// Simple Highs and Lows, by the above definition, can be useful for entries and stops. Because I intend to use them for trailing stops, I want them all, not just the ones that alternate in strict order.
// The difference between this function and f_simpleLowHigh() is that it also tracks the lowest/highest recent level. This level can be useful for trailing stops.
// In effect, these are like more "normal" highs and lows that you would pick by eye, but confirmed faster in many cases than by waiting for the low/high of that particular candle to be taken out on close,
// because they are instead confirmed by ANY subsequent candle having its low/high exceeded. Hence, I call these Enhanced Simple Lows/Highs.
// The levels are taken from the extreme highs/lows, but the bar indexes are given for the candles that were actually used to confirm the Low/High.
// This is by design, because it might be misleading to label the extreme, since we didn't use that candle to confirm the Low/High..
// @param - there are no parameters. The function uses the chart OHLC.
// @returns - boolean values for whether this bar confirms an Enhanced Simple Low/High
// ints for the bar_index of that Low/High
// floats for the values of the recent high/low levels
// floats for the trailing high/low levels (for debug/post-processing)
// bools for market structure bias
export f_enhancedSimpleLowHigh() =>
var float _trailingLow = na, var float _trailingHigh = na // Trail for the low (which is used to confirm Highs), and the high (used to confirm Lows).
var int _enhancedHighIndex = na, var int _enhancedLowIndex = na // The bar index of the Simple High/Low when confirmed.
var int _trailingLowIndex = na, var int _trailingHighIndex = na // The bar index of the last low that changed the trailing low, or high for trailing high.
var bool _pivotHighModeUp = na, var bool _pivotLowModeDown = na // Whether we are trailing the pivot high line up/low line down or not.
var float _pivotHighTrail = na, var float _pivotLowTrail = na // Levels used only to track recent highest/lowest levels to plot. They're NOT used to confirm highs/lows.
var float _pivotHigh = na, var float _pivotLow = na // The levels of the most recent confirmed Enhanced High/Low.
// Setup for calculating Highs
if low > _trailingLow or (na(_trailingLow) and (low > low[1]))
_trailingLow := low // Trail the lows up. If higher, reset, otherwise persist.
_trailingLowIndex := bar_index // When you change the trailing low, store the bar index.
// Setup for calculating Lows
if high < _trailingHigh or (na(_trailingHigh) and (high < high[1]))
_trailingHigh := high // Trail the highs down. If lower, reset, otherwise persist.
_trailingHighIndex := bar_index // When you change the trailing high, store the bar index.
// Confirm Highs, Lows
bool _isEnhancedHigh = close < _trailingLow // Confirm a High on close below the trailing low.
bool _isEnhancedLow = close > _trailingHigh // Confirm a Low on close above the trailing high.
// Track pivot levels
_pivotHighModeUp := na(_pivotHighTrail) and high > high[1] ? true : _isEnhancedHigh ? false : _pivotHighModeUp
_pivotHighTrail := _pivotHighModeUp and high > _pivotHighTrail ? high : _pivotHighModeUp and na(_pivotHighTrail) ? high : _pivotHighTrail
_pivotLowModeDown := na(_pivotLowTrail) and low < low[1] ? true : _isEnhancedLow ? false : _pivotLowModeDown
_pivotLowTrail := _pivotLowModeDown and low < _pivotLowTrail ? low : _pivotLowModeDown and na(_pivotLowTrail) ? low : _pivotLowTrail
// Cleanup
if _isEnhancedHigh
_trailingLow := na // When a High is confirmed, unset the trailing low line.
_enhancedHighIndex := _trailingLowIndex // And store the bar index of the High.
_pivotHigh := na(_pivotHighTrail) ? math.max(high, high[1]) : math.max(_pivotHighTrail,high) // Reset the pivot high line
_pivotHighTrail := na // Unset the pivot high trail
if _isEnhancedLow
_trailingHigh := na // When a Low is confirmed, unset the trailing high line.
_enhancedLowIndex := _trailingHighIndex // And store the bar index of the Low.
_pivotLow := na(_pivotLowTrail) ? math.min(low, low[1]) : math.min(_pivotLowTrail, low) // Reset the pivot low line
_pivotLowTrail := na // Unset the pivot high trail
// Market Structure bias
var bool _isBullish = na, var bool _isBearish = na // Market structure bias
_isBullish := close > _pivotHigh ? true : _isBearish ? false : _isBullish
_isBearish := close < _pivotLow ? true : _isBullish ? false : _isBearish
if na(_isBullish) and na(_isBearish) // Approximate bias on first pivot
_isBullish := _isEnhancedLow ? true : _isBullish
_isBearish := _isEnhancedHigh ? true : _isBearish
[_isEnhancedHigh, _isEnhancedLow, _enhancedHighIndex, _enhancedLowIndex, _pivotHighTrail, _pivotHigh, _pivotLowTrail, _pivotLow, _isBullish, _isBearish]
// Example usage
[isEnhancedHigh, isEnhancedLow, enhancedHighIndex, enhancedLowIndex, pivotHighTrail, pivotHigh, pivotLowTrail, pivotLow, enhancedBullish, enhancedBearish] = f_enhancedSimpleLowHigh()
plotshape(showEnhanced ? isEnhancedHigh : na, title="Enhanced Simple High Confirmed", style=shape.arrowdown, color=color.red, location=location.abovebar, size=size.small)
plotshape(showEnhanced ? isEnhancedLow : na, title="Enhanced Simple Low Confirmed", style=shape.arrowup, color=color.green, location=location.belowbar, size=size.small)
int offsetHighEnhanced = enhancedHighIndex - bar_index, int offsetLowEnhanced = enhancedLowIndex - bar_index // Offset for the label must be negative to offset to the left.
int historyHighEnhanced = bar_index - enhancedHighIndex, int historyLowEnhanced = bar_index - enhancedLowIndex // Offset for the historical operator must be the other way round.
// We have to use a label because plotshape and plotchar don't work for some reason with series offsets even though they're supposed to.
if showEnhanced and isEnhancedLow
SCL_Label.labelLast(_text="Enhanced\nLow", _keepLast = false, _offset=offsetLowEnhanced, _y=low[historyLowEnhanced], _textAlign=text.align_left, _style=label.style_label_up, _color=labelColour)
if showEnhanced and isEnhancedHigh
SCL_Label.labelLast(_text="Enhanced\nHigh", _keepLast = false, _offset=offsetHighEnhanced, _y=high[historyHighEnhanced], _textAlign=text.align_left, _style=label.style_label_down, _color=labelColour)
plot(showEnhanced ? pivotHighTrail : na, title="Recent High Level", linewidth=1, color=color.green, style=plot.style_linebr)
plot(showEnhanced ? pivotHigh : na, title="Enhanced High Level", linewidth=4, color=color.new(color.green,50), style=plot.style_linebr)
plot(showEnhanced ? pivotLowTrail : na, title="Recent Low Level", linewidth=1, color=color.red, style=plot.style_linebr)
plot(showEnhanced ? pivotLow : na, title="Enhanced Low Level", linewidth=4, color=color.new(color.red,50), style=plot.style_linebr)
enhancedBackGroundColour = not showEnhanced ? na : enhancedBullish ? color.new(color.green,80) : enhancedBearish ? color.new(color.red,80) : na
bgcolor(enhancedBackGroundColour)
// 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦 FUNCTION 4 🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦
// @function f_trueLowHigh() // This function finds True Lows and Highs.
// A True High is the candle with the highest recent high, which then has its low taken out on close by a subsequent candle (and vice-versa for True Lows).
// The difference between this and an Enhanced High is that confirmation requires not just any Simple High, but confirmation of the very candle that has the highest high.
// Because of this, confirmation is often later, and multiple Simple Highs and Lows can develop within ranges formed by a single big candle without any of them being confirmed. This is by design.
// A True High looks like the intuitive "real high" when you look at the chart. True Lows and Highs must alternate.
// @param - there are no parameters. The function uses the chart OHLC.
// @returns - boolean values for whether this bar confirms an Enhanced Simple Low/High
// ints for the bar_index of that Low/High
// floats for the values of the recent high/low levels
// floats for the trailing high/low levels (for debug/post-processing)
// bools for market structure bias
export f_trueLowHigh() =>
var float _trailingLow = na, var float _trailingHigh = na // Trail for the low (which is used to confirm Highs), and the high (used to confirm Lows).
var int _trueHighIndex = na, var int _trueLowIndex = na // The bar index of the True High/Low when confirmed.
var int _trailingLowIndex = na, var int _trailingHighIndex = na // The bar index of the last low that changed the trailing low, or high for trailing high.
var string _lastPivot = na // Store whether the most recent pivot was a High or Low.
var bool _isTrueHigh = na, var bool _isTrueLow = na // Whether the Local High/Low counts, because it's in order.
var bool _pivotHighModeUp = na, var bool _pivotLowModeDown = na // Whether we are trailing the pivot high line up/low line down or not.
var float _pivotHighTrail = na, var float _pivotLowTrail = na // Levels used only to track recent highest/lowest levels to plot. Here, they ARE used to identify the candle from which to confirm highs/lows.
var float _pivotHigh = na, var float _pivotLow = na // The levels of the most recent confirmed Enhanced High/Low.
// Track pivot levels
_pivotHighModeUp := na(_pivotHighTrail) and high > high[1] ? true : _isTrueHigh ? false : _pivotHighModeUp
_pivotHighTrail := _pivotHighModeUp and high > _pivotHighTrail ? high : _pivotHighModeUp and na(_pivotHighTrail) ? high : _pivotHighTrail
_pivotLowModeDown := na(_pivotLowTrail) and low < low[1] ? true : _isTrueLow ? false : _pivotLowModeDown
_pivotLowTrail := _pivotLowModeDown and low < _pivotLowTrail ? low : _pivotLowModeDown and na(_pivotLowTrail) ? low : _pivotLowTrail
// Setup for Highs
if high > _pivotHighTrail[1] or na(_pivotHighTrail[1]) and not na(_pivotHighTrail)
_trailingLow := low // Trail the lows up. If higher, reset, otherwise persist.
_trailingLowIndex := bar_index // When you change the trailing low, store the bar index.
// Setup for Lows
var bool _debug1 = na
if low < _pivotLowTrail[1] or na(_pivotLowTrail[1]) and not na(_pivotLowTrail)
_trailingHigh := high // Trail the highs down and stop when we reach a low. If lower, reset, otherwise persist.
_trailingHighIndex := bar_index // When you change the trailing high, store the bar index.
// Confirm Highs, Lows
bool _isLocalHigh = (close < _trailingLow) // Confirm a High on close below the trailing low.
bool _isLocalLow = (close > _trailingHigh) // Confirm a Low on close above the trailing high.
// Cleanup
if _isLocalHigh
_trailingLow := na // When a High is confirmed, unset the trailing low line.
_trueHighIndex := _trailingLowIndex // And store the bar index of the High.
if _isLocalLow
_trailingHigh := na // When a Low is confirmed, unset the trailing high line.
_trueLowIndex := _trailingHighIndex // And store the bar index of the Low.
// Promote Highs, Lows only in strict order
if _isLocalHigh and _lastPivot != "High"
_isTrueHigh := true
_lastPivot := "High"
else
_isTrueHigh := false
if _isLocalLow and _lastPivot != "Low"
_isTrueLow := true
_lastPivot := "Low"
else
_isTrueLow := false
// Moar cleanup
if _isTrueHigh
_pivotHigh := na(_pivotHighTrail) ? math.max(high, high[1]) : math.max(_pivotHighTrail,high) // Reset the pivot high line
_pivotHighTrail := na // Unset the pivot high trail
_pivotLowTrail := low
_trailingHigh := high
_trailingHighIndex := bar_index // Reset the trailing high index, which will reset the True Low Index in due course
if _isTrueLow
_pivotLow := na(_pivotLowTrail) ? math.min(low, low[1]) : math.min(_pivotLowTrail, low) // Reset the pivot low line
_pivotLowTrail := na // Unset the pivot high trail
_pivotHighTrail := high
_trailingLow := low
_trailingLowIndex := bar_index
// Market Structure bias
var bool _isBullish = na, var bool _isBearish = na // Market structure bias
_isBullish := close > _pivotHigh ? true : _isBearish ? false : _isBullish // Flip bullish when we make a higher high
_isBearish := close < _pivotLow ? true : _isBullish ? false : _isBearish
if na(_isBullish) and na(_isBearish) // Approximate bias on first pivot
_isBullish := _isTrueLow ? true : _isBullish
_isBearish := _isTrueHigh ? true : _isBearish
[_isTrueHigh, _isTrueLow, _trueHighIndex, _trueLowIndex, _pivotHighTrail, _pivotHigh, _pivotLowTrail, _pivotLow, _isBullish, _isBearish]
// Example usage
[isTrueHigh, isTrueLow, trueHighIndex, trueLowIndex, trueHighTrail, trueHigh, trueLowTrail, trueLow, trueBullish, trueBearish] = f_trueLowHigh()
plotshape(showTrue ? isTrueHigh : na, title="True High Confirmed", style=shape.arrowdown, color=color.red, location=location.abovebar, size=size.small)
plotshape(showTrue ? isTrueLow : na, title="True Low Confirmed", style=shape.arrowup, color=color.green, location=location.belowbar, size=size.small)
int offsetHighTrue = trueHighIndex - bar_index, int offsetLowTrue = trueLowIndex - bar_index // Offset for the label must be negative to offset to the left.
int historyHighTrue = bar_index - trueHighIndex, int historyLowTrue = bar_index - trueLowIndex // Offset for the historical operator must be the other way round.
if showTrue and isTrueLow
SCL_Label.labelLast(_text="True\nLow", _keepLast = false, _offset=offsetLowTrue, _y=low[historyLowTrue], _textAlign=text.align_left, _style=label.style_label_up, _color=labelColour)
if showTrue and isTrueHigh
SCL_Label.labelLast(_text="True\nHigh", _keepLast = false, _offset=offsetHighTrue, _y=high[historyHighTrue], _textAlign=text.align_left, _style=label.style_label_down, _color=labelColour)
plot(showTrue ? trueHighTrail : na, title="Recent High Level", linewidth=1, color=color.green, style=plot.style_linebr)
plot(showTrue ? trueHigh : na, title="True High Level", linewidth=4, color=color.new(color.green,50), style=plot.style_linebr)
plot(showTrue ? trueLowTrail : na, title="Recent Low Level", linewidth=1, color=color.red, style=plot.style_linebr)
plot(showTrue ? trueLow : na, title="True Low Level", linewidth=4, color=color.new(color.red,50), style=plot.style_linebr)
trueBackGroundColour = not showTrue ? na : trueBullish ? color.new(color.green,80) : trueBearish ? color.new(color.red,80) : na
bgcolor(trueBackGroundColour)
// ================================================= //
// //
// (╯°□°)╯︵ ¡sʎɐʍlɐ `ʇsɹᴉɟ ǝɹnʇɔnɹʇs ʇǝʞɹɐW //
// //
// ================================================= // |
Moving Average of Volume for Up and Down Closes | https://www.tradingview.com/script/vbCQ6dwt-Moving-Average-of-Volume-for-Up-and-Down-Closes/ | mfgfund | https://www.tradingview.com/u/mfgfund/ | 22 | 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/
// © mfgfund
//@version=5
indicator("Moving Average of Volume for Up and Down Closes", overlay = false)
// Input for moving average length
length = input.int(7, title = "MA Length")
// Calculate the moving average of volume for bars with an up close
upVolume = close > open ? volume : 0
maUp = ta.sma(upVolume, length)
// Calculate the moving average of volume for bars with a down close
downVolume = close < open ? volume : 0
maDown = ta.sma(downVolume, length)
// Plot the moving averages in a separate pane from the price chart
plot(maUp, color = color.green, title = "MA Up")
plot(maDown, color = color.red, title = "MA Down")
|
Encoder Decoder | https://www.tradingview.com/script/CTaTaW9e-Encoder-Decoder/ | f4r33x | https://www.tradingview.com/u/f4r33x/ | 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/
// © f4r33x
//@version=5
// @description Example how to encode some values into float number
library("Encoder\Decoder", overlay = true)
import f4r33x/fast_utils/1 as fu
// @function Encode parameter
// @returns encoded value
export calctype(string src_type) =>
int res = switch src_type
'RMA' => 0
'SMA' => 1
'EMA' => 2
'HMA' => 3
'SWMA'=> 4
'VWAP'=> 5
'VWMA'=> 6
'WMA' => 7
//'custom' => 8
res
// @function Decode parameter
// @returns decoded value
export calctype(int src_type) =>
string res = switch src_type
0 => 'RMA'
1 => 'SMA'
2 => 'EMA'
3 => 'HMA'
4 => 'SWMA'
5 => 'VWAP'
6 => 'VWMA'
7 => 'WMA'
//'custom' => 8
res
// @function Encode parameter
// @returns encoded value
export srctype(string src_type) =>
int res = switch src_type
'open' => 0
'high' => 1
'low' => 2
'close'=> 3
'hl2' => 4
'hlc3' => 5
'hlcc4'=> 6
'ohlc4'=> 7
//'custom'=> 8
res
// @function Decode parameter
// @returns decoded value
export srctype(int src_type) =>
res = switch src_type
0 => open
1 => high
2 => low
3 => close
4 => hl2
5 => hlc3
6 => hlcc4
7 => ohlc4
//custom
res
// @function Encodes 4 paramters into float number
// @param calc_type 1st paramter to encode (its values defined in f_calctype functions) max number of values that can be encoded = 100
// @param src_type 2nd paramter to encode (its values defined in f_src_type functions) max number of values that can be encoded = 100
// @param tf tf 3rd paramter to encode (may be int number with format.price precision length!!! (i.e.))
// @param length length 4th paramter to encode (may be any int number)
// @returns float number
export encode(string calc_type, string src_type, int tf = na, series int length = na) => // encodes 2 two number of digits vals and 2 unknown number of digits vals
ident = nz(length)*10000+calctype(calc_type)*100+srctype(src_type)+nz(tf/math.pow(10, fu.count_int_digits(tf)))
// @function Decodes 4 paramters into tuple
// @returns returns tuple [calc_type, src_type, length, tf]
export decode(float ident) =>// decodes 4 vals
//tf_round=math.round((ident%1*math.pow(10,8)))/math.pow(10,8)
tf= ident%1 == 0 ? na : str.tonumber(str.substring(str.tostring(math.round((ident%1), 9)), 2, 11))
//tf = tf_round*(math.pow(10, f_count_floatdigits(tf_round)))
//tf = f_count_floatdigits(tf_round)
float src_type = srctype((int(ident)%100))
string calc_type = calctype(int((int(ident)%1000)*0.01))
int length = int(ident/10000)
[calc_type, src_type, length, tf]
ident = encode('EMA', 'close', 12345678, 400)
[calc_type, src_type, length, tf] = decode(ident)
if barstate.islast
labtext = 'Encoded value: ' + str.tostring(ident, '#.####') + '\n Decoded value: ' + '\n calc_type= ' + calc_type + '\n src_type= ' + str.tostring(src_type) + '\n length= ' + str.tostring(length) + '\n tf= ' + str.tostring(tf)
label=label.new(last_bar_index, high, labtext, textalign = text.align_left)
label.delete(label[1])
|
font | https://www.tradingview.com/script/vmuJYczR-font/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// © kaiouthro
// credits: @wlhm and @Duyck
// Thanks to Pine Script Community who made this library function exist on Pine script.
//@version=5
// @description Unicode Characters Replacement function for strings.
library("font")
// font names
varip _Sans = "Sans"
varip _Sans_Italic = "Sans Italic"
varip _Sans_Bold = "Sans Bold"
varip _Sans_Bold_Italic = "Sans Bold Italic"
varip _Sans_Serif = "Sans-Serif"
varip _Sans_Serif_Italic = "Sans-Serif Italic"
varip _Sans_Serif_Bold = "Sans-Serif Bold"
varip _Sans_Serif_Bold_Italic = "Sans-Serif Bold Italic"
varip _Fraktur = "Fraktur"
varip _Fraktur_Bold = "Fraktur Bold"
varip _Script = "Script"
varip _Script_Bold = "Script Bold"
varip _Double_Struck = "Double-Struck"
varip _Monospace = "Monospace"
varip _Regional_Indicator = "Regional Indicator"
varip _Small = "Small"
varip _Full_Width = "Full Width"
varip _Circled = "Circled"
// fonts
varip _Sans_chars = "𝖺,𝖻,𝖼,𝖽,𝖾,𝖿,𝗀,𝗁,𝗂,𝗃,𝗄,𝗅,𝗆,𝗇,𝗈,𝗉,𝗊,𝗋,𝗌,𝗍,𝗎,𝗏,𝗐,𝗑,𝗒,𝗓,𝖠,𝖡,𝖢,𝖣,𝖤,𝖥,𝖦,𝖧,𝖨,𝖩,𝖪,𝖫,𝖬,𝖭,𝖮,𝖯,𝖰,𝖱,𝖲,𝖳,𝖴,𝖵,𝖶,𝖷,𝖸,𝖹,𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫"
varip _Sansi_chars = "𝘢,𝘣,𝘤,𝘥,𝘦,𝘧,𝘨,𝘩,𝘪,𝘫,𝘬,𝘭,𝘮,𝘯,𝘰,𝘱,𝘲,𝘳,𝘴,𝘵,𝘶,𝘷,𝘸,𝘹,𝘺,𝘻,𝘈,𝘉,𝘊,𝘋,𝘌,𝘍,𝘎,𝘏,𝘐,𝘑,𝘒,𝘓,𝘔,𝘕,𝘖,𝘗,𝘘,𝘙,𝘚,𝘛,𝘜,𝘝,𝘞,𝘟,𝘠,𝘡,𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫"
varip _Sansb_chars = "𝗮,𝗯,𝗰,𝗱,𝗲,𝗳,𝗴,𝗵,𝗶,𝗷,𝗸,𝗹,𝗺,𝗻,𝗼,𝗽,𝗾,𝗿,𝘀,𝘁,𝘂,𝘃,𝘄,𝘅,𝘆,𝘇,𝗔,𝗕,𝗖,𝗗,𝗘,𝗙,𝗚,𝗛,𝗜,𝗝,𝗞,𝗟,𝗠,𝗡,𝗢,𝗣,𝗤,𝗥,𝗦,𝗧,𝗨,𝗩,𝗪,𝗫,𝗬,𝗭,𝟬,𝟭,𝟮,𝟯,𝟰,𝟱,𝟲,𝟳,𝟴,𝟵"
varip _Sansbi_chars = "𝙖,𝙗,𝙘,𝙙,𝙚,𝙛,𝙜,𝙝,𝙞,𝙟,𝙠,𝙡,𝙢,𝙣,𝙤,𝙥,𝙦,𝙧,𝙨,𝙩,𝙪,𝙫,𝙬,𝙭,𝙮,𝙯,𝘼,𝘽,𝘾,𝘿,𝙀,𝙁,𝙂,𝙃,𝙄,𝙅,𝙆,𝙇,𝙈,𝙉,𝙊,𝙋,𝙌,𝙍,𝙎,𝙏,𝙐,𝙑,𝙒,𝙓,𝙔,𝙕,𝟬,𝟭,𝟮,𝟯,𝟰,𝟱,𝟲,𝟳,𝟴,𝟵"
varip _SansS_chars = "𝚊,𝚋,𝚌,𝚍,𝚎,𝚏,𝚐,𝚑,𝚒,𝚓,𝚔,𝚕,𝚖,𝚗,𝚘,𝚙,𝚚,𝚛,𝚜,𝚝,𝚞,𝚟,𝚠,𝚡,𝚢,𝚣,𝙰,𝙱,𝙲,𝙳,𝙴,𝙵,𝙶,𝙷,𝙸,𝙹,𝙺,𝙻,𝙼,𝙽,𝙾,𝙿,𝚀,𝚁,𝚂,𝚃,𝚄,𝚅,𝚆,𝚇,𝚈,𝚉,𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿"
varip _SansSi_chars = "𝘢,𝘣,𝘤,𝘥,𝘦,𝘧,𝘨,𝘩,𝘪,𝘫,𝘬,𝘭,𝘮,𝘯,𝘰,𝘱,𝘲,𝘳,𝘴,𝘵,𝘶,𝘷,𝘸,𝘹,𝘺,𝘻,𝘈,𝘉,𝘊,𝘋,𝘌,𝘍,𝘎,𝘏,𝘐,𝘑,𝘒,𝘓,𝘔,𝘕,𝘖,𝘗,𝘘,𝘙,𝘚,𝘛,𝘜,𝘝,𝘞,𝘟,𝘠,𝘡,𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿"
varip _SansSb_chars = "𝐚,𝐛,𝐜,𝐝,𝐞,𝐟,𝐠,𝐡,𝐢,𝐣,𝐤,𝐥,𝐦,𝐧,𝐨,𝐩,𝐪,𝐫,𝐬,𝐭,𝐮,𝐯,𝐰,𝐱,𝐲,𝐳,𝐀,𝐁,𝐂,𝐃,𝐄,𝐅,𝐆,𝐇,𝐈,𝐉,𝐊,𝐋,𝐌,𝐍,𝐎,𝐏,𝐐,𝐑,𝐒,𝐓,𝐔,𝐕,𝐖,𝐗,𝐘,𝐙,𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗"
varip _SansSbi_chars = "𝒂,𝒃,𝒄,𝒅,𝒆,𝒇,𝒈,𝒉,𝒊,𝒋,𝒌,𝒍,𝒎,𝒏,𝒐,𝒑,𝒒,𝒓,𝒔,𝒕,𝒖,𝒗,𝒘,𝒙,𝒚,𝒛,𝑨,𝑩,𝑪,𝑫,𝑬,𝑭,𝑮,𝑯,𝑰,𝑱,𝑲,𝑳,𝑴,𝑵,𝑶,𝑷,𝑸,𝑹,𝑺,𝑻,𝑼,𝑽,𝑾,𝑿,𝒀,𝒁,𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗"
varip _Fraktur_chars = "𝔞,𝔟,𝔠,𝔡,𝔢,𝔣,𝔤,𝔥,𝔦,𝔧,𝔨,𝔩,𝔪,𝔫,𝔬,𝔭,𝔮,𝔯,𝔰,𝔱,𝔲,𝔳,𝔴,𝔵,𝔶,𝔷,𝔄,𝔅,ℭ,𝔇,𝔈,𝔉,𝔊,ℌ,ℑ,𝔍,𝔎,𝔏,𝔐,𝔑,𝔒,𝔓,𝔔,ℜ,𝔖,𝔗,𝔘,𝔙,𝔚,𝔛,𝔜,ℨ,𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫"
varip _FrakturBo_chars = "𝖆,𝖇,𝖈,𝖉,𝖊,𝖋,𝖌,𝖍,𝖎,𝖏,𝖐,𝖑,𝖒,𝖓,𝖔,𝖕,𝖖,𝖗,𝖘,𝖙,𝖚,𝖛,𝖜,𝖝,𝖞,𝖟,𝕬,𝕭,𝕮,𝕯,𝕰,𝕱,𝕲,𝕳,𝕴,𝕵,𝕶,𝕷,𝕸,𝕹,𝕺,𝕻,𝕼,𝕽,𝕾,𝕿,𝖀,𝖁,𝖂,𝖃,𝖄,𝖅,𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗"
varip _Script_chars = "𝒶,𝒷,𝒸,𝒹,ℯ,𝒻,ℊ,𝒽,𝒾,𝒿,𝓀,𝓁,𝓂,𝓃,ℴ,𝓅,𝓆,𝓇,𝓈,𝓉,𝓊,𝓋,𝓌,𝓍,𝓎,𝓏,𝒜,ℬ,𝒞,𝒟,ℰ,ℱ,𝒢,ℋ,ℐ,𝒥,𝒦,ℒ,ℳ,𝒩,𝒪,𝒫,𝒬,ℛ,𝒮,𝒯,𝒰,𝒱,𝒲,𝒳,𝒴,𝒵,𝟢,𝟣,𝟤,𝟥,𝟦,𝟧,𝟨,𝟩,𝟪,𝟫"
varip _Scriptbold_chars = "𝓪,𝓫,𝓬,𝓭,𝓮,𝓯,𝓰,𝓱,𝓲,𝓳,𝓴,𝓵,𝓶,𝓷,𝓸,𝓹,𝓺,𝓻,𝓼,𝓽,𝓾,𝓿,𝔀,𝔁,𝔂,𝔃,𝓐,𝓑,𝓒,𝓓,𝓔,𝓕,𝓖,𝓗,𝓘,𝓙,𝓚,𝓛,𝓜,𝓝,𝓞,𝓟,𝓠,𝓡,𝓢,𝓣,𝓤,𝓥,𝓦,𝓧,𝓨,𝓩,𝟎,𝟏,𝟐,𝟑,𝟒,𝟓,𝟔,𝟕,𝟖,𝟗"
varip _dbl__chars = "𝕒,𝕓,𝕔,𝕕,𝕖,𝕗,𝕘,𝕙,𝕚,𝕛,𝕜,𝕝,𝕞,𝕟,𝕠,𝕡,𝕢,𝕣,𝕤,𝕥,𝕦,𝕧,𝕨,𝕩,𝕪,𝕫,𝔸,𝔹,ℂ,𝔻,𝔼,𝔽,𝔾,ℍ,𝕀,𝕁,𝕂,𝕃,𝕄,ℕ,𝕆,ℙ,ℚ,ℝ,𝕊,𝕋,𝕌,𝕍,𝕎,𝕏,𝕐,ℤ,𝟘,𝟙,𝟚,𝟛,𝟜,𝟝,𝟞,𝟟,𝟠,𝟡"
varip _mono_chars = "𝚊,𝚋,𝚌,𝚍,𝚎,𝚏,𝚐,𝚑,𝚒,𝚓,𝚔,𝚕,𝚖,𝚗,𝚘,𝚙,𝚚,𝚛,𝚜,𝚝,𝚞,𝚟,𝚠,𝚡,𝚢,𝚣,𝙰,𝙱,𝙲,𝙳,𝙴,𝙵,𝙶,𝙷,𝙸,𝙹,𝙺,𝙻,𝙼,𝙽,𝙾,𝙿,𝚀,𝚁,𝚂,𝚃,𝚄,𝚅,𝚆,𝚇,𝚈,𝚉,𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿"
varip _regional_chars = " 🇦, 🇧, 🇨, 🇩, 🇪, 🇫, 🇬, 🇭, 🇮, 🇯, 🇰, 🇱, 🇲, 🇳, 🇴, 🇵, 🇶, 🇷, 🇸, 🇹, 🇺, 🇻, 🇼, 🇽, 🇾, 🇿, 🇦, 🇧, 🇨, 🇩, 🇪, 🇫, 🇬, 🇭, 🇮, 🇯, 🇰, 🇱, 🇲, 🇳, 🇴, 🇵, 🇶, 🇷, 🇸, 🇹, 🇺, 🇻, 🇼, 🇽, 🇾, 🇿,𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿"
varip _small__chars = "🇦,🇧,🇨,🇩,🇪,🇫,🇬,🇭,🇮,🇯,🇰,🇱,🇲,🇳,🇴,🇵,🇶,🇷,🇸,🇹,🇺,🇻,🇼,🇽,🇾,🇿,🇦,🇧,🇨,🇩,🇪,🇫,🇬,🇭,🇮,🇯,🇰,🇱,🇲,🇳,🇴,🇵,🇶,🇷,🇸,🇹,🇺,🇻,🇼,🇽,🇾,🇿,𝟶,𝟷,𝟸,𝟹,𝟺,𝟻,𝟼,𝟽,𝟾,𝟿"
varip _full_chars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9"
varip _circle_chars = "🅐,🅑,🅒,🅓,🅔,🅕,🅖,🅗,🅘,🅙,🅚,🅛,🅜,🅝,🅞,🅟,🅠,🅡,🅢,🅣,🅤,🅥,🅦,🅧,🅨,🅩,🅐,🅑,🅒,🅓,🅔,🅕,🅖,🅗,🅘,🅙,🅚,🅛,🅜,🅝,🅞,🅟,🅠,🅡,🅢,🅣,🅤,🅥,🅦,🅧,🅨,🅩,⓿,❶,❷,❸,❹,❺,❻,❼,❽,❾"
varip _Pine_font = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9'
// @function Base Substitution
_font( _str, _n ) =>
_chars = switch
_n == 1 => _Sans_chars
_n == 2 => _Sansi_chars
_n == 3 => _Sansb_chars
_n == 4 => _Sansbi_chars
_n == 5 => _SansS_chars
_n == 6 => _SansSi_chars
_n == 7 => _SansSb_chars
_n == 8 => _SansSbi_chars
_n == 9 => _Fraktur_chars
_n == 10 => _FrakturBo_chars
_n == 11 => _Script_chars
_n == 12 => _Scriptbold_chars
_n == 13 => _dbl__chars
_n == 14 => _mono_chars
_n == 15 => _regional_chars
_n == 16 => _small__chars
_n == 17 => _full_chars
_n == 18 => _circle_chars
=> _Sans_chars
_Custom = str.split(_chars,',')
_Pine = str.split(_Pine_font,',')
string _char_str = _str
for [i,_char] in _Pine
_char_str := str.replace_all(_char_str, _char, array.get(_Custom, i))
_char_str
// @function Unicode Font Substitutee
//@param _str Input Strinbg
//@param _number Font by Int input
export uni(string _str, int _number ) =>
_font( _str, math.max(1,math.min(18,_number )))
// @function Unicode Font Substitutee
//@param _str Input Strinbg
//@param _font Font by Name input
export uni(string _str, string _font ) =>
varip _fonts = array.from(_Sans, _Sans_Italic, _Sans_Bold, _Sans_Bold_Italic, _Sans_Serif, _Sans_Serif_Italic, _Sans_Serif_Bold, _Sans_Serif_Bold_Italic,
_Fraktur, _Fraktur_Bold, _Script, _Script_Bold, _Double_Struck, _Monospace, _Regional_Indicator, _Small, _Full_Width, _Circled )
_id = array.indexof(_fonts,_font)
uni( _str, _id )
//@function Hidden WhiteSpace Characterrs
//@param _type (string) WhiteSpace Type
//@returns String Whitespace
export space(string _type) =>
switch _type
"En4" => " "
"En" => " "
"Em3" => " "
"Em4" => " "
"Em6" => " "
"Punc" => " "
"Thin" => " "
"Hair" => " "
=> " "
//@function Hidden WhiteSpace Characterrs
//@param _type (string) WhiteSpace Type
//@returns String Whitespace
export space(int _type) =>
switch _type
7 => " "
6 => " "
5 => " "
4 => " "
3 => " "
2 => " "
1 => " "
=> " "
//@function Indenter
//@param _size (intt) Number of tabs
//@returns String of N number tabs
export indent ( int _size )=> '\n'+array.join(array.new<string>(_size,'\t'),'')
|
Highlight Momentum Candles + 3MAs | https://www.tradingview.com/script/Hxvmyzrv-Highlight-Momentum-Candles-3MAs/ | TechnicallyMark | https://www.tradingview.com/u/TechnicallyMark/ | 5 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TechnicallyMark
//@version=4
study(title="Highlight Momentum Candles", overlay=true)
bullPercentChange = input(defval = 3, title="% Change", group = "Bull Momentum")
bullWickTopPercent = input(defval = .5, title="Top Wick %", group = "Bull Momentum")
bullWickBtmPercent = input(defval = .5, title="Bottom Wick %", group = "Bull Momentum")
bearPercentChange = input(defval = -3, title="% Change", group = "Bear Momentum")
bearWickTopPercent = input(defval = -1.5, title="Top Wick %", group = "Bear Momentum")
bearWickBtmPercent = input(defval = -.5, title="Bottom Wick %", group = "Bear Momentum")
ema20 = input(defval = 20, title="Fast EMA", group = "EMA")
ema100 = input(defval = 100, title="Moderate EMA", group = "EMA")
ema200 = input(defval = 200, title="Slow EMA", group = "EMA")
//hammer = (close = open)
GreenMomentum = (((close-open) / open * 100) >= bullPercentChange) and
(((open-low) / low * 100) <= bullWickBtmPercent) and
(((high-close) / close * 100) <= bullWickTopPercent)
RedMomentum = (((close-open) / open * 100) <= bearPercentChange) and
(((open-high) / high * 100) >= bearWickTopPercent) and
(((low-close) / close * 100) >= bearWickBtmPercent)
barcolor(color=GreenMomentum ? color.green: na, title = "Bull Momentum", editable = true)
barcolor(color=RedMomentum ? color.red: na, title = "Bear Momentum", editable = true)
plot(sma(close, ema20), style=plot.style_line, color=color.orange)
plot(sma(close, ema100), style=plot.style_line, color=color.blue)
plot(sma(close, ema200), style=plot.style_line, color=color.purple)
bgcolor(color=GreenMomentum ? color.green : na, transp = 30)
bgcolor(color=RedMomentum ? color.red : na, transp = 30)
//(((close-close[1]) / close[1] * 100) > 3) and
//and (((open * .99 >= low)) and ((close * .97 >= high)))
//threeRedCandles = (close[2] < open[2]) and (close[1] < open[1])
//and (close < open)
|
High Alert | https://www.tradingview.com/script/cyHGnT4d-High-Alert/ | abhiiiish27 | https://www.tradingview.com/u/abhiiiish27/ | 5 | 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/
// © abhiiiish27
//@version=5
indicator("High Alert", overlay=true)
// Get the opening price of the current day
currentDayOpen = request.security(syminfo.tickerid, "D", open)
// Get the high price of the previous day
previousDayHigh = request.security(syminfo.tickerid, "D", high[1])
// Condition for generating an alert
condition = currentDayOpen > previousDayHigh
// Trigger alert
alertcondition(condition, title="Open above Previous Day High", message="Today's open is above previous day's high!")
|
Market Sessions | https://www.tradingview.com/script/ihMXpnyN-Market-Sessions/ | GreatestUsername | https://www.tradingview.com/u/GreatestUsername/ | 4 | 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/
// © GreatestUsername
//@version=5
indicator("Market Sessions", overlay=true, max_lines_count = 500)
marketOpenHour = input.int(13)
marketOpenMinutes = input.int(00)
marketCloseHour = input.int(22)
marketCloseMinute = input.int(00)
openColor = input.color(color.green)
closeColor = input.color(color.red)
targetOpen = timestamp("UTC", year, month, dayofmonth, marketOpenHour, marketOpenMinutes)
targetClose = timestamp("UTC", year, month, dayofmonth, marketCloseHour, marketCloseMinute)
marketOpen = false
marketClose = false
if dayofweek != dayofweek.saturday and dayofweek != dayofweek.sunday
marketOpen := targetOpen == time
marketClose := targetClose == time
if marketOpen or marketClose
line.new(bar_index, 0, bar_index, 0, color=marketOpen ? openColor : closeColor, extend=extend.both) |
Week designation | https://www.tradingview.com/script/xz1EQKvB/ | Matboom | https://www.tradingview.com/u/Matboom/ | 4 | 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/
// © Matboom
//@version=5
indicator("Week designation", overlay = true)
color_day = input.color(color.new(color.black,50))
color_week = input.color(color.new(color.black,30))
color_month = input.color(color.new(color.black,10))
styleOption = input.string("solid (─)", title="Line Style", options=["solid (─)", "dotted (┈)", "dashed (╌)"])
lineStyle = styleOption == "dotted (┈)" ? line.style_dotted :
styleOption == "dashed (╌)" ? line.style_dashed :
line.style_solid
// Determining the session.
// Określenie sesji
startSession(hour, minute) =>
_start = timestamp(syminfo.timezone, year(timenow), month(timenow), dayofweek(timenow), hour, minute)
_start := na(_start[1]) ? _start : _start + 7 * 24 * 60 * 60 * 1000
// Adding 7 days to move to the next session.
// Dodajemy 7 dni, aby przenieść się do następnej sesji
// Calling a function to determine the start and end of the current session.
// Wywołanie funkcji do określenia początku i końca bieżącej sesji
session_start = startSession(0, 0)
// Checking if the session starts.
// Sprawdzenie czy sesja się rozpoczyna
isSessionStart = ta.change(time("D")) != 0
isSessionStart_2 = ta.change(time("W")) != 0
isSessionStart_3 = ta.change(time("M")) != 0
// If the session starts, insert a vertical line at the beginning of the session.
// Jeśli sesja się rozpoczyna, wstawienie linii pionowej na początku sesji
if (isSessionStart)
line.new(x1=bar_index, y1=close, x2=bar_index, y2=close * 1.01, color=color_day, width=1, extend=extend.both,style = lineStyle)
// If the session starts, insert a vertical line at the beginning of the session.
// Jeśli sesja się rozpoczyna, wstawienie linii pionowej na początku sesji
if (isSessionStart_2)
line.new(x1=bar_index, y1=close, x2=bar_index, y2=close * 1.01, color=color_week, width=1, extend=extend.both,style = lineStyle)
// If the session starts, insert a vertical line at the beginning of the session.
// Jeśli sesja się rozpoczyna, wstawienie linii pionowej na początku sesji
if (isSessionStart_3)
line.new(x1=bar_index, y1=close, x2=bar_index, y2=close * 1.01, color=color_month, width=1, extend=extend.both,style = lineStyle)
// Checking if the current day is Monday (1 represents Monday).
// Sprawdzenie, czy bieżący dzień to poniedziałek (1 oznacza poniedziałek)
isMonday = dayofweek(time) == 2
// If the session starts or it's Monday, insert a vertical line at the beginning of the session.
// Jeśli sesja się rozpoczyna lub to poniedziałek, wstawienie linii pionowej na początku sesji
if (isSessionStart or isMonday)
line.new(x1=bar_index, y1=close, x2=bar_index, y2=close * 1.01, color=color_day, width=1, extend=extend.both,style = lineStyle)
|
norminv | https://www.tradingview.com/script/tyDsKVfp-norminv/ | loxx | https://www.tradingview.com/u/loxx/ | 6 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
// @description An inverse normal distribution is a way to work backwards
// from a known probability to find an x-value. It is an informal term and
// doesn't refer to a particular probability distribution. Returns the
// value of the inverse normal distribution function for a specified value,
// mean, and standard deviation.
// reference:
// https://github.com/teqniqly/norm-inv/blob/master/src/norm-inv.ts
// https://support.microsoft.com/en-us/office/norminv-function-87981ab8-2de0-4cb0-b1aa-e21d4cb879b8
library("norminv")
// Error Function
erf(float xin)=>
float[] cof = array.new<float>(28, 0)
array.set(cof, 0, -1.3026537197817094)
array.set(cof, 1, 6.4196979235649026e-1)
array.set(cof, 2, 1.9476473204185836e-2)
array.set(cof, 3, -9.561514786808631e-3)
array.set(cof, 4, -9.46595344482036e-4)
array.set(cof, 5, 3.66839497852761e-4)
array.set(cof, 6, 4.2523324806907e-5)
array.set(cof, 7, -2.0278578112534e-5)
array.set(cof, 8, -1.624290004647e-6)
array.set(cof, 9, 1.303655835580e-6)
array.set(cof, 10, 1.5626441722e-8)
array.set(cof, 11, -8.5238095915e-8)
array.set(cof, 12, 6.529054439e-9)
array.set(cof, 13, 5.059343495e-9)
array.set(cof, 14, -9.91364156e-10)
array.set(cof, 15, -2.27365122e-10)
array.set(cof, 16, 9.6467911e-11)
array.set(cof, 17, 2.394038e-12)
array.set(cof, 18, -6.886027e-12)
array.set(cof, 19, 8.94487e-13)
array.set(cof, 20, 3.13092e-13)
array.set(cof, 21, -1.12708e-13)
array.set(cof, 22, 3.81e-16)
array.set(cof, 23, 7.106e-15)
array.set(cof, 24, -1.523e-15)
array.set(cof, 25, -9.4e-17)
array.set(cof, 26, 1.21e-16)
array.set(cof, 27, -2.8e-17)
bool isneg = false
float d = 0
float dd = 0
float x = xin
if xin < 0
x := -xin
isneg := true
float t = 2 / (2 + x)
float ty = 4 * t - 2
for j = array.size(cof) - 1 to 1
float tmp = d
d := ty * d - dd + array.get(cof, j)
dd := tmp
float res = t * math.exp(-x * x + 0.5 * (array.get(cof, 0) + ty * d) - dd)
out = isneg ? res - 1 : 1 - res
out
// Complementary Error Function
erfc(float x)=>
out = 1 - erf(x)
out
// Inverse Complementary Error Function
erfcinv(float prob)=>
var float TWOSQRTPI = 1.12837916709551257
float out = 0
if prob >= 2
out := -100
if prob <= 0
out := 100
else
float pp = (prob < 1) ? prob : 2 - prob
float t = math.sqrt(-2 * math.log(pp / 2))
float x = -0.70711 * ((2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t)
for j = 0 to 2 - 1
float err = erfc(x) - pp
x += err / (TWOSQRTPI * math.exp(-x * x) - x * err)
out := (prob < 1) ? x : -x
out
// @function Returns the value of the inverse normal distribution function for a specified value, mean, and standard deviation.
// @param x float, The input to the normal distribution function.
// @param mean float, The mean (mu) of the normal distribution function
// @param stdev float, The standard deviation (sigma) of the normal distribution function.
// @returns float.
export norminv(float x, float mean, float stdev)=>
var float SQRTTWO = 1.41421356237309505
float out = 0
out := -SQRTTWO * stdev * erfcinv(2 * x) + mean
// example usage
out = norminv(0.5, 65.5, 2.5)
plot(out) |
AkselitoLibrary | https://www.tradingview.com/script/rx9SBsPK-AkselitoLibrary/ | akselanil | https://www.tradingview.com/u/akselanil/ | 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/
// © akselanil
//@version=5
// @description TODO: add library description here
library("AkselitoLibrary")
// @function TODO: add function description here
// @param x TODO: add parameter x description here
// @returns TODO: add what function returns
export fun(float x) =>
//TODO : add function body and return value here
x
export hi( float val = high ) =>
var float ath = val
ath := math.max( ath, val )
export oda( float val ) =>
var float oda = val
oda := ta.atr( val )
export uho( float val1, float val2 ) =>
var float uho = val2
uho := ta.ema( val1, val2 )
export dvd( float val1, float val2, float val3 ) =>
var float dvd = val1
dvd := ta.sar( val1, val2, val3 )
export refbu( float val1, float val2 ) =>
var float refbu = val1
refbu := val1 + ( 1 * val2 )
export refbm( float val1 ) =>
var float refbm = val1
refbm := val1
export refba( float val1, float val2 ) =>
var float refba = val1
refba := val1 - ( 1 * val2 )
export refiu( float val1, float val2 ) =>
var float refiu = val1
refiu := val1 + ( 2 * val2 )
export refia( float val1, float val2 ) =>
var float refia = val1
refia := val1 - ( 2 * val2 )
export refuu( float val1, float val2 ) =>
var float refuu = val1
refuu := val1 + ( 3 * val2 )
export refua( float val1, float val2 ) =>
var float refua = val1
refua := val1 - ( 3 * val2 )
export refdu( float val1, float val2 ) =>
var refdu = val1
refdu := val1 + ( 4 * val2 )
export refda( float val1, float val2 ) =>
var float refda = val1
refda := val1 - ( 4 * val2 )
export gd( float val1, float val2, float val3, float val4 ) =>
var float gd = val1
gd := ( val4 - val1 ) / ( val2 - val3 )
export vke( float val1, int val2 ) =>
var float vke = val1
vke := ta.cci( val1, val2 )
export doc( float val1, int val2 ) =>
var float doc = val1
doc := ta.roc( val1, val2 )
export gge( float val1, int val2 ) =>
var float gge = val1
gge := ta.rsi( val1, val2 )
|
combin | https://www.tradingview.com/script/gKZlsr7P-combin/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description The combin function is a the combination function
// as it calculates the number of possible combinations for two given numbers.
// This function takes two arguments: the number and the number_chosen.
// For example, if the number is 5 and the number chosen is 1,
// there are 5 combinations, giving 5 as a result.
// reference:
// https://ideone.com/aDJXNO
// https://support.microsoft.com/en-us/office/combin-function-12a3f276-0a21-423a-8de6-06990aaf638a
library("combin")
// @function Returns the number of combinations for a given number of items. Use to determine the total possible number of groups for a given number of items.
// @param n int, The number of items.
// @param kin int, The number of items in each combination.
// @returns int.
export combin(int n, int kin)=>
int out = 0
int k = kin
if k > n
out := 0
else
if (k * 2) > n
k := n - k
if (k == 0)
out := 1
else
int result = n
int i = 2
while i <= k
result *= n - i + 1
result /= i
i += 1
out := result
out
// example usage; "n choose kin"
out = combin(100, 3)
plot(out) |
ctnd | https://www.tradingview.com/script/9wSBJOVV-ctnd/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
//@description double precision algorithm to compute the cumulative trivariate normal distribution
// found in A.Genz, Numerical computation of rectangular bivariate and trivariate normal
// and t probabilities”, Statistics and Computing, 14, (3), 2004. The cumulative trivariate
// normal is needed to price window barrier options, see G.F. Armstrong, Valuation formulae
// or window barrier options”, Applied Mathematical Finance, 8, 2001.
// references:
// https://link.springer.com/article/10.1023/B%3ASTCO.0000035304.20635.31
// https://www.tandfonline.com/doi/abs/10.1080/13504860210124607
// https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.353.1954&rep=rep1&type=pdf
// The Complete Guide to Option Pricing Formulas, 2nd ed. (Espen Gaarder Haug)
//
library("ctnd")
import loxx/cbnd/1
TRVFND(float T, float B2, float B3, float RHO21, float RHO31, float rho)=>
TRVFND = math.exp(-T * T / 2) * cbnd.CBND3(-T * RHO21 + B2, -T * RHO31 + B3, rho)
TRVFND
KRNRDD(float A, float b, float ABSERR, float b2p,float b3p, float RHO21, float RHO31, float rho)=>
//
// The abscissae and weights are given for the interval (-1,1)
// because of symmetry only the positive abscisae and their
// corresponding weights are given.
//
// XGK - abscissae of the 2N+1-point Kronrod rule:
// XGK(2), XGK(4), ... N-point Gauss rule abscissae;
// XGK(1), XGK(3), ... abscissae optimally added
// to the N-point Gauss rule.
//
// WGK - weights of the 2N+1-point Kronrod rule.
//
// WG - weights of the N-point Gauss rule.
float ABSCIS = 0
float CENTER = 0
float FC = 0
float FUNSUM = 0
float HFLGTH = 0
float RESLTG = 0
float RESLTK = 0
var int N = 12
//
float KRNRDD = 0
float[] WG = array.new<float>(int((N + 1) / 2), 0)
float[] WGK = array.new<float>(N, 0)
float[] XGK = array.new<float>(N, 0)
array.set(WG, 1, 0.0556685671161745)
array.set(WG, 2, 0.125580369464905)
array.set(WG, 3, 0.186290210927735)
array.set(WG, 4, 0.233193764591991)
array.set(WG, 5, 0.262804544510248)
array.set(WG, 0, 0.272925086777901)
//
array.set(XGK, 1, 0.996369613889543)
array.set(XGK, 2, 0.978228658146057)
array.set(XGK, 3, 0.941677108578068)
array.set(XGK, 4, 0.887062599768095)
array.set(XGK, 5, 0.816057456656221)
array.set(XGK, 6, 0.730152005574049)
array.set(XGK, 7, 0.630599520161965)
array.set(XGK, 8, 0.519096129206812)
array.set(XGK, 9, 0.397944140952378)
array.set(XGK, 10, 0.269543155952345)
array.set(XGK, 11, 0.136113000799362)
array.set(XGK, 0, 0)
//
array.set(WGK, 1, 0.00976544104596129)
array.set(WGK, 2, 0.0271565546821044)
array.set(WGK, 3, 0.0458293785644267)
array.set(WGK, 4, 0.0630974247503748)
array.set(WGK, 5, 0.0786645719322276)
array.set(WGK, 6, 0.0929530985969007)
array.set(WGK, 7, 0.105872074481389)
array.set(WGK, 8, 0.116739502461047)
array.set(WGK, 9, 0.125158799100319)
array.set(WGK, 10, 0.131280684229806)
array.set(WGK, 11, 0.135193572799885)
array.set(WGK, 0, 0.136577794711118)
//
//
// List of major variables
//
// CENTER - mid point of the interval
// HFLGTH - half-length of the interval
// ABSCIS - abscissae
// RESLTG - result of the N-point Gauss formula
// RESLTK - result of the 2N+1-point Kronrod formula
//
//
HFLGTH := (b - A) / 2
CENTER := (b + A) / 2
//
// compute the 2N+1-point Kronrod approximation to
// the integral, and estimate the absolute error.
//
FC := TRVFND(CENTER, b2p, b3p, RHO21, RHO31, rho)
RESLTG := FC * array.get(WG, 0)
RESLTK := FC * array.get(WGK, 0)
for j = 1 to N - 1
ABSCIS := HFLGTH * array.get(XGK, j)
FUNSUM := TRVFND(CENTER - ABSCIS, b2p, b3p, RHO21, RHO31, rho)
+ TRVFND(CENTER + ABSCIS, b2p, b3p, RHO21, RHO31, rho)
RESLTK := RESLTK + array.get(WGK, j) * FUNSUM
if j % 2 == 0
RESLTG := RESLTG + array.get(WG, int(j / 2)) * FUNSUM
KRNRDD := RESLTK * HFLGTH
KRNRDD
//ABSERR := 3 * math.abs((RESLTK - RESLTG) * HFLGTH)
ADONED(float A, float b, float TOL, float b2p, float b3p, float RHO21, float RHO31, float rho)=>
//
// One Dimensional Globally Adaptive Integration Function
//
int IM = 1
int IP = 1
var int NL = 100
float[] EI = array.new<float>(NL, 0)
float[] AI = array.new<float>(NL, 0)
float[] BI = array.new<float>(NL, 0)
float[] FI = array.new<float>(NL, 0)
float FIN = 0
float ERR = 0
array.set(AI, IP, A)
array.set(BI, IP, b)
array.set(FI, IP, KRNRDD(array.get(AI, IP), array.get(BI, IP), array.get(EI, IP), b2p, b3p, RHO21, RHO31, rho))
while IM < NL - 1
IM := IM + 1
array.set(BI, IM, array.get(BI, IP))
array.set(AI, IM, array.get(AI, IP) + array.get(BI, IP) / 2)
array.set(BI, IP, array.get(AI, IM))
FIN := array.get(FI, IP)
array.set(FI, IP, KRNRDD(array.get(AI, IP), array.get(BI, IP), array.get(EI, IP), b2p, b3p, RHO21, RHO31, rho))
array.set(FI, IM, KRNRDD(array.get(AI, IM), array.get(BI, IM), array.get(EI, IM), b2p, b3p, RHO21, RHO31, rho))
ERR := math.abs(FIN - array.get(FI, IP) - array.get(FI, IM)) / 2
array.set(EI, IP, array.get(EI, IP) + ERR)
array.set(EI, IM, array.get(EI, IM) + ERR)
IP := 1
ERR := 0
FIN := 0
for i = 1 to IM
if array.get(EI, i) > array.get(EI, IP)
IP := i
FIN := FIN + array.get(FI, i)
ERR := ERR + array.get(EI, i)
ADONED = FIN
ADONED
// @function Returns the Cumulative Trivariate Normal Distribution
// @param LIMIT1 float,
// @param LIMIT2 float,
// @param LIMIT3 float,
// @param SIGMA1 float,
// @param SIGMA2 float,
// @param SIGMA3 float,
// @returns float.
export CTND(float LIMIT1, float LIMIT2, float LIMIT3, float SIGMA1, float SIGMA2, float SIGMA3)=>
//
// A function for computing trivariate normal probabilities.
// This function uses an algorithm given in the paper
// "Numerical Computation of Bivariate and
// Trivariate Normal Probabilities",
// by
// Alan Genz
// Department of Mathematics
// Washington State University
// Pullman, WA 99164-3113
// Email : [email protected]
//
// CTND calculates the probability that X(I) < LIMIT(I), I = 1, 2, 3.
//
// Parameters
//
// LIMIT DOUBLE PRECISION array of three upper integration limits.
// SIGMA DOUBLE PRECISION array of three correlation coefficients,
// SIGMA should contain the lower left portion of the
// correlation matrix R.
// SIGMA(1) = R(2,1), SIGMA(2) = R(3,1), SIGMA(3) = R(3,2).
//
// CTND cuts the outer integral over -infinity to B1 to
// an integral from -8.5 to B1 and then uses an adaptive
// integration method to compute the integral of a bivariate
// normal distribution function.
//
bool TAIL = false
//
// Bivariate normal distribution function CBND is required.
//
float SQ21 = 0
float SQ31 = 0
float rho = 0
float b1 = 0
float B2 = 0
float B3 = 0
float b2p = 0
float b3p = 0
float RHO21 = 0
float RHO31 = 0
float RHO32 = 0
var float SQTWPI = 2.506628274631
var float XCUT = -8.5
var float EPS = 5E-16
float CTND = 0
b1 := LIMIT1
B2 := LIMIT2
B3 := LIMIT3
RHO21 := SIGMA1
RHO31 := SIGMA2
RHO32 := SIGMA3
if math.abs(B2) > math.max(math.abs(b1), math.abs(B3))
b1 := B2
B2 := LIMIT1
RHO31 := RHO32
RHO32 := SIGMA2
else if math.abs(B3) > math.max(math.abs(b1), math.abs(B2))
b1 := B3
B3 := LIMIT1
RHO21 := RHO32
RHO32 := SIGMA1
TAIL := false
if b1 > 0
TAIL := true
b1 := -b1
RHO21 := -RHO21
RHO31 := -RHO31
if b1 > XCUT
if 2 * math.abs(RHO21) < 1
SQ21 := math.sqrt(1 - RHO21 * RHO21)
else
SQ21 := math.sqrt((1 - RHO21) * (1 + RHO21))
if 2 * math.abs(RHO31) < 1
SQ31 := math.sqrt(1 - RHO31 * RHO31)
else
SQ31 := math.sqrt((1 - RHO31) * (1 + RHO31))
rho := (RHO32 - RHO21 * RHO31) / (SQ21 * SQ31)
b2p := B2 / SQ21
RHO21 := RHO21 / SQ21
b3p := B3 / SQ31
RHO31 := RHO31 / SQ31
CTND := ADONED(XCUT, b1, EPS, b2p, b3p, RHO21, RHO31, rho) / SQTWPI
else
CTND := 0
if TAIL == true
CTND := cbnd.CBND3(B2, B3, RHO32) - CTND
CTND
// example usage
float out = 0
if barstate.islast
out := CTND(0., 0., 0., 0., 0., 0.)
plot(out)
|
Strategy PnL Library | https://www.tradingview.com/script/TDx6il5e-Strategy-PnL-Library/ | serkany88 | https://www.tradingview.com/u/serkany88/ | 23 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © serkany88
//@version=5
// @description TODO: This is a library that helps you learn current pnl of position and use it to create your own dynamic take profit or stop loss rules based on current level of your profit.
//
library("Strategy_PnL_Library")
// @function inTrade: Checks if a position is currently open.
// @returns bool: true for yes, false for no.
export inTrade() =>
strategy.position_size != 0 //Checks if any position is open
// @function inTrade: Checks if a position is currently open. Interchangeable with inTrade but just here for simple semantics.
// @returns bool: true for yes, false for no.
export notInTrade() =>
strategy.position_size == 0 // Checks if any position is not open
// @function pnl: Calculates current profit or loss of position after the commission. If the strategy is not in trade it will always return na.
// @returns float: Current Profit or Loss of position, positive values for profit, negative values for loss.
export pnl() =>
//PnL Calculation including comission
sumOpenGrossPL = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenGrossPL += strategy.opentrades.profit(tradeNo) - strategy.opentrades.commission(tradeNo)
profit = inTrade() ? sumOpenGrossPL : na
// @function entryBars: Checks how many bars it's been since the entry of the position.
// @returns int: Returns a int of strategy entry bars back. Minimum value is always corrected to 1 to avoid lookback errors.
export entryBars() =>
//Current bar state of open position used as dynamic length
tradetime = strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
tradetime := tradetime == 0 ? 1 : tradetime
tradetime
// @function pnlvelocity: Calculates the velocity of pnl by following the change in open profit compared to previous bar. If the strategy is not in trade it will always return na.
// @returns float: Returns a float value of pnl velocity.
export pnlvelocity() =>
x = inTrade() ? ta.change(pnl()) : na
// @function pnlacc: Calculates the acceleration of pnl by following the change in profit velocity compared to previous bar. If the strategy is not in trade it will always return na.
// @returns float: Returns a float value of pnl acceleration.
export pnlacc() =>
x = inTrade() ? ta.change(pnlvelocity()) : na
// @function pnljerk: Calculates the jerk of pnl by following the change in profit acceleration compared to previous bar. If the strategy is not in trade it will always return na.
// @returns float: Returns a float value of pnl jerk.
export pnljerk() =>
x = inTrade() ? ta.change(pnlacc()) : na
// @function pnlhigh: Calculates the highest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
// @returns float: Returns a float highest value the pnl has reached.
export pnlhigh() =>
x = inTrade() ? ta.highest(pnl(), entryBars()) : na
// @function pnllow: Calculates the lowest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
// @returns float: Returns a float lowest value the pnl has reached.
export pnllow() =>
x = inTrade() ? ta.lowest(pnl(), entryBars()) : na
// @function pnldev: Calculates the deviance of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
// @returns float: Returns a float deviance value of the pnl.
export pnldev() =>
x = inTrade() ? ta.dev(pnl(), entryBars()) : na
// @function pnlvar: Calculates the variance value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
// @returns float: Returns a float variance value of the pnl.
export pnlvar() =>
x = inTrade() ? ta.variance(pnl(), entryBars()) : na
// @function pnlstdev: Calculates the stdev value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
// @returns float: Returns a float stdev value of the pnl.
export pnlstdev() =>
x = inTrade() ? ta.stdev(pnl(), entryBars()) : na
// @function pnlmedian: Calculates the median value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
// @returns float: Returns a float median value of the pnl.
export pnlmedian() =>
x = inTrade() ? ta.median(pnl(), entryBars()) : na |
EconomicCalendar | https://www.tradingview.com/script/FAShzjTK-EconomicCalendar/ | jdehorty | https://www.tradingview.com/u/jdehorty/ | 144 | library | 5 | MPL-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='EconomicCalendar')
// @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(
"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 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")
) |
normsinv | https://www.tradingview.com/script/yWZIyqXu-normsinv/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description Returns the inverse of the standard normal cumulative distribution.
// The distribution has a mean of zero and a standard deviation of one; i.e.,
// normsinv seeks that value z such that a normal distribtuio of mean of zero
// and standard deviation one is equal to the input probability.
// Reference:
// https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtri.c
library("normsinv")
//
// Inverse of Normal distribution function
//
//
//
// SYNOPSIS:
//
// double x, y, ndtri();
//
// x = ndtri( y );
//
//
//
// DESCRIPTION:
//
// Returns the argument, x, for which the area under the
// Gaussian probability density function (integrated from
// minus infinity to x) is equal to y.
//
//
// For small arguments 0 < y < exp(-2), the program computes
// z = sqrt( -2.0 // log(y) ); then the approximation is
// x = z - log(z)/z - (1/z) P(1/z) / Q(1/z).
// There are two rational functions P/Q, one for 0 < y < exp(-32)
// and the other for y up to exp(-2). For larger arguments,
// w = y - 0.5, and x/sqrt(2pi) = w + w////3 R(w////2)/S(w////2)).
//
//
// ACCURACY:
//
// Relative error:
// arithmetic domain # trials peak rms
// IEEE 0.125, 1 20000 7.2e-16 1.3e-16
// IEEE 3e-308, 0.135 50000 4.6e-16 9.8e-17
//
//
// ERROR MESSAGES:
//
// message condition value returned
// ndtri domain x <= 0 -1E10
// ndtri domain x >= 1 1E10
//
// Evaluates polynomial of degree N
polevl(float x, float[] coef, int n)=>
float ans = array.get(coef, 0)
for i = 1 to n
ans := ans * x + array.get(coef, i)
ans
// Evaluates polynomial of degree N with assumption that coef[N] = 1.0
p1evl(float x, float[] coef, int n)=>
float ans = x + array.get(coef, 0)
for i = 1 to n - 1
ans := ans * x + array.get(coef, i)
ans
// @function Returns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one.
// @param y0 float, probability corresponding to the normal distribution.
// @returns float, z-score
export normsinv(float y0)=>
// Cephes Math Library Release 2.1: January, 1989
// Copyright 1984, 1987, 1989 by Stephen L. Moshier
// Direct inquiries to 30 Frost Street, Cambridge, MA 02140
// sqrt(2pi)
float s2pi = 2.50662827463100050242E0
// approximation for 0 <= |y - 0.5| <= 3/8
var array<float> P0 = array.new_float(5, 0)
array.set(P0, 0, -5.99633501014107895267E1)
array.set(P0, 1, 9.80010754185999661536E1)
array.set(P0, 2, -5.66762857469070293439E1)
array.set(P0, 3, 1.39312609387279679503E1)
array.set(P0, 4, -1.23916583867381258016E0)
var array<float> Q0 = array.new_float(8, 0)
array.set(Q0, 0, 1.95448858338141759834E0)
array.set(Q0, 1, 4.67627912898881538453E0)
array.set(Q0, 2, 8.63602421390890590575E1)
array.set(Q0, 3, -2.25462687854119370527E2)
array.set(Q0, 4, 2.00260212380060660359E2)
array.set(Q0, 5, -8.20372256168333339912E1)
array.set(Q0, 6, 1.59056225126211695515E1)
array.set(Q0, 7, -1.18331621121330003142E0)
// Approximation for interval z = sqrt(-2 log y ) between 2 and 8
// i.e., y between exp(-2) = .135 and exp(-32) = 1.27e-14.
var array<float> P1 = array.new_float(9, 0)
array.set(P1, 0, 4.05544892305962419923E0)
array.set(P1, 1, 3.15251094599893866154E1)
array.set(P1, 2, 5.71628192246421288162E1)
array.set(P1, 3, 4.40805073893200834700E1)
array.set(P1, 4, 1.46849561928858024014E1)
array.set(P1, 5, 2.18663306850790267539E0)
array.set(P1, 6, -1.40256079171354495875E-1)
array.set(P1, 7, -3.50424626827848203418E-2)
array.set(P1, 8, -8.57456785154685413611E-4)
var array<float> Q1 = array.new_float(8, 0)
array.set(Q1, 0, 1.57799883256466749731E1)
array.set(Q1, 1, 4.53907635128879210584E1)
array.set(Q1, 2, 4.13172038254672030440E1)
array.set(Q1, 3, 1.50425385692907503408E1)
array.set(Q1, 4, 2.50464946208309415979E0)
array.set(Q1, 5, -1.42182922854787788574E-1)
array.set(Q1, 6, -3.80806407691578277194E-2)
array.set(Q1, 7, -9.33259480895457427372E-4)
// Approximation for interval z = sqrt(-2 log y ) between 8 and 64
// i.e., y between exp(-32) = 1.27e-14 and exp(-2048) = 3.67e-890.
var array<float> P2 = array.new_float(9, 0)
array.set(P2, 0, 3.23774891776946035970E0)
array.set(P2, 1, 6.91522889068984211695E0)
array.set(P2, 2, 3.93881025292474443415E0)
array.set(P2, 3, 1.33303460815807542389E0)
array.set(P2, 4, 2.01485389549179081538E-1)
array.set(P2, 5, 1.23716634817820021358E-2)
array.set(P2, 6, 3.01581553508235416007E-4)
array.set(P2, 7, 2.65806974686737550832E-6)
array.set(P2, 8, 6.23974539184983293730E-9)
var array<float> Q2 = array.new_float(8, 0)
array.set(Q2, 0, 6.02427039364742014255E0)
array.set(Q2, 1, 3.67983563856160859403E0)
array.set(Q2, 2, 1.37702099489081330271E0)
array.set(Q2, 3, 2.16236993594496635890E-1)
array.set(Q2, 4, 1.34204006088543189037E-2)
array.set(Q2, 5, 3.28014464682127739104E-4)
array.set(Q2, 6, 2.89247864745380683936E-6)
array.set(Q2, 7, 6.79019408009981274425E-9)
float x = 0
float y = 0
float z = 0
float y2 = 0
float x0 = 0
float x1 = 0
int code = 0
if not(y0 <= 0. or y0 >= 1.)
code := 1
y := y0
// 0.135... = exp(-2)
if y > (1.0 - 0.13533528323661269189)
y := 1.0 - y
code := 0
if y > 0.13533528323661269189
y := y - 0.5
y2 := y * y
x := y + y * (y2 * polevl(y2, P0, 4) / p1evl(y2, Q0, 8))
x := x * s2pi
else
x := math.sqrt(-2.0 * math.log(y))
x0 := x - math.log(x) / x
z := 1.0 / x
// y > exp(-32) = 1.2664165549e-14
if x < 8.
x1 := z * polevl(z, P1, 8) / p1evl(z, Q1, 8)
else
x1 := z * polevl(z, P2, 8) / p1evl(z, Q2, 8)
x := x0 - x1
if (code != 0)
x := -x
else
if y0 <= 0.
x := -1E10
if y0 >= 1
x := 1E10
x
// example usage
out = normsinv(0.995)
plot(out) |
cndev | https://www.tradingview.com/script/qHvp8irj-cndev/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description This function returns the inverse of cumulative normal distribution function
// Reference:
// The Full Monte, by Boris Moro, Union Bank of Switzerland . RISK 1995(2)
library("cndev")
// @function Returns the inverse of cumulative normal distribution function
// @param U float,
// @returns float.
export CNDEV(float U)=>
float x = 0
float r = 0
float CNDEV = 0
array<float> A = array.new<float>(4, 0)
array.set(A, 0, 2.50662823884)
array.set(A, 1, -18.61500062529)
array.set(A, 2, 41.39119773534)
array.set(A, 3, -25.44106049637)
array<float> b = array.new<float>(4, 0)
array.set(b, 0, -8.4735109309)
array.set(b, 1, 23.08336743743)
array.set(b, 2, -21.06224101826)
array.set(b, 3, 3.13082909833)
array<float> c = array.new<float>(9, 0)
array.set(c, 0, 0.337475482272615)
array.set(c, 1, 0.976169019091719)
array.set(c, 2, 0.160797971491821)
array.set(c, 3, 0.0276438810333863)
array.set(c, 4, 0.0038405729373609)
array.set(c, 5, 0.0003951896511919)
array.set(c, 6, 3.21767881767818E-05)
array.set(c, 7, 2.888167364E-07)
array.set(c, 8, 3.960315187E-07)
x := U - 0.5
if math.abs(x) < 0.42
r := x * x
r := x
* (((array.get(A, 3) * r
+ array.get(A,2)) * r
+ array.get(A, 1)) * r
+ array.get(A, 0)) / ((((array.get(b, 3) * r
+ array.get(b, 2)) * r
+ array.get(b, 1)) * r
+ array.get(b, 0)) * r
+ 1)
CNDEV := r
else
r := U
if x >= 0
r := 1 - U
r := math.log(-math.log(r))
r := array.get(c, 0)
+ r * (array.get(c, 1)
+ r * (array.get(c, 2)
+ r * (array.get(c, 3)
+ r * (array.get(c, 4)
+ r * (array.get(c, 5)
+ r * (array.get(c, 6)
+ r * (array.get(c, 7)
+ r * array.get(c, 8))))))))
if x < 0
r := -r
CNDEV := r
CNDEV
// example usage
out = CNDEV(.99)
out1 = CNDEV(.01)
plot(out)
plot(out1) |
inChart - Lib | https://www.tradingview.com/script/6VJNfowl-inChart-Lib/ | tv94067 | https://www.tradingview.com/u/tv94067/ | 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/
// © tv94067
//@version=5
// determine if price value is between chart high + x% and low - x% on the visible chart.
library("inChart", true)
// @function Condition to determine if a given bar is visible on the chart.
// @returns (bool) True if the current bar is visible.
barIsVisible() =>
bool result = time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
// @function Determines the value of the highest `high` in visible bars.
// @returns (float) The maximum high value of visible chart bars.
chartHigh() =>
var float chartHigh = na
if barIsVisible() and high >= nz(chartHigh, high)
chartHigh := high
float result = chartHigh
// @function Determines the value of the lowest `low` in visible bars.
// @returns (float) The minimum low value of visible chart bars.
chartLow() =>
var float chartLow = na
if barIsVisible() and low <= nz(chartLow, low)
chartLow := low
float result = chartLow
// @function Condition to determine if price value is between chart high + x % and low - x % on the visible chart.
// @returns (bool) True if price value is between chart high + x% and low - x% on the visible chart.
export inChart(float _price, float x_percent) =>
bool result = _price <= chartHigh() * (1 + x_percent / 100) and _price >= chartLow() * (1 - x_percent / 100)
// Example code of inCHart
_price1 = chartHigh() + chartHigh() * 0.3 / 100
_price2 = chartLow() - chartLow() * 0.5 / 100
plot(inChart(_price1, 0.50) ? _price1 : na, 'Chart High + x %', color.green)
plot(inChart(_price2, 1.25) ? _price2 : na, 'Chart Low - x %', color.red)
|
ta | https://www.tradingview.com/script/UZQxuS7X-ta/ | LucF | https://www.tradingview.com/u/LucF/ | 36 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LucF
//@version=5
// @description This library is a Pine Script™ programmer’s tool containing calcs for my oscillators and some helper functions.
library("ta")
// ta
// v3, 2023.04.06 13:46 — LucF
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
// @function Calculates buoyancy using a target of `src` summed over `targetPeriod` bars, not searching back farther than `maxLookback` bars. See: https://www.tradingview.com/script/18fu8TxD-Volume-Buoyancy-LucF/
// @param src (series float) The source value that is summed to constitute the target.
// @param targetPeriod (series int) The qty of bars to sum `src` for in order to calculate the target.
// @param maxLookback (simple int) The maximum number of bars back the function will search.
// @returns (series float) Buoyancy: the gap between the avg distance of past up and dn bars added to reach the target, divided by the max distance reached. Returns zero when an error condition occurs.
export buoyancy(series float src, series int targetPeriod, simple int maxLookback) =>
bool barUp = ta.rising(close, 1)
bool barDn = ta.falling(close, 1)
float targetSum = math.sum(nz(src), targetPeriod)
float slotUp = 0.
float slotDn = 0.
array<int> barOffsetsUp = array.new<int>(0)
array<int> barOffsetsDn = array.new<int>(0)
// True when the target is found for both up and down bars.
bool targetFound = false
// True when the beginning of the dataset is reached before reaching `maxLookback`.
bool overrun = false
// Start analyzing the current bar and go back in bars, one by one.
int bar = 0
// We go back until the target is found or `maxLookback` or the beginning of the dataset is reached.
while bar <= maxLookback and not (targetFound or overrun)
if barUp[bar] and slotUp < targetSum
slotUp += nz(src[bar])
array.push(barOffsetsUp, bar)
else if barDn[bar] and slotDn < targetSum
slotDn += nz(src[bar])
array.push(barOffsetsDn, bar)
overrun := bar >= bar_index
targetFound := slotUp >= targetSum and slotDn >= targetSum
bar += 1
float delta = array.avg(barOffsetsDn) - array.avg(barOffsetsUp)
int barsAnalyzed = bar - 1
float result = not targetFound ? 0. : nz(delta / barsAnalyzed)
// @function Calculates Efficient Work on `length` bars. See: https://www.tradingview.com/script/yG0rpNzO-Efficient-Work-LucF/
// @param length (simple int) The length of the ALMA used to calculate the result.
// @returns (series float) A -1 to +1 value representing the efficiency of price travel, bar to bar.
export efficientWork(simple int length) =>
float workUp = high - math.min(open, nz(close[1], close))
float workDn = math.max(open, nz(close[1])) - low
float work = workUp + workDn
float ew = nz((close - nz(close[1], open)) / work)
float result = ta.alma(ew, length, 0.85, 6)
// Reference MA names used in the following `ma()` function. The calling script must use these arguments for its `type` parameter for the function to work correctly.
string MA01 = "Simple MA"
string MA02 = "Exponential MA"
string MA03 = "Wilder MA"
string MA04 = "Weighted MA"
string MA05 = "Volume-weighted MA"
string MA06 = "Arnaud Legoux MA"
string MA07 = "Hull MA"
string MA08 = "Symmetrically-weighted MA"
// @function Returns the `type` MA of the `src` over the `length`.
// @param type (simple string) The type of MA required (uses constants that must be defined earlier in the script).
// @param src (series float) The source value used to calculate the MA.
// @param length (simple int) The length value used to calculate the MA.
// @returns (series float) The MA value.
export ma(simple string type, series float src, simple int length) =>
float result = switch type
MA01 => ta.sma( src, length)
MA02 => ta.ema( src, length)
MA03 => ta.rma( src, length)
MA04 => ta.wma( src, length)
MA05 => ta.vwma(src, length)
MA06 => ta.alma(src, length, 0.85, 6)
MA07 => ta.hma( src, length)
MA08 => ta.swma(src)
=> na
// @function Calculates the levels and states of divergence channels, which are created when divergences occur.
// @param divergence (series bool) `true` on divergences, which can be defined any way. On breached channels it creates a new channel, otherwise, channel levels are expanded.
// @param hiSrc (series float) The price source used to set the channel's hi level when a divergence occurs.
// @param loSrc (series float) The price source used to set the channel's lo level when a divergence occurs.
// @param breachHiSrc (series float) The price source that must breach over the channel's `channelHi` level for a breach to occur.
// @param breachLoSrc (series float) The price source that must breach under the channel's `channelLo` level for a breach to occur.
// @returns A tuple containing the following values:
// [
// (series float) channelHi — the channel's high level,
// (series float) channelLo — the channel's low level,
// (series bool) channelIsBull — `true` when `breachHiSrc` is higher than the channel's high,
// (series bool) channelIsBear — `true` when `breachLoSrc` is lower than the channel's low,
// (series bool) channelWasBreached — `true` on the first bar where `breachHiSrc`/`breachHiSrc` breaches the channel's high/low level,
// (series bool) newChannel — `true` when a new divergence on a breached channel causes a new channel to be created,
// (series int) preBreachUpChanges — Number of times the channel's high level was increased,
// (series int) preBreachDnChanges — Number of times the channel's low level was decreased
// ]
export divergenceChannel(series bool divergence, series float hiSrc, series float loSrc, series float breachHiSrc, series float breachLoSrc) =>
// Current hi/lo levels of the channel.
var float channelHi = na
var float channelLo = na
// Used to track the quantity of channel level changes of a yet unbreached channel.
var int preBreachUpChanges = 0
var int preBreachDnChanges = 0
// Determine levels state by comparing the breach source to existing channels levels.
bool channelIsBull = breachHiSrc > channelHi and not divergence
bool channelIsBear = breachLoSrc < channelLo and not divergence
// This is `true` when a channel was already breached at least once.
var bool channelWasBreached = false
// This is `true` on the first bar that breaches a channel.
bool priceBreachesChannel = not divergence and not channelWasBreached and (breachHiSrc > channelHi or breachLoSrc < channelLo)
// Update `breached` state.
channelWasBreached := channelWasBreached or priceBreachesChannel
// `true` when a new channel is created.
bool newChannel = false
// We only change levels on divergences.
if divergence
if channelWasBreached and not divergence[1]
// First divergence since breach out of levels; reset both levels.
channelHi := hiSrc
channelLo := loSrc
// Reset state to neutral.
channelIsBull := false
channelIsBear := false
channelWasBreached := false
// Cue enabling plotting functions to transition to a new channel.
newChannel := true
// Reset cum changes.
preBreachUpChanges := 0
preBreachDnChanges := 0
else
channelHi := math.max(nz(channelHi, hiSrc), hiSrc)
channelLo := math.min(nz(channelLo, loSrc), loSrc)
// Track level changes of the channel.
int levelChangeUp = int(math.abs(math.sign(ta.change(channelHi))))
int levelChangeDn = int(math.abs(math.sign(ta.change(channelLo))))
if not (channelWasBreached or newChannel)
preBreachUpChanges += levelChangeUp
preBreachDnChanges += levelChangeDn
[channelHi, channelLo, channelIsBull, channelIsBear, channelWasBreached, newChannel, preBreachUpChanges, preBreachDnChanges]
// @function Converts the name of a source in the `srcString` to its numerical equivalent.
// @param srcString (series string) The string representing the name of the source value to be returned.
// @returns (series float) The source's value.
export sourceStrToFloat(series string srcString) =>
float result = switch srcString
"open" => open
"high" => high
"low" => low
"close" => close
"hl2" => hl2
"hlc3" => hlc3
"ohlc4" => ohlc4
"hlcc4" => hlcc4
"volume" => volume
// @function Calculates an instant value for Signs of the Times, a directional measure of bar strength.
// @returns (series float) SOTT: a value between -1 and +1.
export sott() =>
// Bar properties.
bool barUp = close > open
bool barDn = close < open
float body = math.abs(close - open)
float wicks = high - low - body
bool risingVolume = ta.change(volume, 1) > 0
// Evaluate up weights.
float up =
// Bar Up/Dn
(barUp ? 1 : 0) +
// Open > previous open
(ta.rising(open, 1) ? 1 : 0) +
// High > previous high
(ta.rising(high, 1) ? 1 : 0) +
// Low > previous low
(ta.rising(low, 1) ? 1 : 0) +
// Close > previous close
(ta.rising(close, 1) ? 1 : 0) +
// Larger body
(barUp and ta.rising(body, 1) ? 1 : 0) +
// Body is larger than wicks.
(barUp and body > wicks ? 1 : 0) +
// Gaps (double-weighted).
(open > close[1] ? 2 : 0) +
// Efficient work returns a float value between -1 and +1 but is double-weighted.
(math.max(0, efficientWork(1)) * 2) +
// Rising volume (double-weighted).
(barUp and risingVolume ? 2 : 0)
// Evaluate down weights.
float dn =
// Bar Up/Dn
(barDn ? 1 : 0) +
// Open < previous open
(ta.falling(open, 1) ? 1 : 0) +
// High < previous high
(ta.falling(high, 1) ? 1 : 0) +
// Low < previous low
(ta.falling(low, 1) ? 1 : 0) +
// Close < previous close
(ta.falling(close, 1) ? 1 : 0) +
// Larger body
(barDn and ta.rising(body, 1) ? 1 : 0) +
// Body is larger than wicks.
(barDn and body > wicks ? 1 : 0) +
// Gaps (double-weighted).
(open < close[1] ? 2 : 0) +
// Efficient work returns a float value between -1 and +1 but is double-weighted.
(math.abs(math.min(0, efficientWork(1))) * 2) +
// Rising volume (double-weighted).
(barDn and risingVolume ? 2 : 0)
// Maximum value that up or dn weights can have, adjusting for charts where no volume is available.
float weightRange = na(risingVolume) ? 11. : 13.
float result = (up - dn) / weightRange
// @function Converts a "bool" cond to 1 when it is `true`, 0 when it's false.
// @param cond (bool) The "bool" value to be converted.
// @returns (int) 1 when `cond` is `true`, `false` otherwise.
export zeroOne(bool cond) =>
int result = cond ? 1 : 0
// @function Appends `sep` and `txt` to `msg` when `cond` is true.
// @param cond (bool) The condition determining if text will be added.
// @param msg (string) The string to which we add text.
// @param txt (string) The text to be added.
// @param sep (string) A separator string to be added before `txt` when `msg` already contains text.
// @returns (int) The modified `msg` string if `cond` is `true`. Returns `msg` unchanged if `cond` is `false`.
export addTextIf(bool cond, string msg, string txt, string sep) =>
string result = cond ? msg + (msg != "" ? sep : "") + txt : msg
// @function Calculates a gradient between two bull or two bear colors, depending on whether the source signal is above/below the centerline.
// The gradient is proportional to the current qty of advances/declines of the `source`.
// The count of advances/declines resets to one when the `source` crosses the `center` and is limited by `steps`.
// @param source (float) input signal.
// @param center (float) (- ∞ to ∞) centerline used to determine if signal is bullish/bearish.
// @param steps (float) Maximum number of steps in the gradient from the weak color to the strong color.
// @param bearWeakColor (color) bear color at adv/dec qty of 1.
// @param bearStrongColor (color) bear color at adv/dec qty of `steps`.
// @param bullWeakColor (color) bull color at adv/dec qty of 1.
// @param bullStrongColor (color) bull color at adv/dec qty of `steps`.
// @returns (color) The calculated color.
export gradientAdvDecPro(float source, float center, float steps, color bearWeakColor, color bearStrongColor, color bullWeakColor, color bullStrongColor) =>
var float qtyAdvDec = 0.
var float maxSteps = math.max(1, steps)
bool xUp = ta.crossover(source, center)
bool xDn = ta.crossunder(source, center)
float chg = ta.change(source)
bool up = chg > 0
bool dn = chg < 0
bool srcBull = source > center
bool srcBear = source < center
qtyAdvDec :=
srcBull ? xUp ? 1 : up ? math.min(maxSteps, qtyAdvDec + 1) : dn ? math.max(1, qtyAdvDec - 1) : qtyAdvDec :
srcBear ? xDn ? 1 : dn ? math.min(maxSteps, qtyAdvDec + 1) : up ? math.max(1, qtyAdvDec - 1) : qtyAdvDec : qtyAdvDec
var color result = na
result :=
srcBull ? color.from_gradient(qtyAdvDec, 1, maxSteps, bullWeakColor, bullStrongColor) :
srcBear ? color.from_gradient(qtyAdvDec, 1, maxSteps, bearWeakColor, bearStrongColor) : result
// @function Determines if the volume for an intrabar is up or down.
// @returns ([float, float]) A tuple of two values, one of which contains the bar's volume. `upVol` is the positive volume of up bars. `dnVol` is the negative volume of down bars.
// Note that when this function is designed to be called with `request.security_lower_tf()`,
// which will return a tuple of "array<float>" arrays containing up and dn volume for all the intrabars in a chart bar.
export upDnIntrabarVolumesByPolarity() =>
float upVol = 0.0
float dnVol = 0.0
switch
// Bar polarity can be determined.
close > open => upVol += volume
close < open => dnVol -= volume
// If not, use price movement since last bar.
close > nz(close[1]) => upVol += volume
close < nz(close[1]) => dnVol -= volume
// If not, use previously known polarity.
nz(upVol[1]) > 0 => upVol += volume
nz(dnVol[1]) < 0 => dnVol -= volume
[upVol, dnVol]
|
fastlog2 | https://www.tradingview.com/script/FDyt1hGn-fastlog2/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description Returns the approximation of Log2 with the maximal error of: 0.000061011436
// Reference:
// https://www.anycodings.com/1questions/2553538/efficient-implementation-of-natural-logarithm-ln-and-exponentiation
library("fastlog2")
// @function Returns the approximation of Log2 with the maximal error of: 0.000061011436
// @param x float
// @returns float, log2 of x
export fastlog2(float x)=>
float fastlog2 = -1.7417939 + (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x) * x
fastlog2
//example usage
out = fastlog2(close/close[1])
plot(out) |
na_skip_highest | https://www.tradingview.com/script/jjCpBZhX-na-skip-highest/ | tartigradia | https://www.tradingview.com/u/tartigradia/ | 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/
// © tartigradia
//@version=5
// @description Finds the highest historic value over len bars but skip na valued bars (eg, off days). In other words, this will ensure we find the highest or lowest value over len bars with a real value, and if there are any na bars in-between, we skip over but the loop will continue. This allows to mimic calculations on markets with off days (eg, weekends).
library("na_skip_highest")
// @function Internal function. Finds the highest or lowest historic value over len bars but skip na valued bars (eg, off days). In other words, this will ensure we find the highest value over len bars with a real value, and if there are any na bars in-between, we skip over but the loop will continue. This allows to mimic calculations on markets with off days (eg, weekends).
// @param src series float source (eg, close)
// @param len int length, number of recent bars to consider in the window to find the highest value
// @param mode int If 0 finds the highest value, if 1 finds the lowest value. Internal parameter.
// @returns highest float highest value found over the len window
export na_skip_highest_or_lowest(series float src, int len, int mode) =>
// Finds the highest or lowest historic value over len bars but skip na valued bars (eg, off days).
// In other words, this will ensure we find the highest or lowest value over len bars with a real value, and if there are any na bars in-between, we skip over but the loop will continue.
// This allows to mimic calculations on markets with off days (eg, weekends).
highest_or_lowest = src
i = 1
j = 1
while i < len and j < len*2 // for the first few historic bars, there is not many previous bars, so we need to limit the maximum number of bars we walk through, here it's len*2, then we give up
val = src[j]
if not na(val)
i += 1
if (mode == 0 and highest_or_lowest < val) or (mode == 1 and highest_or_lowest > val)
highest_or_lowest := val
j += 1
highest_or_lowest
// @function Finds the highest historic value over len bars but skip na valued bars (eg, off days). In other words, this will ensure we find the highest value over len bars with a real value, and if there are any na bars in-between, we skip over but the loop will continue. This allows to mimic calculations on markets with off days (eg, weekends).
// @param src series float source (eg, close)
// @param len int length, number of recent bars to consider in the window to find the highest value
// @returns highest float highest value found over the len window
export na_skip_highest(series float src, int len) =>
// Finds the highest historic value over len bars but skip na valued bars (eg, off days).
// In other words, this will ensure we find the highest value over len bars with a real value, and if there are any na bars in-between, we skip over but the loop will continue.
// This allows to mimic calculations on markets with off days (eg, weekends).
na_skip_highest_or_lowest(src, len, 0)
// @function Finds the lowest historic value over len bars but skip na valued bars (eg, off days). In other words, this will ensure we find the lowest value over len bars with a real value, and if there are any na bars in-between, we skip over but the loop will continue. This allows to mimic calculations on markets with off days (eg, weekends).
// @param src series float source (eg, close)
// @param len int length, number of recent bars to consider in the window to find the highest value
// @returns highest float highest value found over the len window
export na_skip_lowest(series float src, int len) =>
// Finds the lowest historic value over len bars but skip na valued bars (eg, off days).
// In other words, this will ensure we find the lowest value over len bars with a real value, and if there are any na bars in-between, we skip over but the loop will continue.
// This allows to mimic calculations on markets with off days (eg, weekends).
na_skip_highest_or_lowest(src, len, 1)
plot(na_skip_highest(close, 5))
|
KernelFunctions | https://www.tradingview.com/script/e0Ek9x99-KernelFunctions/ | jdehorty | https://www.tradingview.com/u/jdehorty/ | 286 | library | 5 | MPL-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 provides non-repainting kernel functions for Nadaraya-Watson estimator implementations. This allows for easy substition/comparison of different kernel functions for one another in indicators. Furthermore, kernels can easily be combined with other kernels to create newer, more customized kernels.
library("KernelFunctions", true)
// @function Rational Quadratic Kernel - An infinite sum of Gaussian Kernels of different length scales.
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _relativeWeight <simple float> Relative weighting of time frames. Smaller values resut in a more stretched out curve and larger values will result in a more wiggly curve. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Rational Quadratic Kernel.
export rationalQuadratic(series float _src, simple int _lookback, simple float _relativeWeight, simple int startAtBar) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
_size = array.size(array.from(_src))
for i = 0 to _size + startAtBar
y = _src[i]
w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_lookback, 2) * 2 * _relativeWeight))), -_relativeWeight)
_currentWeight += y*w
_cumulativeWeight += w
yhat = _currentWeight / _cumulativeWeight
yhat
// @function Gaussian Kernel - A weighted average of the source series. The weights are determined by the Radial Basis Function (RBF).
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Gaussian Kernel.
export gaussian(series float _src, simple int _lookback, simple int startAtBar) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
_size = array.size(array.from(_src))
for i = 0 to _size + startAtBar
y = _src[i]
w = math.exp(-math.pow(i, 2) / (2 * math.pow(_lookback, 2)))
_currentWeight += y*w
_cumulativeWeight += w
yhat = _currentWeight / _cumulativeWeight
yhat
// @function Periodic Kernel - The periodic kernel (derived by David Mackay) allows one to model functions which repeat themselves exactly.
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _period <simple int> The distance between repititions of the function.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Periodic Kernel.
export periodic(series float _src, simple int _lookback, simple int _period, simple int startAtBar) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
_size = array.size(array.from(_src))
for i = 0 to _size + startAtBar
y = _src[i]
w = math.exp(-2*math.pow(math.sin(math.pi * i / _period), 2) / math.pow(_lookback, 2))
_currentWeight += y*w
_cumulativeWeight += w
yhat = _currentWeight / _cumulativeWeight
yhat
// @function Locally Periodic Kernel - The locally periodic kernel is a periodic function that slowly varies with time. It is the product of the Periodic Kernel and the Gaussian Kernel.
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _period <simple int> The distance between repititions of the function.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Locally Periodic Kernel.
export locallyPeriodic(series float _src, simple int _lookback, simple int _period, simple int startAtBar) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
_size = array.size(array.from(_src))
for i = 0 to _size + startAtBar
y = _src[i]
w = math.exp(-2*math.pow(math.sin(math.pi * i / _period), 2) / math.pow(_lookback, 2)) * math.exp(-math.pow(i, 2) / (2 * math.pow(_lookback, 2)))
_currentWeight += y*w
_cumulativeWeight += w
yhat = _currentWeight / _cumulativeWeight
yhat
// Examples:
yhat1 = rationalQuadratic(close, 8, 1, 25)
yhat2 = gaussian(close, 16, 25)
yhat3 = periodic(close, 8, 100, 25)
yhat4 = locallyPeriodic(close, 8, 24, 25)
plot(yhat1, color = color.red, title = "Rational Quadratic Kernel")
plot(yhat2, color = color.yellow, title = "Gaussian Kernel")
plot(yhat3, color = color.green, title = "Periodic Kernel")
plot(yhat4, color = color.aqua, title = "Locally Periodic Kernel") |
PlurexSignal | https://www.tradingview.com/script/nOspQMBE-PlurexSignal/ | plurex | https://www.tradingview.com/u/plurex/ | 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/
// © plurex
//@version=5
// @description Provides functions that wrap the built in TradingView strategy functions so you can seemlessly integrate with Plurex Signal automation.
// NOTE: Be sure to set your strategy close_entries_rule="ANY" and pyramiding=20 or some other amount appropriate to your strategy in order to have multiple entries.
library("PlurexSignal")
SHORT_SL_ID = "s-sl"
LONG_SL_ID = "l-sl"
// @function Build a Plurex market string from a base and quote asset symbol.
// @returns A market string that can be used in Plurex Signal messages.
export plurexMarket(string base, string quote) => base + "-" + quote
// @function Builds Plurex market string from the syminfo
// @returns A market string that can be used in Plurex Signal messages.
export tickerToPlurexMarket() => plurexMarket(syminfo.basecurrency, syminfo.currency)
// @function Builds Plurex Signal Message json to be sent to a Signal webhook
// @param secret The secret for your Signal on plurex
// @param action The action of the message. One of [LONG, SHORT, CLOSE_LONGS, CLOSE_SHORTS, CLOSE_ALL, CLOSE_LAST_LONG, CLOSE_LAST_SHORT, CLOSE_FIRST_LONG, CLOSE_FIRST_SHORT].
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
// @returns A json string message that can be used in alerts to send messages to Plurex.
export simpleMessage(string secret, string action, string marketOverride = "") =>
market = marketOverride != "" ? marketOverride : tickerToPlurexMarket()
"{\"secret\": \""+secret+"\", \"action\": \""+action+"\", \"market\": \""+market+"\"}"
// @function Open a new long entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
// @param qty Corresponds to strategy.entry qty
export long(string secret, string marketOverride = "", series float qty = 1) =>
longID = str.format("l{0}", time(""))
strategy.entry(longID, strategy.long, qty=qty, alert_message=simpleMessage(secret=secret, action="LONG", marketOverride=marketOverride))
// @function Open a new long entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal stop loss for full open position
// @param secret The secret for your Signal on plurex
// @param stop The trigger price for the stop loss. See strategy.exit documentation
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
// @param qty Corresponds to strategy.entry qty
export longAndSetStopLoss(string secret, float stop, string marketOverride = "", series float qty = 1) =>
longID = str.format("l{0}", time(""))
strategy.cancel(SHORT_SL_ID)
strategy.entry(longID, strategy.long, qty=qty, alert_message=simpleMessage(secret=secret, action="LONG", marketOverride=marketOverride))
strategy.exit(LONG_SL_ID, stop=stop, alert_message = simpleMessage(secret=secret, action="CLOSE_LONGS", marketOverride=marketOverride))
// @function Open a new long entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
// @param secret The secret for your Signal on plurex
// @param trail_offset See strategy.exit documentation
// @param trail_price See strategy.exit documentation
// @param trail_points See strategy.exit documentation
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
// @param qty Corresponds to strategy.entry qty
export longAndSetTrailingStopLoss(string secret, float trail_offset, float trail_price = na, float trail_points = na, string marketOverride = "", series float qty = 1) =>
longID = str.format("l{0}", time(""))
strategy.cancel(SHORT_SL_ID)
strategy.entry(longID, strategy.long, qty=qty, alert_message=simpleMessage(secret=secret, action="LONG", marketOverride=marketOverride))
strategy.exit(LONG_SL_ID, trail_offset = trail_offset, trail_price = trail_price, trail_points = trail_points, alert_message = simpleMessage(secret=secret, action="CLOSE_LONGS", marketOverride=marketOverride))
// @function Open a new short entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
// @param qty Corresponds to strategy.entry qty
export short(string secret, string marketOverride = "", series float qty = 1) =>
shortID = str.format("s{0}", time(""))
strategy.entry(shortID, strategy.short, qty=qty, alert_message=simpleMessage(secret=secret, action="SHORT", marketOverride=marketOverride))
// @function Open a new short entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal stop loss for full open position
// @param secret The secret for your Signal on plurex
// @param stop The trigger price for the stop loss. See strategy.exit documentation
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
// @param qty Corresponds to strategy.entry qty
export shortAndSetStopLoss(string secret, float stop, string marketOverride = "", series float qty = 1) =>
shortID = str.format("s{0}", time(""))
strategy.cancel(LONG_SL_ID)
strategy.entry(shortID, strategy.short, qty=qty, alert_message=simpleMessage(secret=secret, action="SHORT", marketOverride=marketOverride))
strategy.exit(SHORT_SL_ID, stop=stop, alert_message = simpleMessage(secret=secret, action="CLOSE_SHORTS", marketOverride=marketOverride))
// @function Open a new short entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
// @param secret The secret for your Signal on plurex
// @param trail_offset See strategy.exit documentation
// @param trail_price See strategy.exit documentation.
// @param trail_points See strategy.exit documentation
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
// @param qty Corresponds to strategy.entry qty
export shortAndSetTrailingStopLoss(string secret, float trail_offset, float trail_price = na, float trail_points = na, string marketOverride = "", series float qty = 1) =>
shortID = str.format("s{0}", time(""))
strategy.cancel(LONG_SL_ID)
strategy.entry(shortID, strategy.short, qty=qty, alert_message=simpleMessage(secret=secret, action="SHORT", marketOverride=marketOverride))
strategy.exit(SHORT_SL_ID, trail_offset = trail_offset, trail_price = trail_price, trail_points = trail_points, alert_message = simpleMessage(secret=secret, action="CLOSE_SHORTS", marketOverride=marketOverride))
// @function Close all positions. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeAll(string secret, string marketOverride = "") =>
strategy.close_all(alert_message=simpleMessage(secret=secret, action="CLOSE_ALL", marketOverride=marketOverride))
// @function Close all longs. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeLongs(string secret, string marketOverride = "") =>
size = strategy.opentrades.size(strategy.opentrades-1)
if size > 0
strategy.close_all(alert_message=simpleMessage(secret=secret, action="CLOSE_LONGS", marketOverride=marketOverride))
// @function Close all shorts. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeShorts(string secret, string marketOverride = "") =>
size = strategy.opentrades.size(strategy.opentrades-1)
if size < 0
strategy.close_all(alert_message=simpleMessage(secret=secret, action="CLOSE_SHORTS", marketOverride=marketOverride))
// @function Close last long entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeLastLong(string secret, string marketOverride = "") =>
openTrades = strategy.opentrades
lastID = ""
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "l")
lastID := tradeID
lastID := tradeID
if lastID != ""
strategy.close(lastID, alert_message=simpleMessage(secret=secret, action="CLOSE_LAST_LONG", marketOverride=marketOverride))
// @function Close first long entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeFirstLong(string secret, string marketOverride = "") =>
openTrades = strategy.opentrades
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "l")
strategy.close(tradeID, alert_message=simpleMessage(secret=secret, action="CLOSE_FIRST_LONG", marketOverride=marketOverride))
break
// @function Close last short entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeLastShort(string secret, string marketOverride = "") =>
openTrades = strategy.opentrades
lastID = ""
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "s")
lastID := tradeID
if lastID != ""
strategy.close(lastID, alert_message=simpleMessage(secret=secret, action="CLOSE_LAST_SHORT", marketOverride=marketOverride))
// @function Close first short entry. Wraps strategy function and sends plurex message as an alert.
// @param secret The secret for your Signal on plurex
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export closeFirstShort(string secret, string marketOverride = "") =>
openTrades = strategy.opentrades
for i = 0 to (openTrades - 1)
tradeID = strategy.opentrades.entry_id(i)
if str.startswith(tradeID, "s")
strategy.close(tradeID, alert_message=simpleMessage(secret=secret, action="CLOSE_FIRST_SHORT", marketOverride=marketOverride))
break
// The secret unique to your Plurex Signal. needed for each message sent to the webhook
secret = "foo"
earliestBackTestMillis = 1663545605000 // Change this to suit your chart
if time > earliestBackTestMillis
indexDecimal = bar_index % 56
switch indexDecimal
0 => closeAll(secret)
2 => long(secret)
4 => long(secret)
6 => closeLastLong(secret)
8 => closeLastLong(secret)
10 => long(secret)
12 => long(secret)
14 => closeFirstLong(secret)
16 => closeFirstLong(secret)
18 => short(secret)
20 => short(secret)
22 => closeLastShort(secret)
24 => closeLastShort(secret)
26 => short(secret)
28 => short(secret)
30 => closeFirstShort(secret)
32 => closeFirstShort(secret)
34 => long(secret)
36 => long(secret)
38 => closeLongs(secret)
40 => short(secret)
42 => short(secret)
44 => closeShorts(secret)
46 => long(secret)
48 => long(secret)
50 => closeAll(secret)
52 => short(secret)
54 => short(secret)
plot(strategy.position_size) |
Trig | https://www.tradingview.com/script/jD9XwGxd-Trig/ | reees | https://www.tradingview.com/u/reees/ | 24 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
// @description Trigonometric functions
library("Trig", overlay=true)
import reees/Algebra/3 as alg
//----------------------------------------------------------------------------
// Public
//----------------------------------------------------------------------------
// @function Get angle α of a right triangle, given the lengths of its sides
// @param a length of leg a (float)
// @param b length of leg b (float)
// @param c length of hypotenuse (float)
// @param deg flag to return angle in degrees (bool - default = false)
// @returns angle α in radians (or degrees if deg == true)
//
export rt_get_angleAlpha(float a=0, float b=0, float c=0, simple bool deg=false) =>
r = if a != 0 and b != 0
math.atan(a/b)
else if a != 0 and c != 0
math.asin(a/c)
else if b != 0 and c != 0
math.acos(b/c)
else
0
deg==true ? math.todegrees(r) : r
// @function Get angle α of a right triangle formed by the given line
// @param x1 x coordinate 1 (int - optional, required if argument l is not specified)
// @param y1 y coordinate 1 (float - optional, required if argument l is not specified)
// @param x2 x coordinate 2 (int - optional, required if argument l is not specified)
// @param y2 y coordinate 2 (float - optional, required if argument l is not specified)
// @param l line object (line - optional, required if x1, y1, x2, and y2 agruments are not specified)
// @param deg flag to return angle in degrees (bool - default = false)
// @returns angle α in radians (or degrees if deg == true)
//
export rt_get_angleAlphaFromLine(int x1=0, float y1=0.0, int x2=0, float y2=0.0, line l=na, simple bool deg=false) =>
[a,b,c] = alg.line_getRtSides(x1,y1,x2,y2,l)
if a!=0 and b!=0 and c!=0
rt_get_angleAlpha(a,b,c,deg)
else
na
// @function Get angle β of a right triangle, given the lengths of its sides
// @param a length of leg a (float)
// @param b length of leg b (float)
// @param c length of hypotenuse (float)
// @param deg flag to return angle in degrees (bool - default = false)
// @returns angle β in radians (or degrees if deg == true)
//
export rt_get_angleBeta(float a=0, float b=0, float c=0, simple bool deg=false) =>
alpha = rt_get_angleAlpha(a,b,c,deg)
if deg==false
alpha < 0 ? math.toradians(-90) - alpha : math.toradians(90) - alpha
else
alpha < 0 ? -90 - alpha : 90 - alpha
// @function Get angle β of a right triangle formed by the given line
// @param x1 x coordinate 1 (int - optional, required if argument l is not specified)
// @param y1 y coordinate 1 (float - optional, required if argument l is not specified)
// @param x2 x coordinate 2 (int - optional, required if argument l is not specified)
// @param y2 y coordinate 2 (float - optional, required if argument l is not specified)
// @param l line object (line - optional, required if x1, y1, x2, and y2 agruments are not specified)
// @param deg flag to return angle in degrees (bool - default = false)
// @returns angle β in radians (or degrees if deg == true)
//
export rt_get_angleBetaFromLine(int x1=0, float y1=0.0, int x2=0, float y2=0.0, line l=na, simple bool deg=false) =>
alpha = rt_get_angleAlphaFromLine(x1,y1,x2,y2,l,deg)
if deg==false
alpha < 0 ? math.toradians(-90) - alpha : math.toradians(90) - alpha
else
alpha < 0 ? -90 - alpha : 90 - alpha
|
ahpuhelper | https://www.tradingview.com/script/PIlJVLfj-ahpuhelper/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 21 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description Helper Library for Auto Harmonic Patterns UltimateX. It is not meaningful for others. This is supposed to be private library. But, publishing it to make sure that I don't delete accidentally
library("ahpuhelper", overlay = true)
// @function add data to open trades table column
// @param showOpenTrades flag to show open trades table
// @param table_id Table Id
// @param column refers to pattern data
// @param colors backgroud and text color array
// @param values cell values
// @param intStatus status as integer
// @param harmonicTrailingStartState trailing Start state as per configs
// @param lblSizeOpenTrades text size
// @returns nextColumn
export insert_open_trades_table_column(simple bool showOpenTrades, table table_id, int column, color[] colors, string[] values,
int intStatus, simple int harmonicTrailingStartState, string lblSizeOpenTrades) =>
bgcolor = array.get(colors, 0)
text_color = array.get(colors, 1)
if showOpenTrades
highlightBgColor = color.new(bgcolor, 70)
table.cell(table_id=table_id, column=column, row=0, text=array.get(values, 0), bgcolor=bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=1, text=array.get(values, 1), bgcolor=bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=2, text=array.get(values, 2), bgcolor=bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=3, text=array.get(values, 3), bgcolor=bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
isHeader = harmonicTrailingStartState == -1
table.cell(table_id=table_id, column=column, row=4, text=array.get(values, 4), bgcolor=intStatus != 0 or isHeader? bgcolor : highlightBgColor,
text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=5, text=array.get(values, 5), bgcolor=intStatus < harmonicTrailingStartState? highlightBgColor : bgcolor,
text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=6, text=array.get(values, 6), bgcolor=intStatus >= harmonicTrailingStartState and not isHeader? highlightBgColor : bgcolor,
text_color=text_color, text_size=lblSizeOpenTrades)
if(intStatus!=0)
table.cell(table_id=table_id, column=column, row=7, text=array.get(values, 7), bgcolor=intStatus == 1 ? highlightBgColor : bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=8, text=array.get(values, 8), bgcolor=intStatus == 2 ? highlightBgColor : bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=9, text=array.get(values, 9), bgcolor=intStatus == 3 ? highlightBgColor : bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
table.cell(table_id=table_id, column=column, row=10, text=array.get(values, 10), bgcolor=intStatus == 4 ? highlightBgColor : bgcolor, text_color=text_color, text_size=lblSizeOpenTrades)
column+1
getSum(matrix<int> closedStats, int row)=>
statArray = matrix.row(closedStats, row)
sum = array.sum(statArray)
validSum = sum - array.get(statArray, 0)
[statArray, sum, validSum]
getClosedCellVal(closedStats, closedRRStats, retouchStats, sizeStats, rowNumber, cIndex, statsRow, sum, validSum, retouchRow, sizeRow, showStatsInPercentage)=>
currentCount = matrix.get(closedStats, rowNumber, cIndex)
lastCount = cIndex!=0 ? matrix.get(closedStats, rowNumber, cIndex-1) : 0
count = cIndex > 1? array.sum(array.slice(statsRow, cIndex, matrix.columns(closedStats))) : matrix.get(closedStats, rowNumber, cIndex)
touchCount = cIndex > 1? array.sum(array.slice(retouchRow, cIndex, matrix.columns(retouchStats))) : matrix.get(retouchStats, rowNumber, cIndex)
countPercent = cIndex == 0? (sum > 0? (count*100/sum) : 0) : (validSum > 0 ? (count*100/validSum) : 0)
tcount = count+lastCount == 0 ? 0 : count*100/(count+lastCount)
rr = closedRRStats.get(cIndex-2)
trr = closedRRStats.get(cIndex+2)
avgSize = cIndex >1 and count > 0 ? int(array.sum(array.slice(matrix.row(sizeStats, rowNumber), cIndex, matrix.columns(sizeStats)))/count) : 0.0
rrStr = cIndex > 1 and sum > 0 ? '\n'+rr+ (cIndex >2 ? ' / '+trr:'') : ''
wrStr = (showStatsInPercentage? str.tostring(countPercent, format.percent) + (cIndex > 2? ' / ' + str.tostring(tcount, format.percent): ''): (cIndex > 1? str.tostring(touchCount)+' / ': '') +str.tostring(count))
cellVal = wrStr+(showStatsInPercentage ? rrStr : '\n('+str.tostring(avgSize)+')')
cellVal
// @function populate closed stats for harmonic patterns
// @param ClosedStatsPosition Table position for closed stats
// @param bullishCounts Matrix containing bullish trade stats
// @param bearishCounts Matrix containing bearish trade stats
// @param bullishRetouchCounts Matrix containing bullish trade stats for those which retouched entry
// @param bearishRetouchCounts Matrix containing bearish trade stats for those which retouched entry
// @param bullishSizeMatrix Matrix containing data about size of bullish patterns
// @param bearishSizeMatrix Matrix containing data about size of bearish patterns
// @param bullishRR Matrix containing Risk Reward data of bullish patterns
// @param bearishRR Matrix containing Risk Reward data of bearish patterns
// @param allPatternLabels array containing pattern labels
// @param flags display flags
// @param rowMain Pattern header data
// @param rowHeaders header grouping data
// @returns void
export populate_closed_stats(string ClosedStatsPosition, matrix<bool> patternsMatrix,
matrix<int> bullishCounts, matrix<int> bearishCounts, matrix<int> bullishRetouchCounts, matrix<int> bearishRetouchCounts,
matrix<int> bullishSizeMatrix, matrix<int> bearishSizeMatrix, array<string> rr,
array<string> allPatternLabels, string lblSizeClosedTrades, bool[] flags, string[] rowMain, string[] rowHeaders)=>
ShowClosedTradeStats = array.get(flags, 0)
showSelectivePatternStats = array.get(flags, 1)
showPatternStats = array.get(flags, 2)
showStatsInPercentage = array.get(flags, 3)
if(barstate.islast and ShowClosedTradeStats)
closedStats = table.new(ClosedStatsPosition, 2*matrix.columns(bullishCounts)+3, matrix.rows(bullishCounts)+3, border_color=color.black, border_width=2)
longColumnStart = 3
longColumnEnd = longColumnStart + matrix.columns(bullishCounts)-2
shortColumnStart = longColumnEnd + 3
shortColumnEnd = shortColumnStart + matrix.columns(bearishCounts)-2
numberOfRows = matrix.rows(bullishCounts)
[bullishLRow, llSum, llValidSum] = getSum(bullishCounts, numberOfRows-1)
[bearishLRow, slSum, slValidSum] = getSum(bearishCounts, numberOfRows-1)
[bullishLRowRetouch, llSumRetouch, llValidSumRetouch] = getSum(bullishRetouchCounts, numberOfRows-1)
[bearishLRowRetouch, slSumRetouch, slValidSumRetouch] = getSum(bearishRetouchCounts, numberOfRows-1)
[bullishLRowSize, llSumSize, llValidSumSize] = getSum(bullishSizeMatrix, numberOfRows-1)
[bearishLRowSize, slSumSize, slValidSumSize] = getSum(bearishSizeMatrix, numberOfRows-1)
showOpenPatternStats = showSelectivePatternStats and matrix.rows(patternsMatrix) > 0
for [index, val] in rowMain
if(showPatternStats or showOpenPatternStats or index > 0) and (llSum!=0 or index < longColumnStart or index > longColumnEnd) and (slSum!=0 or index < shortColumnStart or index > shortColumnEnd)
and index!=1 and index!=2 and index!=8 and index!=9
table.cell(closedStats, index, 0, val, text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.maroon)
table.cell(closedStats, index, 1, array.get(rowHeaders, index), text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.maroon)
if(showPatternStats or showOpenPatternStats)
table.merge_cells(closedStats, 0,0,0,1)
if(llSum!=0)
table.merge_cells(closedStats, longColumnStart,0,longColumnEnd,0)
if(slSum!=0)
table.merge_cells(closedStats, shortColumnStart,0,shortColumnEnd,0)
closedStatsTooltip = (showStatsInPercentage? 'Win Rate / Trailing Win Rate\nRisk Reward / Trailing Risk Reward':'Retest Count / Hit Count\n(Average Size of Patterns)')
closedStatsTooltipT1 = (showStatsInPercentage? 'Win Rate\nRisk Reward':'Retest Count / Hit Count\n(Average Size of Patterns)')
totalsTooltip = 'Retest Count/ Valid Count / Total Patterns\n(Average Size of Patterns)'
if(showPatternStats or showOpenPatternStats)
for i=0 to numberOfRows-2
patternColumn = matrix.col(patternsMatrix, i)
patternIndex = array.indexof(patternColumn, true)
if(not showOpenPatternStats or showPatternStats or patternIndex >= 0)
[bullishRow, lSum, lValidSum] = getSum(bullishCounts, i)
[bearishRow, sSum, sValidSum] = getSum(bearishCounts, i)
[bullishRowRetouch, lSumRetouch, lValidSumRetouch] = getSum(bullishRetouchCounts, i)
[bearishRowRetouch, sSumRetouch, sValidSumRetouch] = getSum(bearishRetouchCounts, i)
[bullishRowSize, lSumSize, lValidSumSize] = getSum(bullishSizeMatrix, i)
[bearishRowSize, sSumSize, sValidSumSize] = getSum(bearishSizeMatrix, i)
if(lSum != 0 or sSum != 0)
table.cell(closedStats, 0, i+2, array.get(allPatternLabels,i), text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.teal)
if(llSum!=0)
for j=2 to matrix.columns(bullishCounts)-1
cellVal = getClosedCellVal(bullishCounts, rr, bullishRetouchCounts, bullishSizeMatrix, i, j, bullishRow, lSum, lValidSum, bullishRowRetouch, bullishRowSize, showStatsInPercentage)
table.cell(closedStats, j+longColumnStart-2, i+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.new(color.lime,20),
tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeStr = str.tostring(int(lValidSumSize/math.max(lValidSum, 1)))
fCellTxt = str.tostring(lValidSumRetouch)+'/'+str.tostring(lValidSum)+'/'+str.tostring(lSum)+'\n('+avgSizeStr+')'
table.cell(closedStats, longColumnEnd, i+2, fCellTxt, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.aqua, tooltip=totalsTooltip)
if(slSum!=0)
for j=2 to matrix.columns(bearishCounts)-1
cellVal = getClosedCellVal(bearishCounts, rr, bearishRetouchCounts, bearishSizeMatrix, i, j, bearishRow, sSum, sValidSum, bearishRowRetouch, bearishRowSize, showStatsInPercentage)
table.cell(closedStats, j+shortColumnStart-2, i+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.new(color.orange, 20),
tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeStr = str.tostring(int(sValidSumSize/math.max(sValidSum, 1)))
fCellTxt = str.tostring(sValidSumRetouch)+'/'+str.tostring(sValidSum)+'/'+str.tostring(sSum)+'\n('+avgSizeStr+')'
table.cell(closedStats, shortColumnEnd, i+2, fCellTxt, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.aqua, tooltip=totalsTooltip)
totalColor = color.yellow
if(showPatternStats or showOpenPatternStats)
table.cell(closedStats, 0, numberOfRows+2, 'Total', text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.olive)
if(llSum!=0)
for j=2 to matrix.columns(bullishCounts)-1
cellVal = getClosedCellVal(bullishCounts, rr, bullishRetouchCounts, bullishSizeMatrix, numberOfRows-1, j, bullishLRow, llSum, llValidSum, bullishLRowRetouch, bullishLRowSize, showStatsInPercentage)
table.cell(closedStats, j+longColumnStart-2, numberOfRows+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=color.new(showPatternStats or showOpenPatternStats?totalColor:color.lime,20), tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeStr = str.tostring(int(llValidSumSize/math.max(llValidSum, 1)))
fCellTxt = str.tostring(llValidSumRetouch)+'/'+str.tostring(llValidSum)+'/'+str.tostring(llSum)+'\n('+avgSizeStr+')'
table.cell(closedStats, longColumnEnd, numberOfRows+2, fCellTxt, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=showPatternStats or showOpenPatternStats?totalColor:color.lime,
tooltip=totalsTooltip)
if(slSum!=0)
for j=2 to matrix.columns(bearishCounts)-1
cellVal = getClosedCellVal(bearishCounts, rr, bearishRetouchCounts, bearishSizeMatrix, numberOfRows-1, j, bearishLRow, slSum, slValidSum, bearishLRowRetouch, bearishLRowSize, showStatsInPercentage)
table.cell(closedStats, j+shortColumnStart-2, numberOfRows+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=color.new(showPatternStats or showOpenPatternStats?totalColor:color.orange, 20), tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeStr = str.tostring(int(slValidSumSize/math.max(slValidSum, 1)))
fCellTxt = str.tostring(slValidSumRetouch)+'/'+str.tostring(slValidSum)+'/'+str.tostring(slSum)+'\n('+avgSizeStr+')'
table.cell(closedStats, shortColumnEnd, numberOfRows+2,fCellTxt, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=showPatternStats or showOpenPatternStats?totalColor:color.orange,
tooltip=totalsTooltip)
// @function populate risk reward based on entry, stop, and targets
// @param entry Entry price or ratio
// @param stop Stop price or ratio
// @param targets array of target prices or ratios
// @returns array containing risk reward and trailing risk reward
export getRR(float entry, float stop, array<float> targets)=>
var rr = array.new<string>(targets.size()*2)
if(na(rr.first()))
for [i, target] in targets
rr.set(i, str.tostring((target-entry)/(entry-stop), '#.##'))
lastTarget = i == 0? entry : targets.get(i-1)
rr.push(str.tostring((target-lastTarget)/(lastTarget-stop), '#.##'))
rr |
PineHelper | https://www.tradingview.com/script/PF8Z93jp/ | dokang | https://www.tradingview.com/u/dokang/ | 18 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dokang
//@version=5
// @description This library provides various functions to reduce your time.
library("PineHelper", overlay = true)
// @function get a recent opentrade entry bar_index
// @returns (int) bar_index
export recent_opentrade_entry_bar_index() =>
strategy.opentrades != 0 ? strategy.opentrades.entry_bar_index(strategy.opentrades-1) : na
// @function get a recent closedtrade entry bar_index
// @returns (int) bar_index
export recent_closedtrade_entry_bar_index() =>
strategy.closedtrades != 0 ? strategy.closedtrades.entry_bar_index(strategy.closedtrades-1) : na
// @function get a recent closedtrade exit bar_index
// @returns (int) bar_index
export recent_closedtrade_exit_bar_index() =>
strategy.closedtrades != 0 ? strategy.closedtrades.exit_bar_index(strategy.closedtrades-1) : na
// @function get all aopentrades roi
// @returns (float) roi
export all_opnetrades_roi() =>
strategy.opentrades != 0 ? strategy.openprofit/strategy.position_avg_price*100 : na
// @function get bars since recent opentrade entry
// @returns (int) number of bars
export bars_since_recent_opentrade_entry() =>
strategy.opentrades != 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na
// @function get bars since recent closedtrade entry
// @returns (int) number of bars
export bars_since_recent_closedtrade_entry() =>
strategy.closedtrades != 0 ? (bar_index - strategy.closedtrades.entry_bar_index(strategy.closedtrades-1)) : na
// @function get bars since recent closedtrade exit
// @returns (int) number of bars
export bars_since_recent_closedtrade_exit() =>
strategy.closedtrades != 0 ? (bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades-1)) : na
// @function get recent opentrade entry ID
// @returns (string) entry ID
export recent_opentrade_entry_id() =>
strategy.opentrades != 0 ? strategy.opentrades.entry_id(strategy.opentrades-1) : na
// @function get recent closedtrade entry ID
// @returns (string) entry ID
export recent_closedtrade_entry_id() =>
strategy.closedtrades != 0 ? strategy.closedtrades.entry_id(strategy.closedtrades-1) : na
// @function get recent closedtrade exit ID
// @returns (string) exit ID
export recent_closedtrade_exit_id() =>
strategy.closedtrades != 0 ? strategy.closedtrades.exit_id(strategy.closedtrades-1) : na
// @function get recent opentrade entry price
// @returns (float) price
export recent_opentrade_entry_price() =>
strategy.opentrades != 0 ? strategy.opentrades.entry_price(strategy.opentrades-1) : na
// @function get recent closedtrade entry price
// @returns (float) price
export recent_closedtrade_entry_price() =>
strategy.closedtrades != 0 ? strategy.closedtrades.entry_price(strategy.closedtrades-1) : na
// @function get recent closedtrade exit price
// @returns (float) price
export recent_closedtrade_exit_price() =>
strategy.closedtrades != 0 ? strategy.closedtrades.exit_price(strategy.closedtrades-1) : na
// @function get recent opentrade entry time
// @returns (int) time
export recent_opentrade_entry_time() =>
strategy.opentrades != 0 ? strategy.opentrades.entry_time(strategy.opentrades-1) : na
// @function get recent closedtrade entry time
// @returns (int) time
export recent_closedtrade_entry_time() =>
strategy.closedtrades != 0 ? strategy.closedtrades.entry_time(strategy.closedtrades-1) : na
// @function get recent closedtrade exit time
// @returns (int) time
export recent_closedtrade_exit_time() =>
strategy.closedtrades != 0 ? strategy.closedtrades.exit_time(strategy.closedtrades-1) : na
// @function get time since recent opentrade entry
// @returns (int) time
export time_since_recent_opentrade_entry() =>
strategy.opentrades != 0 ? (time - strategy.opentrades.entry_time(strategy.opentrades-1)) : na
// @function get time since recent closedtrade entry
// @returns (int) time
export time_since_recent_closedtrade_entry() =>
strategy.opentrades != 0 ? (time - strategy.closedtrades.entry_time(strategy.closedtrades-1)) : na
// @function get time since recent closedtrade exit
// @returns (int) time
export time_since_recent_closedtrade_exit() =>
strategy.closedtrades != 0 ? (time -strategy.closedtrades.exit_time(strategy.closedtrades-1)) : na
// @function get recent opentrade size
// @returns (float) size
export recent_opentrade_size() =>
strategy.opentrades != 0 ? strategy.opentrades.size(strategy.opentrades-1) : na
// @function get recent closedtrade size
// @returns (float) size
export recent_closedtrade_size() =>
strategy.closedtrades != 0 ? strategy.closedtrades.size(strategy.closedtrades-1) : na
// @function get all opentrades size
// @returns (float) size
export all_opentrades_size() =>
strategy.position_size != 0 ? math.abs(strategy.position_size) : na
// @function get recent opentrade profit
// @returns (float) profit
export recent_opentrade_profit() =>
strategy.opentrades != 0 ? strategy.opentrades.profit(strategy.opentrades-1) : na
// @function get all opentrades profit
// @returns (float) profit
export all_opentrades_profit() =>
strategy.opentrades != 0 ? strategy.openprofit : na
// @function get recent closedtrade profit
// @returns (float) profit
export recent_closedtrade_profit() =>
strategy.closedtrades != 0 ? strategy.closedtrades.profit(strategy.closedtrades-1) : na
// @function get recent opentrade max runup
// @returns (float) runup
export recent_opentrade_max_runup() =>
strategy.opentrades != 0 ? strategy.opentrades.max_runup(strategy.opentrades-1) : na
// @function get recent closedtrade max runup
// @returns (float) runup
export recent_closedtrade_max_runup() =>
strategy.closedtrades != 0 ? strategy.closedtrades.max_runup(strategy.closedtrades-1) : na
// @function get recent opentrade maxdrawdown
// @returns (float) mdd
export recent_opentrade_max_drawdown() =>
strategy.opentrades != 0 ? strategy.opentrades.max_drawdown(strategy.opentrades-1) : na
// @function get recent closedtrade maxdrawdown
// @returns (float) mdd
export recent_closedtrade_max_drawdown() =>
strategy.closedtrades != 0 ? strategy.closedtrades.max_drawdown(strategy.closedtrades-1) : na
// @function get max open trades drawdown
// @returns (float) mdd
export max_open_trades_drawdown() =>
result = 0.
for i = 0 to strategy.opentrades-1
result := math.max(result, strategy.opentrades.max_drawdown(i))
result
// @function get recent opentrade commission
// @returns (float) commission
export recent_opentrade_commission() =>
strategy.opentrades != 0 ? strategy.opentrades.commission(strategy.opentrades-1) : na
// @function get recent closedtrade commission
// @returns (float) commission
export recent_closedtrade_commission() =>
strategy.closedtrades != 0 ? strategy.closedtrades.commission(strategy.closedtrades-1) : na
// @function get qty by percent of equtiy
// @param percent (series float) percent that you want to set
// @returns (float) quantity
export qty_by_percent_of_equity(series float percent) =>
strategy.equity/close * percent * 0.01
// @function get size by percent of position size
// @param percent (series float) percent that you want to set
// @returns (float) size
export qty_by_percent_of_position_size(series float percent) =>
math.abs(strategy.position_size) * percent * 0.01
// @function get bool change of day
// @returns (bool) day is change or not
export is_day_change() =>
ta.change(dayofweek) > 0 ? true : false
// @function get bool using number of bars
// @returns (bool) allowedToTrade
export is_in_trade(int numberOfBars) =>
var lastbar = last_bar_index
allowedToTrade = (lastbar - bar_index <= numberOfBars) or barstate.isrealtime
allowedToTrade
is_leap_year(_year) =>
(_year % 100 == 0) and (_year % 400 != 0) ? true : (_year % 4 == 0)
daysInMonth(_year, _month) =>
int dpm = na
if _month == 2
dpm := 28 + (is_leap_year(_year) ? 1 : 0)
else
evenMonth = _month % 2 == 0
beforeAug = _month < 8
dpm := 30 + (((not evenMonth and beforeAug) or (evenMonth and not beforeAug)) ? 1 : 0)
// @function Check if today is the first day
// @returns (bool) true if today is the first day, false otherwise
export is_first_day() =>
dayofmonth(time) == 1
// @function Check if today is the last day
// @returns (bool) true if today is the last day, false otherwise
export is_last_day() =>
dayofmonth(time) == daysInMonth(year, month)
// @function Check if trade is open
// @returns (bool) true if trade is open, false otherwise
export is_entry() =>
ta.change(strategy.opentrades) > 0
// @function Check if trade is closed
// @returns (bool) true if trade is closed, false otherwise
export is_close() =>
ta.change(strategy.closedtrades) > 0
// @function Check if trade is win
// @returns (bool) true if trade is win, false otherwise
export is_win() =>
ta.change(strategy.wintrades) > 0
// @function Check if trade is loss
// @returns (bool) true if trade is loss, false otherwise
export is_loss() =>
ta.change(strategy.losstrades) > 0
// @function get json format discord message
// @param name (string) name of bot
// @param message (string) message that you want to send
// @returns (string) json format string
export discord_message(string name, string message) =>
json = '{'
+ str.format(
'
"username":"{0}",
"content":"{1}"
', name, message)
+'}'
json
// @function get json format telegram message
// @param chat_id (string) chatId of bot
// @param message (string) message that you want to send
// @returns (string) json format string
export telegram_message(string chat_id, string message) =>
// webhook url : https://api.telegram.org/bot{token}/sendMessage
json = '{'
+ str.format(
'
"chat_id":"{0}",
"text":"{1}"
', chat_id, message)
+'}'
json |
obvFilter | https://www.tradingview.com/script/ZTrzbxlX-obvFilter/ | jordanfray | https://www.tradingview.com/u/jordanfray/ | 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/
// © jordanfray
//@version=5
// @description TODO: Everything you need to add an OBV filter to a trading strategy
// ADD THIS TO THE INDICATOR ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾ ▾
// import jordanfray/obvFilter/2 as obv
// obvSource = input.source(defval=close, title="OBV Source", group="On Balance Volume Filter")
// obvMaType = input.string(defval="EMA", title="OBV Smoothing Type", options = ["EMA", "SMA", "RMA", "WMA"], group="On Balance Volume Filter")
// fastMaLength = input.int(title = "Fast OBV MA Length", defval = 9, minval = 2, maxval = 200, group="On Balance Volume Filter")
// slowMaLength = input.int(title = "Slow OBV MA Length", defval = 21, minval = 1, maxval = 200, group="On Balance Volume Filter")
// [obv, fastObvMa, slowObvMa] = obv.getOnBalanceVolumeFilter(obvSource, obvMaType, fastMaLength, slowMaLength)
// ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴ ▴
library("obvFilter")
getMovingAverage(simple string type, series float source, simple int length) =>
ma = switch type
"EMA" => ta.ema(source, length)
"SMA" => ta.sma(source, length)
"RMA" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
=> na
ma
// @function Get the fast and slow moving average for on balance volume
// @param source hook this up to an 'input.source' input
// @param maType Choose from EMA, SMA, RMA, or WMA
// @param fastMaLength int smoothing length for fast moving average
// @param // @param fastMaLength int smoothing length for fast moving average int smoothing length for slow moving average
// @returns Tupple with fast obv moving average and slow obv moving average
export getOnBalanceVolumeFilter(series float source, simple string maType, simple int fastMaLength, simple int slowMaLength) =>
var cumVol = 0.0
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
obv = ta.cum(math.sign(ta.change(source)) * volume)
fastObvMa = getMovingAverage(maType, obv, fastMaLength)
slowObvMa = getMovingAverage(maType, obv, slowMaLength)
[obv, fastObvMa, slowObvMa]
|
MovingAverages | https://www.tradingview.com/script/ThOJEnKE-MovingAverages/ | wuttikraim | https://www.tradingview.com/u/wuttikraim/ | 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/
// @version=5
library('MovingAverages', true)
isLenInvalid(simple int len, simple string name = 'len') =>
if na(len)
runtime.error("The '"+name+"' param cannot be NA.")
true
else if len < 0
runtime.error("The '"+name+"' param cannot be negative.")
true
else if len == 0
true
else
false
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// VAWMA = VWMA and WMA combined.
// Simply put, this attempts to determine the average price per share over time weighted heavier for recent values.
// Uses triangular algorithm to taper off values in the past (same as WMA does).
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function VAWMA = VWMA and WMA combined. Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. Uses a triangular algorithm to taper off values in the past (same as WMA does).
// @param len The number of bars to measure with.
// @param src The series to measure from. Default is 'hlc3'.
// @param volumeDefault The default value to use when a chart has no (N/A) volume.
// @returns The volume adjusted triangular weighted moving average of the series.
export vawma(
simple int len,
series float src = hlc3,
simple float volumeDefault = na,
simple int startingWeight = 1) =>
var float notAvailable = na
if isLenInvalid(len)
notAvailable
else
sum = 0.0
vol = 0.0
last = len - 1
for i = 0 to last
s = src[i]
v = volume[i]
if na(v) and not na(volumeDefault)
v := volumeDefault
if not na(s) and not na(v)
m = last - i + startingWeight
v *= m
vol += v
sum += s * v
vol == 0 ? na : sum/vol
///////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function Coefficient Moving Avereage (CMA) is a variation of a moving average that can simulate SMA or WMA with the advantage of previous data.
// @param n The number of bars to measure with.
// @param D The series to measure from. Default is 'close'.
// @param C The coefficient to use when averaging. 0 behaves like SMA, 1 behaves like WMA.
// @param compound When true (default is false) will use a compounding method for weighting the average.
export cma(
simple int n,
series float D = close,
simple float C = 1,
simple bool compound = false) =>
var float notAvailable = na
if isLenInvalid(n, 'n')
notAvailable
else
var float result = na
sum = 0.0
weight = 1.0
weightTotal = 0.0
for m = 1 to n
s = D[n - m]
if not na(s)
sum := sum + s * weight
weightTotal += weight
if compound
weight *= 1 + C
else
weight += C
prev = result[n]
if na(prev)
result := sum / weightTotal
else
result := (prev + sum) / (weightTotal + 1)
///////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function Same as ta.ema(src,len) but properly ignores NA values.
// @param len The number of samples to derive the average from.
// @param src The series to measure from. Default is 'close'.
export ema(
simple int len,
series float src = close) =>
var float notAvailable = na
if isLenInvalid(len)
notAvailable
else
var float alpha = 2 / (len + 1)
var float a1 = 1 - alpha
var float s = na
var float ema = na
if not na(src)
s := src
ema := alpha * s + a1 * nz(ema)
///////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function Same as ta.wma(src,len) but properly ignores NA values.
// @param len The number of samples to derive the average from.
// @param src The series to measure from. Default is 'close'.
// @param startingWeight The weight to begin with when calculating the average. Higher numbers will decrease the bias.
export wma(
simple int len,
series float src = close,
simple int startingWeight = 1) =>
var float notAvailable = na
if isLenInvalid(len)
notAvailable
else
sum = 0.0
total = 0
last = len - 1
for i = 0 to last
s = src[i]
if not na(s)
m = last - i + startingWeight // triangular multiple
total += m
sum += s * m
total == 0 ? na : sum/total
///////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function Same as ta.vwma(src,len) but properly ignores NA values.
// @param len The number of bars to measure with.
// @param src The series to measure from. Default is 'hlc3'.
// @param volumeDefault The default value to use when a chart has no (N/A) volume.
export vwma(
simple int len,
series float src = close,
simple float volumeDefault = na) =>
var float notAvailable = na
if isLenInvalid(len)
notAvailable
else
var sum = 0.0
var vol = 0.0
float datum = na
v = volume
if na(v) and not na(volumeDefault)
v := volumeDefault
if not na(src) and not na(v)
vol += v
datum := src * v
sum += datum
else
v := na
vStart = v[len]
dStart = datum[len]
if not na(vStart)
vol -= vStart
if not na(dStart)
sum -= dStart
vol == 0 ? na : sum/vol
///////////////////////////////////////////////////
SMA = 'SMA', EMA = 'EMA', WMA = 'WMA', CMA = 'CMA', VWMA = 'VWMA', VAWMA = 'VAWMA'
///////////////////////////////////////////////////
// @function Generates a moving average based upon a 'type'.
// @param type The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA.
// @param len The number of bars to measure with.
// @param src The series to measure from. Default is 'close'.
// @returns The moving average series requested.
export get(
simple string type,
simple int len,
series float src = close) =>
switch type
WMA => wma(len, src)
EMA => ema(len, src)
VWMA => vwma(len, src)
VAWMA => vawma(len, src)
CMA => cma(len, src)
SMA => ta.sma(src, len)
=>
runtime.error("No matching MA type found.")
ta.sma(src, len)
///////////////////////////////////////////////////
// Demo
plot(ema(20), 'ema(20)', color.red)
plot(wma(20), 'wma(20)', color.yellow)
plot(vwma(20), 'vwma(20)', color.blue)
plot(vawma(20), 'vawma(20)', color.purple) |
TradersCustomLibrary | https://www.tradingview.com/script/0HCpeHTK-TradersCustomLibrary/ | TradersCustom | https://www.tradingview.com/u/TradersCustom/ | 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/
// © nj27548
//@version=5
// @description TODO: add library description here
library("TradersCustomLibrary", overlay=true)
export SelectOptimalTimeframeTrendlineSettings(string symbol) =>
if (str.startswith(symbol, "ETH"))
seconds = timeframe.in_seconds(timeframe.period)
if (seconds <= 300)
['15', 17, '45', 14, '60', 11, '120', 7]
else
['30', 15, '60', 25, '120', 25, '240', 20]
export calculateShortStopLoss(float ResistanceTrendLine_TF1, float ResistanceTrendLine_TF2, float ResistanceTrendLine_TF3, float ResistanceTrendLine_TF4, int tier, float minimumStopLoss) =>
trendLinesAboveCurrentPrice = array.new_float()
tf1Distance = math.abs(high - ResistanceTrendLine_TF1)/high * 100.0
tf2Distance = math.abs(high - ResistanceTrendLine_TF1)/high * 100.0
tf3Distance = math.abs(high - ResistanceTrendLine_TF1)/high * 100.0
tf4Distance = math.abs(high - ResistanceTrendLine_TF1)/high * 100.0
if (high < ResistanceTrendLine_TF1 and tier <= 1 and tf1Distance >= minimumStopLoss)
array.push(trendLinesAboveCurrentPrice, ResistanceTrendLine_TF1)
if (high < ResistanceTrendLine_TF2 and tier <= 2 and tf1Distance >= minimumStopLoss)
array.push(trendLinesAboveCurrentPrice, ResistanceTrendLine_TF2)
if (high < ResistanceTrendLine_TF3 and tier <= 3 and tf1Distance >= minimumStopLoss)
array.push(trendLinesAboveCurrentPrice, ResistanceTrendLine_TF3)
if (high < ResistanceTrendLine_TF4 and tier <= 4 and tf1Distance >= minimumStopLoss)
array.push(trendLinesAboveCurrentPrice, ResistanceTrendLine_TF4)
if (array.size(trendLinesAboveCurrentPrice) == 0)
minimumResistanceTrendLine = 9999999999999999999999
else
minimumResistanceTrendLine = array.min(trendLinesAboveCurrentPrice)
export calculateLongStopLoss(float SupportTrendLine_TF1, float SupportTrendLine_TF2, float SupportTrendLine_TF3, float SupportTrendLine_TF4, int tier, float minimumStopLoss) =>
trendLinesBelowCurrentPrice = array.new_float()
tf1Distance = math.abs(low - SupportTrendLine_TF1)/low * 100.0
tf2Distance = math.abs(low - SupportTrendLine_TF2)/low * 100.0
tf3Distance = math.abs(low - SupportTrendLine_TF3)/low * 100.0
tf4Distance = math.abs(low - SupportTrendLine_TF4)/low * 100.0
if (low > SupportTrendLine_TF1 and tier <= 1 and tf1Distance >= minimumStopLoss)
array.push(trendLinesBelowCurrentPrice, SupportTrendLine_TF1)
if (low > SupportTrendLine_TF2 and tier <= 2 and tf2Distance >= minimumStopLoss)
array.push(trendLinesBelowCurrentPrice, SupportTrendLine_TF2)
if (low > SupportTrendLine_TF3 and tier <= 3 and tf3Distance >= minimumStopLoss)
array.push(trendLinesBelowCurrentPrice, SupportTrendLine_TF3)
if (low > SupportTrendLine_TF4 and tier <= 4 and tf4Distance >= minimumStopLoss)
array.push(trendLinesBelowCurrentPrice, SupportTrendLine_TF4)
if (array.size(trendLinesBelowCurrentPrice) == 0)
maximumSupportTrendLine = 0.0
else
maximumSupportTrendLine = array.max(trendLinesBelowCurrentPrice)
export werdygerTrend(float lb) =>
multiplier = timeframe.multiplier/5.
tofPeriod = int(204./multiplier * lb)
stPeriod = int(72./multiplier * lb)
foPeriod = int(51./multiplier * lb)
tof = ta.sma(close,tofPeriod)
st = ta.ema(close,stPeriod)
fo = ta.ema(close,foPeriod)
werdygerDiff = math.abs(tof - st)
werdygerBullish = (st > tof) and werdygerDiff > werdygerDiff[1]
werdygerBearish = (st < tof) and werdygerDiff > werdygerDiff[1]
[werdygerBullish, werdygerBearish, tof, st, fo, (werdygerDiff<werdygerDiff[1])]
pine_rma(src, length) =>
alpha = 1/length
sum = 0.0
sma = ta.sma(src, length)
sum := na(sum[1]) ? sma : alpha * src + (1 - alpha) * nz(sum[1])
pine_atr(length) =>
trueRange = na(high[1])? high-low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
//true range can be also calculated with ta.tr(true)
pine_rma(trueRange, length)
export trendLines(int length, float slopeModifier) =>
upper = 0.,lower = 0.
slope_ph = 0.,slope_pl = 0.
ph = ta.pivothigh(length,length)
pl = ta.pivotlow(length,length)
slope = pine_atr(length)/length*slopeModifier
slope_ph := ph ? slope : slope_ph[1]
slope_pl := pl ? slope : slope_pl[1]
upper := ph ? ph : upper[1] - slope_ph
lower := pl ? pl : lower[1] + slope_pl
[ph,pl,upper,lower]
export stoch(float multiplier) =>
periodK = int(14*multiplier)//input.int(14, title="%K Length", minval=1)
smoothK = int(3*multiplier)//input.int(1, title="%K Smoothing", minval=1)
periodD = int(3*multiplier)//input.int(3, title="%D Smoothing", minval=1)
_k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(_k, periodD)
[d]
export timeToString(int _t) =>
str.tostring(year(_t), "0000") + "." + str.tostring(month(_t), "00") + "." + str.tostring(dayofmonth(_t), "00") + " " +
str.tostring(hour(_t), "00") + ":" + str.tostring(minute(_t), "00") + ":" + str.tostring(second(_t), "00")
|
SupportResitanceAndTrend | https://www.tradingview.com/script/Pny09NhT-SupportResitanceAndTrend/ | wuttikraim | https://www.tradingview.com/u/wuttikraim/ | 39 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
// @description Contains utilities for finding key levels of support, resistance and direction of trend.
library('SupportResitanceAndTrend',true)
import wuttikraim/MovingAverages/1 as MA
import wuttikraim/DataCleaner/1 as Data
///////////////////////////////////////////////////
// @function A more flexible version of SuperTrend that allows for supplying the series used and sensitivity adjustment by confirming close bars.
// @param multiple The multiple to apply to the average true range.
// @param h The high values.
// @param l The low values.
// @param atr The average true range values.
// @param closeBars The number of bars to confirm a change in trend.
// @returns [trend, up, dn, unconfirmed, warn, reversal]
export superTrendPlus(
simple float multiple,
series float h,
series float l,
series float atr,
simple int closeBars = 0) =>
up = l-(multiple*atr)
up1 = nz(up[1], up)
up := l[1] > up1 ? math.max(up, up1) : up
dn = h+(multiple*atr)
dn1 = nz(dn[1], dn)
dn := h[1] < dn1 ? math.min(dn, dn1) : dn
var lastU = up1
var lastD = dn1
var trend = 0
var confirmation = 0
var unconfirmed = 0
// cover gap cases
if(trend != +1 and l > lastD)
trend := +1
else if(trend != -1 and h < lastU)
trend := -1
// confirmed cases
else if(trend != +1 and h > lastD)
unconfirmed += 1
if(confirmation<closeBars and close[1]>lastD)
confirmation += 1
if(confirmation>=closeBars)
trend := +1
else if(trend != -1 and l < lastU)
unconfirmed += 1
if(confirmation<closeBars and close[1]<lastU)
confirmation += 1
if(confirmation>=closeBars)
trend := -1
if(trend[1]!=trend)
lastU := up1
lastD := dn1
confirmation := 0
unconfirmed := 0
else
lastU := trend==+1 ? math.max(lastU, up1) : up1
lastD := trend==-1 ? math.min(lastD, dn1) : dn1
// Trend is clearly continuing? Reset confirmation.
if(trend==+1 and dn1>dn1[1] or trend==-1 and up1<up1[1])
confirmation := 0
unconfirmed := 0
[trend, lastU, lastD, unconfirmed, unconfirmed[1]==0 and unconfirmed > 0, trend != trend[1]]
///////////////////////////////////////////////////
getATR(simple string mode, simple int period, simple float maxDeviation) =>
trCleaned = maxDeviation==0 ? ta.tr : Data.naOutliers(ta.tr, period, maxDeviation)
MA.get(mode, period, trCleaned)
////
///////////////////////////////////////////////////
// @function superTrendPlus with simplified parameters.
// @param multiple The multiple to apply to the average true range.
// @param period The number of bars to measure.
// @param mode The type of moving average to use with the true range.
// @param closeBars The number of bars to confirm a change in trend.
// @returns [trend, up, dn, unconfirmed, warn, reversal]
export superTrend(
simple float multiple,
simple int period,
simple string mode = 'WMA',
simple int closeBars = 0,
simple float maxDeviation = 0) =>
atr = getATR(mode, period, maxDeviation)
superTrendPlus(multiple, high, low, atr, closeBars)
///////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function superTrendPlus with default compensation for extreme volatility.
// @param multiple The multiple to apply to the average true range.
// @param period The number of bars to measure.
// @param mode The type of moving average to use with the true range.
// @param closeBars The number of bars to confirm a change in trend.
// @param maxDeviation The optional standard deviation level to use when cleaning the series. The default is the value of the provided level.
// @returns [trend, up, dn, unconfirmed, warn, reversal]
export superTrendCleaned(
simple float multiple,
simple int period,
simple string mode = 'WMA',
simple int closeBars = 0,
simple float maxDeviation = 4) =>
atr = getATR(mode, period, maxDeviation)
superTrendPlus(multiple, high, low, atr, closeBars)
///////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function Identifies support and resistance levels by when a stochastic RSI reverses.
// @returns [trend, up, dn, unconfirmed, warn, reversal]
export stochSR(
simple int smoothK,
simple int smoothD,
simple int lengthRSI,
simple int lengthStoch,
series float src = hlc3,
simple float lowerBand = 20,
simple float upperBand = 80,
simple float lowerReversal = 20,
simple float upperReversal = 80) =>
rsi1 = ta.rsi(src, lengthRSI)
stoch = ta.stoch(rsi1, rsi1, rsi1, lengthStoch)
k = ta.wma(stoch, smoothK)
d = ta.sma(k, smoothD)
k_c = ta.change(k)
d_c = ta.change(d)
kd = k - d
var hi = high
var lo = low
var phi = high
var plo = low
var state = 0
if(d<lowerBand)
phi := high
if(d>upperBand)
plo := low
if(high>phi)
phi := high
if(low<plo)
plo := low
if(state!=-1 and d<lowerBand)
state := -1
else if(state!=+1 and d>upperBand)
state := +1
if(hi>phi and state==+1 and k<d and k<lowerReversal)
hi := phi
if(lo<plo and state==-1 and k>d and k>upperReversal)
lo := plo
if(high>hi)
hi := high
if(low<lo)
lo := low
[lo, hi]
///////////////////////////////////////////////////
///////////////////////////////////////////////////
// @function Identifies anchored VWAP levels by when a stochastic RSI reverses.
// @returns [loAVWAP, hiAVWAP, hiAVWAP_next, loAVWAP_next]
export stochAVWAP(
simple int smoothK,
simple int smoothD,
simple int lengthRSI,
simple int lengthStoch,
series float src = hlc3,
simple float lowerBand = 20,
simple float upperBand = 80,
simple float lowerReversal = 20,
simple float upperReversal = 80,
simple bool useHiLow = false) =>
rsi1 = ta.rsi(src, lengthRSI)
stoch = ta.stoch(rsi1, rsi1, rsi1, lengthStoch)
k = ta.wma(stoch, smoothK)
d = ta.sma(k, smoothD)
k_c = ta.change(k)
d_c = ta.change(d)
kd = k - d
var hi = high
var lo = low
var phi = high
var plo = low
var state = 0
var float hiAVWAP_s = 0
var float loAVWAP_s = 0
var float hiAVWAP_v = 0
var float loAVWAP_v = 0
var float hiAVWAP_s_next = 0
var float loAVWAP_s_next = 0
var float hiAVWAP_v_next = 0
var float loAVWAP_v_next = 0
if(d<lowerBand or high>phi)
phi := high
hiAVWAP_s_next := 0
hiAVWAP_v_next := 0
if(d>upperBand or low<plo)
plo := low
loAVWAP_s_next := 0
loAVWAP_v_next := 0
if(high>hi)
hi := high
hiAVWAP_s := 0
hiAVWAP_v := 0
if(low<lo)
lo := low
loAVWAP_s := 0
loAVWAP_v := 0
vwapHi = useHiLow ? high : hlc3
vwapLo = useHiLow ? low : hlc3
hiAVWAP_s += vwapHi * volume
loAVWAP_s += vwapLo * volume
hiAVWAP_v += volume
loAVWAP_v += volume
hiAVWAP_s_next += vwapHi * volume
loAVWAP_s_next += vwapLo * volume
hiAVWAP_v_next += volume
loAVWAP_v_next += volume
if(state!=-1 and d<lowerBand)
state := -1
else if(state!=+1 and d>upperBand)
state := +1
if(hi>phi and state==+1 and k<d and k<lowerReversal)
hi := phi
hiAVWAP_s := hiAVWAP_s_next
hiAVWAP_v := hiAVWAP_v_next
if(lo<plo and state==-1 and k>d and k>upperReversal)
lo := plo
loAVWAP_s := loAVWAP_s_next
loAVWAP_v := loAVWAP_v_next
hiAVWAP = hiAVWAP_s / hiAVWAP_v
loAVWAP = loAVWAP_s / loAVWAP_v
hiAVWAP_next = hiAVWAP_s_next / hiAVWAP_v_next
loAVWAP_next = loAVWAP_s_next / loAVWAP_v_next
[loAVWAP, hiAVWAP, hiAVWAP_next, loAVWAP_next]
///////////////////////////////////////////////////
// Demo
ATR = "Average True Range", CONFIRM = "Confirmation", DISPLAY = "Display"
WMA = "WMA", EMA = "EMA", SMA = "SMA", VWMA = "VWMA", VAWMA = "VAWMA"
mode = input.string(VAWMA, "Mode", options=[SMA,EMA,WMA,VWMA,VAWMA], group=ATR, tooltip="Selects which averaging function will be used to determine the ATR value.")
atrPeriod = input.int(120, "Period", group=ATR, tooltip="The number of bars to use in calculating the ATR value.")
atrM = input.float(3.0, title="Multiplier", step=0.5, group=ATR, tooltip="The multiplier used when defining the super trend limits.")
closeBars = input.int(2, "Closed Bars", minval = 0, group=CONFIRM, tooltip="The number of closed bars that have to exceed the super-trend value before the trend reversal is confirmed.")
[trend1, up, dn, unconfirmed1, warn1, reversal1] =
superTrend(atrM, atrPeriod, mode=mode, closeBars=closeBars)
plot(up)
plot(dn)
[trend2, upCleaned, dnCleaned, unconfirmed2, warn2, reversal2] =
superTrendCleaned(atrM, atrPeriod, mode=mode, closeBars=closeBars)
plot(upCleaned, color=color.green)
plot(dnCleaned, color=color.green) |
FrostyBot | https://www.tradingview.com/script/wSc2YMV8-FrostyBot/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
//@version=5
o__=' © kaigouthro '
// @description rostyBot-js JSON Alert Builder for Binance Futures and FTX orders
// https://github.com/CryptoMF/frostybot-js/wiki/Frostybot-Command-Reference#structure
// TODO: Comment Functions and anotations from command reference ^^
// TODO: Add additonal whitelist/account Functions.
// ===================================================
library("FrostyBot")
// ========================================================
o__:=' ┌─┐┌─┐┌┐┌┌─┐┌┬┐┌─┐┌┐┌┌┬┐┌─┐ '
o__:=' │ │ ││││└─┐ │ ├─┤│││ │ └─┐ '
o__:=' └─┘└─┘┘└┘└─┘ ┴ ┴ ┴┘└┘ ┴ └─┘ '
varip string _BUY = "buy"
varip string _CANCELALL = "cancelall"
varip string _CLOSE = "close"
varip string _CLOSEL = "closel"
varip string _CLOSES = "closes"
varip string _COMMAND = "command"
varip string _LEVERAGE = "leverage"
varip string _LONG = "long"
varip string _MAX = "max"
varip string _MAXSIZE = "maxsize"
varip string _PFTPRICE = "profitprice"
varip string _PFTSIZE = "profitsize"
varip string _PFTTRIGGER = "profittrigger"
varip string _POST = "post"
varip string _PRICE = "price"
varip string _REDUCE = "reduce"
varip string _SELL = "sell"
varip string _SHORT = "short"
varip string _SIZE = "size"
varip string _STOPLOSS = "stoploss"
varip string _STOPPRICE = "stopprice"
varip string _STOPSIZE = "stopsize"
varip string _STOPTRIGGER = "stoptrigger"
varip string _STUB = "stub"
varip string _SYMBOL = "symbol"
varip string _TAKEPRF = "takeprofit"
varip string _TAKEPROFIT = "takeprofit"
varip string _TRADE = "trade"
varip string _TRAILLONG = "traillong"
varip string _TRAILSHORT = "trailshort"
varip string _TRAILSTOP = "trailstop"
varip string _TYPE = "type"
// ========================================================
o__:=' ┬ ┬┌─┐┬ ┌─┐┌─┐┬─┐ ┌─┐┬ ┬┌┐┌┌─┐┌┬┐┬┌─┐┌┐┌┌─┐ '
o__:=' ├─┤├┤ │ ├─┘├┤ ├┬┘ ├┤ │ │││││ │ ││ ││││└─┐ '
o__:=' ┴ ┴└─┘┴─┘┴ └─┘┴└─ └ └─┘┘└┘└─┘ ┴ ┴└─┘┘└┘└─┘ '
// semi-minified..
RP ( _val, _o, _i ) => str.replace_all( _val, _o, _i )
S ( _val ) => str.tostring ( _val )
item ( _st , _key , _value , nest) => str.format((nest?",":"")+'"{0}":"{1}"|', _key, _value)
json ( _st , _key , _value , nest = 0) => s = _st, _st + item(_st, _key, _value, str.endswith(s, "|"))
brace ( x ) => s = RP(RP(RP(x," ",""),"|",""),'""','"'), s := string("{"+s+"}")
base (string cmd, stub, ticker)=> s = '"command":"trade:'+stub+':'+ cmd + '",', s := json (s, _SYMBOL ,'"'+ ticker + '"' )
szType (_sizeType, _qty ) =>
_size = switch _sizeType
"absolute" => S(_qty)
"factor" => S(_qty) + "x"
"percent" => S(_qty) + "%"
prcType(_priceType,_price,_side) =>
switch _priceType
"absolute" => S(_price)
"relative" => _side + S(_price)
"percent" => _side + S(_price) + "%"
=> _side+"0.01%"
// ========================================================
o__:=' ┌┬┐┬─┐┌─┐┌┬┐┌─┐ ┌─┐┬─┐┌┬┐┌─┐┬─┐┌─┐ '
o__:=' │ ├┬┘├─┤ ││├┤ │ │├┬┘ ││├┤ ├┬┘└─┐ '
o__:=' ┴ ┴└─┴ ┴─┴┘└─┘ └─┘┴└──┴┘└─┘┴└─└─┘ '
// @function leverage set alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _lev (int ) Leverage Multiplier (set whenever desired change)
// @param _orders (int ) Order count (1 - N orders, make sure 1/N * Qty > minimum!!)
// @returns (string) Alert Message in JSON format
export leverage ( string stub ,
string ticker ,
int _lev = 20 ,
string _levtype = "cross" ) =>
s = base ( _LEVERAGE , stub , ticker )
s := json ( s , _LEVERAGE , _lev )
s := json ( s , _TYPE , '"'+_levtype+'"' )
brace(s)
// @function buy order alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _qty (float ) Quantity (Changes depending on price type)
// @param _sizeType (string) "absolute" => Exact Size (Position or Qty.. SEE DOCUMENTATION!)
// "factor" => Factor of current Position (1.5 = 150%, .5 = 50%)
// "percent" => Percent of Equity
// @param _priceType (string) "absolute" => exactly the price input is dollars
// "relative" => market + price input is dollars
// "percent" => market + price input is percent
// @param _price (float ) Price Input (SEE DOCUMENTATION!!)
// @param _max (float ) Maximum Position Size Limiter
// @param postonly (bool ) Place as "post only"
// @returns (string) Alert Message in JSON format
export buy ( string stub ,
string ticker ,
float _qty ,
string _sizeType = "percent" ,
string _priceType = "percent" ,
float _price = 0.01 ,
float _max = 10000 ,
bool postonly = false ) =>
_size = szType(_sizeType , _qty )
_prc = prcType(_priceType , _price, "-" )
s = base ( _BUY , stub , ticker )
s := json ( s , _POST , postonly )
s := json ( s , _MAXSIZE , _max )
s := json ( s , _SIZE , _size )
s := json ( s , _PRICE , _prc )
brace(s)
// @function sell order alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _qty (float ) Quantity (Changes depending on price type)
// @param _sizeType (string) "absolute" => Exact Size (Position or Qty.. SEE DOCUMENTATION!)
// "factor" => Factor of current Position (1.5 = 150%, .5 = 50%)
// "percent" => Percent of Equity
// @param _priceType (string) "absolute" => exactly the price input is dollars
// "relative" => market + price input is dollars
// "percent" => market + price input is percent
// @param _price (float ) Price Input (SEE DOCUMENTATION!!)
// @param _max (float ) Maximum Position Size Limiter
// @param postonly (bool ) Place as "post only"
// @returns (string) Alert Message in JSON format
export sell ( string stub ,
string ticker ,
float _qty ,
string _sizeType = "percent" ,
string _priceType = "percent" ,
float _price = 0.01 ,
float _max = 10000 ,
bool postonly = false ) =>
_size = szType(_sizeType , _qty )
_prc = prcType(_priceType , _price, "+" )
s = base ( _SELL , stub , ticker )
s := json ( s , _POST , postonly )
s := json ( s , _MAXSIZE , _max )
s := json ( s , _SIZE , _size )
s := json ( s , _PRICE , _prc )
brace(s)
// @function cancel all open orders (no cancel by id... yet)
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
export cancelall ( string stub ,
string ticker ) =>
brace(base(_CANCELALL, stub, ticker))
// @function close long alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _qty (float ) Quantity (Changes depending on price type)
// @param _priceType (string) "absolute" => exactly the price input is dollars
// "relative" => market + price input is dollars
// "percent" => market + price input is percent
// @param _price (float ) Price Input (SEE DOCUMENTATION!!)
// @param _reduce (bool ) Reduce only order
// @returns (string) Alert Message in JSON format
export closelong ( string stub ,
string ticker ,
float _qty ,
string _priceType = "percent" ,
float _price = na ,
bool _reduce = true ) =>
_prc = prcType(_priceType , _price, "+" )
s = base ( _CLOSE , stub , ticker )
s := json ( s , _SIZE , _qty )
s := json ( s , _REDUCE , _reduce )
s := json ( s , _PRICE , _prc )
brace(s)
// @function close short alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _qty (float ) Quantity (Changes depending on price type)
// @param _priceType (string) "absolute" => exactly the price input is dollars
// "relative" => market + price input is dollars
// "percent" => market + price input is percent
// @param _price (float ) Price Input (SEE DOCUMENTATION!!)
// @param _reduce (bool ) Reduce only order
// @returns (string) Alert Message in JSON format
export closeshort ( string stub ,
string ticker ,
float _qty ,
string _priceType = "percent" ,
float _price = na ,
bool _reduce = true ) =>
_prc = prcType(_priceType , _price, "-" )
s = base ( _CLOSE , stub , ticker )
s := json ( s , _SIZE , _qty )
s := json ( s , _REDUCE , _reduce )
s := json ( s , _PRICE , _prc )
brace(s)
// @function trail sl long alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _offset (float ) Offset to trail by
// @param _reduce (bool ) Reduce only order
// @returns (string) Alert Message in JSON format
export traillong ( string stub ,
string ticker ,
float _offset ,
bool _reduce = true ) =>
s = base ( _TRAILSTOP, stub , ticker )
s := json ( s , _REDUCE , _reduce )
s := json ( s , _TRAILSTOP , "-" + S(_offset) + "%")
brace(s)
// @function trail sl short alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _offset (float ) Offset to trail by
// @param _reduce (bool ) Reduce only order
// @returns (string) Alert Message in JSON format
export trailshort ( string stub ,
string ticker ,
float _offset ,
bool _reduce = true ) =>
s = base ( _TRAILSTOP, stub , ticker )
s := json ( s , _REDUCE , _reduce )
s := json ( s , _TRAILSTOP , "+" + S(_offset) + "%")
brace(s)
// @function set long position alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _qty (float ) Quantity (Changes depending on price type)
// @param _start (float ) Entry price / Offset from Market (Below mark Long, Above for Short)
// @param _dist (float ) Distance from First Price (for spread orders)
// @param _orders (int ) Order count (1 - N orders, make sure 1/N * Qty > minimum!!)
// @param _max (float ) Maximum Position Size Limiter
// @param postonly (bool ) Place as "post only"
// @returns (string) Alert Message in JSON format
export long ( string stub ,
string ticker ,
float _qty ,
float _start = 0.0001 ,
float _dist = .0025 ,
int _orders = 1 ,
float _max = 10000 ,
bool postonly = false ) =>
_last = _start + _dist
s = base ( _LONG , stub , ticker )
s := json ( s , _POST , postonly )
s := json ( s , _MAX , _max )
s := json ( s , _SIZE , "%" + S(_qty ) )
s := json ( s , _PRICE , "-" + S(_start * 100) +
(_orders > 1 ? str.format(",{0},{1}", _last * 100, _orders) : '') )
brace(s)
// @function set short position alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _qty (float ) Quantity (Changes depending on price type)
// @param _start (float ) Entry price / Offset from Market (Below mark Long, Above for Short)
// @param _dist (float ) Distance from First Price (for spread orders)
// @param _orders (int ) Order count (1 - N orders, make sure 1/N * Qty > minimum!!)
// @param _max (float ) Maximum Position Size Limiter
// @param postonly (bool ) Place as "post only"
// @returns (string) Alert Message in JSON format
export short ( string stub ,
string ticker ,
float _qty ,
float _start = 0.0001 ,
float _dist = .0025 ,
int _orders = 1 ,
float _max = 10000 ,
bool postonly = false ) =>
_last = _start + _dist
s = base ( _SHORT , stub , ticker )
s := json ( s , _POST , postonly )
s := json ( s , _MAX , _max )
s := json ( s , _SIZE , "%" + S(_qty ) )
s := json ( s , _PRICE , "+" + S(_start * 100) +
(_orders > 1 ? str.format(",{0},{1}", _last * 100, _orders) : '') )
brace(s)
// @function take profit alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _size (float ) Position Size (DOCUMENTATION!!)
// @param _trig (float ) Trigger Price
// @param _exec (float ) Execution Trigger Price
// @param _reduce (bool ) Reduce only order
// @returns (string) Alert Message in JSON format
export takeprofit ( string stub ,
string ticker ,
float _size ,
float _trig ,
float _exec ,
bool _reduce = true ) =>
s = base ( _TAKEPRF , stub , ticker )
s := json ( s , _PFTSIZE , S(_size ) + "%" )
s := json ( s , _PFTTRIGGER , S(_trig ) )
s := json ( s , _PFTPRICE , S(_exec ) )
s := json ( s , _REDUCE , S(_reduce ) )
brace(s)
// @function stop loss alert constructor for frostybot
// @param stub (string) Stub value for your Frostybot server
// @param ticker (string) Syminfo.tickerid Value (BINANCE:BTCUSDTPERP)
// @param _size (float ) Position Size (DOCUMENTATION!!)
// @param _trig (float ) Trigger Price
// @param _exec (float ) Execution Trigger Price
// @param _reduce (bool ) Reduce only order
// @returns (string) Alert Message in JSON format
export stoploss ( string stub ,
string ticker ,
float _size ,
float _trig ,
float _exec ,
bool _reduce = true ) =>
s = base ( _STOPLOSS , stub , ticker )
s := json ( s , _REDUCE , _reduce )
s := json ( s ,_STOPSIZE , S(_size ) + "%" )
s := json ( s ,_STOPTRIGGER , S(_trig ) )
s := json ( s ,_STOPPRICE , S(_exec ) )
brace(s)
// ========================================================
o__:=' ┌┬┐┌─┐┌─┐ ┌─┐┬ ┬┌┬┐┌┐ ┌─┐┬ '
o__:=' │││├─┤├─┘ └─┐└┬┘│││├┴┐│ ││ '
o__:=' ┴ ┴┴ ┴┴ └─┘ ┴ ┴ ┴└─┘└─┘┴─┘ '
// @function Map a Symbol from Tradingview to your Frostybot (REQUIRED ONCE EVER / SYMBOL)
// No automatic way of this yet (to keep function available for MULTI TICKER scripts.)
// @param _coin (string) the left side of a pair " > ______ < / ..... " ( BTCUSDT => BTC)
// @param _base (string) the right side of a pair " ...... / > ______ < " ( BTCUSDT => USDT)
// @param ticker (string) the built in tickerid for the coin (syminfo.tickerid / input.symbol)
export map (string _coin,
string _base ,
string ticker ) =>
_prefix = syminfo.prefix(ticker)
_ticker = syminfo.ticker(ticker)
s = ''
s := json ( s ,'symbolmap' , 'add' )
s := json ( s , 'exchange' , S(str.upper(_prefix)) )
s := json ( s , 'symbol' , S(str.upper(_prefix+':'+_ticker)))
s := json ( s , 'mapping' , S(_coin +'/'+_base) )
// ========================================================
o__:=' ┌┬┐┌─┐┌─┐┌┬┐ '
o__:=' │ ├┤ └─┐ │ '
o__:=' ┴ └─┘└─┘ ┴ '
// for testing your scripts (default signals are all safe, NO TRANSACTIONS MADE)
// @param _testchoice (int) Alert to test
// @param _ticker (string) Ticker input
// @param _stub (string) Stub input
// @param _checkalert (bool) Send alerts (3 / minute if activer)
// @param _label (bool) Show Alerts on Label
// @returs void
export test(int _testchoice, string _ticker , string _stub ="stup" , bool _checkalert = true, bool _label = true) =>
var label lb = na
label.delete(lb[1])
varip init = true
if second % 20 == 0
init := true
if barstate.islast
string _jleverage = leverage (_stub,_ticker, 5, "cross" )
string _jbuy = buy (_stub,_ticker, 0, "percent" ,"percent", 0.01, 500 )
string _jsell = sell (_stub,_ticker, 0, "percent" ,"percent", 0.01, 500 )
string _jlong = long (_stub,_ticker, 0 )
string _jshort = short (_stub,_ticker, 0 , .1, .3, 10, 500, false )
string _jclosel = closelong (_stub,_ticker, 0 , "percent", 10 )
string _jcloses = closeshort (_stub,_ticker, 0 , "percent", 5 )
string _jstoploss = stoploss (_stub,_ticker, 50 , close[10] , close )
string _jtakeprofit = takeprofit (_stub,_ticker, 50 , close[10] , close )
string _jtraillong = traillong (_stub,_ticker, 5 )
string _jtrailshort = trailshort (_stub,_ticker, 5 )
string _jcancelall = cancelall (_stub,_ticker )
[_alrt,_alrtlbl] = switch _testchoice
1 => [_jleverage , 'leverage' ]
2 => [_jbuy , 'buy' ]
3 => [_jsell , 'sell' ]
4 => [_jlong , 'long' ]
5 => [_jshort , 'short' ]
6 => [_jclosel , 'closel' ]
7 => [_jcloses , 'closes' ]
8 => [_jstoploss , 'stoploss' ]
9 => [_jtakeprofit , 'takeprofit' ]
10 => [_jtraillong , 'traillong' ]
11 => [_jtrailshort , 'trailshort' ]
12 => [_jcancelall , 'cancelall' ]
if _checkalert and init
alert(_alrt ,alert.freq_once_per_bar)
init := false
if _label
lb:= label.new(last_bar_index, close, '⛄ ' + _alrtlbl + '\n\n' + _alrt ,textalign=text.align_left,color=color.white,size=size.normal)
// ===================================================
// testing strings with label.
_chkalrt = input.bool ( true , " Test Webhook W/alert", inline="bools",group="test")
_label = input.bool ( true , " Test Label ", inline="bools",group="test")
_testchoice = input.int ( 1 , " Test Alert #" ,1,12, inline="str ",group="test")
_stub = input.string("StubToTest", " Stub " , inline="str ",group="test")
_tiicker = input.symbol('BTCUSDTPERP')
test(_testchoice, _tiicker, _stub,_chkalrt,_label)
//////////////////////////////////
|
Fibonacci | https://www.tradingview.com/script/QfwEZHhJ-Fibonacci/ | reees | https://www.tradingview.com/u/reees/ | 115 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
// @description General Fibonacci functions. Get fib numbers, ratios, etc.
library("Fibonacci",overlay=true)
import reees/Utilities/2 as u
//--------------------------------------------------------------
// Private
//--------------------------------------------------------------
n50to55() =>
[12586269025,20365011074,32951280099,53316291173,86267571272,139583862445]
//--------------------------------------------------------------
// Public
//--------------------------------------------------------------
// @function Get the precise Fibonacci ratio, to the specified number of decimal places
// @param f Fibonacci ratio (string, in form #.###)
// @param precision Number of decimal places (optional int, dft = 16, max = 32)
// @returns Precise Fibonacci ratio (float)
// * Deprecated (use fib_precise() instead), but keeping it here for science / experimenting with derivations
export fib_derived(float f, simple int precision=16) =>
[n0,n1,n2,n3,n4,n5] = n50to55()
v = switch f
1.618 => n5/n4
2.618 => n5/n3
4.236 => n5/n2
0.618 => n4/n5
0.382 => n3/n5
0.236 => n2/n5
0.146 => n1/n5
0.786 => math.sqrt(n4/n5)
0.886 => math.sqrt(math.sqrt(n4/n5))
1.272 => math.sqrt(n5/n4)
1.414 => math.sqrt(2)
=> na
math.round(v,precision)
// @function Get the precise Fibonacci ratio, to the specified number of decimal places
// @param f Fibonacci ratio (string, in form #.###)
// @param precision Number of decimal places (optional int, dft = 16, max = 16)
// @returns Precise Fibonacci ratio (float)
export fib_precise(float f, simple int precision=16) =>
v = switch f
1.618 => 1.6180339887498948
2.618 => 2.6180339887498948
4.236 => 4.2360679774997896
0.618 => 0.6180339887498948
0.382 => 0.3819660112501052
0.236 => 0.2360679774997897
0.146 => 0.1458980337503155
0.786 => 0.7861513777574233
0.886 => 0.8866517793121622
1.272 => 1.2720196495140689
1.414 => 1.4142135623730950
=> na
math.round(v,precision)
// @function Get fib ratio value from string
// @param r Fib ratio string (e.g. ".618")
// @returns Fibonacci ratio value (float)
export fib_from_string(string r) =>
switch r
".382" => fib_precise(0.382)
".5" => .5
".618" => fib_precise(0.618)
".786" => fib_precise(0.786)
".886" => fib_precise(0.886)
"1.272" => fib_precise(1.272)
"1.414" => fib_precise(1.414)
"1.618" => fib_precise(1.618)
"2.618" => fib_precise(2.618)
//u.print(str.tostring(na(fib_from_string(".618"))))
// @function Calculate the Nth number in the Fibonacci sequence
// @param n Index/number in sequence (int)
// @returns Fibonacci number (int)
export fib_n(int n) =>
phi = fib_precise(1.618)
math.round((math.pow(phi,n) - math.pow(1-phi,n))/math.sqrt(5))
// test=fib_precise(1.618,32)
// u.print(str.tostring(test,"#.################################"))
|
TR_Base_Lib | https://www.tradingview.com/script/j8S0S0Lv/ | Tommy_Rich | https://www.tradingview.com/u/Tommy_Rich/ | 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/
// © Tommy_Rich
//@version=5
// @description TODO: add library description here
library(title ="TR_Base_Lib",overlay =true)
////// //
//// global function group //// **********グローバル関数群**********
// //////
export SetHighLowArray(
float[] _a_PHiLo, int[] _a_IHiLo,
int[] _a_FHiLo, float[] _a_DHiLo,
float _Price, int _Index,
int _Flag, float _Difference,
float[] _a_Price, int[] _a_Index) =>
if _Price >0
// 配列の先頭から最も古いレベルを削除します
array.shift(_a_PHiLo)
array.shift(_a_IHiLo)
array.shift(_a_FHiLo)
array.shift(_a_DHiLo)
// 配列の最後に新しいレベルを追加します
array.push(_a_PHiLo, _Price)
array.push(_a_IHiLo, _Index)
array.push(_a_FHiLo, _Flag)
array.push(_a_DHiLo, _Difference)
// High値のみの配列、Low値のみの配列の更新
array.shift(_a_Price)
array.shift(_a_Index)
array.push (_a_Price, _Price)
array.push (_a_Index, _Index)
[_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _a_Price, _a_Index]
export SetHighLowArray(
float[] _a_PHiLo, int[] _a_IHiLo,
float _Price, int _Index) =>
// 配列の先頭から最も古いレベルを削除します
array.shift(_a_PHiLo)
array.shift(_a_IHiLo)
// 配列の最後に新しいレベルを追加します
array.push(_a_PHiLo, _Price)
array.push(_a_IHiLo, _Index)
[_a_PHiLo, _a_IHiLo]
export SetHighLowArray(
float[] _a_PHiLo, int[] _a_IHiLo, int[] _a_Flg,
float _Price, int _Index, int _Flg) =>
// 配列の先頭から最も古いレベルを削除します
array.shift(_a_PHiLo)
array.shift(_a_IHiLo)
array.shift(_a_Flg)
// 配列の最後に新しいレベルを追加します
array.push(_a_PHiLo, _Price)
array.push(_a_IHiLo, _Index)
array.push(_a_Flg, _Flg)
[_a_PHiLo, _a_IHiLo, _a_Flg]
export ChangeHighLowArray(
float[] _a_PHiLo, int[] _a_IHiLo,
float[] _a_DHiLo, float _Price,
int _Index, float _Difference,
float[] _a_Price, int[] _a_Index) =>
int i_1 =array.size(_a_PHiLo) -1
array.set(_a_PHiLo, i_1, _Price)
array.set(_a_IHiLo, i_1, _Index)
array.set(_a_DHiLo, i_1, _Difference)
int i_2 =array.size(_a_Price) -1
array.set(_a_Price, i_2, _Price)
array.set(_a_Index, i_2, _Index)
[_a_PHiLo, _a_IHiLo, _a_DHiLo, _a_Price, _a_Index]
export ChangeHighLowArray(
float[] _a_PHiLo, int[] _a_IHiLo,
float _Price, int _Index) =>
int i_1 =array.size(_a_PHiLo) -1
array.set(_a_PHiLo, i_1, _Price)
int i_2 =array.size(_a_IHiLo) -1
array.set(_a_IHiLo, i_2, _Index)
[_a_PHiLo, _a_IHiLo]
// @function TODO: Function to display labels
// @param _Text TODO: text (series string) Label text.
// @param _X TODO: x (series int) Bar index.
// @param _Y TODO: y (series int/float) Price of the label position.
// @param _Style TODO: style (series string) Label style.
// @param _Size TODO: size (series string) Label size.
// @param _Yloc TODO: yloc (series string) Possible values are yloc.price, yloc.abovebar, yloc.belowbar.
// @param _Color TODO: color (series color) Label border and arrow color
// @returns TODO: No return values
export ShowLabel(
string _Text,
int _X, float _Y,
string _Style, string _Size,
string _Yloc, color _Color) =>
var label lbl1 = na
lbl1 := label.new(x =_X, y =_Y, text =_Text, yloc =_Yloc, style =_Style, size =_Size, textcolor =_Color, textalign =text.align_center)
// @function TODO: Function to display labels
// @param _Text TODO: text (series string) Label text.
// @param _Tooltip TODO: text (series string) Tooltip text.
// @param _X TODO: x (series int) Bar index.
// @param _Y TODO: y (series int/float) Price of the label position.
// @param _Style TODO: style (series string) Label style.
// @param _Size TODO: size (series string) Label size.
// @param _Yloc TODO: yloc (series string) Possible values are yloc.price, yloc.abovebar, yloc.belowbar.
// @param _Color TODO: color (series color) Label border and arrow color
// @param _TextColor TODO: color (series color) Label text color
// @returns TODO: No return values
export ShowLabel(
string _Text, string _Tooltip,
int _X, float _Y,
string _Style, string _Size,
string _Yloc,
color _Color, color _TextColor) =>
var label lbl1 = na
lbl1 := label.new(x =_X, y =_Y, text =_Text, yloc =_Yloc, style =_Style, size =_Size,color =_Color, textcolor =_TextColor, tooltip =_Tooltip, textalign =text.align_center)
// @function TODO: Function to take out 12 colors in order
// @param _Index TODO: color number.
// @returns TODO: color code
export GetColor(
int _Index) =>
int _count =_Index % 12
color ret =switch _count
0 =>#ffbf7f
1 =>#bf7fff
2 =>#7fffbf
3 =>#ff7f7f
4 =>#7f7fff
5 =>#7fff7f
6 =>#ff7fbf
7 =>#7fbfff
8 =>#bfff7f
9 =>#ff7fff
10 =>#7fffff
11 =>#ffff7f
// @function TODO: Table display position function
// @param _Pos TODO: position.
// @returns TODO: Table position
export Tbl_position(
string _Pos) =>
string _result =switch _Pos
"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
_result
// @function TODO: テーブル表示位置 日本語表示位置を定数に変換
// @param _Pos TODO: 日本語表示位置
// @returns TODO: _result:表示位置の定数を返す
export Tbl_position_JP(
string _Pos) =>
string _result =switch _Pos
"左上" => position.top_left
"真上" => position.top_center
"右上" => position.top_right
"左中" => position.middle_left
"真中" => position.middle_center
"右中" => position.middle_right
"左下" => position.bottom_left
"真下" => position.bottom_center
"右下" => position.bottom_right
_result
// @function TODO: 足変換、TimeFrameを分に変換
// @param _Tf TODO: TimeFrame文字
// @returns TODO: _result:TimeFrameを分に変換した値、_chartTf:チャートのTimeFrameを分に変換した値
export TfInMinutes(
simple string _Tf ="") =>
float _chartTf =
timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
float _result =0.
if _Tf == ''
_result :=_chartTf
else if _Tf == "1D"
_result :=60. * 24
else if _Tf == "1W"
_result :=60. * 24 * 7
else if _Tf == "1M"
_result :=60. * 24 * 365 / 12
else
_result :=str.tonumber(_Tf)
[_result, _chartTf]
// @function TODO: TimeFrameを日本語足名に変換して返す関数 引数がブランクの時はチャートの日本語足名を返す
// @param _tf TODO: TimeFrame文字
// @returns TODO: _result:日本語足名
export TfName_JP(
simple string _Tf = "") =>
string _result =""
if _Tf == ""
int _count =timeframe.multiplier
string _ashi =(
timeframe.isseconds ? "秒" :
timeframe.isminutes ? (_count % 60 != 0) ? "分" : "時間" :
timeframe.isdaily ? "日" :
timeframe.isweekly ? "週" :
timeframe.ismonthly ? "月" : "")
int _cal = _ashi == "時間" ? _count / 60 : _count
_result :=str.tostring(_cal) + _ashi
else
string _ashi =
_Tf == "5" ? "5分" :
_Tf == "15" ? "15分" :
_Tf == "60" ? "1時間" :
_Tf == "240" ? "4時間" :
_Tf == "1D" ? "1日" :
_Tf == "1" ? "1分" :
_Tf == "30" ? "30分" :
_Tf == "45" ? "45分" :
_Tf == "120" ? "2時間" :
_Tf == "180" ? "3時間" :
_Tf == "1W" ? "1週" :
_Tf == "1M" ? "1月" : ""
_result :=_ashi
// @function TODO: Delete Line
// @param TODO: No parameter
// @returns TODO: No return value
export DeleteLine() =>
for currentElement in line.all
line.delete(currentElement)
// @function TODO: Delete Label
// @param TODO: No parameter
// @returns TODO: No return value
export DeleteLabel() =>
for currentElement in label.all
label.delete(currentElement)
|
PEAKTROUGHLIB268 | https://www.tradingview.com/script/u4Gukstr-PEAKTROUGHLIB268/ | agungkuswanto | https://www.tradingview.com/u/agungkuswanto/ | 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/
// © agungkuswanto
//@version=5
library(title = "PEAKTROUGHLIB268", overlay=true)
h4daysago = high[4]
h3daysago = high[3]
h2daysago = high[2]
h1daysago = high[1]
thePeakCond = h4daysago <= h3daysago and h3daysago >= h2daysago and h3daysago >= h1daysago and h3daysago > high
thePeak = ta.valuewhen(thePeakCond, h3daysago, 0)
l4daysago = low[4]
l3daysago = low[3]
l2daysago = low[2]
l1daysago = low[1]
theTroughCond = l4daysago >= l3daysago and l3daysago <= l2daysago and l2daysago <= l1daysago and l3daysago <= low
theTrough = ta.valuewhen(theTroughCond, l3daysago, 0)
plot (thePeak, title="PEAK", color=color.lime, linewidth=1 )
plot (theTrough, title="TROUGH", color=color.orange, linewidth=1 )
export showThePeak() =>
ta.valuewhen(thePeakCond, h3daysago, 0)
export showTheTrough() =>
ta.valuewhen(theTroughCond, l3daysago, 0)
|
AllTimeHighLow | https://www.tradingview.com/script/xZj2wmdS-AllTimeHighLow/ | mehmegunes | https://www.tradingview.com/u/mehmegunes/ | 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/
// © mehmegunes
//@version=5
// @description Provides functions calculating the all-time high/low of values.
library("AllTimeHighLow", true)
// @function Calculates the all-time high of a series.
// @param val Series to use (`high` is used if no argument is supplied).
// @returns The all-time high for the series.
export hi(float val = high) =>
var float ath = val
ath := math.max(ath, val)
// @function Calculates the all-time low of a series.
// @param val Series to use (`low` is used if no argument is supplied).
// @returns The all-time low for the series.
export lo(float val = low) =>
var float atl = val
atl := math.min(atl, val)
plot(hi(),"high")
plot(lo(), "low")
|
myAutoviewAlerts | https://www.tradingview.com/script/vYZ5U3Zw-myAutoviewAlerts/ | incryptowetrust100k | https://www.tradingview.com/u/incryptowetrust100k/ | 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/
// © incryptowetrust100k
//@version=5
// @description My Alerts Functions - To use with autoview
// @returns - These functions returns a string to use in alerts to send commands to autoview. You can open an order, place a stop or take order, close an opened order or a opened position, or open a hedge position.
library("myAutoviewAlerts")
// @param a = String - Account Identification
// @param e = String - Exchange
// @param s = String - Symbol
// @param b = String - Book Side
// @param q = Float - Quantity
// @param fp = Float - Fixed Price
// @param delay = Integer - In Seconds
// @param i = Integer - Account Index (to multiple accounts allerts)
// @param base = String - Base Currency (bitmex) - "Tether" or "Bitcoin"
// @param fsl = Float - Stop Loss Limit Price
// @param c = String - Close -> "order" or "position"
// @param ro = Bool - Reduce Only
// @param sl = Bool - Stop Loss -> bitfinex
// @param t = String - Type -> "market" or "limit"
// @function f_order => Open Orders
// @function f_stop => Set Stop Loss Order
// @function f_take => Set Take Order
// @function f_closeOrder => Close Open Orders
// @function f_closePosition => Close Open Positions
// @function f_hedge => To Open a Hedge Position (short 100% of balance)
export f_order(string a, string e, string s, string b, float q, float fp, int delay, int i, string base) =>
_q = switch base
'TETHER' => q * fp / 100
'FIAT' => math.round(math.round(q * close) / 100) * 100
'ASSET' => q
_u = base == "TETHER" ? " u=currency" : ""
_delay = i == 0 ? " delay=" + str.tostring(delay) + " " : " "
_msg = " a=" + a + " e=" + e + " s=" + s + _delay + " b=" + b + " q=" + str.tostring(_q) + _u + " fp=" + str.tostring(fp) + " | "
_msg
export f_start(string a, string e, string s, string b, float q, float fp, float fsl, int delay, int i, string base) =>
_q = switch base
'TETHER' => q * fp / 100
'FIAT' => math.round(math.round(q * close) / 100) * 100
'ASSET' => q
_u = base == "TETHER" ? " u=currency" : ""
_delay = i == 0 ? " delay=" + str.tostring(delay) + " " : " "
_msg = e != "BITFINEX" ?
" a=" + a + " e=" + e + " s=" + s + _delay + " b=" + b + " q=" + str.tostring(_q) + _u + " fsl=" + str.tostring(fsl) + " fp=" + str.tostring(fp) + " | "
:
" a=" + a + " e=" + e + " s=" + s + _delay + " b=" + b + " q=" + str.tostring(_q) + _u + " sl=1" + " fp=" + str.tostring(fp) + " | "
_msg
export f_stop(string a, string e, string s, float q, float fp, float fsl, int delay, int i, string base) =>
_q = switch base
'TETHER' => q * fp / 100
'FIAT' => math.round(math.round(q * close) / 100) * 100
'ASSET' => q
_u = base == "TETHER" ? " u=currency" : ""
_delay = i == 0 ? " delay=" + str.tostring(delay) + " " : " "
_msg = e != "BITFINEX" ?
" a=" + a + " e=" + e + " s=" + s + _delay + " q=" + str.tostring(_q) + _u + " c=position fsl=" + str.tostring(fsl) + " fp=" + str.tostring(fp) + " ro=1 | "
:
" a=" + a + " e=" + e + " s=" + s + _delay + " q=" + str.tostring(_q) + _u + " c=position sl=1" + " fp=" + str.tostring(fsl) + " ro=1 | "
_msg
export f_take(string a, string e, string s, float q, float fp, int delay, int i, string base) =>
_q = switch base
'TETHER' => q * fp / 100
'FIAT' => math.round(math.round(q * close) / 100) * 100
'ASSET' => q
_u = base == "TETHER" ? " u=currency" : ""
_delay = i == 0 ? " delay=" + str.tostring(delay) + " " : " "
_msg = " a=" + a + " e=" + e + " s=" + s + _delay + " q=" + str.tostring(_q) + _u + " c=position fp=" + str.tostring(fp) + " ro=1 | "
_msg
export f_closeOrder(string a, string e, string s, int delay, int i) =>
_delay = i == 0 ? " delay=" + str.tostring(delay) + " " : " "
_msg = " a=" + a + " e=" + e + " s=" + s + _delay + " c=order | "
_msg
export f_closePosition(string a, string e, string s, int delay, int i) =>
_delay = i == 0 ? " delay=" + str.tostring(delay) + " " : " "
_msg = " a=" + a + " e=" + e + " s=" + s + _delay + " c=position t=market ro=1 | "
_msg
export f_hedge(string a, string e, string s, int delay, int i) =>
_delay = i == 0 ? " delay=" + str.tostring(delay) + " " : " "
_msg = " a=" + a + " e=" + e + " s=" + s + _delay + " b=short q=100% t=limit | "
_msg
|
L_Beta | https://www.tradingview.com/script/rOwfkhJU-L-Beta/ | fourkhansolo | https://www.tradingview.com/u/fourkhansolo/ | 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/
// © fourkhansolo
//@version=5
// @description TODO: add library description here
library("L_Beta")//, overlay=true)
// **************************************** Importing Modules ****************************************
import fourkhansolo/L_Index_4khansolo/2 as index
// **************************************** Beta Score More Systematic ****************************************
//x = close
//y = close
//std_of_x = ta.stdev(x, length)
//std_of_y = ta.stdev(y, length)
//correlation_of_x_and_y=ta.correlation(x,y,length)
//beta = (std_of_x*std_of_y)/correlation_of_x_and_y
//plot(beta)
// **************************************** Beta Score More Systematic ****************************************
export beta_length(string resolution,int multiplier)=>
// Use this instead for simplicity sake
//beta_length = beta_length(period,multiplier); monthly set for period and multipier set to Monthly
// This works as per year
conversion = if resolution == "D"
251//365//252 days in a year (open days)
else if resolution == "W"
52 // 52 weeks in a year
else if resolution == "M"
12 //12 months in a year
else if resolution == "3M"
4 // 3Months (4x) in a year
else if resolution == "12M"
1 // 1 year
beta_length = conversion * multiplier
// TO invole
// anualized_period = length(intervals,multiplier)
// **************************************** Beta Score More Systematic ****************************************
export beta_less_intuitive(series float price_x, series float price_y, series int length)=>
// Beta implies slope {rise over run}
// Berk, J. B., T., H. J. V., DeMarzo, P. M., Stangeland, D., & Marosi András. (2020). Fundamentals of Corporate Finance. Pearson.
// (Berk et al., p. 406)
// Beta. Wikipedia. Accessed on Aug 27, 2022. https://en.wikipedia.org/wiki/Beta_(finance)
mean_x = ta.sma(price_x, length) // Intended for stock_returns
mean_y = ta.sma(price_y, length) // Intended for index_returns
//closer1=x+y*length
mean_xy = 0.0
mean_xx = 0.0
mean_yy = 0.0
for i=0 to length -1
mean_xy := mean_xy+price_x[i]*price_y[i]
mean_xy := mean_xy/length
covariance_xy = mean_xy - (mean_x*mean_y)
//[mean_x,mean_y,mean_xy, covariance_xy]
// Variance for X and Y
for j=0 to length -1
mean_xx := mean_xx+price_x[j]*price_x[j]
mean_yy := mean_yy+price_y[j]*price_y[j]
mean_xx:=mean_xx/length
mean_yy:=mean_yy/length
//[mean_xx,mean_yy,mean_xy,covariance_xy]
// variances for X and y
variance_for_x=mean_xx-(mean_x*mean_x)
variance_for_y=mean_yy-(mean_y*mean_y)
//[variance_for_x,variance_for_y,mean_xy,covariance_xy]
// correlation score
correlation=covariance_xy/math.sqrt(variance_for_x*variance_for_y)
betaScore=covariance_xy/variance_for_y
[variance_for_x,variance_for_y,mean_xy,correlation,betaScore]
export beta(series float stock_returns, series float index_returns,int length)=>
// To Replicate the beta values from other sources (like Yahoo Finace)...
// ... The Parameter from the top must be selected to "M", and "M" on the indicator then 5 Years on the indicator
// Berk, J. B., T., H. J. V., DeMarzo, P. M., Stangeland, D., & Marosi András. (2020). Fundamentals of Corporate Finance. Pearson.
// (Berk et al., p. 406)
correlation = ta.correlation(stock_returns, index_returns, length)
return_index_std = ta.stdev(index_returns, length)
return_stock_std = ta.stdev(stock_returns, length)
beta_returns = return_stock_std* correlation/return_index_std
// **************************************** Auto select if selected ****************************************
export index_auto_select(simple string index_select)=>
index_selected = if index_select == "Auto"
index.indexName()//indexName=
else
index_select
// **************************************** Auto select TIMEFRAME ****************************************
export timeframe_auto_select(simple string intervals)=>
// interval = input.session("Auto", "Day | Week | Month | Quarter | Year", options=["Auto","D", "W", "M","3M","12M"])
result = if intervals == "Auto"
timeframe.period
else
intervals
// To invoke the function
// intervals = timeframe_auto_select(interval)
// **************************************** Time-frame based checker ****************************************
export return_checker (string test)=>
// Source:
// Comparing timeframes. Trading View. Accessed on Aug 29, 2022. https://www.tradingview.com/pine-script-docs/en/v5/concepts/Timeframes.html#timeframe-string-specifications
// This function prevents the codes in the comments below
// you can also highlight by the way
// oneYearInterval = timeframe.change("12M") // goes back 1year
// oneQuarterInterval = timeframe.change("3M") // goes back 3 Months
// oneMonthInterval = timeframe.change("1M") // goes back 1Month
// oneWeekInterval = timeframe.change("1W") // goes back 1Month
// oneDayInterval = timeframe.change("1D") // goes back 1Month
result = if test == "12M"
oneYearInterval = timeframe.change("12M") // goes back 1year
else if test == "3M"
oneQuarterInterval = timeframe.change("3M") // goes back 3 Months
else if test == "M"
oneMonthInterval = timeframe.change("1M") // goes back 1Month
else if test == "W"
oneWeekInterval = timeframe.change("1W") // goes back 1Month
else if test == "D"
oneDayInterval = timeframe.change("1D") // goes back 1Month
output = result
// **************************************** Returns Calculation ****************************************
export returns(series float stock_price, series float index_price)=>
// Pre-requisites
// 1) Index Price (request.security(index_name, period, close, lookahead=barmerge.lookahead_on))
// 2) Stock Price (request.security(stock_name, period, close, lookahead=barmerge.lookahead_on))
// This function will handout two variables with prices attached to them
// The return values are calculated below
stock_returns = (stock_price-stock_price[1])/stock_price[1] // ((Today Price)-(Yesterday Price))/-(Yesterday Price)
index_returns = (index_price-index_price[1])/index_price[1] // ((Today Price)-(Yesterday Price))/-(Yesterday Price)
stock_returns_percentage = stock_returns * 100 // Converting to Percentages
index_returns_percentage = index_returns * 100 // Converting to Percentages
[stock_returns, index_returns, stock_returns_percentage, index_returns_percentage]
// the following to invoke
// [stock_returns,index_returns]=returns(stock_price,index_price)
// **************************************** Real Work ****************************************
interval = input.session("Auto", "Intervals: Day Week Month", options=["Auto","D", "W", "M","3M","12M"])
intervals = timeframe_auto_select(interval)
multiplier = input.int(5, title="Year Multiplier (For how Long?)", options=[1,2,3,4,5,10,15,20])
length = beta_length(intervals,multiplier)
stock_name = syminfo.tickerid
simple_stock_close = request.security(stock_name,"D",close)
current_stock_price=request.security(stock_name,intervals,simple_stock_close)
index_select = input.session("Auto", "Pick Your Index", options=["Auto","TSX", "SPX", "IXIC","W4500","Gold","Silver"])
index_name = index_auto_select(index_select)
simple_index_close = request.security(index_name,intervals,close, currency=syminfo.currency)
current_index_price = request.security(index_name,intervals,simple_index_close, currency=syminfo.currency)
//plot(current_index_price)//
// **************************************** Frequency Check ****************************************
frequency_checker = return_checker(intervals)
bgcolor(frequency_checker ? color.new(color.blue,70) : na)
// **************************************** Real Work ****************************************
[stock_returns, index_returns, stock_returns_percentage, index_returns_percentage]=returns(current_stock_price,current_index_price)
x = stock_returns_percentage
y = index_returns_percentage
correlations = ta.correlation(x,y,length)
[variance_for_x,variance_for_y,mean_xy,correlation,betaScore]=beta_less_intuitive(x,y,length)
plot(betaScore,color=color.teal)
beta = ta.stdev(x,length)*correlations/ta.stdev(y,length)
plot(beta, "Manually Derived Beta", color=color.red)
beta_beta=beta(stock_returns,index_returns,length)
plot(beta_beta,"Formula_Based_Function", color=color.yellow)
// The scores are the same compared to yahoo finance or investing.com. With "M" selected for parameter, and 5Y period.
// AAPL. Yahoo Finance. Accessed as of Aug 31, 2022. https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch
// AAPL. Investing.com. Accessed as of Aug 31, 2022. https://ca.investing.com/equities/apple-computer-inc
export positron(series float number)=>
// This will basically change color based on positivity :)
// This is also available under the index library
if number >= 0
color.new(color.green,1)
else
color.new(color.red,1)
// **************************************** Table ****************************************
tableNotification = table.new(position = position.middle_right, rows = 6, columns = 2, bgcolor = color.new(color.yellow,70), border_width=0)
table.cell(tableNotification, row = 0, column = 0, text = "Legend", text_color = color.yellow)
table.cell(tableNotification, row = 0, column = 1, text = "", text_color = color.yellow)
table.cell_set_tooltip(tableNotification, row = 0, column = 0, tooltip = "Legend")
//Source: https://www.tradingview.com/pine-script-reference/v5/#fun_str{dot}tonumber
// Beta
beta_string =str.tostring(math.round(beta_beta,2))
table.cell(tableNotification, row = 1, column = 0, text = "Beta", text_color = color.white, bgcolor=color.new(color.black,50))
table.cell(tableNotification, row = 1, column = 1, text = beta_string, text_color = color.white, bgcolor=color.new(color.black,50)) // Adding the datum into the table
// Correlations
correlations_string =str.tostring(math.round(correlations,2))
table.cell(tableNotification, row = 2, column = 0, text = "Correlations", text_color = color.white)
table.cell(tableNotification, row = 2, column = 1, text = correlations_string, text_color = color.white) // Adding the datum into the table
// Correlations
year_string =str.tostring(math.round(multiplier,2))
table.cell(tableNotification, row = 3, column = 0, text = "For This Year Long (Y) ", text_color = color.white, bgcolor=color.new(color.black,50))
table.cell(tableNotification, row = 3, column = 1, text = year_string, text_color = color.white, bgcolor=color.new(color.black,50)) // Adding the datum into the table
// Length
length_string =str.tostring(math.round(length,2))
table.cell(tableNotification, row = 4, column = 0, text = "Frequency: " +intervals, text_color = color.white)
table.cell(tableNotification, row = 4, column = 1, text = length_string, text_color = color.white) // Adding the datum into the table
table.cell_set_tooltip(tableNotification, row = 4, column = 0, tooltip = "Day = 251, W = 52, M = 12, 12M, = 1Year")
table.cell_set_tooltip(tableNotification, row = 4, column = 1, tooltip = "Day = 251, W = 52, M = 12, 12M, = 1Year")
// Index
index_string =str.tostring(math.round(current_index_price,2))
table.cell(tableNotification, row = 5, column = 0, text = index_name +" , "+ syminfo.currency, text_color = color.white, bgcolor=color.new(color.black,50))
table.cell(tableNotification, row = 5, column = 1, text = index_string, text_color = color.white, bgcolor=color.new(color.black,50)) // Adding the datum into the table
|
Library: Array | https://www.tradingview.com/script/B4sp6K4x-Library-Array/ | tuele99 | https://www.tradingview.com/u/tuele99/ | 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/
// © tuele99
//@version=5
// @description Additional functions for array.
library(title="xarray", overlay=true)
// n_args = 1
// @function Remove duplicates in arrays.
// @param array_in (int[]/float[]/string[]) Array contains duplicates.
export remove_duplicates(int[] array_in_out) =>
array_out = array_in_out
int i = 0
int j = na
while i < array.size(array_out)
while true
j := array.lastindexof(array_out, array.get(array_out, i))
if j > i
array.remove(array_out, j)
else
break
i += 1
export remove_duplicates(float[] array_in_out) =>
array_out = array_in_out
int i = 0
int j = na
while i < array.size(array_out)
while true
j := array.lastindexof(array_out, array.get(array_out, i))
if j > i
array.remove(array_out, j)
else
break
i += 1
export remove_duplicates(string[] array_in_out) =>
array_out = array_in_out
int i = 0
int j = na
while i < array.size(array_out)
while true
j := array.lastindexof(array_out, array.get(array_out, i))
if j > i
array.remove(array_out, j)
else
break
i += 1
export remove_duplicates(bool[] array_in_out) =>
array_out = array_in_out
int i = 0
int j = na
while i < array.size(array_out)
while true
j := array.lastindexof(array_out, array.get(array_out, i))
if j > i
array.remove(array_out, j)
else
break
i += 1
// n_args = 2
// @param array_in_out_1 (int[]/float[]/string[]) Array contains duplicates.
// @param array_in_out_2 (int[]/float[]/string[]) Array contains duplicates.
export remove_duplicates(int[] array_in_out_1, float[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
export remove_duplicates(float[] array_in_out_1, int[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
//
export remove_duplicates(int[] array_in_out_1, string[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
export remove_duplicates(string[] array_in_out_1, int[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
//
export remove_duplicates(float[] array_in_out_1, string[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
export remove_duplicates(string[] array_in_out_1, float[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
//
export remove_duplicates(int[] array_in_out_1, int[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
export remove_duplicates(float[] array_in_out_1, float[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
export remove_duplicates(string[] array_in_out_1, string[] array_in_out_2) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
else
j += 1
i += 1
// n_args = 3
export remove_duplicates(int[] array_in_out_1, float[] array_in_out_2, bool[] array_in_out_3) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
array_out_3 = array_in_out_3
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i) and array.get(array_out_3, j) == array.get(array_out_3, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
array.remove(array_out_3, j)
else
j += 1
i += 1
export remove_duplicates(float[] array_in_out_1, int[] array_in_out_2, bool[] array_in_out_3) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
array_out_3 = array_in_out_3
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i) and array.get(array_out_3, j) == array.get(array_out_3, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
array.remove(array_out_3, j)
else
j += 1
i += 1
export remove_duplicates(int[] array_in_out_1, float[] array_in_out_2, string[] array_in_out_3) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
array_out_3 = array_in_out_3
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i) and array.get(array_out_3, j) == array.get(array_out_3, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
array.remove(array_out_3, j)
else
j += 1
i += 1
export remove_duplicates(float[] array_in_out_1, int[] array_in_out_2, string[] array_in_out_3) =>
array_out_1 = array_in_out_1
array_out_2 = array_in_out_2
array_out_3 = array_in_out_3
int i = 0
while i < array.size(array_out_1)
int j = i + 1
while j < array.size(array_out_1)
if array.get(array_out_1, j) == array.get(array_out_1, i) and array.get(array_out_2, j) == array.get(array_out_2, i) and array.get(array_out_3, j) == array.get(array_out_3, i)
array.remove(array_out_1, j)
array.remove(array_out_2, j)
array.remove(array_out_3, j)
else
j += 1
i += 1
|
Demand Index | https://www.tradingview.com/script/phVPMpjQ-Demand-Index/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 20 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © melihtuna
//@version=5
library("DemandIndex")
export di(int period = 10, int priceRange = 2, int smooth = 10) =>
p = (close - open) / open
di = 0.0
va = 0.0
bp = 1.0
sp = 1.0
h = ta.highest(high, priceRange)
l = ta.lowest(low, priceRange)
va := h - l
va := ta.sma(va, period)
if va == 0
va := 1
va
k = 3 * close / va
p *= k
if close > open
bp := volume
sp := volume / p
sp
else
bp := volume / p
sp := volume
sp
if math.abs(bp) > math.abs(sp)
di := sp / bp
di
else
di := bp / sp
di
di := ta.ema(di, smooth)
plot(di(), color=color.new(color.navy, 0))
plot(0, color=color.new(color.purple, 60))
|
Chaikin Money Flow - Library | https://www.tradingview.com/script/Jidt0Ejm-Chaikin-Money-Flow-Library/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 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/
// © melihtuna
//@version=5
library("ChaikinMoneyFlow")
export cmf(int length = 20, bool showma = true, int smalen = 5) =>
clv = high == low ? 0 : (close - low - (high - close)) / (high - low)
mfv = clv * volume
//adLine = cum(mfv) --Chaikin's Accum/Distrib Line
cmfLine = math.sum(mfv, length) / math.sum(volume, length)
sma_1 = ta.sma(cmfLine, smalen)
smaLine = showma ? sma_1 : na
hiValue = math.max(cmfLine, 0)
loValue = math.min(cmfLine, 0)
[cmfLine, smaLine, hiValue, loValue]
[calc_cmfLine, calc_smaLine, calc_hiValue, calc_loValue] = cmf()
cmfPlot = plot(calc_cmfLine, title='CMF', color=color.new(color.green, 0), linewidth=2)
smaPlot = plot(calc_smaLine, title='SMA', color=color.new(color.black, 0), linewidth=1)
midPlot = plot(0, title='Mid Line', color=color.new(color.black, 0), linewidth=1)
hiPlot = plot(series=calc_hiValue, color=na)
fill(hiPlot, midPlot, color=color.new(color.green, 50))
loPlot = plot(series=calc_loValue, color=na)
fill(loPlot, midPlot, color=color.new(color.red, 50)) |
Tosch Stacked EMAs (Fibonacci) | https://www.tradingview.com/script/PPYLiduS-Tosch-Stacked-EMAs-Fibonacci/ | AirshipPirate | https://www.tradingview.com/u/AirshipPirate/ | 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/
// © AirshipPirate
//@version=5
library("Tosch_Stacked_EMAs", overlay=true)
//----------------------------
ma(length) => ta.ema(close,length)
float ema05 = ma(5)
float ema08 = ma(8)
float ema13 = ma(13)
float ema21 = ma(21)
float ema34 = ma(34)
float ema55 = ma(55)
float ema89 = ma(89)
//----------------------------
// array with true/false values if the MA-pairs are lined up (true) or not (false)
the_bear_truth() =>
the_array = array.from( (ema05<=ema08), (ema08<=ema13), (ema13<=ema21), (ema21<=ema34), (ema34<=ema55), (ema55<=ema89) )
the_array
the_bull_truth() =>
the_array = array.from( (ema05>=ema08), (ema08>=ema13), (ema13>=ema21), (ema21>=ema34), (ema34>=ema55), (ema55>=ema89) )
the_array
bool[] ar_bear = the_bear_truth()
bool[] ar_bull = the_bull_truth()
//----------------------------
get_array(ar) =>
the_ar = array.copy(ar)
bool[] bull_ar = get_array(ar_bull)
bool[] bear_ar = get_array(ar_bear)
//----------------------------
// count how many MAs are lined up
stack_count(ar) =>
the_count = 0
for el in ar
the_count += (el ? 1 : 0)
the_count
int bear_count = stack_count(ar_bear)
int bull_count = stack_count(ar_bull)
//----------------------------
// MAs stacked?
bool emastack_bear = (bear_count == 6)
bool emastack_bull = (bull_count == 6)
//----------------------------
// @function Returns the EMA values for lengths 5, 8, 13, 21, 34, 55, 89
export emas() => [ema05,ema08,ema13,ema21,ema34,ema55,ema89]
//----------------------------
// @function Returns true if all EMAs are stacked, either way.
export stacked() => (emastack_bear or emastack_bull)
//----------------------------
// @function Returns true if the EMAs are stacked bullish/bearish, false otherwise
export bullish() => emastack_bull
export bearish() => emastack_bear
//----------------------------
// @function Returns the number of stacked EMAs
export bear_count() => bear_count
export bull_count() => bull_count
//----------------------------
// @function Returns the arrays of the true/false values if one EMA is below/above the next one
// bear: [ (ema05<=ema08), (ema08<=ema13), (ema13<=ema21), (ema21<=ema34), (ema34<=ema55), (ema55<=ema89) ]
// bull: [ (ema05>=ema08), (ema08>=ema13), (ema13>=ema21), (ema21>=ema34), (ema34>=ema55), (ema55>=ema89) ]
export bear_bool_array() => bear_ar
export bull_bool_array() => bull_ar
//-------------------------------------------------------------------------------------------------
show_ema = input.bool(defval=true, title="Show Fibonacci EMAs", group="Show Indicator", inline="FibEMA")
colo_ema = input.bool(defval=true, title="Color Bars", group="Show Indicator", inline="FibEMA")
show_cnt = input.bool(defval=true, title="Show counters", group="Show Indicator")
//----------------------------
// plot all lines
plot(ema05, style=plot.style_line, color=color.new(color.orange, 10), display=show_ema?display.all:display.none, linewidth=2)
plot(ema08, style=plot.style_line, color=color.new(color.white, 20), display=show_ema?display.all:display.none)
plot(ema13, style=plot.style_line, color=color.new(color.white, 30), display=show_ema?display.all:display.none)
plot(ema21, style=plot.style_circles, color=color.new(color.white, 10), display=show_ema?display.all:display.none, linewidth=2)
plot(ema34, style=plot.style_line, color=color.new(color.white, 50), display=show_ema?display.all:display.none)
plot(ema55, style=plot.style_line, color=color.new(color.white, 60), display=show_ema?display.all:display.none)
plot(ema89, style=plot.style_line, color=color.new(color.lime, 10), display=show_ema?display.all:display.none, linewidth=2)
//----------------------------
// color the bars
the_col = color.yellow
if (emastack_bear or emastack_bull)
if emastack_bull
the_col := color.green
else
the_col := color.red
barcolor(the_col, display=colo_ema?display.all:display.none)
//----------------------------
// display counters
label.new(bar_index, math.max(ema05,ema89), "bull\n"+str.tostring(bull_count)+"\nbear\n"+str.tostring(bear_count), style=show_cnt?label.style_label_down:label.style_none, textcolor=color.white)
|
Tosch Market Sessions (US/GB/JP) | https://www.tradingview.com/script/o1HH2wHB-Tosch-Market-Sessions-US-GB-JP/ | AirshipPirate | https://www.tradingview.com/u/AirshipPirate/ | 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/
// © AirshipPirate
//@version=5
// @description Returns if the NYSE, London SE, Tokyo SE are open
library("Tosch_Market_Sessions", overlay=true)
// @function Returns if the NYSE (US), London SE (GB), Tokyo SE (JP) are open
// @returns
// bus,bgb,bjp - bool: true if the corresponding exchange is open
// count - int: count of how many exchanges are open at the moment
// ccolor - color: color that indicates the number of open exchanges
// 0 => color.black
// 1 => color.blue
// 2 => color.orange
// 3 => color.white
export show_markets() =>
// GMT-5 / GMT-4 (06.11-13.03) -> GMT 0430-1100 / GMT 0530-1200
bus = not na(time(timeframe.period,"0930-1600:1234567", "America/New_York"))
// GMT / GMT+1 (27.03-30.10) -> GMT 0800-1630 / GMT 0900-1730
bgb = not na(time(timeframe.period,"0800-1630:1234567", "Europe/London"))
// GMT+9 -> GMT 0000-0230,0330-0600
bjp = not na(time(timeframe.period,"0900-1130,1230-1500:1234567", "Asia/Tokyo"))
// jp 20:00-22:30 23:30-02:00 (02:00-03:00 0) 1h
// gb 03:00-11:30 (09:30-11:30 2) 2h
// us 09:30-16:00 (16:00-20:00 0) 4h
count = 0
count += bus ? 1 : 0
count += bgb ? 1 : 0
count += bjp ? 1 : 0
ccolor = switch count
0 => color.black
1 => color.blue
2 => color.orange
3 => color.white
[bus,bgb,bjp,count,ccolor]
[pus,pgb,pjp,count,ccolor] = show_markets()
// indicator at top of the pane
plotshape(count, location=location.top,style=shape.circle, size=size.tiny, color=color.new(ccolor, 20))
bgcolor(count==1 ? color.new(color.blue, 90) : na)
bgcolor(count==2 ? color.new(color.orange, 90) : na)
|
KlintLibrary | https://www.tradingview.com/script/brjV2vtb-KlintLibrary/ | programmerder | https://www.tradingview.com/u/programmerder/ | 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/
// © programmerder
//@version=5
library("KlintLibrary", true)
export GetDecimals() => ta.highest(20) |
Utilities | https://www.tradingview.com/script/QuH9GE4Z-Utilities/ | reees | https://www.tradingview.com/u/reees/ | 19 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
// @description General utilities
library("Utilities", overlay = true)
//
//*********** Private ************
//
print_array(a, position = position.bottom_center, show_index = true, from_index = 0, to_index = last_bar_index) =>
size = array.size(a)
if bar_index == to_index
if size > 0
var t = table.new(position = position, columns = size, rows = 2, bgcolor = color.new(color.black,40), border_width = 1)
for i=from_index to size-1
txt = array.get(a,i)
r = -1
if show_index==true
r+=1
table.cell(table_id = t, text_color=color.white, column = i, row = r, text = str.tostring(i), text_size = size.tiny)
r+=1
table.cell(table_id = t, text_color=color.white,column = i, row = r, text = str.tostring(txt))
//
//************ Public *************
//
// @function Print series values
// @param s Series (string)
// @param skip_na Flag to skip na values (optional bool, dft = false)
// @param position Position to print the Table (optional string, dft = position.bottom_center)
// @param show_index Flag to show series indices (optional bool, dft = true)
// @param from_index First index to print (optional int, dft = 0)
// @param to_index Last index to print (optional int, dft = last_bar_index)
// @param label label for series table
// @returns Table object, if series was printed
export print_series(string s, simple bool skip_na = false, simple string position = position.bottom_center, simple bool show_index = true, int from_index = 0, int to_index = last_bar_index) =>
if bar_index == to_index
t = table.new(position = position, columns = to_index+1, rows = 2, bgcolor = color.new(color.black,40), border_width = 1)
for i=from_index to to_index
txt = s[to_index-i]
r = 0
if skip_na==false or (skip_na==true and txt!="NaN")
if show_index==true
table.cell(table_id = t, text_color=color.white, column = i, row = r, text = str.tostring(i), text_size = size.tiny)
r+=1
table.cell(table_id = t, text_color=color.white,column = i, row = r, text = txt)
r+=1
t
// e.g. print pivot highs last 200 bars
s1 = ta.pivothigh(high,5,5)
print_series(str.tostring(s1), true, from_index = last_bar_index-200)
// @function Print value
// @param v Value (string)
// @param position Position to print the Table (optional string, dft = position.bottom_center)
// @param at_index Index at which to print (optional int, dft = bar_index)
// @returns Table object, if value was printed
export print(string v, simple string position = position.bottom_center, int at_index = bar_index) =>
if bar_index == at_index
t = table.new(position = position, columns = 1, rows = 1, bgcolor = color.new(color.black,40), border_width = 1)
table.cell(table_id = t, text_color=color.white, column = 0, row = 0, text = str.tostring(v))
t
// e.g. print highest high last 200 bars
h = ta.highest(high,200)
print(str.tostring(h), position.top_right)
// @function Print value
// @param v Value (int)
// @param position Position to print the Table (optional string, dft = position.bottom_center)
// @param at_index Index at which to print (optional int, dft = bar_index)
// @returns Table object, if value was printed
export print(int v, simple string position = position.bottom_center, int at_index = bar_index) =>
if bar_index == at_index
t = table.new(position = position, columns = 1, rows = 1, bgcolor = color.new(color.black,40), border_width = 1)
table.cell(table_id = t, text_color=color.white, column = 0, row = 0, text = str.tostring(v))
t
// @function Print value
// @param v Value (float)
// @param position Position to print the Table (optional string, dft = position.bottom_center)
// @param at_index Index at which to print (optional int, dft = bar_index)
// @returns Table object, if value was printed
export print(float v, simple string position = position.bottom_center, int at_index = bar_index) =>
if bar_index == at_index
t = table.new(position = position, columns = 1, rows = 1, bgcolor = color.new(color.black,40), border_width = 1)
table.cell(table_id = t, text_color=color.white, column = 0, row = 0, text = str.tostring(v))
t
// @function Print value
// @param v Value (bool)
// @param position Position to print the Table (optional string, dft = position.bottom_center)
// @param at_index Index at which to print (optional int, dft = bar_index)
// @returns Table object, if value was printed
export print(bool v, simple string position = position.bottom_center, int at_index = bar_index) =>
if bar_index == at_index
t = table.new(position = position, columns = 1, rows = 1, bgcolor = color.new(color.black,40), border_width = 1)
table.cell(table_id = t, text_color=color.white, column = 0, row = 0, text = str.tostring(v))
t
// @function return array of offsets (int) of true values
export boolToIntArr(bool[] a) =>
int[] r = array.new_int(0)
for i=0 to array.size(a)-1
if array.get(a,i)
array.push(r,i)
r
export intToBoolArr(int[] a, int n) =>
bool[] r = array.new_bool(n,false)
for i in a
array.set(r,i,true)
r
|
lower_tf | https://www.tradingview.com/script/UxiDkNg0-lower-tf/ | PineCoders | https://www.tradingview.com/u/PineCoders/ | 68 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PineCoders
//@version=5
library("lower_tf")
// LTF Library
// v4, 2023.03.25
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/Time/4 as PCtime
//#region ———————————————————— Constants and Inputs
// ————— Constants
color WHITE = color.white
color GRAY = color.gray
string LTF1 = "Covering most chart bars (least precise)"
string LTF2 = "Covering some chart bars (less precise)"
string LTF3 = "Covering less chart bars (more precise)"
string LTF4 = "Covering few chart bars (very precise)"
string LTF5 = "Covering the least chart bars (most precise)"
string LTF6 = "~12 intrabars per chart bar"
string LTF7 = "~24 intrabars per chart bar"
string LTF8 = "~50 intrabars per chart bar"
string LTF9 = "~100 intrabars per chart bar"
string LTF10 = "~250 intrabars per chart bar"
string TT_LTF = "Your selection here controls how many intrabars will be analyzed for each chart bar.
The more intrabars you analyze, the more precise the calculations will be,
but the less chart bars will be covered by the indicator's calculations because a maximum of 100K intrabars can be analyzed.\n\n
The first five choices determine the lower timeframe used for intrabars using how much chart coverage you want.
The last five choices allow you to select approximately how many intrabars you want analyzed per chart bar."
string TAB_TXT = "Uses intrabars at {0}\nAvg intrabars per chart bar: {1,number,#.#}\nChart bars covered: {2} of {3} ({4,number,#.##}%)"
string ERR_TXT = "No intrabar information exists at the '{0}' timeframe."
// ————— Inputs
string ltfModeInput = input.string(LTF3, "Intrabar precision", options = [LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10], tooltip = TT_LTF)
bool showInfoBoxInput = input.bool(true, "Show information box ")
string infoBoxSizeInput = input.string("normal", "Size ", inline = "01", options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "↕", inline = "01", options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "↔", inline = "01", options = ["left", "center", "right"])
color infoBoxColorInput = input.color(GRAY, "", inline = "01")
color infoBoxTxtColorInput = input.color(WHITE, "T", inline = "01")
//#endregion
//#region ———————————————————— Functions
// @function Filters small timeframes by returning the original value if it is greater than or equal to 5 seconds, or 1 second otherwise.
// @param tfInSeconds (simple int) A timeframe in seconds.
// @returns (int) The filtered timeframe in seconds.
filterSmallTfs(simple int tfInSeconds) =>
int result = tfInSeconds < 5 ? 1 : tfInSeconds
// @function Selects a LTF from the chart's TF, depending on the `userSelection` input string.
// @param userSelection (simple string) User-selected input string which must be one of the `choicex` arguments.
// @param choice1 (simple string) Input selection corresponding to "Covering most chart bars (least precise)".
// @param choice2 (simple string) Input selection corresponding to "Covering some chart bars (less precise)".
// @param choice3 (simple string) Input selection corresponding to "Covering less chart bars (more precise)".
// @param choice4 (simple string) Input selection corresponding to "Covering few chart bars (very precise)".
// @param choice5 (simple string) Input selection corresponding to "Covering the least chart bars (most precise)".
// @param choice6 (simple string) Input selection corresponding to "~12 intrabars per chart bar".
// @param choice7 (simple string) Input selection corresponding to "~24 intrabars per chart bar".
// @param choice8 (simple string) Input selection corresponding to "~50 intrabars per chart bar".
// @param choice9 (simple string) Input selection corresponding to "~100 intrabars per chart bar".
// @param choice10 (simple string) Input selection corresponding to "~250 intrabars per chart bar".
// @returns (simple string) A timeframe string to be used with `request.security_lower_tf()`.
export ltf( simple string userSelection,
simple string choice1,
simple string choice2,
simple string choice3,
simple string choice4,
simple string choice5,
simple string choice6,
simple string choice7,
simple string choice8,
simple string choice9,
simple string choice10) =>
// Qty of minutes in each reference TF.
int ONE_MIN = 1
int ONE_SEC = ONE_MIN / 60
int ONE_HOUR = ONE_MIN * 60
int ONE_DAY = ONE_HOUR * 24
int ONE_WEEK = ONE_DAY * 7
float chartTfInMinutes = timeframe.in_seconds() / 60.
bool marketIs24Hours = syminfo.type == "crypto" or syminfo.type == "forex"
float marketIs24HoursFactor = marketIs24Hours ? 0.25 : 1.0
// Determine user selection.
bool leastPrecise = false
bool lessPrecise = false
bool morePrecise = false
bool veryPrecise = false
bool mostPrecise = false
bool intrabars12 = false
bool intrabars24 = false
bool intrabars50 = false
bool intrabars100 = false
bool intrabars250 = false
switch userSelection
choice1 => leastPrecise := true
choice2 => lessPrecise := true
choice3 => morePrecise := true
choice4 => veryPrecise := true
choice5 => mostPrecise := true
choice6 => intrabars12 := true
choice7 => intrabars24 := true
choice8 => intrabars50 := true
choice9 => intrabars100 := true
choice10 => intrabars250 := true
// Find the LTF corresponding to user's selection.
string result =
switch
leastPrecise => PCtime.secondsToTfString(timeframe.in_seconds() / 4)
veryPrecise =>
switch
chartTfInMinutes <= ONE_HOUR => "5S"
chartTfInMinutes <= ONE_HOUR * 2 => "15S"
chartTfInMinutes <= ONE_HOUR * 4 => "30S"
chartTfInMinutes <= ONE_HOUR * 12 => marketIs24Hours ? "1" : "30S"
chartTfInMinutes <= ONE_DAY => marketIs24Hours ? "2" : "1"
chartTfInMinutes <= ONE_WEEK => marketIs24Hours ? "15" : "5"
=> marketIs24Hours ? "60" : "30"
mostPrecise =>
switch
chartTfInMinutes <= ONE_HOUR => "1S"
chartTfInMinutes <= ONE_HOUR * 2 => "5S"
chartTfInMinutes <= ONE_HOUR * 4 => "15S"
chartTfInMinutes <= ONE_HOUR * 12 => marketIs24Hours ? "30S" : "15S"
chartTfInMinutes <= ONE_DAY => marketIs24Hours ? "1" : "30S"
chartTfInMinutes <= ONE_WEEK => marketIs24Hours ? "10" : "3"
=> marketIs24Hours ? "30" : "15"
lessPrecise =>
switch
chartTfInMinutes <= ONE_MIN => "5S"
chartTfInMinutes <= ONE_MIN * 2 => "10S"
chartTfInMinutes <= ONE_MIN * 3 => "15S"
chartTfInMinutes <= ONE_MIN * 5 => "30S"
chartTfInMinutes <= ONE_MIN * 15 => "1"
chartTfInMinutes <= ONE_HOUR => "3"
chartTfInMinutes < ONE_HOUR * 2 => "5"
chartTfInMinutes < ONE_HOUR * 4 => "15"
chartTfInMinutes < ONE_HOUR * 6 => "30"
chartTfInMinutes < ONE_HOUR * 12 => marketIs24Hours ? "60" : "30"
chartTfInMinutes < ONE_DAY => marketIs24Hours ? "120" : "30"
chartTfInMinutes < ONE_WEEK => marketIs24Hours ? "720" : "120"
=> "D"
morePrecise =>
switch
chartTfInMinutes <= ONE_MIN => "1S"
chartTfInMinutes <= ONE_MIN * 2 => "5S"
chartTfInMinutes <= ONE_MIN * 3 => "10S"
chartTfInMinutes <= ONE_MIN * 5 => "15S"
chartTfInMinutes <= ONE_MIN * 15 => "30S"
chartTfInMinutes <= ONE_HOUR => "1"
chartTfInMinutes < ONE_HOUR * 2 => "2"
chartTfInMinutes < ONE_HOUR * 4 => "3"
chartTfInMinutes < ONE_HOUR * 6 => "5"
chartTfInMinutes < ONE_HOUR * 12 => marketIs24Hours ? "10" : "5"
chartTfInMinutes < ONE_DAY => marketIs24Hours ? "15" : "5"
chartTfInMinutes < ONE_WEEK => marketIs24Hours ? "120" : "30"
=> "720"
intrabars12 => PCtime.secondsToTfString(filterSmallTfs(timeframe.in_seconds() / int((48 * marketIs24HoursFactor))))
intrabars24 => PCtime.secondsToTfString(filterSmallTfs(timeframe.in_seconds() / int((96 * marketIs24HoursFactor))))
intrabars50 => PCtime.secondsToTfString(filterSmallTfs(timeframe.in_seconds() / int((200 * marketIs24HoursFactor))))
intrabars100 => PCtime.secondsToTfString(filterSmallTfs(timeframe.in_seconds() / int((400 * marketIs24HoursFactor))))
intrabars250 => PCtime.secondsToTfString(filterSmallTfs(timeframe.in_seconds() / int((1000 * marketIs24HoursFactor))))
=> "1S"
// @function Returns statistics about analyzed intrabars and chart bars covered by calls to `request.security_lower_tf()`.
// @param intrabarValues (float[]) The ID of a float array containing values fetched by a call to `request.security_lower_tf()`.
// @returns A 3-element tuple: ([(series int) intrabarsInChartBar, (series int) chartBarsCovered, (series float) avgIntrabars].
export ltfStats(float[] intrabarValues) =>
// Qty of intrabars in the current chart bar.
int intrabarsInChartBar = array.size(intrabarValues)
// Chart bars where intrabar information is available.
int chartBarsCovered = int(ta.cum(math.sign(intrabarsInChartBar)))
// Avg qty of intrabars per chart bar.
float avgIntrabars = nz(ta.cum(intrabarsInChartBar) / chartBarsCovered)
[intrabarsInChartBar, chartBarsCovered, avgIntrabars]
//#endregion
//#region ———————————————————— Calculations
// Get the LTF corresponding to user's selection.
// NOTE
// This is a good example of a case where we declare a variable with `var` to improve the script's execution time.
// Declaring it this way calls the `ltf()` function only once, on the dataset's first bar.
// The `ltf()` function has many string arguments and because it only needs to return a "simple string" for use in `request.security_lower_tf()`,
// this entails that its value cannot change on further bars, so there is no need to execute it on them.
// Because the function's code mostly manipulates strings, which the Pine runtime doesn't process as efficiently as numbers, this speeds up the script.
var string ltfString = ltf(ltfModeInput, LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8, LTF9, LTF10)
// Get array of `close` values for each intrabar in the chart's bar.
float[] intrabarCloses = request.security_lower_tf(syminfo.tickerid, ltfString, close)
// ———— Intrabar stats
[intrabars, chartBarsCovered, avgIntrabars] = ltfStats(intrabarCloses)
int chartBars = bar_index + 1
//#endregion
//#region ———————————————————— Visuals
// Plots visible in the pane.
plot(avgIntrabars, "Average intrabars", color.silver, 6)
plot(intrabars, "Intrabars", color.blue, 2)
// Values visible in the Data Window and in the script's status line.
plot(chartBarsCovered, "Chart bars covered", display = display.data_window + display.status_line)
plot(chartBars, "Chart bars total", display = display.data_window + display.status_line)
// Information box.
if showInfoBoxInput
var table infoBox = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 1, 1)
string formattedLtf = PCtime.formattedNoOfPeriods(timeframe.in_seconds(ltfString) * 1000)
string txt = str.format(TAB_TXT, formattedLtf, avgIntrabars, chartBarsCovered, chartBars, chartBarsCovered / chartBars * 100)
if barstate.isfirst
table.cell(infoBox, 0, 0, txt, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxColorInput)
else if barstate.islast
table.cell_set_text(infoBox, 0, 0, txt)
// Error if no intrabars exist.
if ta.cum(intrabars) == 0 and barstate.islast
runtime.error(str.format(ERR_TXT, ltfString))
//#endregion
|
Console | https://www.tradingview.com/script/AoHb5KPb-Console/ | KLiC67 | https://www.tradingview.com/u/KLiC67/ | 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/
// © KLiC67
//@version=5
library("Console",overlay=true)
// @function initialise: creates the message array
// @param no parameters
// @returns message array: this is assigned to the "console" identifier
export initialise()=>
var arr_print_message = array.new<string>()
// @function used to output the desired text string to the console
// @param _consoleName : the message array
// @param _message : the console message
// @returns none
export print(string[] _consoleName, string _message)=>
array.push(_consoleName,_message)
//--- end print array}
// @function display: placed in the last section of code. Displays the console messages
// @param _consoleName : the message array
// @param _lineOffset : the setting of the scroll bar (time widget)
// @param _rowsToDisplay : how many rows to show in the console table
// @param _gotoMsg : which message to display from (default is 0)
// @param _posn : where the console table will be displayed
// @returns none
export display(string[] _consoleName,
int _lineOffset,
int _rowsToDisplay,
int _gotoMsg=0,
string _posn="bottom_right")=>
// check if the chart bar iteration has currency on the bar where the scroll handle (timestamp widget) is.
// Use the offset value to represents the offset of the first display message in the print table
// from the the first message in the print message array
// ie table row 1 message is <offset> elements from the first element in the print array
// declare persistant variables within scope of function
var int scrollHandleIndex = na // the bar_index of the timestamp handle
var int scrollOffset = na // integer offset of the handle from the last chart bar.
if time >= _lineOffset and time[1] < _lineOffset
// chart bar has currency on the scroll handle. Set handle variables
scrollHandleIndex := bar_index
scrollOffset := (last_bar_index - scrollHandleIndex) + (_gotoMsg > 0 ? _gotoMsg - 1 : 0)
if barstate.islast
messageCount = array.size(_consoleName)
displayRows = math.min(_rowsToDisplay, messageCount)
line.new(_lineOffset, high, _lineOffset, low, extend = extend.both,
color = color.rgb(255, 255, 255, 58), width=10, xloc=xloc.bar_time)
line.new(x1=_lineOffset, y1=high, x2=_lineOffset, y2=low, extend=extend.both,
color=color.orange, width=2, xloc=xloc.bar_time)
var scroll_handle_label = label.new(x=scrollHandleIndex, y=low, color=color.rgb(255, 0, 0, 52), textcolor=color.white)
var tbl_printMessage = table.new(position=_posn,
columns=2,
rows= _rowsToDisplay,
bgcolor = color.rgb(255, 255, 255, 92))
scrollHandleText = ""
scrollHandleText := "Messages \n" +
str.tostring(scrollOffset + 1) +
" to " +
str.tostring(scrollOffset + displayRows) +
"\nof " +
str.tostring(messageCount)
if messageCount == 0
scrollHandleText := "NO MESSAGES"
else if (messageCount - scrollOffset) < displayRows
scrollHandleText := "No more messages"
scrollOffset := messageCount - displayRows
label.set_text(scroll_handle_label, scrollHandleText)
if messageCount > 0
for i = 0 to displayRows - 1
// column 1 display the message line number
table.cell(tbl_printMessage,
column=0,
row=i,
text=str.tostring(i + scrollOffset + 1),
text_color = color.rgb(147, 147, 147),
text_halign = text.align_left)
// column 2 display the message
table.cell(tbl_printMessage,
column=1,
row=i,
text=array.get(_consoleName, i + scrollOffset),
text_color = color.white,
text_halign = text.align_left)
// display messages function start }
//***** COPY THIS BLOCK INTO SCRIPT THAT REQUIRES DEBUGGING{
// -- console setup input section
//
// Set the "SCROLLSTART" constant to YOUR time so the scroll bar is near the end of the chart...
// var string SCROLLSTART = "25 Dec 2022 14:30 +0000" <<--- change this
//
// con1 and con2 are two console's that can be written to seperately the name is arbitrary but
// one MUST be specified
// var con1=initialise() <--- must specify at least one 'console' name with the initialise function
// var con2=initialise()
//
// -- suggested last block of code...
// var bool printed = false // "printed" bool prevents messages being written
// // to console every time there is a new last bar
// if barstate.islast and not printed
// printed := true
// if i_sampleInput
// print(con1,"summary" + str.tostring(1))
//
// this line is needed
// if i_showMessages
// console(i_lineOffset, i_rowsToDisplay, i_gotoMsg, i_Posn)
//***** and optionally the logic to prevent aditional print messages on every last bar
//
var string SCROLLSTART = "25 Dec 2022 14:30 +0000" // << update this constant to your date/time
var con1=initialise()
var con2=initialise()
// -- inputs
var string g_message = "Console Settings"
i_lineOffset = input.time(timestamp(SCROLLSTART), "scroll Bar position", confirm = false, group=g_message)
// i_lineOffset = input.time(timestamp("15 Sep 2022 13:30 +0000"), "scroll Bar position", confirm = false, group=g_message)
i_rowsToDisplay = input.int(defval=10,title="Rows to Display", minval=1, group=g_message, inline="a")
i_gotoMsg = input.int(defval=0, title="Start Message", group=g_message, inline="a")
i_PosY = input.string("bottom","Position",group=g_message, inline="posn", options=["bottom",
"middle",
"top"])
i_PosX = input.string("right","",group=g_message, inline="posn", options=["right",
"center",
"left"])
var string posn = i_PosY + "_" + i_PosX
i_showMessages = input.bool(defval=true, title="Show Messages", group=g_message,inline="display")
i_displayTable = input.string("con1","Console Name:",["con1","con2","other (you decide)"])
// user code ...
i_sampleInput = input.bool(defval=true, title="Sample")
// some more code here
// some more code here
// some more code here
// some more code here
// some code below to illustrate.... THIS WOULD BE YOUR CODE
var count = 0, count +=1
if bar_index % 150 == 0
print(con1,"bar_index = " + str.tostring(bar_index)) // only print bar_index numbers divisible by 150
// some more code here
// some more code here
// some more code here
// some more code here
// ... end of user code
// suggested summary code - make sure this is at the end of your code
var bool printed = false // "printed" bool prevents messages being written
// to console every time there is a new last bar
if barstate.islast and not printed
printed := true
if i_sampleInput
print(con1,"THE END")
print(con2,"total candles =" + str.tostring(count))
// last line of code (needed)
if i_showMessages
if i_displayTable == "con1"
display(con1, i_lineOffset, i_rowsToDisplay, i_gotoMsg, posn)
else
display(con2, i_lineOffset, i_rowsToDisplay, i_gotoMsg, posn)
//****** END OF COPY BLOCK } |
Algebra | https://www.tradingview.com/script/xPDChIFF-Algebra/ | reees | https://www.tradingview.com/u/reees/ | 23 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
// Algebraic functions
library("Algebra",overlay=true)
//----------------------------------------------------------------------------
// Private
//----------------------------------------------------------------------------
// Get the hypotenuse of a right triangle, given the lengths of its legs
rt_get_hyp(a,b) =>
math.sqrt(a*a + b*b)
//----------------------------------------------------------------------------
// Public
//----------------------------------------------------------------------------
// @function Get line slope and y-intercept from coordinates
// @param x1 x coordinate 1 (int - bar index)
// @param y1 y coordinate 1 (float - price/value)
// @param x2 x coordinate 2 (int - bar index)
// @param y2 y coordinate 2 (float - price/value)
// @returns [slope, y-intercept] of line
//
export line_fromXy(int x1, float y1, int x2, float y2) =>
slope = (y1-y2)/(x1-x2)
yInt = y1 - slope*x1
[slope,yInt]
// @function Get price at X coordinate, given line slope and y-intercept
// @param x x coordinate to solve for y (int - bar index)
// @param slope slope of line (float)
// @param yInt y-intercept of line (float)
// @returns y (price/value)
//
export line_getPrice(int x, float slope, float yInt) =>
slope*x+yInt
// @function Get price at X coordinate, given two points on a line
// @param x x coordinate to solve for y (int - bar index)
// @param x1 x coordinate 1 (int - bar index)
// @param y1 y coordinate 1 (float - price/value)
// @param x2 x coordinate 2 (int - bar index)
// @param y2 y coordinate 2 (float - price/value)
// @returns y (price/value)
//
export line_getPrice_fromXy(int x, int x1, float y1, int x2, float y2) =>
[slope,yInt] = line_fromXy(x1,y1,x2,y2)
line_getPrice(x,slope,yInt)
// @function Get length of sides of a right triangle formed by a given line
// @param x1 x coordinate 1 (int - optional, required if argument l is not specified)
// @param y1 y coordinate 1 (float - optional, required if argument l is not specified)
// @param x2 x coordinate 2 (int - optional, required if argument l is not specified)
// @param y2 y coordinate 2 (float - optional, required if argument l is not specified)
// @param l line object (line - optional, required if x1, y1, x2, y2 agruments are not specified)
// @returns [a (Δy), b (Δx), c (Hypotenuse)]
//
export line_getRtSides(int x1=0, float y1=0.0, int x2=0, float y2=0.0, line l=na) =>
x_1 = 0
x_2 = 0
y_1 = 0.0
y_2 = 0.0
if not na(l)
x_1 := line.get_x1(l)
x_2 := line.get_x2(l)
y_1 := line.get_y1(l)
y_2 := line.get_y2(l)
else
x_1 := x1
x_2 := x2
y_1 := y1
y_2 := y2
a = y_2-y_1
b = x_2-x_1
c = if a != 0 and b != 0
rt_get_hyp(a,b)
else
0
[a,b,c]
// @function Get length of line, given a line object or two sets of coordinates
// @param x1 x coordinate 1 (int - optional, required if argument l is not specified)
// @param y1 y coordinate 1 (float - optional, required if argument l is not specified)
// @param x2 x coordinate 2 (int - optional, required if argument l is not specified)
// @param y2 y coordinate 2 (float - optional, required if argument l is not specified)
// @param l line object (line - optional, required if x1, y1, x2, y2 agruments are not specified)
// @returns length of line (float)
//
export line_length(int x1=0, float y1=0.0, int x2=0, float y2=0.0, line l=na) =>
[a,b,c] = line_getRtSides(x1,y1,x2,y2,l)
if a == 0
b
else if b == 0
a
else
c
|
ccIndidatorTime | https://www.tradingview.com/script/oBsdrmxw/ | ccTradingCourse | https://www.tradingview.com/u/ccTradingCourse/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ccTradingCourse
//@version=5
library("ccIndidatorTime")
export isDateRange(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Long1(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Long2(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Long3(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Long4(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Short1(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Short2(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Short3(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish
export isDateRange_Short4(
int _fromYear=2020, int _fromMonth=01, int _fromDay=01, int _fromHour=0, int _fromSecond=0,
int _endYear=2024, int _endMonth=12, int _endDay=31, int _endHour=23, int _endSecond=59) =>
start = timestamp(_fromYear, _fromMonth, _fromDay, _fromHour, _fromSecond)
finish = timestamp(_endYear, _endMonth, _endDay, _endHour, _endSecond)
isDate = time >= start and time <= finish |
ccIndidatorDrawing | https://www.tradingview.com/script/SOLghKzD/ | ccTradingCourse | https://www.tradingview.com/u/ccTradingCourse/ | 0 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ccTradingCourse
//@version=5
library("ccIndidatorDrawing")
export showWarningTable() =>
table warnings = table.new(position.bottom_center, rows=3, columns=1, frame_width=1, frame_color=color.gray, border_width=1, border_color=color.red, bgcolor=color.red)
table.cell(warnings, row=0, column=0, text='Warning!!!!', text_color=color.white, text_halign=text.align_center, bgcolor=color.gray)
table.cell(warnings, row=1, column=0, text='This Not Readdy', text_color=color.white, text_halign=text.align_center)
table.cell(warnings, row=2, column=0, text="XXXYYY", text_color=color.white, text_halign=text.align_left) |
TA | https://www.tradingview.com/script/5z2MSoiw-TA/ | reees | https://www.tradingview.com/u/reees/ | 44 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
// @description General technical analysis functions
library("TA",overlay=true)
import reees/Algebra/3 as alg
import reees/Trig/2 as trig
import reees/Fibonacci/4 as fib
import reees/Utilities/5 as u
//-----------------------------------------
// Divergence
//-----------------------------------------
// (private) Divergence strength of a change in series values
deltaStrength(y1,y2,std) =>
// Ideally want Δy in terms of standard deviation
if not na(std)
math.abs(y2-y1)/(std*2)
// If we don't yet have a standard deviation, use the percent change in values
else if math.abs(y1) > math.abs(y2) and y1 != 0
1 - math.abs(y2/y1)
else if math.abs(y2) > math.abs(y1) and y2 != 0
1 - math.abs(y1/y2)
else if y1 == y2 // should never be true if we've already detected divergence
0.0
else
.5
// @function Test for bullish divergence
//
// @param pS Price series (float)
// @param iS Indicator series (float)
// @param cp_length_after Bars after current (divergent) pivot low to be considered a valid pivot (optional int)
// @param cp_length_before Bars before current (divergent) pivot low to be considered a valid pivot (optional int)
// @param pivot_length Bars before and after prior pivot low to be considered valid pivot (optional int)
// @param lookback Bars back to search for prior pivot low (optional int)
// @param lookback_pivs Pivots back to search for prior pivot low (optional int)
// @param no_broken Flag to only consider divergence valid if the pivot-to-pivot trendline is unbroken (optional bool)
// @param pW Weight of change in price, used in degree of divergence calculation (optional float)
// @param iW Weight of change in indicator, used in degree of divergence calculation (optional float)
// @param hidW Weight of hidden divergence, used in degree of divergence calculation (optional float)
// @param regW Weight of regular divergence, used in degree of divergence calculation (optional float)
//
// @returns [flag,degree,type,lx1,ly1,lx2,ly2]
// flag = true if divergence exists (bool)
// degree = degree (strength) of divergence (float)
// type = 1 = regular, 2 = hidden (int)
// lx1 = x coordinate 1 (int)
// ly1 = y coordinate 1 (float)
// lx2 = x coordinate 2 (int)
// ly2 = y coordinate 2 (float)
//
export div_bull(float pS, float iS, simple int cp_length_after=2, simple int cp_length_before=4, simple int pivot_length=4, simple int lookback=50, simple int lookback_pivs=5, simple bool no_broken=true, simple float pW=1.0, simple float iW=1.0, simple float hidW=.8, simple float regW = 1.2) =>
p = ta.pivotlow(pS,pivot_length,pivot_length)
cpp = ta.pivotlow(pS,cp_length_before,cp_length_after)
ip = ta.pivotlow(iS,pivot_length,pivot_length)
ix1 = ta.lowestbars(iS,cp_length_after+2) // current indicator pivot is lowest bar between current bar and two bars prior to the price pivot
ix1 := int(math.sign(ix1) * ix1)
pStd = ta.stdev(pS, bar_index<100 ? bar_index + 1 : 100)
iStd = ta.stdev(iS,bar_index<100 ? bar_index + 1 : 100)
flag = false
degree = 0.0
type = 0
lx1 = 0
ly1 = 0.0
lx2 = 0
ly2 = 0.0
j = 0 // pivot count
// if price is pivoting low
if not na(cpp)
// check last <#> bars before current pivot low for any previous pivot low
for i=cp_length_after to lookback+cp_length_after
if j == lookback_pivs
break
// Found a prior price pivot low, AND the indicator also pivoted low on the same bar, the previous bar, or the next bar
if not na(p[i]) and (not na(ip[i]) or not na(ip[i+1]) or (i==0 ? false : not na(ip[i-1])))
j+=1
// prior indicator pivot:
// if indicator pivoted on the bar before or after the price pivot, use that value
// else the pivot occurred on the same bar as the price pivot
ix2 = if not na(ip[i+1])
i + pivot_length + 1
else if not na(ip[i-1])
i + pivot_length - 1
else
i + pivot_length
// test for divergence
if p[i] > pS[cp_length_after] and iS[ix2] < iS[ix1]
flag := true
// degree = Δprice strength + Δindicator strength (multiplied by specified weights)
degree := (deltaStrength(p[i],pS[cp_length_after],pStd)*pW + deltaStrength(iS[ix1],iS[ix2],iStd)*iW)*regW
type := 1
else if p[i] < pS[cp_length_after] and iS[ix2] > iS[ix1]
flag := true
// degree = Δprice strength + Δindicator strength (multiplied by specified weights)
degree := (deltaStrength(p[i],pS[cp_length_after],pStd)*pW + deltaStrength(iS[ix1],iS[ix2],iStd)*iW)*hidW
type := 2
// if divergence exists, get line
if flag
lx1 := bar_index-i-pivot_length
ly1 := p[i]
lx2 := bar_index-cp_length_after
ly2 := pS[cp_length_after]
[slope,yInt] = alg.line_fromXy(lx1,ly1,lx2,ly2)
if no_broken
// invalidate divergence if an intermediate low breaks divergence trendline
for k=lx1 to lx2
if pS[bar_index-k] < (alg.line_getPrice(k,slope,yInt)*.99)
flag := false
degree := 0.0
type := 0
lx1 := 0
ly1 := 0.0
lx2 := 0
ly2 := 0.0
break
break
[flag,degree,type,lx1,ly1,lx2,ly2]
// @function Test for bearish divergence
//
// @param pS Price series (float)
// @param iS Indicator series (float)
// @param cp_length_after Bars after current (divergent) pivot high to be considered a valid pivot (optional int)
// @param cp_length_before Bars before current (divergent) pivot highto be considered a valid pivot (optional int)
// @param pivot_length Bars before and after prior pivot high to be considered valid pivot (optional int)
// @param lookback Bars back to search for prior pivot high (optional int)
// @param lookback_pivs Pivots back to search for prior pivot high (optional int)
// @param no_broken Flag to only consider divergence valid if the pivot-to-pivot trendline is unbroken (optional bool)
// @param pW Weight of change in price, used in degree of divergence calculation (optional float)
// @param iW Weight of change in indicator, used in degree of divergence calculation (optional float)
// @param hidW Weight of hidden divergence, used in degree of divergence calculation (optional float)
// @param regW Weight of regular divergence, used in degree of divergence calculation (optional float)
//
// @returns [flag,degree,type,lx1,ly1,lx2,ly2]
// flag = true if divergence exists (bool)
// degree = degree (strength) of divergence (float)
// type = 1 = regular, 2 = hidden (int)
// lx1 = x coordinate 1 (int)
// ly1 = y coordinate 1 (float)
// lx2 = x coordinate 2 (int)
// ly2 = y coordinate 2 (float)
//
export div_bear(float pS, float iS, simple int cp_length_after=2, simple int cp_length_before=4, simple int pivot_length=4, simple int lookback=50, simple int lookback_pivs=5, simple bool no_broken=true, simple float pW=1.0, simple float iW=1.0, simple float hidW=.8, simple float regW = 1.2) =>
p = ta.pivothigh(pS,pivot_length,pivot_length)
cpp = ta.pivothigh(pS,cp_length_before,cp_length_after)
ip = ta.pivothigh(iS,pivot_length,pivot_length)
ix1 = ta.highestbars(iS,cp_length_after+2) // current indicator pivot is highest bar between current bar and two bars prior to the price pivot
ix1 := int(math.sign(ix1) * ix1)
pStd = ta.stdev(pS, bar_index<100 ? bar_index + 1 : 100)
iStd = ta.stdev(iS,bar_index<100 ? bar_index + 1 : 100)
flag = false
degree = 0.0
type = 0
lx1 = 0
ly1 = 0.0
lx2 = 0
ly2 = 0.0
j = 0 // pivot count
// if price is pivoting high
if not na(cpp)
// check last <#> bars before current pivot high for any previous pivot high
for i=cp_length_after to lookback+cp_length_after
if j == lookback_pivs
break
// Found a prior price pivot high, AND the indicator also pivoted high on the same bar, the previous bar, or the next bar
if not na(p[i]) and (not na(ip[i]) or not na(ip[i+1]) or (i==0 ? false : not na(ip[i-1])))
j+=1
// prior indicator pivot:
// if indicator pivoted on the bar before or after the price pivot, use that value
// else the pivot occurred on the same bar as the price pivot
ix2 = if not na(ip[i+1])
i + pivot_length + 1
else if not na(ip[i-1])
i + pivot_length - 1
else
i + pivot_length
// test for divergence
if p[i] > pS[cp_length_after] and iS[ix2] < iS[ix1]
flag := true
// degree = Δprice strength + Δindicator strength (multiplied by specified weights)
degree := (deltaStrength(p[i],pS[cp_length_after],pStd)*pW + deltaStrength(iS[ix1],iS[ix2],iStd)*iW)*hidW
type := 2
else if p[i] < pS[cp_length_after] and iS[ix2] > iS[ix1]
flag := true
// degree = Δprice strength + Δindicator strength (multiplied by specified weights)
degree := (deltaStrength(p[i],pS[cp_length_after],pStd)*pW + deltaStrength(iS[ix1],iS[ix2],iStd)*iW)*regW
type := 1
// if divergence exists, get line
if flag
lx1 := bar_index-i-pivot_length
ly1 := p[i]
lx2 := bar_index-cp_length_after
ly2 := pS[cp_length_after]
[slope,yInt] = alg.line_fromXy(lx1,ly1,lx2,ly2)
if no_broken
// invalidate divergence if an intermediate low breaks divergence trendline
for k=lx1 to lx2
if pS[bar_index-k] > (alg.line_getPrice(k,slope,yInt)*1.01)
flag := false
degree := 0.0
type := 0
lx1 := 0
ly1 := 0.0
lx2 := 0
ly2 := 0.0
break
break
[flag,degree,type,lx1,ly1,lx2,ly2]
//-----------------------------------------
// Harmonics
//-----------------------------------------
// (private) Validate AB leg of XABCD
test_ab(ab,xa,pErr,p_types) =>
var f618 = fib.fib_precise(0.618)
var f382 = fib.fib_precise(0.382)
var f786 = fib.fib_precise(0.786)
t0=false,t1=false,t2=false,t3=false,t4=false,t5=false
rat = ab/xa
// gartley
if array.get(p_types,0)
t0 := rat <= f618*(1+pErr/100) and rat >= f618*(1-pErr/100) ? true : false // within acceptable % error
// bat
if array.get(p_types,1)
t1 := (rat <= f382*(1+pErr/100) and rat >= f382*(1-pErr/100)) or (rat <= .5*(1+pErr/100) and rat >= .5*(1-pErr/100)) ? true : false
// butterfly
if array.get(p_types,2)
t2 := rat <= f786*(1+pErr/100) and rat >= f786*(1-pErr/100) ? true : false
// crab
if array.get(p_types,3)
t3 := (rat <= f382*(1+pErr/100) and rat >= f382*(1-pErr/100)) or (rat <= f618*(1+pErr/100) and rat >= f618*(1-pErr/100)) ? true : false
// shark
if array.get(p_types,4)
t4 := rat < 1 // no AB validation defined for shark
// cypher
if array.get(p_types,5)
t5 := (rat <= f382*(1+pErr/100) and rat >= f382*(1-pErr/100)) or (rat <= f618*(1+pErr/100) and rat >= f618*(1-pErr/100)) ? true : false
[t0,t1,t2,t3,t4,t5]
// (private) Validate BC leg of XABCD
test_bc(bc,ab,pErr,p_types) =>
var f382 = fib.fib_precise(0.382)
var f886 = fib.fib_precise(0.886)
var f1618 = fib.fib_precise(1.618)
var f1272 = fib.fib_precise(1.272)
var f1414 = fib.fib_precise(1.414)
t0=false,t1=false,t2=false,t3=false,t4=false,t5=false
rat = bc/ab
pass = (rat <= f886*(1+pErr/100) and rat >= f886*(1-pErr/100)) or (rat <= f382*(1+pErr/100) and rat >=f382*(1-pErr/100)) ? true : false
// gartley
if array.get(p_types,0)
t0 := pass
// bat
if array.get(p_types,1)
t1 := pass
// butterfly
if array.get(p_types,2)
t2 := pass
// crab
if array.get(p_types,3)
t3 := pass
// shark
if array.get(p_types,4)
t4 := (rat <= 1.13*(1+pErr/100) and rat >= 1.13*(1-pErr/100)) or (rat <= f1618*(1+pErr/100) and rat >=f1618*(1-pErr/100))
// cypher
if array.get(p_types,5)
t5 := (rat <= f1272*(1+pErr/100) and rat >= f1272*(1-pErr/100)) or (rat <= f1414*(1+pErr/100) and rat >=f1414*(1-pErr/100))
[t0,t1,t2,t3,t4,t5]
//@function Validate CD leg of XABCD
export test_cd(float cd, float bc, float xa, float xc, float ad, float pErr, bool[] p_types) =>
var f1618 = fib.fib_precise(1.618)
var f2618 = fib.fib_precise(2.618)
var f786 = fib.fib_precise(0.786)
var f886 = fib.fib_precise(0.886)
var f1272 = fib.fib_precise(1.272)
t0=false,t1=false,t2=false,t3=false,t4=false,t5=false
rat = cd/bc
rat2 = ad/xa
rat3 = cd/xc
// test D against both BC and XA legs
// gartley
if array.get(p_types,0)
bc_test = (rat <= f1272*(1+pErr/100) and rat >= f1272*(1-pErr/100)) or (rat <= f1618*(1+pErr/100) and rat >= f1618*(1-pErr/100))
xa_test = rat2 <= f786*(1+pErr/100) and rat2 >= f786*(1-pErr/100)
t0 := bc_test and xa_test ? true : false
// bat
if array.get(p_types,1)
bc_test = (rat <= f1618*(1+pErr/100) and rat >= f1618*(1-pErr/100)) or (rat <= f2618*(1+pErr/100) and rat >= f2618*(1-pErr/100))
xa_test = rat2 <= f886*(1+pErr/100) and rat2 >= f886*(1-pErr/100)
t1 := bc_test and xa_test ? true : false
// butterfly
if array.get(p_types,2)
bc_test = (rat <= f1618*(1+pErr/100) and rat >= f1618*(1-pErr/100)) or (rat <= f2618*(1+pErr/100) and rat >= f2618*(1-pErr/100))
xa_test = (rat2 <= f1272*(1+pErr/100) and rat2 >= f1272*(1-pErr/100)) or (rat2 <= f1618*(1+pErr/100) and rat2 >= f1618*(1-pErr/100))
t2 := bc_test and xa_test ? true : false
// crab
if array.get(p_types,3)
bc_test = (rat <= 2.24*(1+pErr/100) and rat >= 2.24*(1-pErr/100)) or (rat <= 3.618*(1+pErr/100) and rat >= 3.618*(1-pErr/100))
xa_test = rat2 <= f1618*(1+pErr/100) and rat2 >= f1618*(1-pErr/100)
t3 := bc_test and xa_test ? true : false
// shark
if array.get(p_types,4)
bc_test = (rat <= f1618*(1+pErr/100) and rat >= f1618*(1-pErr/100)) or (rat <= 2.24*(1+pErr/100) and rat >= 2.24*(1-pErr/100))
xa_test = (rat2 <= f886*(1+pErr/100) and rat2 >= f886*(1-pErr/100)) or (rat2 <= 1.13*(1+pErr/100) and rat2 >= 1.13*(1-pErr/100))
t4 := bc_test and xa_test ? true : false
// cypher
if array.get(p_types,5)
bc_test = true
xc_test = rat3 <= f786*(1+pErr/100) and rat3 >= f786*(1-pErr/100) // cypher point D retraces XC
t5 := bc_test and xc_test ? true : false
//
[t0,t1,t2,t3,t4,t5]
// (private)
// @function Validate ΔX symmetry of XABCD pattern
export pat_xabcd_testSym(int xax, int abx, int bcx, int cdx=na, float pAsym=500.0) =>
if not na(cdx) and (cdx > ((xax+abx+bcx)/3)*(1+pAsym/100) or cdx < ((xax+abx+bcx)/3)*(1-pAsym/100))
false
else if bcx > ((xax+abx+cdx)/3)*(1+pAsym/100) or bcx < ((xax+abx+cdx)/3)*(1-pAsym/100)
false
else if abx > ((xax+bcx+cdx)/3)*(1+pAsym/100) or abx < ((xax+bcx+cdx)/3)*(1-pAsym/100)
false
else if xax > ((abx+bcx+cdx)/3)*(1+pAsym/100) or xax < ((abx+bcx+cdx)/3)*(1-pAsym/100)
false
else
true
// @function Validate harmonic XABCD pattern
//
// @param xX X coordinate of point X (int)
// @param xY Y coordinate of point X (float)
// @param aX X coordinate of point A (int)
// @param aY Y coordinate of point A (float)
// @param bX X coordinate of point B (int)
// @param bY Y coordinate of point B (float)
// @param cX X coordinate of point C (int)
// @param cY Y coordinate of point C (float)
// @param dX X coordinate of point D (int)
// @param dY Y coordinate of point D (float)
// @param pErr Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
// @param pAsym Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
// @param pivot_length Bars before and after prior pivot high to be considered valid pivot (optional int)
// @param gart Flag to validate Gartley pattern (bool)
// @param bat Flag to validate Bat pattern (bool)
// @param bfly Flag to validate Butterfly pattern (bool)
// @param crab Flag to validate Crab pattern (bool)
// @param shark Flag to validate Shark pattern (bool)
// @param cyph Flag to validate Cypher pattern (bool)
//
// @returns [flag,t1,t2,t3,t4,t5,t6]
// flag = true if valid harmonic
// t1 = true if valid gartley
// t2 = true if valid bat
// t3 = true if valid butterfly
// t4 = true if valid crab
// t5 = true if valid shark
// t6 = true if valid cypher
//
export harmonic_xabcd_validate(int xX,float xY,int aX,float aY,int bX,float bY,int cX,float cY,int dX,float dY,float pErr=20,float pAsym=250,
bool gart=true,bool bat=true,bool bfly=true,bool crab=true,bool shark=true,bool cyph=true) =>
bool[] p_types = array.from(gart,bat,bfly,crab,shark,cyph)
xa = math.abs(xY-aY)
xax = math.abs(xX-aX)
ab = math.abs(aY-bY)
abx = math.abs(aX-bX)
bc = math.abs(bY-cY)
bcx = math.abs(bX-cX)
cd = math.abs(cY-dY)
ad = math.abs(aY-dY)
xc = math.abs(xY-cY)
cdx = math.abs(cX-dX)
// Test ΔX symmetry first. If failure, no need to check the ratios.
if pat_xabcd_testSym(xax,abx,bcx,cdx,pAsym)==false
[false,false,false,false,false,false,false]
else
[ab_t1,ab_t2,ab_t3,ab_t4,ab_t5,ab_t6] = test_ab(ab,xa,pErr,p_types)
p_types := array.from(ab_t1,ab_t2,ab_t3,ab_t4,ab_t5,ab_t6)
[bc_t1,bc_t2,bc_t3,bc_t4,bc_t5,bc_t6] = test_bc(bc,ab,pErr,p_types)
p_types := array.from(bc_t1,bc_t2,bc_t3,bc_t4,bc_t5,bc_t6)
[t1,t2,t3,t4,t5,t6] = test_cd(cd,bc,xa,xc,ad,pErr,p_types)
flag = t1 or t2 or t3 or t4 or t5 or t6
[flag,t1,t2,t3,t4,t5,t6]
// @function Validate the first 3 legs of a harmonic XABCD pattern
//
// @param xX X coordinate of point X (int)
// @param xY Y coordinate of point X (float)
// @param aX X coordinate of point A (int)
// @param aY Y coordinate of point A (float)
// @param bX X coordinate of point B (int)
// @param bY Y coordinate of point B (float)
// @param cX X coordinate of point C (int)
// @param cY Y coordinate of point C (float)
// @param pErr Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
// @param pAsym Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
// @param pivot_length Bars before and after prior pivot high to be considered valid pivot (optional int)
// @param gart Flag to validate Gartley pattern (bool)
// @param bat Flag to validate Bat pattern (bool)
// @param bfly Flag to validate Butterfly pattern (bool)
// @param crab Flag to validate Crab pattern (bool)
// @param shark Flag to validate Shark pattern (bool)
// @param cyph Flag to validate Cypher pattern (bool)
//
// @returns [flag,t1,t2,t3,t4]
// flag = true if valid harmonic
// t1 = true if valid gartley
// t2 = true if valid bat
// t3 = true if valid butterfly
// t4 = true if valid crab
// t5 = true if valid shark
// t6 = true if valid cypher
//
export harmonic_xabcd_validateIncomplete(int xX,float xY,int aX,float aY,int bX,float bY,int cX,float cY,float pErr=30,float pAsym=75,
bool gart=true,bool bat=true,bool bfly=true,bool crab=true,bool shark=true,bool cyph=true) =>
bool[] p_types = array.from(gart,bat,bfly,crab,shark,cyph)
xa = math.abs(xY-aY)
xax = math.abs(xX-aX)
ab = math.abs(aY-bY)
abx = math.abs(aX-bX)
bc = math.abs(bY-cY)
bcx = math.abs(bX-cX)
// Test ΔX symmetry first. If failure, no need to check the ratios.
if pat_xabcd_testSym(xax,abx,bcx,na,pAsym)==false
[false,false,false,false,false,false,false]
else
[ab_t1,ab_t2,ab_t3,ab_t4,ab_t5,ab_t6] = test_ab(ab,xa,pErr,p_types)
p_types := array.from(ab_t1,ab_t2,ab_t3,ab_t4,ab_t5,ab_t6)
[t1,t2,t3,t4,t5,t6] = test_bc(bc,ab,pErr,p_types)
flag = t1 or t2 or t3 or t4 or t5 or t6
[flag,t1,t2,t3,t4,t5,t6]
// @function Get the potential reversal zone (PRZ) levels of a harmonic XABCD pattern
//
// @param type Harmonic pattern type (int - 1 = Gartley, 2 = Bat, 3 = Butterfly, 4 = Crab, 5 = Shark, 6 = Cypher)
// @param xY Y coordinate of point X (float)
// @param aY Y coordinate of point A (float)
// @param bY Y coordinate of point B (float)
// @param cY Y coordinate of point C (float)
//
// @returns [bc_u, bc_l, xa_u, xa_l]
// bc_u = nearest BC retracement/extension level (nearest to point C)
// bc_l = farthest BC retracement/extension level (nearest to point C)
// xa_u = nearest XA retracement/extension level (or the only XA level, if applicable)
// xa_l = farthest XA retracement/extension level (or na if not applicable)
//
export harmonic_xabcd_prz(int type=1, float xY, float aY, float bY, float cY) =>
var f1618 = fib.fib_precise(1.618)
var f2618 = fib.fib_precise(2.618)
var f786 = fib.fib_precise(0.786)
var f886 = fib.fib_precise(0.886)
var f1272 = fib.fib_precise(1.272)
float bc_u = na, float bc_l = na
float xa_u = na, float xa_l = na
bc = cY-bY
xa = aY-xY
xc = cY-xY
if type == 1 // Gartley
bc_u := cY - (f1272*bc)
bc_l := cY - (f1618*bc)
xa_u := aY - (f786*xa)
else if type == 2 // Bat
bc_u := cY - (f1618*bc)
bc_l := cY - (f2618*bc)
xa_u := aY - (f886*xa)
else if type == 3 // Butterfly
bc_u := cY - (f1618*bc)
bc_l := cY - (f2618*bc)
xa_u := aY - (f1272*xa)
xa_l := aY - (f1618*xa)
else if type == 4 // Crab
bc_u := cY - (2.24*bc)
bc_l := cY - (3.618*bc)
xa_u := aY - (f1618*xa)
else if type == 5 // Shark
bc_u := cY - (f1618*bc)
bc_l := cY - (2.24*bc)
xa_u := aY - (f886*xa)
xa_l := aY - (1.13*xa)
else if type == 6 // Cypher
xa_u := cY - (f786*xc) // cypher uses retracement of XC
// if type==6
// xa_u := xa_u > 0 ? xa_u : 0
// else
// bc_u := bc_u > 0 ? bc_u : 0
// bc_l := bc_l > 0 ? bc_l : 0
// xa_u := xa_u > 0 ? xa_u : 0
// if not na(xa_l)
// xa_l := xa_l > 0 ? xa_l : 0
[bc_u, bc_l, xa_u, xa_l]
// @function Get the confluent PRZ levels (i.e. the two closest PRZ levels)
//
// Order of arguments does not matter
// @param l1 level 1 (float)
// @param l2 level 2 (float)
// @param l3 level 3 (float)
// @param l4 level 4 (optional, float)
//
// @returns [lL,lH]
// lL = lower confluent PRZ level
// lH = higher confluent PRZ level
//
export harmonic_xabcd_przClosest(float l1=na, float l2=na, float l3=na, float l4=na) =>
float lL = na, float lH = na
a = array.new_float(0)
if not na(l1)
array.push(a,l1)
if not na(l2)
array.push(a,l2)
if not na(l3)
array.push(a,l3)
if not na(l4)
array.push(a,l4)
if array.size(a) == 1
lL := array.get(a,0)
lH := array.get(a,0)
else if array.size(a) == 2
lL := array.min(a)
lH := array.max(a)
else if array.size(a) > 2
array.sort(a)
lL := array.get(a,0)
lH := array.get(a,1)
ld = lH - lL
if array.get(a,2) - array.get(a,1) < ld
ld := array.get(a,2) - array.get(a,1)
lL := array.get(a,1)
lH := array.get(a,2)
if array.size(a) == 4
if array.get(a,3) - array.get(a,2) < ld
ld := array.get(a,3) - array.get(a,2)
lL := array.get(a,2)
lH := array.get(a,3)
[lL,lH]
// @function Get upper and lower PRZ levels
export harmonic_xabcd_przRange(float l1,float l2=na,float l3=na,float l4=na) =>
a = array.from(l1,l2,l3,l4)
[array.max(a),array.min(a)]
// @function Measure closeness of D to either of the two closest PRZ levels, relative to height of the XA leg
export harmonic_xabcd_eD(float cpl1,float cpl2,float xY,float aY,float dY) =>
h = math.abs(aY-xY)
dCpl = math.abs(cpl1-dY) > math.abs(cpl2-dY) ? math.abs(cpl2-dY) : math.abs(cpl1-dY)
dCpl/h
// @function Measure the closeness of the two closest PRZ levels, relative to the height of the XA leg
export harmonic_xabcd_przScore(float xY,float aY,float l1=na,float l2=na,float l3=na,float l4=na) =>
h = math.abs(aY-xY)
[v1,v2] = harmonic_xabcd_przClosest(l1,l2,l3,l4)
// score = closeness of the two closest PRZ levels (% relative XA height)
score = 1 - ((v2-v1)/h)
[score, v1, v2]
// @function Get the ratio of two pattern legs, and the percent error from the theoretical harmonic ratio
//
// Order of arguments does not matter
// @param type Harmonic pattern type (int - 1 = Gartley, 2 = Bat, 3 = Butterfly, 4 = Crab)
// @param l Leg ID ("xab", "abc", "bcd", or "xad") (string)
// @param l1 Line 1 height (float)
// @param l2 Line 2 height (float)
//
// @returns [r,e]
//
export harmonic_xabcd_rAndE(int type, string l, float l1, float l2) =>
var f1618 = fib.fib_precise(1.618)
var f2618 = fib.fib_precise(2.618)
var f786 = fib.fib_precise(0.786)
var f886 = fib.fib_precise(0.886)
var f1272 = fib.fib_precise(1.272)
var f618 = fib.fib_precise(0.618)
var f382 = fib.fib_precise(0.382)
var f1414 = fib.fib_precise(1.414)
float r = na
float e = na
if l=="xab"
r := math.abs(l1)/math.abs(l2)
e := switch type
1 => math.abs(1-(r/f618))
2 => math.min(math.abs(1-(r/f382)),math.abs(1-(r/.5)))
3 => math.abs(1-(r/f786))
4 => math.min(math.abs(1-(r/f382)),math.abs(1-(r/f618)))
5 => na
6 => math.min(math.abs(1-(r/f382)),math.abs(1-(r/f618)))
else if l=="abc"
r := math.abs(l1)/math.abs(l2)
e := switch type
5 => math.min(math.abs(1-(r/1.13)),math.abs(1-(r/f1618)))
6 => math.min(math.abs(1-(r/f1272)),math.abs(1-(r/f1414)))
=> math.min(math.abs(1-(r/f382)),math.abs(1-(r/f886)))
else if l=="bcd"
r := math.abs(l1)/math.abs(l2)
e := switch type
1 => math.min(math.abs(1-(r/f1272)),math.abs(1-(r/f1618)))
2 => math.min(math.abs(1-(r/f1618)),math.abs(1-(r/f2618)))
3 => math.min(math.abs(1-(r/f1618)),math.abs(1-(r/f2618)))
4 => math.min(math.abs(1-(r/2.24)),math.abs(1-(r/3.618)))
5 => math.min(math.abs(1-(r/f1618)),math.abs(1-(r/2.24)))
6 => na
else if l=="xad"
r := math.abs(l1)/math.abs(l2)
e := switch type
1 => math.abs(1-(r/f786))
2 => math.abs(1-(r/f886))
3 => math.min(math.abs(1-(r/f1272)),math.abs(1-(r/f1618)))
4 => math.abs(1-(r/f1618))
5 => math.min(math.abs(1-(r/f886)),math.abs(1-(r/1.13)))
6 => math.abs(1-(r/f786))
[r,e]
// @function Get the avg retracement ratio % error
export harmonic_xabcd_eAvg(float xbre,float acre,float bdre,float xdre,float xcdre=na) =>
r = array.new_float(0)
if not na(xbre)
array.push(r,xbre)
if not na(acre)
array.push(r,acre)
if not na(bdre)
array.push(r,bdre)
if not na(xdre)
array.push(r,xdre)
if not na(xcdre)
array.push(r,xcdre)
array.avg(r)
targetBasis(b,xY,aY,bY,cY,dY) =>
switch b
"AD" => aY-dY
"XA" => aY-xY
"CD" => cY-dY
// map actual target level from param
resolveTarget(tgt,xY,aY,bY,cY,dY) =>
a = str.split(tgt," ")
if array.size(a) == 1
switch tgt
"A" => aY
"B" => bY
"C" => cY
else
r = fib.fib_from_string(array.get(a,0))
b = targetBasis(array.get(a,1),xY,aY,bY,cY,dY)
(b*r + dY) > 0 ? b*r + dY : 0.0
// @function Get the avg asymmetry %
export pat_xabcd_asym(int xX,int aX,int bX,int cX,int dX) =>
if na(dX)
xa = math.abs(1 - ((aX-xX) / (((bX-aX)+(cX-bX))/2)))
ab = math.abs(1 - ((bX-aX) / (((aX-xX)+(cX-bX))/2)))
bc = math.abs(1 - ((cX-bX) / (((aX-xX)+(bX-aX))/2)))
(xa+ab+bc)/3
else
xa = math.abs(1 - ((aX-xX) / (((bX-aX)+(cX-bX)+(dX-cX))/3)))
ab = math.abs(1 - ((bX-aX) / (((aX-xX)+(cX-bX)+(dX-cX))/3)))
bc = math.abs(1 - ((cX-bX) / (((aX-xX)+(bX-aX)+(dX-cX))/3)))
cd = math.abs(1 - ((dX-cX) / (((aX-xX)+(bX-aX)+(cX-bX))/3)))
(xa+ab+bc+cd)/4
// @function Get potential entry levels for a harmonic XABCD pattern
export harmonic_xabcd_entry(bool t, int tp, float xY, float aY, float bY, float cY, float dY=na,
bool e_afterC=true, string e_lvlc="Nearest confluent PRZ level", bool e_afterD=true, float e_lvldPct=1.0) =>
[bcN,bcF,xaN,xaF] = harmonic_xabcd_prz(tp,xY,aY,bY,cY)
[lPrz,hPrz] = harmonic_xabcd_przClosest(bcN,bcF,xaN,xaF)
[u,l] = harmonic_xabcd_przRange(bcN,bcF,xaN,xaF)
float afterD = na
float afterC = na
if e_afterD
afterD := if na(dY)
na
else
t ? dY * (1 + e_lvldPct/100) : dY * (1 - e_lvldPct/100)
if e_afterC
afterC := switch e_lvlc
"Nearest confluent PRZ level" => t ? hPrz : lPrz
"Farthest confluent PRZ level" => t ? lPrz : hPrz
"Nearest PRZ level" => t ? u : l
"Farthest PRZ level" => t ? l : u
=> hPrz - ((hPrz-lPrz)/2)
afterD := afterD<0 ? 0 : afterD
afterC := afterC<0 ? 0 : afterC
// if we have a value for both entry params, use the closest one
lvl = if not na(afterD) and not na(afterC)
t ? math.max(afterD,afterC) : math.min(afterD,afterC)
else if not na(afterD)
afterD
else
afterC
// [nearest lvl, after C lvl, after D lvl]
[lvl,afterC,afterD]
// @function Determine if entry level was reached. Assumes pattern is active/not timed out.
export xabcd_entryHit(bool t, float afterC, float afterD, int dX=na,
bool e_afterC=true, bool e_afterD=true, int dValBars=1) =>
int bar = na
float eLvl = na
flag = false
// if allowing entry after point C, check between C and valid point D
if e_afterC and not na(afterC) and (na(dX) or bar_index < (dX+dValBars))
if t and low <= afterC
flag := true
bar := bar_index
eLvl := open>afterC ? afterC : open // if hit from above, entry will be on the target level, else open price
else if t == false and high >= afterC
flag := true
bar := bar_index
eLvl := open<afterC ? afterC : open // if hit from below, entry will be on the target level, else open price
// if we didn't hit entry between C and D and we allow entry after D and we have a valid point D
else if e_afterD and not na(dX) and not na(afterD)
if t and low <= afterD
flag := true
bar := bar_index
eLvl := open>afterD ? afterD : open // if hit from above, entry will be on the target level, else open price
else if t == false and high >= afterD
flag := true
bar := bar_index
eLvl := open<afterD ? afterD : open // if hit from below, entry will be on the target level, else open price
[flag,bar,eLvl]
// (private) Validate AB leg of custom XABCD
test_ab_custom(ab,abx,xa,xab,pErr) =>
rat = ab/xa
na(xab) ? true : rat <= xab*(1+pErr/100) and rat >= xab*(1-pErr/100)
// (private) Validate BC leg of custom XABCD
test_bc_custom(bc,bcx,ab,abc,pErr) =>
rat = bc/ab
na(abc) ? true : rat <= abc*(1+pErr/100) and rat >= abc*(1-pErr/100)
// (private) Validate CD leg of custom XABCD
test_cd_custom(cd,cdx,bc,xa,xc,ad,bcd,xad,xcd,pErr) =>
rat = cd/bc
rat2 = ad/xa
rat3 = cd/xc
// test D against both BC, XA, and/or XC legs
bc_test = na(bcd) ? true : rat <= bcd*(1+pErr/100) and rat >= bcd*(1-pErr/100)
xa_test = na(xad) ? true : rat2 <= xad*(1+pErr/100) and rat2 >= xad*(1-pErr/100)
xc_test = na(xcd) ? true : rat3 <= xcd*(1+pErr/100) and rat2 >= xcd*(1-pErr/100)
bc_test and xa_test and xc_test
// @function Validate custom XABCD pattern
//
// @param xX X coordinate of point X (int)
// @param xY Y coordinate of point X (float)
// @param aX X coordinate of point A (int)
// @param aY Y coordinate of point A (float)
// @param bX X coordinate of point B (int)
// @param bY Y coordinate of point B (float)
// @param cX X coordinate of point C (int)
// @param cY Y coordinate of point C (float)
// @param dX X coordinate of point D (int)
// @param dY Y coordinate of point D (float)
// @param pErr Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
// @param pAsym Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
//
// @returns TRUE if pattern is valid
//
export pat_xabcd_validate(int xX,float xY,int aX,float aY,int bX,float bY,int cX,float cY,int dX,float dY,
float xab, float abc, float bcd, float xad, float xcd=na,float pErr=20,float pAsym=250) =>
xa = math.abs(xY-aY)
xax = math.abs(xX-aX)
ab = math.abs(aY-bY)
abx = math.abs(aX-bX)
bc = math.abs(bY-cY)
bcx = math.abs(bX-cX)
cd = math.abs(cY-dY)
cdx = math.abs(cX-dX)
ad = math.abs(aY-dY)
xc = math.abs(xY-cY)
// Test ΔX symmetry first. If failure, no need to check the ratios.
if pat_xabcd_testSym(xax,abx,bcx,cdx,pAsym) == false
false
else if test_ab_custom(ab,abx,xa,xab,pErr) == false
false
else if test_bc_custom(bc,bcx,ab,abc,pErr) == false
false
else if test_cd_custom(cd,cdx,bc,xa,xc,ad,bcd,xad,xcd,pErr) == false
false
else
true
// @function Validate the first 3 legs of a custom XABCD pattern
//
// @param xX X coordinate of point X (int)
// @param xY Y coordinate of point X (float)
// @param aX X coordinate of point A (int)
// @param aY Y coordinate of point A (float)
// @param bX X coordinate of point B (int)
// @param bY Y coordinate of point B (float)
// @param cX X coordinate of point C (int)
// @param cY Y coordinate of point C (float)
// @param pErr Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
// @param pAsym Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
//
// @returns TRUE if first 3 legs are valid
//
export pat_xabcd_validateIncomplete(int xX,float xY,int aX,float aY,int bX,float bY,int cX,float cY,float xab, float abc,float pErr=30,float pAsym=250) =>
xa = math.abs(xY-aY)
xax = math.abs(xX-aX)
ab = math.abs(aY-bY)
abx = math.abs(aX-bX)
bc = math.abs(bY-cY)
bcx = math.abs(bX-cX)
// Test ΔX symmetry first. If failure, no need to check the ratios.
if pat_xabcd_testSym(xax,abx,bcx,na,pAsym) == false
false
else if test_ab_custom(ab,abx,xa,xab,pErr) == false
false
else if test_bc_custom (bc,bcx,ab,abc,pErr) == false
false
else
true
// @function Get the potential reversal zone (PRZ) levels of a custom XABCD pattern
//
// @param xY Y coordinate of point X (float)
// @param aY Y coordinate of point A (float)
// @param bY Y coordinate of point B (float)
// @param cY Y coordinate of point C (float)
//
// @returns [xad_lvl,bcd_lvl,xcd_lvl]
//
export pat_xabcd_prz(float xY, float aY, float bY, float cY, float xad, float bcd, float xcd=na) =>
float xad_lvl = na
float bcd_lvl = na
float xcd_lvl = na
bc = cY-bY
xa = aY-xY
xc = cY-xY
xad_lvl := aY - (xad*xa)
xcd_lvl := cY - (xcd*xc)
bcd_lvl := cY - (bcd*bc)
[xad_lvl,bcd_lvl,xcd_lvl]
//@function Get the average deviation of an XABCD pattern
export pat_xabcd_avgDev(int xX, float xY, int aX, float aY, int bX, float bY, int cX, float cY,int dX=na,float dY=na) =>
float dev = na
if bar_index - xX < 500 // can't check more than 500 bars back
a = array.new_float(0)
[xa_slope,xa_yInt] = alg.line_fromXy(xX,xY,aX,aY)
i1 = (bar_index - aX) + 1
i2 = (bar_index - xX) - 1
for i=i1 to i2
p = alg.line_getPrice(bar_index-i,xa_slope,xa_yInt)
diff = math.max(math.abs(p-low[i]),math.abs(high[i]-p))
array.push(a,diff)
[ab_slope,ab_yInt] = alg.line_fromXy(aX,aY,bX,bY)
i1 := (bar_index - bX) + 1
i2 := (bar_index - aX) - 1
for i=i1 to i2
p = alg.line_getPrice(bar_index-i,ab_slope,ab_yInt)
diff = math.max(math.abs(p-low[i]),math.abs(high[i]-p))
array.push(a,diff)
[bc_slope,bc_yInt] = alg.line_fromXy(bX,bY,cX,cY)
i1 := (bar_index - cX) + 1
i2 := (bar_index - bX) - 1
for i=i1 to i2
p = alg.line_getPrice(bar_index-i,bc_slope,bc_yInt)
diff = math.max(math.abs(p-low[i]),math.abs(high[i]-p))
array.push(a,diff)
if not na(dX)
[cd_slope,cd_yInt] = alg.line_fromXy(cX,cY,dX,dY)
i1 := (bar_index - dX) + 1
i2 := (bar_index - cX) - 1
for i=i1 to i2
p = alg.line_getPrice(bar_index-i,cd_slope,cd_yInt)
diff = math.max(math.abs(p-low[i]),math.abs(high[i]-p))
array.push(a,diff)
dev := array.avg(a)
dev
height(xY,aY,cY,dY) =>
if xY < aY
math.max(aY,cY) - math.min(xY,dY)
else
math.max(xY,dY) - math.min(aY,cY)
//@function Get score values for a pattern
export harmonic_xabcd_score(int tp, int xX, float xY, int aX, float aY, int bX, float bY, int cX, float cY,int dX=na,float dY=na) =>
[_,xbre] = harmonic_xabcd_rAndE(tp,"xab",aY-bY,aY-xY)
[_,acre] = harmonic_xabcd_rAndE(tp,"abc",cY-bY,aY-bY)
[_,bdre] = harmonic_xabcd_rAndE(tp,"bcd",cY-dY,cY-bY)
[_,xdre] = harmonic_xabcd_rAndE(tp,"xad", tp==6 ? cY-dY : aY-dY, tp==6 ? cY-xY : aY-xY)
[bcN,bcF,xaN,xaF] = harmonic_xabcd_prz(tp,xY,aY,bY,cY)
[przscore,cpl1,cpl2] = harmonic_xabcd_przScore(xY,aY,bcN,bcF,xaN,xaF)
eavg = harmonic_xabcd_eAvg(xbre,acre,bdre,xdre)
asym = pat_xabcd_asym(xX,aX,bX,cX,dX)
eD = harmonic_xabcd_eD(cpl1,cpl2,xY,aY,dY)
dev = 1 - (pat_xabcd_avgDev(xX,xY,aX,aY,bX,bY,cX,cY,dX,dY)/height(xY,aY,cY,dY))
[eavg,asym,eD,przscore,dev,cpl1,cpl2]
// @function Get total weighted score value for a pattern
export harmonic_xabcd_scoreTot(float asym, float eavg, float przscore, float eD, int tp, float w_a, float w_e, float w_p, float w_d)=>
if not na(eD)
if tp==6 // PRZ confluence doesn't apply to Cypher pattern (only XA retracement defined)
((1-asym)*w_a + (1-eavg)*w_e + (1-eD)*w_d)/(w_a+w_e+w_d)
else
((1-asym)*w_a + (1-eavg)*w_e + przscore*w_p + (1-eD)*w_d)/(w_a+w_e+w_p+w_d)
else // else incomplete pattern score
if tp==6
((1-asym)*w_a + (1-eavg)*w_e)/(w_a+w_e)
else
((1-asym)*w_a + (1-eavg)*w_e + przscore*w_p)/(w_a+w_e+w_p)
// @function Get target level
export harmonic_xabcd_targets(float xY,float aY,float bY,float cY,float dY,string tgt1,string tgt2=na,string tgt3=na) =>
t1 = resolveTarget(tgt1,xY,aY,bY,cY,dY)
t2 = na(tgt2) ? na : resolveTarget(tgt2,xY,aY,bY,cY,dY)
t3 = na(tgt3) ? na : resolveTarget(tgt3,xY,aY,bY,cY,dY)
[t1,t2,t3]
// @function Get stop level
export harmonic_xabcd_stop(string stop, float stopPct, bool bull, float xY, float dY, float upper, float lower, float t1, float eY) =>
e = na(eY) ? dY : eY
if bull
switch stop
"% beyond Point D" => dY * (1-stopPct/100) > 0 ? dY * (1-stopPct/100) : 0.0
"% beyond X or D" => math.min(xY,dY) * (1-stopPct/100) > 0 ? math.min(xY,dY) * (1-stopPct/100) : 0.0
"% beyond entry" => e * (1-stopPct/100) > 0 ? e * (1-stopPct/100) : 0.0
"% of distance to target 1, beyond entry" => e - (stopPct/100)*(t1-e) > 0 ? e - (stopPct/100)*(t1-e) : 0.0
=> lower * (1-stopPct/100) > 0 ? lower * (1-stopPct/100) : 0.0
else
switch stop
"% beyond Point D" => dY * (1+stopPct/100)
"% beyond X or D" => math.max(xY,dY) * (1+stopPct/100)
"% beyond entry" => e * (1+stopPct/100)
"% of distance to target 1, beyond entry" => e + (stopPct/100)*(e-t1)
=> upper * (1+stopPct/100)
// @function Get fib ratio display text
export harmonic_xabcd_fibDispTxt(int tp) =>
rb = switch tp
1 => "0.618"
2 => "0.382 | 0.5"
3 => "0.786"
4 => "0.382 | 0.618"
5 => "NA"
6 => "0.382 | 0.618"
//
rc = switch tp
1 => "0.382 | 0.886"
2 => "0.382 | 0.886"
3 => "0.382 | 0.886"
4 => "0.382 | 0.886"
5 => "1.13 | 1.618"
6 => "1.272 | 1.414"
//
rd1 = switch tp
1 => "1.272 | 1.618"
2 => "1.618 | 2.618"
3 => "1.618 | 2.618"
4 => "2.24 | 3.618"
5 => "1.618 | 2.24"
6 => "NA"
//
rd2 = switch tp
1 => "0.786"
2 => "0.886"
3 => "1.272 | 1.618"
4 => "1.618"
5 => "0.886 | 1.13"
6 => "0.786"
[rb,rc,rd1,rd2]
// @function Get pattern symbol
export harmonic_xabcd_symbol(int tp) =>
switch tp
1 => "Ɠ"
2 => "🦇"
3 => "🦋"
4 => "🦀"
5 => "🦈"
6 => "Ƈ"
=> ""
//-----------------------------------------
// Patterns
//-----------------------------------------
// @function Determine if an XABCD pattern has just completed (i.e. point D is on the previous bar)
// @param x_is_low Flag to determine if point X is a low pivot, i.e. bullish pattern (bool, dft = true)
// @param pivot_length Number of bars before and after a valid pivot (int, dft = 5)
// @param source Source series (float, dft = na, will use high and low series)
// @param conf_length Number of trailing bars after pivot point D to confirm a valid pattern (int, dft = 1)
// @param incomplete Flag to return an incomplete XABC pattern (bool, dft = false)
// @returns [flag,xx,xy,ax,ay,bx,by,cx,cy,dx,dy]
// flag = true if valid XABCD pattern completed on previous bar
// xx = X coordinate of point X (int)
// xy = Y coordinate of point X (float)
// ax = X coordinate of point A (int)
// ay = Y coordinate of point A (float)
// bx = X coordinate of point B (int)
// by = Y coordinate of point B (float)
// cx = X coordinate of point C (int)
// cy = Y coordinate of point C (float)
// dx = X coordinate of point D (int)
// dy = Y coordinate of point D (float)
//
export pat_xabcd(bool x_is_low=true, int pivot_length=5, float source = na, int conf_length=1, bool incomplete=false) =>
r_flag = false
x = -1, a = -1, b = -1, c = -1, d = -1
x_y=0.0, a_y=0.0, b_y=0.0, c_y=0.0, d_y=0.0
lb = pivot_length * 30 > bar_index ? bar_index : pivot_length * 30
hsrc = na(source) ? high : source
lsrc = na(source) ? low : source
pl = ta.pivotlow(lsrc,pivot_length,pivot_length)
ph = ta.pivothigh(hsrc,pivot_length,pivot_length)
lbLow = ta.pivotlow(lsrc,pivot_length,conf_length)
lbHigh = ta.pivothigh(hsrc,pivot_length,conf_length)
hSince = 0.0
lSince = 0.0
// Check for bullish XABCD
if x_is_low
if not na(lbLow) or incomplete // *** Valid D ***
d := incomplete ? -1 : bar_index - conf_length
d_y := incomplete ? 0.0 : lbLow
for i=(incomplete?0:conf_length) to pivot_length
if hsrc[i] > hSince // get highest between D and first potential pivot
hSince := hsrc[i]
if lsrc[i] < lSince or lSince == 0 // get lowest between D and first potential pivot
lSince := lsrc[i]
// Loop back to look for points C, B, A, and X
for i=0 to lb
if hsrc[i+pivot_length] > hSince // highest since last valid pivot
hSince := hsrc[i+pivot_length]
if lsrc[i+pivot_length] < lSince or lSince == 0 // lowest since last valid pivot
lSince := lsrc[i+pivot_length]
if c == -1 // *** Find C ***
if not na(pl[i]) // next pivot is low
if pl[i] < d_y // if low is lower than D, pattern is invalid (else skip to next bar)
break
else if not na(ph[i]) // next pivot is high
if ph[i] < d_y // if high is lower than D, pattern is invalid
break
else if hSince > ph[i] // if higher intermediate high (not valid pivot), pattern is invalid
break
else // else valid pivot high, valid C
c := bar_index - i - pivot_length
c_y := ph[i]
hSince := 0.0
lSince := 0.0
else if incomplete
break
else if b == -1 // *** Find B ***
if not na(ph[i]) // next pivot is high
if ph[i] > c_y // if high is higher than C, pattern is invalid (else skip to next bar)
break
else if not na(pl[i]) // next pivot is low
if pl[i] > c_y // if low is higher than C, pattern is invalid
break
else if lSince < pl[i] // if lower intermediate low (not valid pivot), pattern is invalid
break
else // else valid pivot low, valid B
b := bar_index - i - pivot_length
b_y := pl[i]
hSince := 0.0
lSince := 0.0
else if a == -1 // *** Find A ***
if not na(pl[i]) // next pivot is low
if pl[i] < b_y // if low is lower than B, pattern is invalid (else skip to next bar)
break
else if not na(ph[i]) // next pivot is high
if ph[i] < b_y // if high is lower than B, pattern is invalid
break
else if hSince > ph[i] // if higher intermediate high (not valid pivot), pattern is invalid
break
else // else valid pivot high, valid A
a := bar_index - i - pivot_length
a_y := ph[i]
hSince := 0.0
lSince := 0.0
else if x == -1 // *** Find X ***
if not na(ph[i]) // next pivot is high
if ph[i] > a_y // if high is higher than A, pattern is invalid (else skip to next bar)
break
else if not na(pl[i]) // next pivot is low
if pl[i] > a_y // if low is higher than A, pattern is invalid
break
else if lSince < pl[i] // if lower intermediate low (not valid pivot), pattern is invalid
break
else // else valid pivot low, valid X
r_flag := true // valid XABCD pattern
x := bar_index - i - pivot_length
x_y := pl[i]
break
// Check for bearish XABCD
else
if not na(lbHigh) or incomplete // *** Valid D ***
d := incomplete ? -1 : bar_index - conf_length
d_y := incomplete ? 0.0 : lbHigh
for i=(incomplete?0:conf_length) to pivot_length
if hsrc[i] > hSince // get highest between D and first potential pivot
hSince := hsrc[i]
if lsrc[i] < lSince or lSince == 0 // get lowest between D and first potential pivot
lSince := lsrc[i]
// Loop back to look for points C, B, A, and X
for i=0 to lb
if hsrc[i+pivot_length] > hSince // highest since last valid pivot
hSince := hsrc[i+pivot_length]
if lsrc[i+pivot_length] < lSince or lSince == 0 // lowest since last valid pivot
lSince := lsrc[i+pivot_length]
if c == -1 // *** Find C ***
if not na(ph[i]) // next pivot is high
if ph[i] > d_y and incomplete==false // if high is higher than D, pattern is invalid (else skip to next bar)
break
else if not na(pl[i]) // next pivot is low
if pl[i] > d_y and incomplete==false // if low is higher than D, pattern is invalid
break
else if lSince < pl[i] // if lower intermediate low (not valid pivot), pattern is invalid
break
else // else valid pivot low, valid C
c := bar_index - i - pivot_length
c_y := pl[i]
hSince := 0.0
lSince := 0.0
else if incomplete
break
else if b == -1 // *** Find B ***
if not na(pl[i]) // next pivot is low
if pl[i] < c_y // if low is lower than C, pattern is invalid (else skip to next bar)
break
else if not na(ph[i]) // next pivot is high
if ph[i] < c_y // if high is lower than C, pattern is invalid
break
else if hSince > ph[i] // if higher intermediate high (not valid pivot), pattern is invalid
break
else // else valid pivot high, valid B
b := bar_index - i - pivot_length
b_y := ph[i]
hSince := 0.0
lSince := 0.0
else if a == -1 // *** Find A ***
if not na(ph[i]) // next pivot is high
if ph[i] > b_y // if high is higher than B, pattern is invalid (else skip to next bar)
break
else if not na(pl[i]) // next pivot is low
if pl[i] > b_y // if low is higher than B, pattern is invalid
break
else if lSince < pl[i] // if lower intermediate low (not valid pivot), pattern is invalid
break
else // else valid pivot low, valid A
a := bar_index - i - pivot_length
a_y := pl[i]
hSince := 0.0
lSince := 0.0
else if x == -1 // *** Find X ***
if not na(pl[i]) // next pivot is low
if pl[i] < a_y // if low is lower than A, pattern is invalid (else skip to next bar)
break
else if not na(ph[i]) // next pivot is high
if ph[i] < a_y // if high is lower than A, pattern is invalid
break
else if hSince > ph[i] // if higher intermediate high (not valid pivot), pattern is invalid
break
else // else valid pivot high, valid X
r_flag := true // valid XABCD pattern
x := bar_index - i - pivot_length
x_y := ph[i]
break
[r_flag,x,x_y,a,a_y,b,b_y,c,c_y,d,d_y]
//***
// find_pattern() =>
// [f,xX,xY,aX,aY,bX,bY,cX,cY,dX,dY] = pat_xabcd(true,3,incomplete=true)
// // if aX >= 0
// // u.print(str.tostring(aX),at_index=9110)
// // u.print(str.tostring(bX),position.bottom_right,at_index=9110)
// // u.print(str.tostring(cX),position.middle_right,at_index=9110)
// // u.print(str.tostring(dX),position.middle_center,at_index=9110)
// // if pat_xabcd_validateIncomplete(aX,aY,bX,bY,cX,cY,dX,dY,0.618,1.414,15.0,250.0)
// // ""
// find_pattern()
// @function Determine if an XABCD pattern is in progress (point C was just confirmed)
// @param x_is_low Flag to determine if point X is a low pivot, i.e. bullish M pattern (bool, dft = true)
// @param pivot_length Number of bars before and after a valid pivot (int, dft = 5)
// @param source Source series (float, dft = na, will use high and low series)
// @param conf_length Number of trailing bars after pivot point D to confirm a valid pattern (int, dft = 1)
// @returns [flag,xx,xy,ax,ay,bx,by,cx,cy]
// flag = true if valid XABC pattern completed on bar_index[conf_length]
// xx = X coordinate of point X (int)
// xy = Y coordinate of point X (float)
// ax = X coordinate of point A (int)
// ay = Y coordinate of point A (float)
// bx = X coordinate of point B (int)
// by = Y coordinate of point B (float)
// cx = X coordinate of point C (int)
// cy = Y coordinate of point C (float)
// dx = X coordinate of point D (int)
// dy = Y coordinate of point D (float)
//
export pat_xabcdIncomplete(bool x_is_low=true, int pivot_length=5, float source = na, int conf_length=1) =>
r_flag = false
x = -1, a = -1, b = -1, c = -1
x_y=0.0, a_y=0.0, b_y=0.0, c_y=0.0
lb = pivot_length * 25 > bar_index ? bar_index : pivot_length * 25
hsrc = na(source) ? high : source
lsrc = na(source) ? low : source
pl = ta.pivotlow(lsrc,pivot_length,pivot_length)
ph = ta.pivothigh(hsrc,pivot_length,pivot_length)
confLow = ta.pivotlow(lsrc,pivot_length,conf_length)
confHigh = ta.pivothigh(hsrc,pivot_length,conf_length)
hSince = 0.0
lSince = 0.0
int start = na
float highest = na
float lowest = na
// Check for bullish XABC
if x_is_low
for i=0 to pivot_length
if na(highest) or high[i] > highest
highest := high[i]
if not na(confHigh[i])
if confHigh[i] >= highest
c := bar_index[conf_length+i]
c_y := confHigh[i]
start := conf_length + i
break
if c > -1 // *** Valid C ***
for i=start to pivot_length
if hsrc[i] > hSince // get highest between C and first potential pivot
hSince := hsrc[i]
if lsrc[i] < lSince or lSince == 0 // get lowest between C and first potential pivot
lSince := lsrc[i]
// Loop back to look for points B, A, and X
for i=start to lb
if hsrc[i+pivot_length] > hSince // highest since last valid pivot
hSince := hsrc[i+pivot_length]
if lsrc[i+pivot_length] < lSince or lSince == 0 // lowest since last valid pivot
lSince := lsrc[i+pivot_length]
if b == -1 // *** Find B ***
if hSince > c_y
break
else if not na(ph[i]) // next pivot is high
if ph[i] > c_y // if high is higher than C, pattern is invalid (else skip to next bar)
break
else if not na(pl[i]) // next pivot is low
if pl[i] > c_y // if low is higher than C, pattern is invalid
break
else if lSince < pl[i] // if lower intermediate low (not valid pivot), pattern is invalid
break
else // else valid pivot low, valid B
b := bar_index - i - pivot_length
b_y := pl[i]
hSince := 0.0
lSince := 0.0
else if a == -1 // *** Find A ***
if lSince < b_y
break
else if not na(pl[i]) // next pivot is low
if pl[i] < b_y // if low is lower than B, pattern is invalid (else skip to next bar)
break
else if not na(ph[i]) // next pivot is high
if ph[i] < b_y // if high is lower than B, pattern is invalid
break
else if hSince > ph[i] // if higher intermediate high (not valid pivot), pattern is invalid
break
else // else valid pivot high, valid A
a := bar_index - i - pivot_length
a_y := ph[i]
hSince := 0.0
lSince := 0.0
else if x == -1 // *** Find X ***
if hSince > a_y
break
else if not na(ph[i]) // next pivot is high
if ph[i] > a_y // if high is higher than A, pattern is invalid (else skip to next bar)
break
else if not na(pl[i]) // next pivot is low
if pl[i] > a_y // if low is higher than A, pattern is invalid
break
else if lSince < pl[i] // if lower intermediate low (not valid pivot), pattern is invalid
break
else // else valid pivot low, valid X
r_flag := true // valid XABCD pattern
x := bar_index - i - pivot_length
x_y := pl[i]
break
// Check for bearish XABC
else
for i=0 to pivot_length
if na(lowest) or low[i] < lowest
lowest := low[i]
if not na(confLow[i])
if confLow[i] <= lowest
c := bar_index[conf_length+i]
c_y := confLow[i]
start := conf_length + i
break
if c > -1 // *** Valid C ***
for i=start to pivot_length
if hsrc[i] > hSince // get highest between C and first potential pivot
hSince := hsrc[i]
if lsrc[i] < lSince or lSince == 0 // get lowest between C and first potential pivot
lSince := lsrc[i]
// Loop back to look for points B, A, and X
for i=start to lb
if hsrc[i+pivot_length] > hSince // highest since last valid pivot
hSince := hsrc[i+pivot_length]
if lsrc[i+pivot_length] < lSince or lSince == 0 // lowest since last valid pivot
lSince := lsrc[i+pivot_length]
if b == -1 // *** Find B ***
if lSince < c_y
break
else if not na(pl[i]) // next pivot is low
if pl[i] < c_y // if low is lower than C, pattern is invalid (else skip to next bar)
break
else if not na(ph[i]) // next pivot is high
if ph[i] < c_y // if high is lower than C, pattern is invalid
break
else if hSince > ph[i] // if higher intermediate high (not valid pivot), pattern is invalid
break
else // else valid pivot high, valid B
b := bar_index - i - pivot_length
b_y := ph[i]
hSince := 0.0
lSince := 0.0
else if a == -1 // *** Find A ***
if hSince > b_y
break
else if not na(ph[i]) // next pivot is high
if ph[i] > b_y // if high is higher than B, pattern is invalid (else skip to next bar)
break
else if not na(pl[i]) // next pivot is low
if pl[i] > b_y // if low is higher than B, pattern is invalid
break
else if lSince < pl[i] // if lower intermediate low (not valid pivot), pattern is invalid
break
else // else valid pivot low, valid A
a := bar_index - i - pivot_length
a_y := pl[i]
hSince := 0.0
lSince := 0.0
else if x == -1 // *** Find X ***
if lSince < a_y
break
else if not na(pl[i]) // next pivot is low
if pl[i] < a_y // if low is lower than A, pattern is invalid (else skip to next bar)
break
else if not na(ph[i]) // next pivot is high
if ph[i] < a_y // if high is lower than A, pattern is invalid
break
else if hSince > ph[i] // if higher intermediate high (not valid pivot), pattern is invalid
break
else // else valid pivot high, valid X
r_flag := true // valid XABCD pattern
x := bar_index - i - pivot_length
x_y := ph[i]
break
[r_flag,x,x_y,a,a_y,b,b_y,c,c_y]
//-----------------------------------------
// General functions
//-----------------------------------------
// @function Determine if trade is successful
//
// @param eX Entry bar index (int)
// @param stop Stop level (float)
// @param t1 Target 1 level (float)
// @param t2 Target 2 level (float)
//
// @returns [t1Hit,t2Hit,t1x,t1y,t2x,t2y]
//
export success(int eX, float stop, float t1, float t2=na) =>
bool t1Hit = na
bool t2Hit = na
int t1x = na
float t1y = na
int t2x = na
float t2y = na
n = bar_index - eX
for i = 0 to n
if stop < t1 // long
// i==0 is entry bar, check that target wasn't hit before entry. Can't actually do this with historical bar data,
// but checking open/close in relation to the target covers most scenarios.
if high[n-i] >= t2 and not na(t2) and (i!=0 or open[n-i]<t2 or close[n-i]>=t2)
t1x := bar_index-(n-i)
t1y := t1
t2x := bar_index-(n-i)
t2y := t2
t1Hit := true
t2Hit := true
break
else if high[n-i] >= t1 and (i!=0 or open[n-i]<t1 or close[n-i]>=t2)
t1x := bar_index-(n-i)
t1y := t1
t1Hit := true
else if low[n-i] < stop and (i!=0 or open[n-i]>stop or close[n-i]<=stop)
t1Hit := t1Hit ? true : false
t2Hit := false
if t1Hit==false
t1x := bar_index-(n-i)
t1y := stop
break
else
if low[n-i] <= t2 and not na(t2) and (i!=0 or open[n-i]>t2 or close[n-i]<=t2)
t1x := bar_index-(n-i)
t1y := t1
t2x := bar_index-(n-i)
t2y := t2
t1Hit := true
t2Hit := true
break
else if low[n-i] <= t1 and (i!=0 or open[n-i]>t1 or close[n-i]<=t1)
t1x := bar_index-(n-i)
t1y := t1
t1Hit := true
else if high[n-i] > stop and (i!=0 or open[n-i]<stop or close[n-i]>=stop)
t1Hit := t1Hit ? true : false
t2Hit := false
if t1Hit==false
t1x := bar_index-(n-i)
t1y := stop
break
[t1Hit,t2Hit,t1x,t1y,t2x,t2y]
// @function Determine if Target or Stop was hit on the current bar
export tradeClosed(int eX, float eY, float stop, bool t1h, bool t2h, float t1, float t2=na) =>
bool t1Hit = na
bool t2Hit = na
bool sHit = na
int t1x = na
float t1y = na
int t2x = na
float t2y = na
if stop < t1 // long
// If on entry bar, check that target wasn't hit before entry. Can't actually do this with historical bar data,
// but checking open/close in relation to the target covers most scenarios.
if na(t2h) and high >= t2 and not na(t2) and (bar_index!=eX or open<eY or close>=t2)
t1x := bar_index
t1y := t1
t2x := bar_index
t2y := t2
t1Hit := true
t2Hit := true
else if na(t1h) and high >= t1 and (bar_index!=eX or open<eY or close>=t1)
t1x := bar_index
t1y := t1
t1Hit := true
else if (na(t2h) or t2h==false) and low < stop and (bar_index!=eX or open>stop or close<=stop)
sHit := true
t1Hit := t1Hit or t1h ? true : false
t2Hit := false
if t1Hit==false
t1x := bar_index
t1y := stop
else
t1Hit := t1h
t2Hit := t2h
else
if na(t2h) and low <= t2 and not na(t2) and (bar_index!=eX or open>eY or close<=t2)
t1x := bar_index
t1y := t1
t2x := bar_index
t2y := t2
t1Hit := true
t2Hit := true
else if na(t1h) and low <= t1 and (bar_index!=eX or open>eY or close<=t1)
t1x := bar_index
t1y := t1
t1Hit := true
else if (na(t2h) or t2h==false) and high > stop and (bar_index!=eX or open<stop or close>=stop)
sHit := true
t1Hit := t1Hit or t1h ? true : false
t2Hit := false
if t1Hit==false
t1x := bar_index
t1y := stop
else
t1Hit := t1h
t2Hit := t2h
[t1Hit,t2Hit,sHit,t1x,t1y,t2x,t2y]
|
MYX_LEAP_DB | https://www.tradingview.com/script/8iLqeIzE-MYX-LEAP-DB/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description TODO: Library for Malaysia LEAP Market
library('MYX_LEAP_DB')
// ————————————————————————————————————————————————————————————————————————————— db {
// @function TODO: Library for Malaysia LEAP Market
// @param x TODO: id
// @returns TODO: id
export db(string[] id) =>
array.push(id, '1TECH') // 0
array.push(id, 'ACEINNO') // 1
array.push(id, 'AMLEX') // 2
array.push(id, 'AORB') // 3
array.push(id, 'ASTRA') // 4
array.push(id, 'AURORA') // 5
array.push(id, 'BABA') // 6
array.push(id, 'BVLH') // 7
array.push(id, 'CARZO') // 8
array.push(id, 'CCIB') // 9
array.push(id, 'CETECH') // 10
array.push(id, 'CLOUD') // 11
array.push(id, 'CRG') // 12
array.push(id, 'DSR') // 13
array.push(id, 'DYNAFNT') // 14
array.push(id, 'ENEST') // 15
array.push(id, 'ETH') // 16
array.push(id, 'FBBHD') // 17
array.push(id, 'GPP') // 18
array.push(id, 'ICTZONE') // 19
array.push(id, 'IDBTECH') // 20
array.push(id, 'JISHAN') // 21
array.push(id, 'LSH') // 22
array.push(id, 'MCOM') // 23
array.push(id, 'MFGROUP') // 24
array.push(id, 'MHCARE') // 25
array.push(id, 'MMIS') // 26
array.push(id, 'MPSOL') // 27
array.push(id, 'NP') // 28
array.push(id, 'NPS') // 29
array.push(id, 'POLYDM') // 30
array.push(id, 'REDIDEA') // 31
array.push(id, 'RGS') // 32
array.push(id, 'RPLANET') // 33
array.push(id, 'RTSTECH') // 34
array.push(id, 'SEERS') // 35
array.push(id, 'SGBHD') // 36
array.push(id, 'SKHAWK') // 37
array.push(id, 'SLIC') // 38
array.push(id, 'SMILE') // 39
array.push(id, 'SNOWFIT') // 40
array.push(id, 'SUNMOW') // 41
array.push(id, 'SUPREME') // 42
array.push(id, 'TOPVISN') // 43
array.push(id, 'UNIWALL') // 44
array.push(id, 'UTAMA') // 45
[id]
// } |
DegreeALine | https://www.tradingview.com/script/5Q10DJfV-DegreeALine/ | atazed | https://www.tradingview.com/u/atazed/ | 13 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © atazed
//@version=5
// @description TODO: add library description here
library("DegreeALine",overlay=true)
// @function TODO: add function description here
// @param x1 First X coordinate of a line, index of the bar where the line starts.
// @param y1 First Y coordinate of a line, price on the price scale.
// @param x2 Second X coordinate of a line, index of the bar where the line ends.
// @param y2 Second Y coordinate of a line, price on the price scale.
// @returns Degree Of Line
export Degree(int X1,float Y1,int X2,float Y2) =>
rad2degree = 180 / 3.14159265359
HighRange=ta.highest(close,100)
LowRange=ta.lowest(close,100)
Navasan=((HighRange-LowRange)*100)/LowRange
navasanAlan=((math.abs(Y2 - Y1)*100)/Y1)
NavasaneKoli=(navasanAlan*100)/Navasan
ang = Y2>Y1?rad2degree * math.atan(NavasaneKoli / math.abs(X2-X1)):-1*rad2degree * math.atan(NavasaneKoli / math.abs(X2-X1))
ang
|