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
|
---|---|---|---|---|---|---|---|---|
SAT_LIB | https://www.tradingview.com/script/eawfpdbD-SAT-LIB/ | sosso_bott | https://www.tradingview.com/u/sosso_bott/ | 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/
// © sosso_bott
//@version=5
// @description TODO: This library regroups indicator's functions i use a lot
library("SAT_LIB")
no_rep(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isrealtime ? 1:0])[barstate.isrealtime ? 0 : 1]
// ######################################## RENKO LEVELS ######################################
// @function TODO: RenkoLevels indicator by Mongolor function
// @param upColor1 TODO: (Type: color) renko up color
// @param dnColor1 TODO: (Type: color) renko down color
// @param HIGH TODO: (Type: float)
// @param LOW TODO: (Type: float)
// @param ATR TODO: (Type: float)
// @returns TODO: Renkolevelsfloat
export getRENKOLEVELS(color upColor1, color dnColor1, float HIGH, float LOW, float ATR) =>
float RENKOUP = na
float RENKODN = na
COLOR = color.white
float H = na
float BUY = na
float SELL = na
bool CHANGE = na
RENKOUP := na(RENKOUP[1]) ? ((HIGH+LOW)/2)+(ATR/2) : RENKOUP[1]
RENKODN := na(RENKOUP[1]) ? ((HIGH+LOW)/2)-(ATR/2) : RENKODN[1]
H := na(RENKOUP[1]) or na(RENKODN[1]) ? RENKOUP-RENKODN : RENKOUP[1]-RENKODN[1]
COLOR := na(COLOR[1]) ? color.white : COLOR[1]
BUY := na(BUY[1]) ? 0 : BUY[1]
SELL := na(SELL[1]) ? 0 : SELL[1]
CHANGE := false
renkoState = 0
if(not CHANGE and close >= RENKOUP[1]+H*3)
CHANGE := true
RENKOUP := RENKOUP[1]+ATR*3
RENKODN := RENKOUP[1]+ATR*2
COLOR := upColor1
SELL := 0
BUY := BUY+3
if(not CHANGE and close >= RENKOUP[1]+H*2)
CHANGE := true
RENKOUP := RENKOUP[1]+ATR*2
RENKODN := RENKOUP[1]+ATR
COLOR := upColor1
SELL := 0
BUY := BUY+2
if(not CHANGE and close >= RENKOUP[1]+H)
CHANGE := true
RENKOUP := RENKOUP[1]+ATR
RENKODN := RENKOUP[1]
COLOR := upColor1
SELL := 0
BUY := BUY+1
/////////////// sell \\\\\\\\\\\\\\\\\\\\\
if(not CHANGE and close <= RENKODN[1]-H*3)
CHANGE := true
RENKODN := RENKODN[1]-ATR*3
RENKOUP := RENKODN[1]-ATR*2
COLOR := dnColor1
BUY := 0
SELL := SELL+3
if(not CHANGE and close <= RENKODN[1]-H*2)
CHANGE := true
RENKODN := RENKODN[1]-ATR*2
RENKOUP := RENKODN[1]-ATR
COLOR := dnColor1
BUY := 0
SELL := SELL+2
if(not CHANGE and close <= RENKODN[1]-H)
CHANGE := true
RENKODN := RENKODN[1]-ATR
RENKOUP := RENKODN[1]
COLOR := dnColor1
BUY := 0
SELL := SELL+1
brenko = BUY > 0
srenko = SELL > 0
diff = (RENKOUP - RENKODN) / RENKODN *100
RENKOMID = RENKODN*(1+(diff/200))
EXTRAUP = RENKOUP * (1 + ((RENKOUP - RENKOMID)/RENKOUP))
EXTRADN = RENKODN * (1 - ((RENKOMID - RENKODN)/RENKOMID))
[brenko, srenko, diff, RENKOMID, EXTRAUP, EXTRADN, RENKOUP, RENKODN, COLOR, CHANGE]
// ####################################### RENKO LEVELS END ###################################
// ######################################## RENKO RSI #########################################
// @function TODO: RENKO RSI indicator by @LonesomeTheBlue function
// @param valu TODO: (Type: float)
// @returns TODO: ATR boxSize
export conv_atr(float valu)=>
a = 0
num = syminfo.mintick
s = valu
if na(s)
s := syminfo.mintick
if num < 1
for i = 1 to 20
num := num * 10
if num > 1
break
a := a +1
for x = 1 to a
s := s * 10
s := math.round(s)
for x = 1 to a
s := s / 10
s := s < syminfo.mintick ? syminfo.mintick : s
s
// @function TODO: RENKO RSI indicator by @LonesomeTheBlue function
// @param mode TODO: (Type: string)
// @param atrboxsize TODO: (Type: float)
// @param boxsize TODO: (Type: float)
// @param source TODO: (Type: string)
// @returns TODO: [box, icloseprice, iopenprice, trend]
export boxTreatment(string mode, float atrboxsize, float boxsize, string source) =>
float box = na
box := na(box[1]) ? mode == 'ATR' ? atrboxsize : boxsize : box[1]
reversal = 2
top = 0.0
bottom = 0.0
trend = 0
trend := barstate.isfirst ? 0 : nz(trend[1])
currentprice = 0.0
currentprice := source == 'close' ? close : trend == 1 ? high : low
float beginprice = na
beginprice := barstate.isfirst ? math.floor(open / box) * box : nz(beginprice[1])
iopenprice = 0.0
icloseprice = 0.0
if trend == 0 and box * reversal <= math.abs(beginprice - currentprice)
if beginprice > currentprice
numcell = math.floor(math.abs(beginprice - currentprice) / box)
iopenprice := beginprice
icloseprice := beginprice - numcell * box
trend := -1
if beginprice < currentprice
numcell = math.floor(math.abs(beginprice - currentprice) / box)
iopenprice := beginprice
icloseprice := beginprice + numcell * box
trend := 1
if trend == -1
nok = true
if beginprice > currentprice and box <= math.abs(beginprice - currentprice)
numcell = math.floor(math.abs(beginprice - currentprice) / box)
icloseprice := beginprice - numcell * box
trend := -1
beginprice := icloseprice
nok := false
else
iopenprice := iopenprice == 0 ? nz(iopenprice[1]) : iopenprice
icloseprice := icloseprice == 0 ? nz(icloseprice[1]) : icloseprice
tempcurrentprice = source == 'close' ? close : high
if beginprice < tempcurrentprice and box * reversal <= math.abs(beginprice - tempcurrentprice) and nok //new column
numcell = math.floor(math.abs(beginprice - tempcurrentprice) / box)
iopenprice := beginprice + box
icloseprice := beginprice + numcell * box
trend := 1
beginprice := icloseprice
else
iopenprice := iopenprice == 0 ? nz(iopenprice[1]) : iopenprice
icloseprice := icloseprice == 0 ? nz(icloseprice[1]) : icloseprice
else
if trend == 1
nok = true
if beginprice < currentprice and box <= math.abs(beginprice - currentprice)
numcell = math.floor(math.abs(beginprice - currentprice) / box)
icloseprice := beginprice + numcell * box
trend := 1
beginprice := icloseprice
nok := false
else
iopenprice := iopenprice == 0 ? nz(iopenprice[1]) : iopenprice
icloseprice := icloseprice == 0 ? nz(icloseprice[1]) : icloseprice
tempcurrentprice = source == 'close' ? close : low
if beginprice > tempcurrentprice and box * reversal <= math.abs(beginprice - tempcurrentprice) and nok //new column
numcell = math.floor(math.abs(beginprice - tempcurrentprice) / box)
iopenprice := beginprice - box
icloseprice := beginprice - numcell * box
trend := -1
beginprice := icloseprice
else
iopenprice := iopenprice == 0 ? nz(iopenprice[1]) : iopenprice
icloseprice := icloseprice == 0 ? nz(icloseprice[1]) : icloseprice
//if icloseprice changed then recalculate box size
box := ta.change(icloseprice) ? mode == 'ATR' ? atrboxsize : boxsize : box
[box, icloseprice, iopenprice, trend]
// @function TODO: RENKO RSI indicator by @LonesomeTheBlue function
// @param ser TODO: (Type: float)
// @param len TODO: (Type: int)
// @param trcnt TODO: (Type: int)
// @param obox TODO: (Type: float)
// @param trch TODO: (Type: bool)
// @param trend TODO: (Type: int)
// @returns TODO: renkRSI
export Renko_rsi(float ser, int len, int trcnt, float obox, bool trch, int trend)=>
float res = na
if nz(ser) != 0 and nz(ser[trcnt]) != 0
float rsup = na
float rsdn = na
if ta.change(ser) == 0
res := res[1]
rsup := rsup[1]
rsdn := rsdn[1]
if ta.change(ser) != 0
if math.abs(ser - ser[trcnt]) == obox
u = math.max(ser - ser[trcnt], 0) // upward change
d = math.max(ser[trcnt] - ser, 0) // downward change
rsup := (u + (len - 1) * nz(rsup[trcnt])) / len
rsdn := (d + (len - 1) * nz(rsdn[trcnt])) / len
rs = rsup / rsdn
res := rsdn == 0 ? 100 : 100 - 100 / (1 + rs)
if math.abs(ser - ser[trcnt]) > obox
bb = ser > ser[trcnt] ? obox : -obox
u = trch ? math.max(bb*2, 0) : math.max(bb, 0) // upward change
d = trch ? math.max(-bb*2, 0) : math.max(-bb, 0) // downward change
rsup := (u + (len - 1) * nz(rsup[trcnt])) / len
rsdn := (d + (len - 1) * nz(rsdn[trcnt])) / len
ktsy = trch ? 3 : 2
cc = ser > nz(ser[trcnt]) ? nz(ser[trcnt]) + ktsy * obox : nz(ser[trcnt]) - ktsy * obox
k = math.floor((math.abs(cc - ser) / obox))
k := k > 20 ? 20 : k
loop = trch ? (trend == -1 and cc>=ser) or (trend == 1 and cc<=ser) ? true : false : true
if loop
for x = 0 to k
u = math.max(bb, 0) // upward change
d = math.max(-bb, 0) // downward change
rsup := (u + (len - 1) * rsup) / len
rsdn := (d + (len - 1) * rsdn) / len
rs = rsup / rsdn
res := rsdn == 0 ? 100 : 100 - 100 / (1 + rs)
res
// ##################################### RENKO RSI END #########################################
// ############################# DOUBLE MOVING AVERAGES ########################################
//alligator
smma(src, length) =>
smma = 0.0
smma := na(smma[1]) ? ta.sma(src, length) : (smma[1] * (length - 1) + src) / length
smma
// @function TODO: [ SMA , SMMA , EMA , VWMA , HULL, TEMA ] Between this options this function return a fast and a slow moving averages.
// @param fast_ma_type TODO: string fast MA type
// @param fast_ma_length TODO: int fast MA type
// @param fast_ma_src TODO: float fast MA source
// @param fast_ma_type TODO: string slow MA type
// @param fast_ma_length TODO: int slow MA type
// @param fast_ma_src TODO: float slow MA source
// @returns TODO: [fast_ma, slow_ma]
export getDoubleMovingAverages(string fast_ma_type, simple int fast_ma_length, float fast_ma_src, string slow_ma_type, simple int slow_ma_length, float slow_ma_src) =>
//FAST MOVING AVERAGES
e1 = ta.ema(fast_ma_src, fast_ma_length)
fast_sma = ta.sma(fast_ma_src, fast_ma_length)
fsm_ma = smma(fast_ma_src, fast_ma_length)
fvolume_ma = ta.vwma(fast_ma_src, fast_ma_length)
hullma = ta.wma(2 * ta.wma(fast_ma_src, fast_ma_length/2) - ta.wma(fast_ma_src, fast_ma_length), math.floor(math.sqrt(fast_ma_length)))
ema1 = ta.ema(fast_ma_src, fast_ma_length)
ema2 = ta.ema(ema1, fast_ma_length)
ema3 = ta.ema(ema2, fast_ma_length)
tema = 3 * (ema1 - ema2) + ema3
//SLOW MOVING AVERAGES
e = ta.ema(slow_ma_src, slow_ma_length)
slow_sma = ta.sma(slow_ma_src, slow_ma_length)
sm_ma = smma(slow_ma_src, slow_ma_length)
volume_ma = ta.vwma(slow_ma_src, slow_ma_length)
hullma1 = ta.wma(2 * ta.wma(slow_ma_src, slow_ma_length/2) - ta.wma(slow_ma_src, slow_ma_length), math.floor(math.sqrt(slow_ma_length)))
ema4 = ta.ema(slow_ma_src, slow_ma_length)
ema5 = ta.ema(ema4, slow_ma_length)
ema6 = ta.ema(ema5, slow_ma_length)
tema1 = 3 * (ema4 - ema5) + ema6
choice_fast = fast_ma_type == "TEMA" ? tema : fast_ma_type == "SMA" ? fast_sma : fast_ma_type == "HULL" ? hullma : fast_ma_type == "SMMA" ? fsm_ma : fast_ma_type =="EMA" ? e1:fast_ma_type =="VWMA"? fvolume_ma:na
choice_slow = slow_ma_type == "TEMA" ? tema1: slow_ma_type == "SMA" ? slow_sma : fast_ma_type == "HULL" ? hullma1 : slow_ma_type == "SMMA" ? sm_ma : slow_ma_type =="EMA"? e :slow_ma_type =="VWMA"? volume_ma :na
b_maz = choice_fast[1] < choice_slow[1] and choice_fast > choice_slow //crossover(choice_fast, choice_slow)
s_maz = choice_fast[1] > choice_slow[1] and choice_fast < choice_slow //crossunder(choice_fast, choice_slow)
var int maz_state = 0
if b_maz
maz_state := 1
if s_maz
maz_state := -1
[choice_fast, choice_slow, b_maz, s_maz, maz_state]
// @function TODO: [ SMA , SMMA , EMA , VWMA , HULL, TEMA ] Between this options this function return a fast and a slow moving averages.
// @param fast_ma_type TODO: string fast MA type
// @param fast_ma_length TODO: int fast MA type
// @param fast_ma_src TODO: float fast MA source
// @returns TODO: fast_ma
export getMovingAverage(string fast_ma_type, simple int fast_ma_length, float fast_ma_src) =>
e1 = ta.ema(fast_ma_src, fast_ma_length)
fast_sma = ta.sma(fast_ma_src, fast_ma_length)
fsm_ma = smma(fast_ma_src, fast_ma_length)
fvolume_ma = ta.vwma(fast_ma_src, fast_ma_length)
hullma = ta.wma(2 * ta.wma(fast_ma_src, fast_ma_length/2) - ta.wma(fast_ma_src, fast_ma_length), math.floor(math.sqrt(fast_ma_length)))
ema1 = ta.ema(fast_ma_src, fast_ma_length)
ema2 = ta.ema(ema1, fast_ma_length)
ema3 = ta.ema(ema2, fast_ma_length)
tema = 3 * (ema1 - ema2) + ema3
choice_fast = fast_ma_type == "TEMA" ? tema : fast_ma_type == "SMA" ? fast_sma : fast_ma_type == "HULL" ? hullma : fast_ma_type == "SMMA" ? fsm_ma : fast_ma_type =="EMA" ? e1:fast_ma_type =="VWMA"? fvolume_ma:na
choice_fast
// ############################# DOUBLE MOVING AVERAGES END ####################################
// ############################# RANGE FILTER #################################### By @DonovanWall
//Conditional Sampling EMA Function
export Cond_EMA(float x, bool cond, int n)=>
var val = array.new_float(0)
var ema_val = array.new_float(1)
if cond
array.push(val, x)
if array.size(val) > 1
array.remove(val, 0)
if na(array.get(ema_val, 0))
array.fill(ema_val, array.get(val, 0))
array.set(ema_val, 0, (array.get(val, 0) - array.get(ema_val, 0))*(2/(n + 1)) + array.get(ema_val, 0))
EMA = array.get(ema_val, 0)
EMA
//Conditional Sampling SMA Function
export Cond_SMA(float x, bool cond, int n)=>
var vals = array.new_float(0)
if cond
array.push(vals, x)
if array.size(vals) > n
array.remove(vals, 0)
SMA = array.avg(vals)
SMA
//Standard Deviation Function
export Stdev(float x, int n)=>
math.sqrt(Cond_SMA(math.pow(x, 2), 1, n) - math.pow(Cond_SMA(x, 1, n), 2))
//Range Size Function
export rng_size(float x,string scale, float qty, int n)=>
ATR = Cond_EMA(ta.tr(true), 1, n)
AC = Cond_EMA(math.abs(x - x[1]), 1, n)
SD = Stdev(x, n)
rng_size = scale=="Pips" ? qty*0.0001 : scale=="Points" ? qty*syminfo.pointvalue : scale=="% of Price" ? close*qty/100 : scale=="ATR" ? qty*ATR :
scale=="Average Change" ? qty*AC : scale=="Standard Deviation" ? qty*SD : scale=="Ticks" ? qty*syminfo.mintick : qty
// ############################# RANGE FILTER ####################################
// ############################# HOTT LOTT #################################### By @KivancOzbilgic
// @function TODO: HOTT LOTT indicator by @KivancOzbilgic function
// @param src TODO: float
// @param length TODO: int
// @returns TODO: float VAR
export Var_Func(float src, int length)=>
valpha=2/(length+1)
vud1=src>src[1] ? src-src[1] : 0
vdd1=src<src[1] ? src[1]-src : 0
vUD=math.sum(vud1,9)
vDD=math.sum(vdd1,9)
vCMO=nz((vUD-vDD)/(vUD+vDD))
VAR=0.0
VAR:=nz(valpha*math.abs(vCMO)*src)+(1-valpha*math.abs(vCMO))*nz(VAR[1])
VAR
// @function TODO: WWMA by @KivancOzbilgic function
// @param src TODO: float
// @param length TODO: int
// @returns TODO: float WWMA
export Wwma_Func(float src, int length) =>
wwalpha = 1/ length
WWMA = 0.0
WWMA := wwalpha*src + (1-wwalpha)*nz(WWMA[1])
WWMA
// @function TODO: ZLEMA by @KivancOzbilgic function
// @param src TODO: float
// @param length TODO: int
// @returns TODO: float ZLEMA
export Zlema_Func(float src, int length) =>
zxLag = length/2==math.round(length/2) ? length/2 : (length - 1) / 2
zxEMAData = (src + (src - src[zxLag]))
ZLEMA = ta.ema(zxEMAData, length)
ZLEMA
// @function TODO: TSF by @KivancOzbilgic function
// @param src TODO: float
// @param length TODO: int
// @returns TODO: float ZLEMA
export Tsf_Func(float src, int length) =>
lrc = ta.linreg(src, length, 0)
lrc1 = ta.linreg(src,length,1)
lrs = (lrc-lrc1)
TSF = ta.linreg(src, length, 0)+lrs
TSF
// @function TODO: getMA by @KivancOzbilgic function cutomised
// @param mav TODO: string
// @param src TODO: float
// @param length TODO: int
// @param x TODO: string type
// @param VAR1 TODO: float
// @param VAR2 TODO: float
// @param WWMA1 TODO: float
// @param WWMA2 TODO: float
// @param ZLEMA1 TODO: float
// @param ZLEMA2 TODO: float
// @param TSF1 TODO: float
// @param TSF2 TODO: float
// @returns TODO: float ZLEMA
export getMA(string mav, float src,simple int length, string x, float VAR1, float VAR2, float WWMA1, float WWMA2, float ZLEMA1, float ZLEMA2, float TSF1, float TSF2) =>
ma1 = 0.0
ma2 = 0.0
if mav == "SMA" and x == "m1"
ma1 := ta.sma(src, length)
ma1
if mav == "SMA" and x == "m2"
ma2 := ta.sma(src, length)
ma2
if mav == "EMA" and x == "m1"
ma1 := ta.ema(src, length)
ma1
if mav == "EMA" and x == "m2"
ma2 := ta.ema(src, length)
ma2
if mav == "WMA" and x == "m1"
ma1 := ta.wma(src, length)
ma1
if mav == "WMA" and x == "m2"
ma2 := ta.wma(src, length)
ma2
if mav == "TMA" and x == "m1"
ma1 := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
ma1
if mav == "TMA" and x == "m2"
ma2 := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
ma2
if mav == "VAR" and x == "m1"
ma1 := VAR1
ma1
if mav == "VAR" and x == "m2"
ma2 := VAR2
ma2
if mav == "WWMA" and x == "m1"
ma1 := WWMA1
ma1
if mav == "WWMA" and x == "m2"
ma2 := WWMA2
ma2
if mav == "ZLEMA" and x == "m1"
ma1 := ZLEMA1
ma1
if mav == "ZLEMA" and x == "m2"
ma2 := ZLEMA2
ma2
if mav == "TSF" and x == "m1"
ma1 := TSF1
ma1
if mav == "TSF" and x == "m2"
ma2 := TSF2
ma2
var float result = na
if x == "m1"
result := ma1
else
result := ma2
result
// @function TODO: getMA by @KivancOzbilgic function cutomised
// @param mav TODO: string
// @param src TODO: float
// @param length TODO: int
// @param DEMA TODO: float
// @param VAR TODO: float
// @param WWMA TODO: float
// @param ZLEMA TODO: float
// @param TSF TODO: float
// @param HMA TODO: float
// @returns TODO: float ZLEMA
export getMA2(string mav, float src, simple int length, float DEMA, float VAR, float WWMA, float ZLEMA, float TSF, float HMA) =>
ma = 0.0
if mav == 'SMA'
ma := ta.sma(src, length)
ma
if mav == 'EMA'
ma := ta.ema(src, length)
ma
if mav == 'WMA'
ma := ta.wma(src, length)
ma
if mav == 'DEMA'
ma := DEMA
ma
if mav == 'TMA'
ma := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
ma
if mav == 'VAR'
ma := VAR
ma
if mav == 'WWMA'
ma := WWMA
ma
if mav == 'ZLEMA'
ma := ZLEMA
ma
if mav == 'TSF'
ma := TSF
ma
if mav == 'HULL'
ma := HMA
ma
ma
// @param length TODO: simple int
// @param hLEn TODO: int
// @param lLen TODO: int
// @param mav TODO: string
// @param percent TODO: float
// @returns TODO: [HOTT, LOTT]
export full_hott_lott(simple int length, int hLen, int lLen, string mav, float percent)=>
highs = ta.highest(high, hLen)
lows = ta.lowest(low, lLen)
VAR1 = Var_Func(highs,length)
WWMA1 = Wwma_Func(highs,length)
ZLEMA1 = Zlema_Func(highs,length)
TSF1 = Tsf_Func(highs,length)
VAR2 = Var_Func(lows,length)
WWMA2 = Wwma_Func(lows,length)
ZLEMA2 = Zlema_Func(lows,length)
TSF2 = Tsf_Func(lows,length)
MAvg1 = getMA(mav, highs, length, "m1", VAR1, VAR2, WWMA1, WWMA2, ZLEMA1, ZLEMA2, TSF1, TSF2)
fark1 = MAvg1*percent*0.01
longStop1 = MAvg1 - fark1
longStopPrev1 = nz(longStop1[1], longStop1)
longStop1 := MAvg1 > longStopPrev1 ? math.max(longStop1, longStopPrev1) : longStop1
shortStop1 = MAvg1 + fark1
shortStopPrev1 = nz(shortStop1[1], shortStop1)
shortStop1 := MAvg1 < shortStopPrev1 ? math.min(shortStop1, shortStopPrev1) : shortStop1
dir1 = 1
dir1 := nz(dir1[1], dir1)
dir1 := dir1 == -1 and MAvg1 > shortStopPrev1 ? 1 : dir1 == 1 and MAvg1 < longStopPrev1 ? -1 : dir1
MT1 = dir1==1 ? longStop1 : shortStop1
MAvg2 = getMA(mav, lows, length, "m2", VAR1, VAR2, WWMA1, WWMA2, ZLEMA1, ZLEMA2, TSF1, TSF2)
fark2 = MAvg2*percent*0.01
longStop2 = MAvg2 - fark2
longStopPrev2 = nz(longStop2[1], longStop2)
longStop2 := MAvg2 > longStopPrev2 ? math.max(longStop2, longStopPrev2) : longStop2
shortStop2 = MAvg2 + fark2
shortStopPrev2 = nz(shortStop2[1], shortStop2)
shortStop2 := MAvg2 < shortStopPrev2 ? math.min(shortStop2, shortStopPrev2) : shortStop2
dir2 = 1
dir2 := nz(dir2[1], dir2)
dir2 := dir2 == -1 and MAvg2 > shortStopPrev2 ? 1 : dir2 == 1 and MAvg2 < longStopPrev2 ? -1 : dir2
MT2 = dir2==1 ? longStop2 : shortStop2
HOTT = MAvg1 > MT1 ? MT1*(200+percent)/200 : MT1*(200-percent)/200
LOTT = MAvg2 > MT2 ? MT2*(200+percent)/200 : MT2*(200-percent)/200
[HOTT, LOTT]
// ############################# HOTT LOTT ####################################
// ############################# ATR BANDS ####################################
getBandOffsetSource(srcIn, isUpperBand) =>
// Initialize the return to our fail-safe 'close', which is also the default input, then update thru the switch statement
ret = close
switch srcIn
"close" => ret := close
"wicks" => ret := isUpperBand ? high : low
=> ret := close
ret
// @function TODO: get ATR function cutomised
// @param atrPeriod TODO: int
// @param (atrPeriod) TODO: float
// @param atrSourceRef TODO: string
// @returns TODO: [upperATRBand, lowerATRBand]
export getATRBands(simple int atrPeriod, float atrMultiplier, string atrSourceRef) =>
atr = ta.atr(atrPeriod)
scaledATR = atr * atrMultiplier
upperATRBand = getBandOffsetSource(atrSourceRef, true) + scaledATR
lowerATRBand = getBandOffsetSource(atrSourceRef, false) - scaledATR
[upperATRBand, lowerATRBand]
// ############################# ATR BANDS END ####################################
// ############################# ATR TREND BANDS ####################################
// @function TODO: get ATR function cutomised
// @param src TODO: float
// @param delta TODO: float
// @returns TODO: [midb, upperb, lowerb]
// @function get trend ATR bands.
export getATRTrendBands(float src, float delta)=>
float upperb = 0.0
float lowerb = 0.0
upperb := nz(upperb[1])
lowerb := nz(lowerb[1])
if src > nz(upperb[1])
upperb := math.max(nz(upperb[1]), math.max(src, nz(src[1])))
lowerb := upperb - delta
if lowerb < nz(lowerb[1]) or lowerb > nz(lowerb[1]) and upperb == nz(upperb[1])
lowerb := nz(lowerb[1])
else if src < nz(lowerb[1])
lowerb := math.min(nz(lowerb[1]), math.min(src, nz(src[1])))
upperb := lowerb + delta
if upperb > nz(upperb[1]) or upperb < nz(upperb[1]) and lowerb == nz(lowerb[1])
upperb := nz(upperb[1])
midb = (lowerb + upperb) / 2
[midb, upperb, lowerb]
// ############################# ATR TREND BANDS END ####################################
// ############################# RANGIFY ####################################
// @function TODO: return an array containing up to 21 levels divising a Range
// @param hvalue TODO: float
// @param lvalue TODO: float
// @param divider TODO: int
// @returns TODO: levels
export rangify(float hvalue, float lvalue, int divider) =>
var levels = array.new_float((divider - 1), na)
diffcentage = (hvalue - lvalue) / lvalue
renge_perc = diffcentage / divider
loop_limit = divider - 1
indexer = 0
for i = 1 to loop_limit
lv = hvalue * ( 1 - (renge_perc * i))
array.set(levels, indexer, lv)
indexer += 1
levels
// ############################# RANGIFY END ####################################
// ============== BANDS DIVIDERS ===========================
// @function TODO : plot up to 21 levels divising a Range
// @param upperb TODO : float
// @param lowerb TODO : float
// @param rg_divider TODO : int
// @returns TODO: levels
export range_dividers(float upperb, float lowerb, int rg_divider) =>
// countOccurenceWithinLookback
var float rgDivider0 = na
var float rgDivider1 = na
var float rgDivider2 = na
var float rgDivider3 = na
var float rgDivider4 = na
var float rgDivider5 = na
var float rgDivider6 = na
var float rgDivider7 = na
var float rgDivider8 = na
var float rgDivider9 = na
var float rgDivider10 = na
var float rgDivider11 = na
var float rgDivider12 = na
var float rgDivider13 = na
var float rgDivider14 = na
var float rgDivider15 = na
var float rgDivider16 = na
var float rgDivider17 = na
var float rgDivider18 = na
var float rgDivider19 = na
var float rgDivider20 = na
levels = rangify(upperb, lowerb, rg_divider)
rgDivider0 := rg_divider >= 2 ? array.get(levels, 0) : na
rgDivider1 := rg_divider >= 3 ? array.get(levels, 1) : na
rgDivider2 := rg_divider >= 4 ? array.get(levels, 2) : na
rgDivider3 := rg_divider >= 5 ? array.get(levels, 3) : na
rgDivider4 := rg_divider >= 6 ? array.get(levels, 4) : na
rgDivider5 := rg_divider >= 7 ? array.get(levels, 5) : na
rgDivider6 := rg_divider >= 8 ? array.get(levels, 6) : na
rgDivider7 := rg_divider >= 9 ? array.get(levels, 7) : na
rgDivider8 := rg_divider >= 10 ? array.get(levels, 8) : na
rgDivider9 := rg_divider >= 11 ? array.get(levels, 9) : na
rgDivider10 := rg_divider >= 12 ? array.get(levels, 10) : na
rgDivider11 := rg_divider >= 13 ? array.get(levels, 11) : na
rgDivider12 := rg_divider >= 14 ? array.get(levels, 12) : na
rgDivider13 := rg_divider >= 15 ? array.get(levels, 13) : na
rgDivider14 := rg_divider >= 16 ? array.get(levels, 14) : na
rgDivider15 := rg_divider >= 17 ? array.get(levels, 15) : na
rgDivider16 := rg_divider >= 18 ? array.get(levels, 16) : na
rgDivider17 := rg_divider >= 19 ? array.get(levels, 17) : na
rgDivider18 := rg_divider >= 20 ? array.get(levels, 18) : na
rgDivider19 := rg_divider >= 21 ? array.get(levels, 19) : na
rgDivider20 := rg_divider >= 22 ? array.get(levels, 20) : na
// Plot Range Splitter
// line.new(x1=showRgSplitter ? bar_index[1] : na, y1=mid_b, x2=showRgSplitter ? bar_index : na, y2=mid_b, color=color.gray, width=3)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider0, x2=showRgDividers ? bar_index : na, y2=rgDivider0, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider1, x2=showRgDividers ? bar_index : na, y2=rgDivider1, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider2, x2=showRgDividers ? bar_index : na, y2=rgDivider2, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider3, x2=showRgDividers ? bar_index : na, y2=rgDivider3, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider4, x2=showRgDividers ? bar_index : na, y2=rgDivider4, color=not darkMode ? color.black : color.white, width=3)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider5, x2=showRgDividers ? bar_index : na, y2=rgDivider5, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider6, x2=showRgDividers ? bar_index : na, y2=rgDivider6, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider7, x2=showRgDividers ? bar_index : na, y2=rgDivider7, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider8, x2=showRgDividers ? bar_index : na, y2=rgDivider8, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider9, x2=showRgDividers ? bar_index : na, y2=rgDivider9, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider10, x2=showRgDividers ? bar_index : na, y2=rgDivider10, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider11, x2=showRgDividers ? bar_index : na, y2=rgDivider11, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider12, x2=showRgDividers ? bar_index : na, y2=rgDivider12, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider13, x2=showRgDividers ? bar_index : na, y2=rgDivider13, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider14, x2=showRgDividers ? bar_index : na, y2=rgDivider14, color=not darkMode ? color.black : color.white, width=3)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider15, x2=showRgDividers ? bar_index : na, y2=rgDivider15, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider16, x2=showRgDividers ? bar_index : na, y2=rgDivider16, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider17, x2=showRgDividers ? bar_index : na, y2=rgDivider17, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider18, x2=showRgDividers ? bar_index : na, y2=rgDivider18, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider19, x2=showRgDividers ? bar_index : na, y2=rgDivider19, color=not darkMode ? color.black : color.white, width=1)
// line.new(x1=showRgDividers ? bar_index[1] : na, y1=rgDivider20, x2=showRgDividers ? bar_index : na, y2=rgDivider20, color=not darkMode ? color.black : color.white, width=1)
[levels, rgDivider0, rgDivider1, rgDivider2, rgDivider3, rgDivider4, rgDivider5, rgDivider6, rgDivider7, rgDivider8, rgDivider9, rgDivider10, rgDivider11, rgDivider12, rgDivider13, rgDivider14, rgDivider15, rgDivider16, rgDivider17, rgDivider18, rgDivider19, rgDivider20]
// ============== ATR BANDS DIVIDERS END ===========================
// ############################# RANGE_MID ####################################
// @function TODO: return average Range and state value
// @param ha_close TODO: float
// @param ha_high TODO: float
// @param ha_low TODO: float
// @param darkMode TODO: bool
// @returns TODO: [mid, uppish, downish, midUp, midDn, realb, reals]
export rangeValue(float ha_close, float ha_high, float ha_low, bool darkMode) =>
float up = na
float down = na
//MID
up := ha_close < nz(up[1]) and ha_close>down[1] ? nz(up[1]) : ha_high
down := ha_close < nz(up[1]) and ha_close>down[1] ? nz(down[1]) : ha_low
mid = math.avg(up,down)
ranje = (mid-mid[1])/mid[1] * 100
uppish = up == nz(up[1]) ? up : na
downish = down == nz(down[1]) ? down: na
midUp = mid * (1 + ((uppish - mid) / uppish)/2)
midDn = mid * (1 - ((mid - downish) / mid)/2)
// --- MID conditions --- \\\\
var int mid_state = 0
buy_mid = ranje[1]== 0 and ranje > 0 or ranje[1] < 0 and ranje > 0
sell_mid = ranje[1]== 0 and ranje < 0 or ranje[1] > 0 and ranje < 0
if buy_mid
mid_state := 1
if sell_mid
mid_state := -1
realb = buy_mid and mid_state == 1 and mid_state != mid_state[1]
reals = sell_mid and mid_state == -1 and mid_state != mid_state[1]
midColor = ranje > 0 ? color.new(color.green, 0) : ranje < 0 ? color.new(color.red, 0) : not darkMode ? color.new(color.black, 0) : color.new(color.white, 0)
[mid, ranje, midColor, mid_state, uppish, downish, midUp, midDn, realb, reals]
// @function TODO: return posistive / negative variation candle of a serie
// @param serie TODO: float
// @returns TODO: [variation, state, realb, reals]
export variation_status(float serie) =>
variation = (serie - serie[1]) / serie[1] * 100
var int state = 0
positive_var = variation[1]== 0 and variation > 0 or variation[1] < 0 and variation > 0
negativ_var = variation[1]== 0 and variation < 0 or variation[1] > 0 and variation < 0
if positive_var
state := 1
if negativ_var
state := -1
realb = positive_var and state == 1 and state != state[1]
reals = negativ_var and state == -1 and state != state[1]
[variation, state, realb, reals, positive_var, negativ_var]
// ############################# RANGE_MID END ####################################
// @function TODO: getMA by @KivancOzbilgic function cutomised
// @param source TODO: float
// @param length TODO: int
// @param type TODO: float
// @returns TODO: float ZLEMA
export SmMA(float source, simple int length, string type) =>
var m = matrix.new<float>(1, length, 0)
for i = 0 to length-1
matrix.set(m, 0, i, source)
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "SMMA (RMA)" ? ta.rma(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
type == "HMA" ? ta.hma(source, length) :
type == "ALMA" ? ta.alma(source, length, 0.85, 6) :
type == "SWMA" ? ta.swma(source) :
type == "RMA" ? ta.rma(source, length) :
type == "VWAP" ? ta.vwap(source) :
type == "LSMA" ? ta.linreg(source, length, 0) :
na
// ############################# LOOKBACK ####################################
// @function TODO: Modifiy a boolean to false if the value for the past leftlookback have changed
// @param value TODO: float
// @param leftlookback TODO: int
// @returns TODO: nothing
export unchanged_value(int leftlookback, float value) =>
var changed = false
for i = 0 to leftlookback - 1
if value == value[i]
changed := true
else
changed := false
changed
// @function TODO: Modifiy a boolean to false if the value for the past leftlookback have changed
// @param cond TODO: bool
// @param leftlookback TODO: int
// @returns TODO: nothing
export unchanged_condition(int leftlookback, bool cond) =>
var changed = false
for i = 0 to leftlookback - 1
if cond
changed := true
else
changed := false
changed
// @function TODO: cumulates a series value for the past leftlookback
// @param value TODO: float
// @param leftlookback TODO: int
// @returns TODO: cummulative total
export cumulative_lookback(int leftlookback, float value) =>
var float total = na
for i = 0 to leftlookback - 1
total += value
total
// @function TODO: cumulates a series value for the past leftlookback depending on a valid and invalid condition
// @param value TODO: float
// @param leftlookback TODO: int
// @param valid_cond TODO: bool
// @param invalid_cond TODO: bool
// @returns TODO: cummulative total
export reseting_cmltv_lookback(int leftlookback, float value, bool invalid_cond, bool valid_cond) =>
var changed = false
var float total = na
if invalid_cond
total := na
if valid_cond
for i = 0 to leftlookback - 1
total += value
total
// @function TODO: Modifiy a boolean to false if 3 values for the past leftlookback have not changed
// @param value TODO: float
// @param leftlookback TODO: int
// @returns TODO: nothing
export three_V_unchanged(int leftlookback, float value1, float value2, float value3) =>
var changed = false
for k = 0 to leftlookback
if value1 == value1[k] and value2 == value2[k] and value3 == value3[k]
changed := true
else
changed := false
changed
// ############################# LOOKBACK END ####################################
// ################################ CONDITION OCCURENCE ########################################
// @function TODO: Show Only first occurence depending on another condition
// @param boolean TODO: (Type: bool)
// @param bool1 TODO: (Type: bool)
// @param bool1_switchOff_cond TODO: (Type: bool)
// @param bool2 TODO: (Type: bool)
// @param bool2_switchOff_cond TODO: (Type: bool)
// @returns TODO: Filterred [bool1, booll2]
export showOnlyFirstSignal(bool boolean, bool bool1, bool bool1_switchOff_cond, bool bool2, bool bool2_switchOff_cond) =>
var int bool1Occured = 0
var int bool2Occured = 0
if bool1
bool1Occured := 1
if bool2
bool2Occured := 1
if bool1_switchOff_cond
bool1Occured := 0
if bool2_switchOff_cond
bool2Occured := 0
buy = boolean ? bool1Occured[1] != 1 and bool1Occured == 1 : bool1
sell = boolean ? bool2Occured[1] != 1 and bool2Occured == 1 : bool2
[buy, sell]
// @function Single out the occurence of a bool series between to 2 bool series.
// @param booleanInput to activate or deactivate occurences filtering.
// @returns filterred or not bool series.
export showOnlyFirstOccurence(bool booleanInput, bool buycon, bool sellcond) =>
var int buyconOccured = 0
var int sellconOccured = 0
if buycon
buyconOccured := 1
sellconOccured := -1
if sellcond
sellconOccured := 1
buyconOccured := -1
buy = booleanInput ? buyconOccured[1] != 1 and buyconOccured == 1 : buycon
sell = booleanInput ? sellconOccured[1] != 1 and sellconOccured == 1 : sellcond
[buy, sell]
// @function TODO: find the first occurrence of a condtion depending on a prior condition
// @param priorCond TODO: bool
// @param cond2 TODO: bool
// @param cond3 TODO: bool decide when we look for first prior condition occurence or not
// @returns TODO: the candle where cond 2 happened
export ConditionedCondition(bool priorCond, bool cond2, bool cond3) =>
var int priorCond_state = 0
var int seconCondition_state = 0
if priorCond
priorCond_state := 1
seconCondition_state := -1 /// -1 : we lookin second condition
if cond3 // we not looking anymore
priorCond_state := 0
seconCondition_state := 0
if priorCond_state == 1 and seconCondition_state == -1 and cond2
seconCondition_state := 1
priorCond_state := 0
happened = seconCondition_state[1] != 1 and seconCondition_state == 1
priorHappened = priorCond_state[1] !=1 and priorCond_state == 1
[happened, priorHappened]
// @function TODO: find the first occurrence or all occurences of a condtion depending on a prior condition
// @param priorCond TODO: bool
// @param cond2 TODO: bool
// @param singleton TODO: bool
// @returns TODO: the candle where cond 2 happened
export ConditionedFisrtOccurence(bool priorCond, bool cond2, bool singleton) =>
var int cond2_state = 0
if singleton
while priorCond
if cond2
cond2_state := 1
else
cond2_state := 0
else
if priorCond and cond2
cond2_state := 1
else
cond2_state := 0
happened = cond2_state[1] != 1 and cond2_state == 1
// ################################ CONDITION OCCURENCE ########################################
// ############################ TWO TRENDZ STATE ###############################
// @function TODO: return 2 trendz state
// @param long_trigger) TODO: bool
// @param short_trigger TODO: bool
// @returns TODO: [long_trend_state, short_trend_state]
export TwoTrendzState( bool long_trigger, bool short_trigger)=>
var bool long_trend_state = na
var bool short_trend_state = na
if long_trigger
long_trend_state := true
short_trend_state := false
if short_trigger
long_trend_state := false
short_trend_state := true
[long_trend_state, short_trend_state]
// ########################## TWO TRENDZ STATE END #############################
// ############################ Line_between_lines from perc ###############################
// @function TODO: return a line between 2 lines, the line position depend of the percent parameter
// @param hl1 (higher line) TODO: float
// @param ll2 (lower line) TODO: float
// @param percent TODO: float
// @returns TODO: return a line between 2 lines, the line position depend of the percent parameter
export lineBetweenLines(float hl1, float ll2, float percent) =>
ranje = ( (hl1 - ll2) / hl1 ) * percent
line_value = ll2 * (1 + ranje)
line_value
// ########################## Line_between_lines from perc END #############################
// ############################ variation_beetweenlines ###############################
// @function TODO: return a the percent distance between 2 ylines, the line position depend of the percent parameter
// @param hl1 (higher line) TODO: float
// @param ll2 (lower line) TODO: float
// @returns TODO: return float distance percent
export abs_variation_beetweenlines(float hl1, float ll2) =>
ranje = math.abs(( (hl1 - ll2) / hl1 ) * 100)
ranje
// ########################## variation_beetweenlines END #############################
// ############################ AbsPercentChange ###############################
// @function TODO: return the variation percent of a serie
// @param src TODO: float
// @returns TODO: return the variation percent of a serie
export AbsPercentChange(float src) =>
value = math.abs((src - src[1])/src[1]) * 100
value
// ########################## AbsPercentChange END #############################
// ############################ AbsPercent ###############################
// @function TODO: return the percent difference between 2 series
// @param src1 TODO: float
// @param src2 TODO: float
// @returns TODO: return the variation percent of a serie
export AbsPercent(float src1, float src2) =>
distance = math.abs(src1 - src2) // Calculate the absolute distance
percentage = (distance / src2) * 100
// ########################## AbsPercent END #############################
// ################### ConditionedCummulativePercentage #####################
// @function TODO: return the cummuled variation percent of a serie depending on bool cond
// @param cond1 TODO: bool
// @param src2 TODO: float
// @param cond2 TODO: bool
// @returns TODO: return the cumuled variation percent of a serie
export CondiCummulPercent(bool cond1, float src, bool cond2) =>
var float value = 0.0
if cond1
value += math.abs((src - src[1])/src[1]) * 100
if cond2
value := 0.0
value
// ################ ConditionedCummulativePercentage END ######################
// ################### TriggeringConditionedCummulativePercentage #####################
// @function TODO: return the cummuled variation percent of a serie depending on bool cond
// @param triggeringcond1 TODO: bool
// @param src2 TODO: float
// @param cancelingcond2 TODO: bool
// @returns TODO: return the cumuled variation percent of a serie
export trigCondiCummulPercent(bool triggeringcond1, float src, bool resettingcond2) =>
var float value = 0.0
var int state = 0
if triggeringcond1
state := 1
if resettingcond2
state := -1
if state == 1
value += math.abs((src - src[1])/src[1]) * 100
if resettingcond2
state := -1
if state == -1
value := 0.0
if triggeringcond1
state := 1
value
// ################ TriggeringConditionedCummulativePercentage END ######################
// ################### S&R PRICE #####################
// @function TODO: return the price
// @param _osc TODO: float
// @param _thresh TODO: float
// @param _cross TODO: string
// @returns TODO: return return_1
export f_getPrice(float _osc, float _thresh, string _cross) =>
avgHigh = math.avg(high, close)
avgLow = math.avg(low , close)
var return_1 = 0.
if _cross == 'over' or _cross == 'both'
if ta.crossover(_osc, _thresh)
return_1 := avgHigh
return_1
if _cross == 'under' or _cross == 'both'
if ta.crossunder(_osc, _thresh)
return_1 := avgLow
return_1
return_1
// ################ S&R PRICE END ######################
// ################### ICT_DONCHIAN #####################
// @returns TODO: return donchian levels
// @param prd TODO: int
// @returns TODO: return donchian levels
export ict_donchian(int prd) =>
// ~~ Variables {
var Up = float(na)
var Dn = float(na)
var iUp = int(na)
var iDn = int(na)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Pivots {
Up := math.max(Up[1],high)
Dn := math.min(Dn[1],low)
pvtHi = ta.pivothigh(high,prd,prd)
pvtLo = ta.pivotlow(low,prd,prd)
if pvtHi
Up := pvtHi
if pvtLo
Dn := pvtLo
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Premium & Discount {
PremiumTop = Up-(Up-Dn)*.1
PremiumBot = Up-(Up-Dn)*.25
DiscountTop = Dn+(Up-Dn)*.25
DiscountBot = Dn+(Up-Dn)*.1
MidTop = Up-(Up-Dn)*.45
MidBot = Dn+(Up-Dn)*.45
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
[Up, Dn, PremiumTop, PremiumBot, DiscountTop, DiscountBot, MidTop, MidBot]
// ################ ICT_DONCHIAN END ######################
// ################### Session_ticks #####################
open_bar(string ses, string ref_res) =>
t = time(ref_res, ses)
na(t[1]) and not na(t) or t[1] < t
is_open(ses) =>
not na(time(timeframe.period, ses))
// @returns TODO: return session h-l
// @param rth_ses TODO: string
// @param prcolorid TODO: color
// @param ref_res TODO: string
// @returns TODO: return donchian levels
export session_tick( string rth_ses , color colori, string ref_res) =>
rth_open_bar = open_bar(rth_ses, ref_res)
rth_is_open = is_open(rth_ses)
rth_low = float(na)
rth_low := rth_is_open ? rth_open_bar ? low : math.min(rth_low[1], low) : rth_low[1]
rth_high = float(na)
rth_high := rth_is_open ? rth_open_bar ? high : math.max(rth_high[1], high) : rth_high[1]
rth_fill_color = rth_is_open ? colori : na
[rth_low, rth_high, rth_fill_color, rth_open_bar, rth_is_open]
// ################ Session_ticks END ######################
// ################### is_newbar #####################
// @returns TODO: rreturn is new bar of timeframe
// @param res TODO: string
// @returns TODO: return is new bar of timeframe
export is_newbar(string res) =>
t = time(res)
not na(t) and (na(t[1]) or t > t[1])
// ################ is_newbar END ######################
// ################### is_newbar #####################
// @returns TODO: Function to calculate the daily high and low
// @returns TODO: return [float dailyHigh,float dailyLow]
export getDailyHighLow() =>
var float dailyHigh = na
var float dailyLow = na
if ta.change(time("D")) != 0
dailyHigh := high
dailyLow := low
else if high > dailyHigh
dailyHigh := high
else if low < dailyLow
dailyLow := low
[dailyHigh, dailyLow]
// ################ is_newbar END ######################
// ################### RSI BANDZ #####################
// @function TODO: RSI BANDZ
// @param float rsiSourceInput
// @param int rsiLengthInput
// @param int up_level
// @param int dn_level
// @returns TODO: RSI BANDZ DATA [rsi, up_lev_line, dn_lev_line, rsi_range, rsi_line_chart]
export calculateRSI_BANDZ(float rsiSourceInput,int rsiLengthInput, int up_level, int dn_level) =>
maValue = ta.rma(ohlc4, rsiLengthInput)
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
up_lev_line = ta.rma(ta.highest(rsiLengthInput)[1], rsiLengthInput)
dn_lev_line = ta.rma(ta.lowest(rsiLengthInput)[1], rsiLengthInput)
rsi_range = (up_lev_line - dn_lev_line) / (up_level - dn_level) * 100
rsi_line_chart = maValue + (rsi - 50) / 100 * rsi_range
[rsi, up_lev_line, dn_lev_line, rsi_range, rsi_line_chart]
// ################ RSI BANDZ END ######################
// ################### RTI LVLZ #####################
// @function TODO: RTI Level
// @param float rsiSourceInput
// @param int trend_sens_percent
// @param int up_level
// @param int dn_level
// @returns TODO: RTI Level [rsi, up_lev_line, dn_lev_line, rsi_range, rsi_line_chart]
export RTI(int trend_sens_percent, int data_count, int signal_length )=>
upper_trend = close + ta.stdev(close, 2)
lower_trend = close - ta.stdev(close, 2)
upper_array = array.new<float>(0)
lower_array = array.new<float>(0)
for i = 0 to data_count - 1
upper_array.push(upper_trend[i])
lower_array.push(lower_trend[i])
upper_array.sort()
lower_array.sort()
upper_index = math.round(trend_sens_percent / 100 * data_count) - 1
lower_index = math.round((100 - trend_sens_percent) / 100 * data_count) - 1
UpperTrend = upper_array.get(upper_index)
LowerTrend = lower_array.get(lower_index)
Rti = ((close - LowerTrend) / (UpperTrend - LowerTrend))*100
MA_Rti = ta.ema(Rti,signal_length)
[Rti, MA_Rti]
// ################ RSI BANDZ END ######################
|
VonnyPublicLibrary | https://www.tradingview.com/script/eRLKPy7C-VonnyPublicLibrary/ | VonnyFX | https://www.tradingview.com/u/VonnyFX/ | 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/
// @VonnyFX
// Last Updated August 21, 2022
// @version=5
// @description A collection functions commonly used within my scripts
library("VonnyPublicLibrary")
// --- BEGIN UTILITY FUNCTIONS {
// @function Calculate when a bullish condition occurs. (When you have two variables)
// @param float Enter first variable
// @param float Enter second variable
// @returns True the first bar of your bullish condition
export EntryBull(float _close, float _supertrend) =>
bool(_close > _supertrend and _close[1] < _supertrend[1])
//-----------------------------------------------------------------------------------------------------------
// @function Calculate when a bearish condition occurs. (When you have two variables)
// @param float Enter first variable
// @param float Enter second variable
// @returns True the first bar of your bearish condition
export EntryBear(float _close, float _supertrend) =>
bool(_close < _supertrend and _close[1] > _supertrend[1])
//-----------------------------------------------------------------------------------------------------------
// @function Calculate the low of your bearish condition
// @param bool bullish condition
// @param bool bearish condition
// @param bool candle buffer to prevent the script from crashing. Since were working with a Dynamic Length
// @param float Enter what you want to see the low off? Low of the bar OR Close of the bar
// @param float Enter what you want to see the low off? Low of the bar OR Open of the bar might see pointless but some times the Lowest open is lower then the Lowest Close
// @returns the Lowest point of your sell condition when ever your buy condition is triggered
export LowestPivot(bool _EntryBull, bool _EntryBear, bool _barDEX, float _lowRClose, float _lowROpen) =>
_lookbackBuy = (ta.barssince(_EntryBull))
_lookbackSell = (ta.barssince(_EntryBear))
_lookback = _lookbackBuy > _lookbackSell ? _lookbackBuy : _lookbackSell
_lowLevel = _barDEX ? ta.lowest(_lowRClose,_lookback ) : na
_lowLevelOpen = _barDEX ? ta.lowest(open,_lookback) : na
_lowLevelX = _lowLevelOpen < _lowLevel ? _lowLevelOpen : _lowLevel
float((_lowLevelX < _lowROpen) ? _lowLevelX : _lowROpen)
//-----------------------------------------------------------------------------------------------------------
// @function Calculate the high of your bullish condition
// @param bool bullish condition
// @param bool bearish condition
// @param bool candle buffer to prevent the script from crashing. Since were working with a Dynamic Length
// @param float Enter what you want to see the high off? High of the bar OR Close of the bar
// @param float Enter what you want to see the high off? High of the bar OR Open of the bar might see pointless but some times the Highest Open is Higher then the Highest Close
// @returns the Highest point of your buy condition when ever your sell condition is triggered
export HighestPivot(bool _EntryBull, bool _EntryBear, bool _barDEX, float _highRClose, float _highROpen) =>
_lookbackBuy = (ta.barssince(_EntryBull))
_lookbackSell = (ta.barssince(_EntryBear))
_lookback = _lookbackBuy > _lookbackSell ? _lookbackBuy : _lookbackSell
_highLevel = _barDEX ? ta.highest(_highRClose,(_lookback )) : na
_highLevelOpen = _barDEX ? ta.highest(open,(_lookback )) : na
_highLevelX = _highLevelOpen > _highLevel ? _highLevelOpen : _highLevel
float((_highLevelX > _highROpen) ? _highLevelX : _highROpen)
//-----------------------------------------------------------------------------------------------------------
// @function Calculate how many bars since your bullish condition and bearish condition.
// @param bool enter bullish condition
// @param bool enter bearish condition
// @returns the condition with the most bars
export lookBack(bool _EntryBull, bool _EntryBear) =>
_lookbackBuy = (ta.barssince(_EntryBull))
_lookbackSell = (ta.barssince(_EntryBear))
int(_lookbackBuy > _lookbackSell ? _lookbackBuy : _lookbackSell)
//-----------------------------------------------------------------------------------------------------------
|
MYX_ACE_DB | https://www.tradingview.com/script/gRkTYcEy-MYX-ACE-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 ACE Market
library('MYX_ACE_DB')
// ————————————————————————————————————————————————————————————————————————————— db {
// @function TODO: Library for Malaysia ACE Market
// @param x TODO: id
// @returns TODO: id
export db(string[] id) =>
array.push(id, 'ACO') // 0
array.push(id, 'AEMULUS') // 1
array.push(id, 'AGMO') // 2
array.push(id, 'AIM') // 3
array.push(id, 'AIMFLEX') // 4
array.push(id, 'ALRICH') // 5
array.push(id, 'ANCOMLB') // 6
array.push(id, 'ANEKA') // 7
array.push(id, 'APPASIA') // 8
array.push(id, 'ARTRONIQ') // 9
array.push(id, 'ASDION') // 10
array.push(id, 'ASIAPLY') // 11
array.push(id, 'AT') // 12
array.push(id, 'BAHVEST') // 13
array.push(id, 'BCMALL') // 14
array.push(id, 'BINACOM') // 15
array.push(id, 'BIOHLDG') // 16
array.push(id, 'BTECH') // 17
array.push(id, 'CABNET') // 18
array.push(id, 'CATCHA') // 19
array.push(id, 'CEKD') // 20
array.push(id, 'CENGILD') // 21
array.push(id, 'CNERGEN') // 22
array.push(id, 'CORAZA') // 23
array.push(id, 'DFX') // 24
array.push(id, 'DGB') // 25
array.push(id, 'DPIH') // 26
array.push(id, 'EAH') // 27
array.push(id, 'ECOMATE') // 28
array.push(id, 'EDUSPEC') // 29
array.push(id, 'EFRAME') // 30
array.push(id, 'EIB') // 31
array.push(id, 'ESAFE') // 32
array.push(id, 'ESCERAM') // 33
array.push(id, 'EVD') // 34
array.push(id, 'FAST') // 35
array.push(id, 'FINTEC') // 36
array.push(id, 'FLEXI') // 37
array.push(id, 'FOCUS') // 38
array.push(id, 'FOCUSP') // 39
array.push(id, 'GENETEC') // 40
array.push(id, 'GFM') // 41
array.push(id, 'GNB') // 42
array.push(id, 'GOCEAN') // 43
array.push(id, 'HAILY') // 44
array.push(id, 'HEXIND') // 45
array.push(id, 'HHGROUP') // 46
array.push(id, 'HHHCORP') // 47
array.push(id, 'HLT') // 48
array.push(id, 'HPPHB') // 49
array.push(id, 'IFCAMSC') // 50
array.push(id, 'INFOTEC') // 51
array.push(id, 'INNITY') // 52
array.push(id, 'IRIS') // 53
array.push(id, 'JAG') // 54
array.push(id, 'JFTECH') // 55
array.push(id, 'K1') // 56
array.push(id, 'KANGER') // 57
array.push(id, 'KGROUP') // 58
array.push(id, 'KHJB') // 59
array.push(id, 'KRONO') // 60
array.push(id, 'KTC') // 61
array.push(id, 'LAMBO') // 62
array.push(id, 'LGMS') // 63
array.push(id, 'LKL') // 64
array.push(id, 'LYC') // 65
array.push(id, 'MAG') // 66
array.push(id, 'MATANG') // 67
array.push(id, 'MCLEAN') // 68
array.push(id, 'MEGASUN') // 69
array.push(id, 'MESTRON') // 70
array.push(id, 'MGRC') // 71
array.push(id, 'MICROLN') // 72
array.push(id, 'MIKROMB') // 73
array.push(id, 'MLAB') // 74
array.push(id, 'MMAG') // 75
array.push(id, 'MNC') // 76
array.push(id, 'MNHLDG') // 77
array.push(id, 'MOBILIA') // 78
array.push(id, 'MPAY') // 79
array.push(id, 'MQTECH') // 80
array.push(id, 'MTAG') // 81
array.push(id, 'MTOUCHE') // 82
array.push(id, 'N2N') // 83
array.push(id, 'NADIBHD') // 84
array.push(id, 'NESTCON') // 85
array.push(id, 'NETX') // 86
array.push(id, 'NEXGRAM') // 87
array.push(id, 'NOVAMSC') // 88
array.push(id, 'OPCOM') // 89
array.push(id, 'OPENSYS') // 90
array.push(id, 'OPTIMAX') // 91
array.push(id, 'ORGABIO') // 92
array.push(id, 'OSKVI') // 93
array.push(id, 'OVERSEA') // 94
array.push(id, 'OVH') // 95
array.push(id, 'PARLO') // 96
array.push(id, 'PASUKGB') // 97
array.push(id, 'PEKAT') // 98
array.push(id, 'PINEAPP') // 99
array.push(id, 'PLABS') // 100
array.push(id, 'PPJACK') // 101
array.push(id, 'PRIVA') // 102
array.push(id, 'PUC') // 103
array.push(id, 'PWRWELL') // 104
array.push(id, 'QES') // 105
array.push(id, 'RAMSSOL') // 106
array.push(id, 'REDTONE') // 107
array.push(id, 'REXIT') // 108
array.push(id, 'RGTECH') // 109
array.push(id, 'SAMAIDEN') // 110
array.push(id, 'SANICHI') // 111
array.push(id, 'SCBUILD') // 112
array.push(id, 'SCC') // 113
array.push(id, 'SCOMNET') // 114
array.push(id, 'SCOPE') // 115
array.push(id, 'SDS') // 116
array.push(id, 'SEDANIA') // 117
array.push(id, 'SERSOL') // 118
array.push(id, 'SFPTECH') // 119
array.push(id, 'SIAB') // 120
array.push(id, 'SMETRIC') // 121
array.push(id, 'SMRT') // 122
array.push(id, 'SMTRACK') // 123
array.push(id, 'SOLUTN') // 124
array.push(id, 'SPRING') // 125
array.push(id, 'SRIDGE') // 126
array.push(id, 'STRAITS') // 127
array.push(id, 'SUNZEN') // 128
array.push(id, 'SYSTECH') // 129
array.push(id, 'TASHIN') // 130
array.push(id, 'TCS') // 131
array.push(id, 'TDEX') // 132
array.push(id, 'TELADAN') // 133
array.push(id, 'TEXCYCL') // 134
array.push(id, 'TFP') // 135
array.push(id, 'TRIMODE') // 136
array.push(id, 'UCREST') // 137
array.push(id, 'UMC') // 138
array.push(id, 'UNIQUE') // 139
array.push(id, 'UNITRAD') // 140
array.push(id, 'VC') // 141
array.push(id, 'VINVEST') // 142
array.push(id, 'VIS') // 143
array.push(id, 'VOLCANO') // 144
array.push(id, 'VSOLAR') // 145
array.push(id, 'WAJA') // 146
array.push(id, 'WIDAD') // 147
array.push(id, 'XOX') // 148
array.push(id, 'XOXNET') // 149
array.push(id, 'XOXTECH') // 150
array.push(id, 'YBS') // 151
array.push(id, 'YEWLEE') // 152
array.push(id, 'YGL') // 153
array.push(id, 'YXPM') // 154
array.push(id, 'ZENTECH') // 155
[id]
// } |
loxxdynamiczone | https://www.tradingview.com/script/rezad7KS-loxxdynamiczone/ | loxx | https://www.tradingview.com/u/loxx/ | 25 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
// @description Dynamic Zones
// Derives Leo Zamansky and David Stendahl's Dynamic Zone,
// see "Stocks & Commodities V15:7 (306-310): Dynamic Zones by Leo Zamansky, Ph .D., and David Stendahl"
library("loxxdynamiczone", overlay = true)
// @function method for retrieving the dynamic zone levels from input source.
// @param type string, value of either 'buy' or 'sell'.
// @param src float, source, either regular source type or some other caculated value.
// @param pval float, probability defined by extension over/under source, a number <= 1.0.
// @param per int, period lookback.
// @returns float dynamic zone level.
// usage:
// dZone("buy", close, 0.2, 70)
export dZone(string type, float src, float pval, int per)=>
float left = -ta.highest(high, per * 3) /syminfo.mintick
float right = ta.highest(high, per * 3) /syminfo.mintick
float eps = math.min(syminfo.mintick, 0.001)
int maxSteps = 0
float yval = (left + right) / 2.0
yval := na(yval) ? close : yval
float delta = yval - left
while (delta > eps * 5 and maxSteps < per * 2)
maxSteps += 1
int count = 0
if type == "buy"
for k = 0 to per - 1 by 1
if src[k] < yval
count += 1
float prob = count/per
if prob > (pval + eps)
right := yval
yval := (yval + left) / 2.
if prob < (pval - eps)
left := yval
yval := (yval + right) / 2.
if prob < pval + eps and prob > (pval - eps)
right := yval
yval := (yval + left) / 2.
delta := yval - left
delta
else
for k = 0 to per - 1 by 1
if src[k] > yval
count += 1
float prob = count/per
if prob > (pval + eps)
left := yval
yval := (yval + right) / 2.
if prob < (pval - eps)
right := yval
yval := (yval + left) / 2.
if prob < pval + eps and prob > (pval - eps)
left := yval
yval := (yval + right) / 2.
delta := yval - left
yval
//example usage
inter = ta.sma(close, 20)
buylevel = dZone("buy", inter, 0.2, 70)
selllevel = dZone("sell", inter, 0.2, 70)
plot(buylevel, color = color.blue)
plot(selllevel, color = color.white)
|
calc | https://www.tradingview.com/script/PjwF9sqT-calc/ | 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 Library for math functions. will expand over time.
library("calc")
// =============================================================================
// misc
// @function Split a large number into integer sized chunks
// @param _sumTotal (int) Total numbert of items
// @param _divideBy (int) Groups to make
// @param _forceMinimum (bool) force minimum number 1/group
// @param _haltOnError (bool) force error if too few groups
// @returns int[] array of items per group
export split( int _sumTotal, int _divideBy, bool _forceMinimum = true, bool _haltOnError = false)=>
varip _counts = array.new<int>(_divideBy)
switch
_sumTotal < _divideBy =>
switch
_haltOnError => runtime.error('Size < Divisions')
_forceMinimum => array.fill(_counts,1)
=> array.fill(_counts,1)
_sumTotal % _divideBy == 0 =>
for i = 0 to _divideBy - 1
array.set(_counts,i,_sumTotal/_divideBy)
=>
_base = _divideBy - (_sumTotal % _divideBy)
_fl = math.floor(_sumTotal/_divideBy)
for i = 0 to _divideBy -1
if ( i >= _base)
array.set(_counts, i , _fl + 1)
else
array.set(_counts, i , _fl )
_counts
// @function Absolute distance between any two float values, agnostic to +/-
// @param _value1 First value
// @param _value2 Second value
// @returns Absolute Positive Distance
export gapSize(float _value1, float __value2) =>
varip float _top = na
varip float _bot = na
varip float _out = na
_top := math.max(_value1,__value2)
_bot := math.min(_value1,__value2)
_out := switch
_bot > 0 or _top < 0 => _top - _bot
=> _top + 0 - _bot
// test demo
_value1 = input.float(1 ,step=0.25)
// _value2 = input.float(-1.5 ,step=0.25)
// plot(gapSize(_value1,_value2))
// =============================================================================
// fractions (as of lib revision 5, very fast. using Richards algo.)
// @function Helper
greatestDenom(_numerator, _denominator)=>
_greatestCommon = _numerator
_den = _denominator
_swap = _den
while _den != 0
_greatestCommon %= _den
_swap := _den
_den := _greatestCommon
_greatestCommon := _swap
_greatestCommon
//function Simplify fraction to lowest form
// @param _num (int) Input fraction numerator
// @param _den (int) Input fraction dennominator
// @returns Simplified Fraction
export simplifyFraction(int _num, int _den)=>
common = greatestDenom(_num, _den)
_numLowest = int(_num / common)
_denLowest = int(_den / common)
[_numLowest,_denLowest]
// @function Convert Decimal to tuple fraction Output, 1/0 resolves to [1,1]
// note : it is suboptimal, will be updating with a much faster algorithm
// @param _input Decimal Input
// @param _epsilon (OPTIONAL) to precision (10e-N)
// @param _iterations Maximum iterations (OPTIONAL)
// @returns [num,den] Simplified Fraction (if negative, Numerator gets the sign)
export toFraction(float _source, int _epsilon = 6, int _iterations = 20) =>
switch
_source == int(_source) => [int(_source),1]
na (_source) => [0 , 1]
=>
_d = array.new<int>(_iterations+2,0)
_num = math.abs(_source)
array.set(_d,1,1)
_z = _num, _n = 1
_t = 1
while _num and _t < _iterations and math.abs(_n/array.get(_d,_t) - _num) > math.pow(10, -_epsilon)
_t += 1
_z := 1/(_z - int(_z))
array.set(_d,_t,array.get(_d,_t-1) * int(_z) + array.get(_d,_t-2))
_n := int(_num * array.get(_d,_t) + 0.5)
simplifyFraction(int(math.sign(_source)*_n),int(array.get(_d,_t)))
//@function Measure percent (0.##) of Distance between two points
// @param signal value to check
// @param _startVal first value limit
// @param _endVal second value limit
export percentOfDistance(float signal, float _startVal, float _endVal) =>
varip _max = 0.,varip _min = 0.,varip _signal = 0.
varip _num = 0.,varip _den = 0.,varip _position = 0.
_max := math.max( _startVal , _endVal )
_min := math.min( _startVal , _endVal )
_signal := math.max( _min , math.min ( _max, signal ) )
_num := gapSize ( _signal , _startVal )
_den := gapSize ( _endVal , _startVal )
_position := switch
_num == 0 or _den == 0 => 0
=> _num / _den
//@function Measure percent (0.##) of Distance between two points
// @param signal value to check
// @param _startVal first value limit
// @param _endVal second value limit
// @returns [Num,Denom] fraction
export fractionOfDistance(float signal, float _startVal, float _endVal) =>
toFraction(percentOfDistance(signal,_startVal,_endVal))
//@function Power of 10 scale up
//@param _src Input value
//@param _pow Number of * 10 to perform
//@returns Value with decimal moved + right, - left
export pow10 (float _src, int _pow = 2) =>
switch _pow
0 => _src
=>_src * math.pow(10,math.max(1,_pow))
//@function Power of 10 to req to integer
//@param _src Input value) =>
//@returns Decimals required to reach integer from minimum tick. (useful for for non ohlc vals)
export pow10chk(float _src) =>
varip _p = 1, varip _v = float(na)
_v := math.round_to_mintick(_src)
while _v != int(_v)
_p += 1
_v *= 10
_p
// @function Measure a source distance from a mid point as +/- 1.0 being he furhest distance the have been
// @param _src Input value
// @param _mid The mid point to Measure fron
export from_center(float _src, float _mid = 0 ) =>
var float _limit = 0
_limit := math.max(_limit, gapSize(_src,_mid))
percentOfDistance(gapSize(_src,_mid) , 0, _limit) * math.sign(_src-_mid)
|
HSV and HSL gradient Tools ( Built-in Drop-in replacement ) | https://www.tradingview.com/script/7poJ0BTX-HSV-and-HSL-gradient-Tools-Built-in-Drop-in-replacement/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 59 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kaigouthro
//@version=5
// @description HSV and HSL Color Tools
library("hsvColor")
import kaigouthro/calc/5
//@funcction Limiter for out of range values
//@param _h _hueValue input to limit signals before using color.
//@param _s _saturation input to limit signals before using color.
//@param _vl _value input to limit signals before using color.
//@param _a _alpha input to limit signals before using color.
export hslimit(float _h,float _s,float _vl,float _a) =>
_saturation = 0., _alpha = 0., _valOrLum = 0.
_hueValue = nz(_h)
if _hueValue < 0 or _hueValue >= 360
while _hueValue < 0
_hueValue += 360
if _hueValue >= 360
_hueValue %= 360
_saturation := math.max ( 0 , math.min ( 1 , nz(_s) ))
_alpha := math.max ( 0 , math.min ( 1 , nz(_a) ))
_valOrLum := math.max ( 0 , math.min ( 1 , nz(_vl) ))
[_hueValue,_saturation,_valOrLum,_alpha]
//@funcction helper for hsl
hue2rgb(p, q, tr) =>
var _2thrd = 2/3.
var _1six = 1/6.
var _1half = 1/2.
_trasnparency = tr
while (_trasnparency < 0)
_trasnparency += 1
while (_trasnparency > 1)
_trasnparency -= 1
switch
(_trasnparency < _1six ) => p + (q - p) * 6 * _trasnparency
(_trasnparency < _1half) => q
(_trasnparency < _2thrd) => p + (q - p) * (_2thrd - _trasnparency) * 6
=> p/1.
// @function RGB Color to HSV Values
// @param _col Color input (#abc012 or color.name or color.rgb(0,0,0,0))
// @returns [_hueValue,_saturation,_value,_alpha] values
export rgbhsv(color _col) =>
var _255 = 1/255.
_red = color.r(_col) * _255
_green = color.g(_col) * _255
_blue = color.b(_col) * _255
_value = math.max(_red, _green, _blue)
_chroma = _value - math.min(_red, _green, _blue)
_saturation = _value == 0 ? 0 : _chroma / _value
_hue = 0.
_hue := switch
_chroma == 0 => 0.0
_value == _red => 60 * (0 + (_green - _blue) / _chroma)
_value == _green => 60 * (2 + (_blue - _red) / _chroma)
=> 60 * (4 + (_red - _green) / _chroma)
_alpha = 1 - color.t(_col)/100.
[_h,_s,_v,_a] = hslimit(_hue,_saturation,_value,_alpha)
// @function RGB Color to HSV Values
// @param _r Red 0 - 255
// @param _g Green 0 - 255
// @param _b Blue 0 - 255
// @param _t Transp 0 - 100
// @returns [_hueValue,_saturation,_value,_alpha] values
export rgbhsv(float _r, float _g, float _b, float _t = 0)=>
rgbhsv(color.rgb(_r,_g,_b,_t))
// @function HSV colors, Auto fix if past boundaries
// @param _h Hue Input (-360 - 360) or further
// @param _s Saturation 0.- 1.
// @param _v Value 0.- 1.
// @param _a Alpha 0.- 1.
// @returns Color output
export hsv ( float _h, float _s, float _v, float _a = 1) =>
[_hueValue,_saturation,_value,_alpha] = hslimit(_h,_s,_v,_a)
varip _red = 0., varip _green = 0., varip _blue = 0., var color out = na
_hueValue := switch
_s == 0 or _v == 0 => _hueValue
=> _hueValue/60.
_chroma = _value * _saturation
_secondaryChroma = _chroma * ( 1 - math.abs ( _hueValue % 2 - 1 ) )
_mval = _value - _chroma
_red := _chroma , _green:=_chroma ,_blue:=_chroma
if _saturation > 0
switch math.floor(_hueValue)
0 => _red := _chroma , _green := _secondaryChroma , _blue := 0
1 => _red := _secondaryChroma , _green := _chroma , _blue := 0
2 => _red := 0 , _green := _chroma , _blue := _secondaryChroma
3 => _red := 0 , _green := _secondaryChroma , _blue := _chroma
4 => _red := _secondaryChroma , _green := 0 , _blue := _chroma
5 => _red := _chroma , _green := 0 , _blue := _secondaryChroma
_trasnparency = 100 - _a * 100
out := switch
_trasnparency < 100 => color.rgb((_mval+_red)*255,(_mval+_green)*255,(_mval+_blue)*255,_trasnparency)
=> color.rgb(0,0,0,100)
// @function returns 0-359 hue on color wheel
// @param _col
// @param _rotate Turn output by N degrees (+/-)
// @returns 360 degree hue value
export hue (color _col, float _rotate = 0.) =>
[_hueValue,_s,_v,_a] = rgbhsv(_col)
_hueValue += _rotate
// @function HSL vals from rgb col in
// @param _col The Color
// @returns HSLA tuple out
export rgbhsl ( color _col)=>
var _red = 0., var _green = 0., var _blue = 0.
_trasnparency = color.t(_col)
_red := color.r(_col)/255
_green := color.g(_col)/255
_blue := color.b(_col)/255
max = math.max(_red, _green, _blue)
min = math.min(_red, _green, _blue)
_hueValue = hue(_col)
_saturation = 0.
_distance = 0.
_luminosity = max + min
_luminosity *= .5
switch max
min =>
_hueValue := 0
_saturation := 0
=>
_distance := max - min
_saturation := _luminosity > 0.5 ? _distance / (2 - max - min) : _distance / (max + min)
_alpha = 1 - _trasnparency/100
[_h,_s,_l,_a] = hslimit(_hueValue, _saturation, _luminosity, _alpha)
// @function HLS input to color output
// @param _hueValue hue
// @param _saturation saturation
// @param _luminosity lightness
// @returns The RGB Color
export hsl(float _h, float _s, float _l, float _a) =>
var _red = 0., var _green = 0., var _blue = 0.
var color out = na, var _1thr = 1/3.
[_hueValue,_saturation,_luminosity,_alpha] = hslimit(_h,_s,_l,_a)
_hueValue /= 360
_red := _luminosity
_green := _luminosity
_blue := _luminosity
if _saturation > 0
q = _luminosity < 0.5 ? _luminosity * (1 + _saturation) : _luminosity + _saturation - _luminosity * _saturation
p = 2 * _luminosity - q
_red := hue2rgb(p, q, _hueValue + _1thr)
_green := hue2rgb(p, q, _hueValue)
_blue := hue2rgb(p, q, _hueValue - _1thr)
_trasnparency = 100 - _a * 100
out := switch
_trasnparency <= 99 => color.rgb(_red * 255, _green * 255, _blue * 255, _trasnparency)
=> color.rgb(0,0,0,100)
//@function helper
_hueValue(x)=>varip _value=x,_value+=x,_value/=2
fix(x)=> varip a = 1+x , a := 1 + x , varip b = 1-x , b := 1 - x , math.sqrt( (a*a+b*b) / 2 )
// @function Calculate relative luminance in sRGB colour space
// for use in WCAG 2.0 compliance
// @link http://www.w3.org/TR/WCAG20/#relativeluminancedef
// @param col (hex,rgb,color.___)
// @returns float
export relativeluminance (color col) =>
newrgb = array.new<float>()
//Convert hex to 0-1 scale
_rgb = array.from(color.r(col)/254,color.g(col)/254,color.b(col)/254)
//Correct for web
for val in _rgb
_chroma = val
if _chroma <= 0.04045
_chroma /= 12.92
else
_chroma := math.pow(((_chroma + 0.055) / 1.055), 2.4)
array.push(newrgb,_chroma)
// output (correccted to 0-1.0 rathern than 1-21)
0.05 + (array.get(newrgb,0) * 0.2126 + array.get(newrgb,1) * 0.7152 + array.get(newrgb,2) * 0.0722)/20
// @function Calculate Brightness Level of color.
// @param col (hex,rgb,color.___)
// @returns float brightness level
export bright(color col) =>
varip _1223 = 12+23/25.
varip _11200 = 11 / 200.
varip _1011 = _11200 + 1
varip _red = 0.
varip _green = 0.
varip _blue = 0.
_value = 0.
_red := color.r(col)
_green := color.g(col)
_blue := color.b(col)
_value += 212 / 500. * ((_red / 255.) <= 1/25. ? (_red / 255.)/(_1223) : math.pow(((_red /255.) + _11200)/_1011, 2.4))
_value += 143 / 200. * ((_green/ 255.) <= 1/25. ? (_green / 255.)/(_1223) : math.pow(((_green /255.) + _11200)/_1011, 2.4))
_value += 9 / 125. * ((_blue / 255.) <= 1/25. ? (_blue / 255.)/(_1223) : math.pow(((_blue /255.) + _11200)/_1011, 2.4))
_value <= 3 / 1000. ? _value * _1223 : _1011 * math.pow(_value,1/2.4) - _11200
// @function Switch between colors based on Color Brightness
// @param _signal color control signal
// @param _th threshold for switch between colors
// @param _colora if below threshold
// @param _colorb if above threshold
// @returns Contrasting color switched by input control color
export tripswitch(float _signal, float _th = 0, color _colora = #000000, color _colorb = #ffffff) =>
var color _out = _colora
_out := switch
_signal < _th => _colora
_signal > _th => _colorb
=> _out
// @function Switch between colors based on Color Brightness
// @param _color color control signal
// @param _th threshold for switch between colors
// @param _colora if below threshold (default white)
// @param _colorb if above threshold (default black)
// @returns Contrasting color switched by input control color
export tripswitch(color _col, float _th = 0.5, color _colora = #ffffff, color _colorb = #000000) =>
var color _out = _colora
_signal = bright(_col)
_out := switch
_signal < _th => _colora
_signal > _th => _colorb
=> _out
//@function shape easing utility for sat/val/lum/alpha
//@input ( 0 - 1.0 )
//@returns this -> _/`` eased value
export easeBoth (float _val) =>
out = switch
_val < 0.5 => 4 * _val * _val * _val
=> 1 - math.pow(-2 * _val + 2, 3) / 2
math.max(0,math.min(1,out))
//@function shape easing utility for sat/val/lum/alpha
//@input ( 0 - 1.0 )
//@returns this -> __/ eased value
export easeIn (float _val) =>
out = switch _val
0 => 0
=> math.pow(2, 10 * _val - 10)
math.max(0,math.min(1,out))
//@function shape easing utility for sat/val/lum/alpha
//@input ( 0 - 1.0 )
//@returns this -> /``` eased value
export easeOut (float _val) =>
out = switch _val
1 => 1
=> 1 - math.pow(2, -10 * _val)
math.max(0,math.min(1,out))
// @function Color Gradient Replacement Function for HSV calculated Gradents
// @param signal Control signal
// @param _startVal start color limit
export hsvInvert(color _color) =>
[_h,_s ,_v ,_a] = rgbhsv(_color)
_v := 1 - easeBoth(_v)
hsv(_h,_s,_v,_a)
//@function Invert _alpha color with hsl method (original experimental)
//@param _color color input
//@returns inverted color
export hslInvert(color _color) =>
[_h ,_s ,_l ,_a] = rgbhsv(_color)
_l := 1 - easeBoth(_l)
hsl(_h,_s,_l,_a)
// @function Color Gradient Replacement Function for HSV calculated Gradents
// @param signal Control signal
// @param _startVal start color limit
// @param _endVal end color limit
// @param _startCol start color
// @param _endCol end color
// @returns HSV calculated gradient
export hsv_gradient(float signal, float _startVal, float _endVal,color _startCol,color _endCol)=>
varip _hueValue=0.,varip _saturation=0.,varip _value =0.,varip _alpha=0.
[ h1,s1,v1,a1 ] = rgbhsv(_startCol)
[ h2,s2,v2,a2 ] = rgbhsv(_endCol)
varip _position = 0.
_position := calc.percentOfDistance(signal,_startVal,_endVal)
switch
_startVal != _endVal =>
_hueValue := h1 + 360 + _position * ((h2 - h1 + 540 ) % 360 - 180)
_saturation := s1 + (s2 - s1) * _position
_value := v1 + (v2 - v1) * _position
_alpha := a1 + (a2 - a1) * _position
hsv(_hueValue, _saturation, _value, _alpha)
// @function Color Gradient Replacement Function for HSV calculated Gradents
// @param signal Control signal
// @param _startVal start color limit
// @param _endVal end color limit
// @param _startCol start color
// @param _endCol end color
// @returns HSV calculated gradient
export hsl_gradient(float signal, float _startVal, float _endVal,color _startCol,color _endCol)=>
varip _hueValue=0.,varip _saturation=0.,varip _luminosity=0.,varip _alpha=0.
[ h1,s1,l1,a1 ] = rgbhsl(_startCol)
[ h2,s2,l2,a2 ] = rgbhsl(_endCol)
varip _position = 0.
_position := calc.percentOfDistance(signal,_startVal,_endVal)
switch
_startVal != _endVal =>
_hueValue := h1 + 360 + _position * ((h2 - h1 + 540 ) % 360 - 180)
_saturation := s1 + (s2 - s1) * _position
_luminosity := l1 + (l2 - l1) * _position
_alpha := a1 + (a2 - a1) * _position
hsl(_hueValue, _saturation, _luminosity, _alpha)
// @function Step of multiplot hue shifter by source value.
// @param _source (float) value being plotted
// @param _basehue (float) starting point hue from step 0
// @param _step (float) in a stack of plots, which number is it
// @param _range (float) hue range to have mobility in.
// @returns Float for Hue
export stepHue(float _src, float _basehue, float _step, float _range) =>
varip _min = float(na), varip _max = float(na),varip _source = float(na)
_source := nz(_src,_source)
_min := nz(_min,_src)
_max := nz(_max,_src)
_min := math.avg(ta.sma(ta.lowest (_source,7),7),_min)
_max := math.avg(ta.sma(ta.highest(_source,7),7),_max)
_basehue + _step * _range + easeBoth(calc.percentOfDistance(_src,0,calc.gapSize(_min,_max))) * _range
// @function Gradient color helper for fills
// @param _source value to folloow
// @param _soften adjusts edging short of value (fill softener)
// @param _step Which step of the muliplot is this
// @param _color1 Color at Low
// @param _color2 Color at high
// @return Color for fill usage (plot,not linefill)
export stepGradient(float _src, float _soften, float _step, color _color1,color _color2) =>
var _col = #000000, varip _min = float(na), varip _max = float(na),varip float _source = na
_srci = _step * fix(_soften) * fix(_src)
_source := nz(_srci,_source)
_min := math.min(nz(_min[1],_source),nz(_min[1]))
_max := math.max(nz(_max[1],_source),nz(_max[1]))
_min := ta.sma(math.avg(_min,_source),15)
_max := ta.sma(math.avg(_max,_source),15)
_Avg = math.avg(nz(_min),nz(_max))
_source += _Avg
_col := hsv_gradient(_source, _min, _max , _color1, _color2)
// @function Angle of travel
// @param _src Input to get angle for
// @param _hist distane back along source for origin point
// @returns angle +/- from 0 being flat
export degree(float _src,int _hist) =>
varip _y = float(na)
_y := nz(_src,_y)
deltaX = math.max(_hist,1)
deltaY = _y/_y[deltaX] -1
rad = math.atan(deltaY)
deg = rad * (180 / math.pi)
deg
|
SumOfCandles | https://www.tradingview.com/script/BKeRoxmi-SumOfCandles/ | boitoki | https://www.tradingview.com/u/boitoki/ | 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/
// © boitoki
//@version=5
// @description This function returns sum of candlestick's body.
library("SumOfCandles", overlay=false)
f_madev (v, m) => ((v - m) / m) * 100
// @function This function returns a value without any post-processing.
// @param _open Source
// @param _close Source
// @param _len Period
export simple_sum (float _open, float _close, int _len) => math.sum(_close - _open, _len)
// @function This function returns a value without any post-processing.
// @param _int Period
export simple_sum (int _len) => math.sum(close - open, _len)
// @function Returns the sum of candlestick body.
// @param _open Source
// @param _close Source
// @param _len Period
// @param _malen MA Period
// @param _usema A flag of using MA
// @returns sum
export calc (float _open, float _close, int _len, simple int _malen, bool _usema = true) =>
sum = ta.rma(ta.rma(simple_sum(_open, _close, _len), 2), 2)
oc2 = math.avg(_open, _close)
f = ta.rma(oc2, 2)
s = ta.rma(oc2, _malen)
d = _usema ? f_madev(f, s) : 0
res = sum + d
[res, ta.change(res)]
// @function Returns the sum of candlestick body.
// @param _len Period
// @param _malen MA period
// @param _usema A flag of using MA
// @returns sum
export calc (int _len, simple int _malen = 1, bool _usema = true) =>
sum = ta.rma(ta.rma(simple_sum(open, close, _len), 2), 2)
oc2 = math.avg(open, close)
f = ta.rma(oc2, 2)
s = ta.rma(oc2, _malen)
d = _usema ? f_madev(f, s) : 0
res = sum + d
[res, ta.change(res)]
[sum, sum_changed] = calc(3, 14, true)
barcolor = sum > 0
? sum_changed > 0 ? color.green : color.from_gradient(60, 0, 100, color.green, color.black)
: sum_changed < 0 ? color.red : color.from_gradient(60, 0, 100, color.red, color.black)
barcolor(barcolor)
hline(0)
plot(sum, color=barcolor, style=plot.style_columns) |
Hex | https://www.tradingview.com/script/hWjJ7FSZ-Hex/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// © kaigouthro
//@version=5
//@description Hex String Utility
library('Hex')
// @function helper Binary half octet to hex character
// @param _n Digits to convert
export intToHex(int _n) =>
switch _n
0 => '0'
1 => '1'
2 => '2'
3 => '3'
4 => '4'
5 => '5'
6 => '6'
7 => '7'
8 => '8'
9 => '9'
10 => 'A'
11 => 'B'
12 => 'C'
13 => 'D'
14 => 'E'
15 => 'F'
=> '%ERROR'
// @function Digits to Hex String output
// @param _input Integer Input
// @param _buffer Number of 0's to pad Hex with
// @returns string output hex character value buffered to desired length (00-ff default)
export fromDigits (int _input, int _buffer = 2) =>
_dec = _input
_out = ''
switch _input
0 => _out := '00'
=>
while _dec > 0
_n = _dec/16
_f = math.floor(_n)
_r = (_n -_f ) * 16
_out := intToHex(_r) + _out
_dec := _f
while str.length(_out )%_buffer > 0
_out := '0'+_out
_out
// Demo
if barstate.islastconfirmedhistory
c = 0
a = ''
for i = 0 to 255
c+=1
a += fromDigits(i*1000,8)
a +=' \n'
if (i+1) % 16== 0
label lb = na
label.delete(lb[1])
lb := label.new(last_bar_index-i, close,a,size=size.huge,color=color.white,size=size.tiny)
c:=0
|
PointofControl | https://www.tradingview.com/script/QQ6WwrQO-PointofControl/ | JohnBaron | https://www.tradingview.com/u/JohnBaron/ | 95 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JohnBaron
//@version=5
// This library provides a single funciton which outputs an array as a result
// The purpose of the function is to provide a volume profile POC to a script author
library(title="PointofControl",overlay=true)
Round_to_Level(s_,t_)=>
math.round(s_/t_)*t_
// Use average range across chart to estimate an increment
Auto_Incr()=>
avg_range = math.round_to_mintick(ta.cum(high-low)/(bar_index+1)) //calculate the running average of the range rounded to mintick
wn_ = avg_range/syminfo.mintick // transform and convert to whole number
pow_ = math.pow(10,int(math.log10(wn_))) //use only integer portion of log
target_ = 2*math.ceil(wn_/pow_)*syminfo.mintick*pow_ //transform back to scale
// @function Calculates the point of control
// @param val Series to use (`low` is used if no argument is supplied).
// @param bool reset_flag forces the reset based on a condition in the main script and only used when bars_ parm is 0
// @param int bars_. when 0 is input the reset_flag drives the reset, otherwise # of bars passed until reset
// @param float incr_, input on the price increment, if 0 is used then the function will use the auto calculated level
//-----------
// @returns An 11 element array
// [0] = upper_bound
// [1] = lower_bound
// [2] = POC
// [3] = historical POC immediately above price
// [4] = historical POC immediately below price
// [5] = Grand POC, the POC for the entire data set
// [6] = Entire data set rank order 2 of POC
// [7] = Entire data set rank order 3 of POC
// [8] = Entire data set rank order 4 of POC
// [9] = auto_increment value
// [10]= reset_flag, lets you know when a reset occurred
//===========
//
export POC_f(bool reset_flag, int bars_, float incr_in)=>
var bar_count =0
var ub_ = high
var lb_ = low
var max_v =0.
var POC_ = hlc3
var Grand_poc2 = 0.
var Grand_poc3 = 0.
var Grand_poc4 = 0.
var hist_POC_above=hlc3
var hist_POC_below=hlc3
var v_ = array.new_float(0,0.)
var p_ = array.new_float(0,0.)
var hp_ = array.new_float(0,0.)
var hv_ = array.new_float(0,0.)
var error= na(volume) //determine if volume is available for the symbol
if error
runtime.error("Indicator is only valid on symbols with volume data") //generate error message if no volume for symbol
src_ = high
auto_incr = Auto_Incr()
incr_ = incr_in==0? auto_incr: incr_in
reset_ = switch
bars_==0 => reset_flag
=> bar_count>=bars_
if reset_ or bar_index==0
POC_idx = array.indexof(hp_,POC_)
if POC_idx== -1 // if -1 is returned it means the POC_ was not found, so we will save it
array.push(hp_,POC_)
array.push(hv_,max_v)
else // if the index and POC_ exists, then update the volume
hv_element=array.get(hv_,POC_idx)
array.set(hv_,POC_idx,(max_v+hv_element))
bar_count:=0
ub_ := Round_to_Level(high,incr_) //Set upper bound
lb_ := math.min(ub_-incr_,Round_to_Level(low,incr_)) //Set lower bound
array.clear(v_) //Clear the price and volume arrays
array.clear(p_)
array.push(v_,volume/2) //Add the initial two values to arrays
array.push(v_,volume/2)
array.push(p_, ub_)
array.push(p_, lb_)
bar_count +=1 //increment bar count
break_up = math.max(0.,high - ub_) //high vs upper bound
break_dn = math.max(0.,lb_ - low) //low vs lower bound
max_incr = int(break_up/incr_)+ (break_up%incr_>0? 1:0) //number of increments needed
min_decr = int(break_dn/incr_)+ (break_dn%incr_>0? 1:0) //
// If upper boundary needs to change
// Then add new upper increments to the beginning of the arrays
if max_incr>0
i = 1
while i<= max_incr
vol_incr = volume/max_incr
ub_ += incr_
array.unshift(v_,vol_incr)
array.unshift(p_, ub_)
i +=1
// If lower boundary needs to change
// Then add new lower increments to the end of the array
if min_decr>0
j=1
while j<= min_decr
vol_incr = volume/min_decr
lb_ -= incr_
array.push(v_,vol_incr)
array.push(p_, lb_)
j+=1
//
//If there is no change in the boundaries then locate current price in the defined levels
if max_incr==0 and min_decr==0
for [idx,element] in p_
if src_ > element and idx>0
v_element = array.get(v_,idx-1)
array.set(v_,idx-1, volume+v_element) //Volume accumulated into level
break
//== find point of control
max_v :=array.max(v_)
max_idx = array.indexof(v_,max_v)
POC_ := array.get(p_,max_idx)
//== sort chart dataset points of control
hp_sorted_ =array.sort_indices(hp_,order.descending)
hv_sorted_ =array.sort_indices(hv_,order.descending)
//== get historical POCs around current price
for [idx,element] in hp_sorted_
hp_value = array.get(hp_,element)
hist_POC_above := hp_value
if src_>hp_value
hist_POC_below:= hp_value
if idx>=1
higher_idx = array.get(hp_sorted_,idx-1)
hist_POC_above:= array.get(hp_, higher_idx)
break
//== find POC across all period POCs, the max of all POCs
max_max_idx = array.get(hv_sorted_,0)
Grand_POC = array.get(hp_,max_max_idx)
//== get the next 3 high volume levels
if array.size(hv_sorted_)>=4
max2_idx = array.get(hv_sorted_,1)
max3_idx = array.get(hv_sorted_,2)
max4_idx = array.get(hv_sorted_,3)
Grand_poc2 := array.get(hp_, max2_idx)
Grand_poc3 := array.get(hp_, max3_idx)
Grand_poc4 := array.get(hp_, max4_idx)
out_ = array.from(ub_, lb_, POC_, hist_POC_above, hist_POC_below, Grand_POC, Grand_poc2, Grand_poc3, Grand_poc4,auto_incr,(reset_?1.:0.))
//=====================================================
//==== Library Sample
//======= Inputs
use_week=input.bool(false,"Weekly Reset",group="Reset Trigger")
bars_ = input.int(800,title="# of Candles the reset",group="Reset Trigger",tooltip="Candles are counted from left to right")
//________Inputs for level increment
incr_ = input.float(0.,title="Price increment for levels, 0 results in auto increment",group="Levels")
see_suggestion=input.bool(false,"Show Auto_Incr",group="Levels")
//________Inputs for display
show_hist=input.bool(true,title="Show historic POCs",group="Display" ,tooltip="Historical POC above/below current price")
show_grands=input.bool(false,"Show Grand POC",group="Display",tooltip="Top POC for the entire data set")
show_rank = input.bool(false,"Show Next 3 Chart POCs",group="Display", tooltip="Rank 2-4 POCs for the entire data set")
show_mnmx=input.bool(false,"Show upper and lower bounds",group="Display")
reset_trigger = use_week? timeframe.change("W"):false
bars_in = use_week? 0 : bars_
POC_array = POC_f(reset_trigger,bars_in,incr_)
//=============== Plots and Drawings
plot(show_hist? array.get(POC_array,3):na,color=color.aqua,style=plot.style_cross,linewidth=1,title="hist_POC_above")
plot(show_hist? array.get(POC_array,4):na,color=color.aqua,style=plot.style_cross,linewidth=1,title="hist_POC_below")
plot(show_grands? array.get(POC_array,5):na,color=color.red,style=plot.style_cross,linewidth=2,title="Grand POC_")
plot(show_grands? array.get(POC_array,6):na,color=color.fuchsia,style=plot.style_cross,linewidth=1,title="Grand POC_2")
plot(show_grands? array.get(POC_array,7):na,color=color.fuchsia,style=plot.style_cross,linewidth=1,title="Grand POC_3")
plot(show_grands? array.get(POC_array,8):na,color=color.fuchsia,style=plot.style_cross,linewidth=1,title="Grand POC_4")
plot(show_mnmx? array.get(POC_array,0):na,color=color.blue)
plot(show_mnmx? array.get(POC_array,1):na, color=color.blue)
plot(array.get(POC_array,2),color=color.yellow,style=plot.style_linebr,linewidth=1,title="POC_")
//______________ Setup label and line
var lab_1 = label.new(na,na,text=na,color=color.white,textcolor=color.black,size=size.small)
var line_1 = line.new(na,na,na,na,color=color.gray, style= line.style_dashed,extend=extend.both)
//______________ Show the auto increment value
if barstate.islast and see_suggestion
label.set_xy(lab_1,bar_index,high+2*array.get(POC_array,9))
label.set_text(lab_1,str.tostring(array.get(POC_array,9)))
//______________ Draw Verticle line Marking the Reset Point
if array.get(POC_array,10)==1
line.set_xy1(line_1,bar_index,0.)
line.set_xy2(line_1,bar_index,close)
|
catchChecks | https://www.tradingview.com/script/N6ouqu0s-catchChecks/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// © kaigouthro
//@version=5
// @description Type Check for Function Builders to allow Single item to be
// passed in, and determine what to do with the item, ie: need an x value?
// function that allows label, line, box, float, or even a string..
// check item type? string ? 'str.tonumber(_item)' can be in the same
// switch as a 'line.get_price(_item, bar_index)' both outputting float
// or for pulling a value from simple, array, or matrix, one function
// that can switch between them. reduce overhead of many functions.
// there are many ways to use this tool, the simplest may be
// string/floats on one switch or grabbing colors from line/fill/label
// please Share any great recipes you come up with!
library("catchChecks")
_arrdummy(_temp) => array.set ( _temp , 0, array.get(_temp, 0 ))
_mtxdummy(_temp) => matrix.set ( _temp , 0, 0, matrix.get(_temp, 0,0))
_nrmdummy(_temp) => _temp == _temp[1] ? '' : ''
// @function Input anything.. Determine what it is.
// @param _temp (any) Matrix, Array, or Simple Item
// @param _doMeth (bool) True for M/A/S , false for int/float/string.. etc..
// @returns (string) Type of item checked.
export typeIs(int _temp, bool _doMeth = false)=> _s = _nrmdummy(_temp) , (_doMeth ? 'simple' : 'int' ) + _s
export typeIs(float _temp, bool _doMeth = false)=> _s = _nrmdummy(_temp) , (_doMeth ? 'simple' : 'float' ) + _s
export typeIs(bool _temp, bool _doMeth = false)=> _s = _nrmdummy(_temp) , (_doMeth ? 'simple' : 'bool' ) + _s
export typeIs(string _temp, bool _doMeth = false)=> _s = _nrmdummy(_temp) , (_doMeth ? 'simple' : 'string' ) + _s
export typeIs(color _temp, bool _doMeth = false)=> _s = _nrmdummy(_temp) , (_doMeth ? 'simple' : 'color' ) + _s
export typeIs(line _temp, bool _doMeth = false)=> _tmp = _temp, line.delete (_tmp) , (_doMeth ? 'simple' : 'line' )
export typeIs(label _temp, bool _doMeth = false)=> _tmp = _temp, label.delete (_tmp) , (_doMeth ? 'simple' : 'label' )
export typeIs(box _temp, bool _doMeth = false)=> _tmp = _temp, box.delete (_tmp) , (_doMeth ? 'simple' : 'box' )
export typeIs(table _temp, bool _doMeth = false)=> _tmp = _temp, table.delete (_tmp) , (_doMeth ? 'simple' : 'table' )
export typeIs(linefill _temp, bool _doMeth = false)=> _tmp = _temp, linefill.delete (_tmp) , (_doMeth ? 'simple' : 'linefill')
export typeIs(int [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'int' )
export typeIs(float [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'float' )
export typeIs(bool [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'bool' )
export typeIs(string [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'string' )
export typeIs(color [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'color' )
export typeIs(line [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'line' )
export typeIs(label [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'label' )
export typeIs(box [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'box' )
export typeIs(table [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'table' )
export typeIs(linefill [] _temp, bool _doMeth = false)=> _arrdummy(_temp) , (_doMeth ? 'array' : 'linefill')
export typeIs(matrix <int> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'int' )
export typeIs(matrix <float> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'float' )
export typeIs(matrix <bool> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'bool' )
export typeIs(matrix <string> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'string' )
export typeIs(matrix <color> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'color' )
export typeIs(matrix <line> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'line' )
export typeIs(matrix <label> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'label' )
export typeIs(matrix <box> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'box' )
export typeIs(matrix <table> _temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'table' )
export typeIs(matrix <linefill>_temp, bool _doMeth = false)=> _mtxdummy(_temp) , (_doMeth ? 'matrix' : 'linefill')
// demo
lb1 = 0 == hour% 5 ? label.new ( time , close , typeIs ( matrix.new<float>(1,1,0.5)) , xloc = xloc.bar_time, size = size.large, color = #ffaa00) : label(na)
lb2 = 0 == hour% 7 ? label.new ( time , close , typeIs ( array.new<label> (1, lb1 )) , xloc = xloc.bar_time, size = size.large, color = #99ccaa) : label(na)
lb3 = 0 == hour% 9 ? label.new ( time , close , typeIs ( lb2 ) , xloc = xloc.bar_time, size = size.large, color = #aaffcc) : label(na)
lb1a = 0 == hour% 3 ? label.new ( time , close , typeIs ( matrix.new<float>(1,1,0.5) , true ), xloc = xloc.bar_time, size = size.large, color = #ccaaff) : label(na)
lb2a = 0 == hour% 7 ? label.new ( time , close , typeIs ( array.new<string>(1, label.get_text(lb1a )) , true ), xloc = xloc.bar_time, size = size.large, color = #ff6600) : label(na)
lb3a = 0 == hour% 11? label.new ( time , close , typeIs ( lb2a , true ), xloc = xloc.bar_time, size = size.large, color = #ff00ff) : label(na)
|
loxxvarietyrsi | https://www.tradingview.com/script/iKTE0aCF-loxxvarietyrsi/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description RSI Variety
// 7 varieties of RSI used in Loxx's indicators and strategies.
// "rsi_rsi" is regular ta.rsi()
// "rsi_slo" is slowed down version of regular RSI
// "rsi_rap" is ta.rsi() but uses SMA instead of RMA, this is the same as Cuttlers RSI
// "rsi_har" is Michael Harris RSI, but a word of "warning". I left the Harris' rsi in the choices of rsi,
// but be advised that, due to the way how Harris rsi is calculated,
// if price filtering is used (ie: some randomness is taken away from price series)
// Harris RSI tends to produce results that can be "surprising" at the least in some cases.
// Even though Harris RSI is good when it comes to natural (semi-random) price usage,
// keep in mind what happens if the prices are filtered and why it happens
// "rsi_rsx" is Jurik's RSX
// "rsi_cut" is ta.rsi() but uses SMA instead of RMA, this is the same as Rapid RSI
// "rsi_ehl" is Ehles' Smoothed RSI
library("loxxvarietyrsi")
import loxx/loxxrsx/1
// @function method for returning 1 of 7 different RSI calculation outputs.
// @param rsiMode string, rsi mode, can be 1 of 7 of the following: "rsi_rsi", "rsi_slo", "rsi_rap", "rsi_har", "rsi_rsx", "rsi_cut", "rsi_ehl"; defaults to "rsi_rsi"
// @param src float, source, either regular source type or some other caculated value.
// @param per int, period lookback.
// @returns float RSI.
// usage:
// rsiVariety("rsi_rsi", src, per)
export rsiVariety(string rsiMode = "rsi_rsi", float src, int per)=>
out = 0.
float _change = 0.
float _changa = 0.
switch (rsiMode)
//Regular RSI, same as ta.rsi(src, per)
"rsi_rsi"=>
float alpha = 1.0/math.max(per, 1)
float change = src - nz(src[1])
_change := nz(_change[1]) + alpha * (change - nz(_change[1]) )
_changa := nz(_changa[1]) + alpha * (math.abs(change) - nz(_changa[1]))
out := _changa != 0. ? 50.0 * (_change/_changa + 1) : 50.
// Slow RSI
"rsi_slo"=>
float up = 0., float dn = 0., float _rsival = 0.
for k = 0 to per - 1
float diff = nz(src[k]) - nz(src[k+1])
if(diff > 0.)
up += diff
else
dn -= diff
if(up + dn == 0.)
_rsival := nz(_rsival[1]) + (1 / math.max(per, 1)) * (50 - nz(_rsival[1]))
else
_rsival := nz(_rsival[1]) + (1 / math.max(per, 1)) * (100 * up / (up + dn) - nz(_rsival[1]))
out := _rsival
// Rapid RSI, same as Cuttlers RSI
"rsi_rap"=>
float up = 0., float dn = 0.
for k = 0 to per - 1
float diff = nz(src[k]) - nz(src[k+1])
if(diff > 0.)
up += diff
else
dn -= diff
out := up + dn == 0. ? 50. : 100 * up / (up + dn)
// Harris RSI
"rsi_har"=>
float avgUp = 0., float avgDn = 0., float up = 0., float dn = 0.
for k = 0 to per - 1
float diff = nz(src[k]) - nz(src[k+1])
if(diff > 0.)
avgUp += diff
up := up + 1
else
avgDn -= diff
dn := dn + 1
if (up != 0.)
avgUp /= up
if (dn != 0.)
avgDn /= dn
float rs = 1
rs := avgDn != 0. ? avgUp / avgDn : rs
out := 100-100 / (1.0 + rs)
// RSX RSI
"rsi_rsx"=>
out := loxxrsx.rsx(src, per)
// Cuttlers RSI, same as Rapid RSI
"rsi_cut"=>
float sump = 0., float sumn = 0.
for k = 0 to per - 1
float diff = nz(src[k]) - nz(src[k+1])
if (diff > 0.)
sump += diff
if (diff < 0.)
sumn -= diff
out := sumn > 0. ? 100. - 100. / (1. + sump / sumn) : 50.
//Ehlers' Smoothed RSI
"rsi_ehl"=>
float up = 0., float dn = 0.
_prices = (bar_index > 2) ? (src + 2. * src[1] + src[2]) / 4.0 : src
for k = 0 to per - 1
float diff = nz(_prices[k]) - nz(_prices[k+1])
if(diff > 0.)
up += diff
else
dn -= diff
out := 50 * (up-dn) / (up+dn) + 50
=> 0.
out
//example usage
src = close
per = 15
rsi_rsi = rsiVariety("rsi_rsi", src, per)
rsi_slo = rsiVariety("rsi_slo", src, per)
rsi_rap = rsiVariety("rsi_rap", src, per)
rsi_har = rsiVariety("rsi_har", src, per)
rsi_rsx = rsiVariety("rsi_rsx", src, per)
rsi_cut = rsiVariety("rsi_cut", src, per)
rsi_ehl = rsiVariety("rsi_ehl", src, per)
plot(rsi_rsi, "Regular RSI", color = color.white)
plot(rsi_slo, "Slow RSI", color = color.lime)
plot(rsi_rap, "Rapid RSI", color = color.red)
plot(rsi_rsx, "RSX RSI", color = color.fuchsia)
plot(rsi_har, "Harris RSI", color = color.yellow)
plot(rsi_cut, "Cuttlers RSI", color = color.aqua)
plot(rsi_ehl, "Ehlers' Smoothed RSI", color = color.gray)
plot(50., color = bar_index % 2 ? color.white : na)
|
FunctionDynamicTimeWarping | https://www.tradingview.com/script/kcFoMVxO-FunctionDynamicTimeWarping/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 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/
// © RicardoSantos
//@version=5
// @description
// "In time series analysis, dynamic time warping (DTW) is an algorithm for
// measuring similarity between two temporal sequences, which may vary in
// speed. For instance, similarities in walking could be detected using DTW,
// even if one person was walking faster than the other, or if there were
// accelerations and decelerations during the course of an observation.
// DTW has been applied to temporal sequences of video, audio, and graphics
// data — indeed, any data that can be turned into a linear sequence can be
// analyzed with DTW. A well-known application has been automatic speech
// recognition, to cope with different speaking speeds. Other applications
// include speaker recognition and online signature recognition.
// It can also be used in partial shape matching applications."
//
// "Dynamic time warping is used in finance and econometrics to assess the
// quality of the prediction versus real-world data."
//
// ~~ wikipedia
//
// reference:
// https://en.wikipedia.org/wiki/Dynamic_time_warping
// https://towardsdatascience.com/dynamic-time-warping-3933f25fcdd
// https://github.com/shunsukeaihara/pydtw/blob/master/pydtw/dtw.pyx
//
library(title='FunctionDynamicTimeWarping')
d_argmin (float a, float b, float c) => a <= b or a <= c ? 0 : (b <= c ? 1 : 2)
distance (float a, float b) => math.abs(a - b)
// @function Dynamic Time Warping procedure.
// @param a array<float>, data series.
// @param b array<float>, data series.
// @param w int , minimum window size.
// @returns
// matrix<float> optimum match matrix.
export cost_matrix (
array<float> a,
array<float> b,
int w
) => //{
int _size_a = array.size(a) + 1
int _size_b = array.size(b) + 1
//
float _inf = 1.0e308 // near enough to infinity :o)
int _w = math.max(w, math.abs(_size_a - _size_b)) // adapt window size
matrix<float> _dtw = matrix.new<float>(_size_a, _size_b, _inf)
matrix.set(_dtw, 0, 0, 0.0)
for _i = 1 to _size_a - 1
for _j = math.max(1, _i - _w) to math.min(_size_b - 1, _i + _w)
matrix.set(_dtw, _i, _j, 0)
for _i = 1 to _size_a - 1
for _j = math.max(1, _i - _w) to math.min(_size_b - 1, _i + _w)
float _cost = distance(array.get(a, _i-1), array.get(b, _j-1))
matrix.set(_dtw, _i, _j, _cost + math.min(matrix.get(_dtw, _i - 1, _j), matrix.get(_dtw, _i, _j - 1), matrix.get(_dtw, _i - 1, _j - 1)))
matrix.remove_col(_dtw, 0)
matrix.remove_row(_dtw, 0)
_dtw
// example:
a = array.from(1.0, 2, 3, 3, 5)
b = array.from(1.0, 2, 2, 2, 2, 2, 2, 4)
c = cost_matrix(a, b, 3)
var la = label.new(bar_index, 0.0, '')
// if barstate.islast
// label.set_x(la, bar_index)
// label.set_text(la, str.tostring(c))
//}
// @function perform a backtrace on the cost matrix and retrieve optimal paths and cost between arrays.
// @param M matrix<float>, cost matrix.
// @returns
// tuple:
// array<int> aligned 1st array of indices.
// array<int> aligned 2nd array of indices.
// float final cost.
// reference:
// https://github.com/shunsukeaihara/pydtw/blob/master/pydtw/dtw.pyx
export traceback (
matrix<float> M
) => //{
int _i = matrix.rows(M) - 1
int _j = matrix.columns(M) - 1
float _cost = matrix.get(M, _i, _j)
array<int> _a = array.new<int>(1, _i)
array<int> _b = array.new<int>(1, _j)
int _match = int(na)
while _i > 0 and _j > 0
_match := d_argmin(matrix.get(M, _i - 1, _j - 1), matrix.get(M, _i - 1, _j), matrix.get(M, _i, _j - 1))
switch _match
0 => _i -= 1 , _j -= 1
1 => _i -= 1
=> _j -= 1
array.push(_a, _i), array.push(_b, _j)
array.reverse(_a), array.reverse(_b)
[_a, _b, _cost]
//}
// @function report ordered arrays, cost and cost matrix.
// @param a array<float>, data series.
// @param b array<float>, data series.
// @param w int , minimum window size.
// @returns
// string report.
export report (
array<float> a,
array<float> b,
int w
) => //{
matrix<float> _cost_mat = cost_matrix(a, b, w)
[_align_a, _align_b, _cost] = traceback(_cost_mat)
str.format('cost: {0}\nalign a: {1}\nalign b: {2}\ncost matrix:\n{3}', str.tostring(_cost), str.tostring(_align_a), str.tostring(_align_b), str.tostring(_cost_mat))
//
s = report(a, b, 3)
if barstate.islast
label.set_x(la, bar_index)
label.set_text(la, s)
//}
|
loxxjuriktools | https://www.tradingview.com/script/Ax6wmKSL-loxxjuriktools/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description loxxjuriktools: Jurik tools used in Loxx's idicators and strategies
library("loxxjuriktools", overlay = true)
// @function jcfbaux
// @param src float
// @param len int
// @returns result float
export jcfbaux(float src, float depth) =>
jrc04 = 0.0, jrc05 = 0.0, jrc06 = 0.0, jrc13 = 0.0, jrc03 = 0.0, jrc08 = 0.0
if (bar_index >= bar_index - depth * 2)
for k = math.ceil(depth) - 1 to 0
jrc04 += math.abs(nz(src[k]) - nz(src[k+1]))
jrc05 += (depth + k) * math.abs(nz(src[k]) - nz(src[k+1]))
jrc06 += nz(src[k+1])
if(bar_index < bar_index - depth * 2)
jrc03 := math.abs(src - nz(src[1]))
jrc13 := math.abs(nz(src[depth]) - nz(src[depth+1]))
jrc04 := jrc04 - jrc13 + jrc03
jrc05 := jrc05 - jrc04 + jrc03 * depth
jrc06 := jrc06 - nz(src[depth+1]) + nz(src[1])
jrc08 := math.abs(depth * src - jrc06)
jcfbaux = jrc05 == 0.0 ? 0.0 : jrc08/jrc05
jcfbaux
// @function jcfb
// @param src float
// @param len int
// @param len int
// @returns result float
export jcfb(float src, int len, int smth) =>
a1 = array.new<float>(0, 0)
c1 = array.new<float>(0, 0)
d1 = array.new<float>(0, 0)
cumsum = 2.0, result = 0.0
//crete an array of 2^index, pushed onto itself
//max values with injest of depth = 10: [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 512]
for i = 0 to len -1
array.push(a1, math.pow(2, i))
array.push(a1, math.pow(2, i))
//cumulative sum of 2^index array
//max values with injest of depth = 10: [2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536]
for i = 0 to array.size(a1) - 1
array.push(c1, cumsum)
cumsum += array.get(a1, i)
//add values from jcfbaux calculation using the cumumulative sum arrary above
for i = 0 to array.size(c1) - 1
array.push(d1, jcfbaux(src, array.get(c1, i)))
baux = array.copy(d1)
cnt = array.size(baux)
arrE = array.new<float>(cnt, 0)
arrX = array.new<float>(cnt, 0)
if bar_index <= smth
for j = 0 to bar_index - 1
for k = 0 to cnt - 1
eget = array.get(arrE, k)
array.set(arrE, k, eget + nz(array.get(baux, k)[bar_index - j]))
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget / bar_index)
else
for k = 0 to cnt - 1
eget = nz(array.get(arrE, k))
array.set(arrE, k, eget + (nz(array.get(baux, k)) - nz(array.get(baux, k)[smth])) / smth)
if bar_index > 5
a = 1.0, b = 1.0
for k = 0 to cnt - 1
if (k % 2 == 0)
array.set(arrX, k, b * nz(array.get(arrE, k)))
b := b * (1 - nz(array.get(arrX, k)))
else
array.set(arrX, k, a * nz(array.get(arrE, k)))
a := a * (1 - nz(array.get(arrX, k)))
sq = 0.0, sqw = 0.0
for i = 0 to cnt - 1
sqw += nz(array.get(arrX, i)) * nz(array.get(arrX, i)) * nz(array.get(c1, i))
for i = 0 to array.size(arrX) - 1
sq += math.pow(nz(array.get(arrX, i)), 2)
result := sq == 0.0 ? 0.0 : sqw / sq
result
// @function jurik_filt
// @param src float
// @param len int
// @param phase float
// @returns result float
export jurik_filt(float src, int len, float phase) =>
//static variales
volty = 0.0, avolty = 0.0, vsum = 0.0, bsmax = src, bsmin = src
len1 = math.max(math.log(math.sqrt(0.5 * (len-1))) / math.log(2.0) + 2.0, 0)
len2 = math.sqrt(0.5 * (len - 1)) * len1
pow1 = math.max(len1 - 2.0, 0.5)
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
div = 1.0 / (10.0 + 10.0 * (math.min(math.max(len-10, 0), 100)) / 100)
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : 1.5 + phase * 0.01
bet = len2 / (len2 + 1)
//Price volatility
del1 = src - nz(bsmax[1])
del2 = src - nz(bsmin[1])
volty := math.abs(del1) > math.abs(del2) ? math.abs(del1) : math.abs(del2)
//Relative price volatility factor
vsum := nz(vsum[1]) + div * (volty - nz(volty[10]))
avolty := nz(avolty[1]) + (2.0 / (math.max(4.0 * len, 30) + 1.0)) * (vsum - nz(avolty[1]))
dVolty = avolty > 0 ? volty / avolty : 0
dVolty := math.max(1, math.min(math.pow(len1, 1.0/pow1), dVolty))
//Jurik volatility bands
pow2 = math.pow(dVolty, pow1)
Kv = math.pow(bet, math.sqrt(pow2))
bsmax := del1 > 0 ? src : src - Kv * del1
bsmin := del2 < 0 ? src : src - Kv * del2
//Jurik Dynamic Factor
alpha = math.pow(beta, pow2)
//1st stage - prelimimary smoothing by adaptive EMA
jrkout = 0.0, ma1 = 0.0, det0 = 0.0, e2 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
//2nd stage - one more prelimimary smoothing by Kalman filter
det0 := (src - ma1) * (1 - beta) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
//3rd stage - final smoothing by unique Jurik adaptive filter
e2 := (ma2 - nz(jrkout[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jrkout := e2 + nz(jrkout[1])
jrkout
//example usage
out = jurik_filt(close, 25, 0)
plot(out)
|
DateNow | https://www.tradingview.com/script/1rke9MRw-DateNow/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description TODO: Provide today's date based on UNIX time
library('DateNow', overlay = true)
// ————————————————————————————————————————————————————————————————————————————— DateNow {
// @function : DateNow
// @param : _timezone
// @returns : YYYY, YY, M, MM, MMM, DD
export dateNow(string _timezone = 'GMT+8') =>
dt = timenow
Y1 = year( dt)
M1 = month( dt)
D1 = dayofmonth(dt)
Y2 = year(timestamp( _timezone, 1970, 1, 1, 0, 0, 0))
M2 = month(timestamp( _timezone, 1970, 1, 1, 0, 0, 0))
D2 = dayofmonth(timestamp(_timezone, 1970, 1, 1, 0, 0, 0))
YY = Y1 - Y2 - 31
YYYY = Y1 - Y2 - 31 + 2000
LEAP = Y1 % 4 ? 31 : 30
M = M1 - M2 + 12
[MM, MMM] = switch M
1 => ['JAN', 'JANUARY']
2 => ['FEB', 'FEBRUARY']
3 => ['MAR', 'MARCH']
4 => ['APR', 'APRIL']
5 => ['MAY', 'MAY']
6 => ['JUN', 'JUNE']
7 => ['JUL', 'JULY']
8 => ['AUG', 'AUGUST']
9 => ['SEP', 'SEPTEMBER']
10 => ['OCT', 'OCTOBER']
11 => ['NOV', 'NOVEMBER']
12 => ['DEC', 'DECEMBER']
DD = YYYY <= 1984 ? D1 - D2 + LEAP + 1 : D1 - D2 + LEAP
[YYYY, YY, M, MM, MMM, DD]
// }
// ————————————————————————————————————————————————————————————————————————————— Example {
[YYYY, YY, M, MM, MMM, DD] = dateNow()
var dateTable = table.new(position.middle_center, 2, 4, border_width = 1)
if barstate.islast
table.cell(dateTable, 0, 0, 'FORMAT', bgcolor = color.white)
table.cell(dateTable, 0, 1, 'DD MM YYYY', bgcolor = color.white)
table.cell(dateTable, 0, 2, 'DD MMM YYYY', bgcolor = color.white)
table.cell(dateTable, 0, 3, 'DD/M/YY', bgcolor = color.white)
table.cell(dateTable, 1, 0, 'OUTPUT', bgcolor = color.white)
table.cell(dateTable, 1, 1, str.tostring(DD) + ' ' + str.tostring(MM) + ' ' + str.tostring(YYYY), bgcolor = color.white)
table.cell(dateTable, 1, 2, str.tostring(DD) + ' ' + str.tostring(MMM) + ' ' + str.tostring(YYYY), bgcolor = color.white)
table.cell(dateTable, 1, 3, str.tostring(DD) + '/' + str.tostring(M) + '/' + str.tostring(YY), bgcolor = color.white)
// } |
CyclicRsiLib | https://www.tradingview.com/script/zsbC61Hf-CyclicRsiLib/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description TODO: add library description here
library('CyclicRsiLib')
// 0. AlertFrequency
// 1. CyclicRSI
// 2. AddToZigzag
// 3. UpdateZigzag
// 4. BoolZigzag
// 4. NoiseSwitch
// 5. StringSwitch
// 6. LineGray
// 7. LabelDir
// 8. TernaryLabel
// 9. TernaryColor
// 10. ColorNewSwitch
// ————————————————————————————————————————————————————————————————————————————— 0. AlertFrequency {
// @function : AlertFrequency
// @param : _string
// @returns : _freq
export AlertFrequency(string _string) =>
_freq = switch _string
'Once Per Bar Close' => alert.freq_once_per_bar_close
'Once Per Bar' => alert.freq_once_per_bar
'All' => alert.freq_all
// }
// ————————————————————————————————————————————————————————————————————————————— 1. CyclicRSI {
// @function : CyclicRSI
// @param : _source, _length, _expression
// @returns : osc
// Credits to WhenToTrade
export CyclicRSI(float _source, int _length, string _expression) =>
//TODO : add function body and return value here
crsi = 0.0
vibration = 10
torque = 0.618 / (vibration + 1)
phasingLag = (vibration - 1) / 0.618
rsi = ta.rsi(_source, _length)
crsi := torque * (2 * rsi - rsi[phasingLag]) + (1 - torque) * nz(crsi[1])
osc = switch _expression
'Cyclic RSI' => crsi
'RSI' => rsi
[osc, crsi, rsi]
// }
// ————————————————————————————————————————————————————————————————————————————— 2. AddToZigzag {
// @function : AddToZigzag
// @param : _id, value, max_array_size
// @returns : array.unshift, array.pop
// Credits to LonesomeTheBlue
export AddToZigzag(simple float[] _id, float value, int max_array_size = 10) =>
array.unshift(_id, bar_index)
array.unshift(_id, value)
if array.size(_id) > max_array_size
array.pop(_id)
array.pop(_id)
// }
// ————————————————————————————————————————————————————————————————————————————— 3. UpdateZigzag {
// @function : UpdateZigzag
// @param : _id, value, max_array_size, dir
// @returns : AddToZigzag, array.set
// Credits to LonesomeTheBlue
export UpdateZigzag(simple float[] _id, float value, int max_array_size = 10, int dir = 0) =>
if array.size(_id) == 0
AddToZigzag(_id, value, max_array_size)
else
if dir == 1 and value > array.get(_id, 0) or dir == -1 and value < array.get(_id, 0)
array.set(_id, 0, value)
array.set(_id, 1, bar_index)
0.
// }
// ————————————————————————————————————————————————————————————————————————————— 4. BoolZigzag {
// @function : BoolZigzag
// @param : ph, pl, dirchanged, _id, dir
// @returns : AddToZigzag, UpdateZigzag
// Credits to LonesomeTheBlue
export BoolZigzag(float ph, float pl, float dirchanged, simple float[] _id, int dir) =>
if ph or pl
if dirchanged
AddToZigzag(_id, dir == 1 ? ph : pl)
else
UpdateZigzag(_id, dir == 1 ? ph : pl, dir)
// }
// ————————————————————————————————————————————————————————————————————————————— 4. NoiseSwitch {
// @function : NoiseSwitch
// @param : _string, _id
// @returns : FilterNoise
export NoiseSwitch(string _string, simple float[] _id) =>
FilterNoise = switch _string
'35 < value < 65' => array.get(_id, 2) <= 65 and array.get(_id, 2) >= 35
'50 < value < 65' => array.get(_id, 2) >= 35
'30 < value < 50' => array.get(_id, 2) <= 65
FilterNoise
// }
// ————————————————————————————————————————————————————————————————————————————— 5. StringSwitch {
// @function : StringSwitch
// @param : _string
// @returns : str_OB, str_OS
export StringSwitch(string _string) =>
[str_OB, str_OS] = switch _string
'both' => ['OB\n▼', '▲\nOS']
'OB/OS' => [ 'OB', 'OS']
'arrow' => [ '▼', '▲']
[str_OB, str_OS]
// }
// ————————————————————————————————————————————————————————————————————————————— 6. LineGray {
// @function : LineGray
// @param : _id
// @returns : LineGray
export LineGray(simple float[] _id) =>
line.new(
x1 = math.round(array.get(_id, 1)),
y1 = array.get(_id, 0),
x2 = math.round(array.get(_id, 3)),
y2 = array.get(_id, 2),
color = color.gray,
width = 2)
// }
// ————————————————————————————————————————————————————————————————————————————— 7. LabelDir {
// @function : LabelDir
// @param : _id, _string, _color, _dir
// @returns : LabelDir
export LabelDir(simple float[] _id, string _string, color _color, float _dir) =>
label.new(
x = math.round(array.get(_id, 1)),
y = array.get(_id, 0),
text = _string,
color = color.new(color.blue, 100),
textcolor = _color,
style = _dir == 1 ? label.style_label_down : label.style_label_up)
// }
// ————————————————————————————————————————————————————————————————————————————— 8. TernaryLabel {
// @function : TernaryLabel
// @param : _dir, _bool1, _bool2, _string1, _string2
// @returns : str_label
export TernaryLabel(int _dir, bool _bool1, bool _bool2, string _string1, string _string2) =>
str_label = _dir == 1 ?
_bool1 ? _string1 : '◍' :
_bool2 ? _string2 : '◍'
// }
// ————————————————————————————————————————————————————————————————————————————— 9. TernaryColor {
// @function : TernaryColor
// @param : _dir, _bool1, _bool2
// @returns : col_label
export TernaryColor(int _dir, bool _bool1, bool _bool2) =>
col_label = _dir == 1 ?
_bool1 ? color.red : color.teal :
_bool2 ? color.teal : color.red
// }
// ————————————————————————————————————————————————————————————————————————————— 10. ColorNewSwitch {
// @function : ColorNewSwitch
// @param : _dir, _bool1, _bool2
// @returns : NewColor
export ColorNewSwitch(int _int1 = 0, bool _bool, int _int2 = 0, int _int3 = 0) =>
_color = switch _int1
0 => color.teal
1 => color.red
2 => color.yellow
_transp1 = switch _int2
0 => 0
1 => 65
_transp2 = switch _int3
0 => 50
1 => 100
cn = color.new(_color, _bool ? _transp1 : _transp2)
cn
// }
|
TR_HighLow | https://www.tradingview.com/script/5ZhhkaPw/ | Tommy_Rich | https://www.tradingview.com/u/Tommy_Rich/ | 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/
// © Tommy_Rich
//@version=5
// @description TODO: add library description here
library(title ="TR_HighLow",overlay =true)
////// //
//// local function group //// **********ローカル関数群**********
// //////
SetHighLowArray(
float[] _a_Price, int[] _a_Index,
int[] _a_Flag, float[] _a_Difference,
float _Price, int _Index,
int _Flag, float _Difference) =>
if _Price >0
// 配列の先頭から最も古いレベルを削除します
array.shift(_a_Price)
array.shift(_a_Index)
array.shift(_a_Flag)
array.shift(_a_Difference)
// 配列の最後に新しいレベルを追加します
array.push(_a_Price, _Price)
array.push(_a_Index, _Index)
array.push(_a_Flag, _Flag)
array.push(_a_Difference, _Difference)
[_a_Price, _a_Index, _a_Flag, _a_Difference]
ChangeHighLowArray(
float[] _a_Price, int[] _a_Index,
float[] _a_Difference, float _Price,
int _Index, float _Difference,
int _Histories) =>
if _Price >0
array.set(_a_Price, _Histories-1, _Price)
array.set(_a_Index, _Histories-1, _Index)
array.set(_a_Difference, _Histories-1, _Difference)
[_a_Price, _a_Index, _a_Difference]
////// //
//// global function group //// **********グローバル関数群**********
// //////
// @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) Color of the label border and arrow
// @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 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: 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)
// @function TODO: Draw a zig-zag line.
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low INDEX array
// @param _a_FHiLo TODO: High-Low flag array sequence 1:High 2:Low
// @param _a_DHiLo TODO: High-Low Price Differential Array
// @param _Histories TODO: Array size (High-Low length)
// @param _Provisional_PHiLo TODO: Provisional High-Low Price
// @param _Provisional_IHiLo TODO: Provisional High-Low INDEX
// @param _Color1 TODO: Normal High-Low color
// @param _Width1 TODO: Normal High-Low width
// @param _Color2 TODO: Provisional High-Low color
// @param _Width2 TODO: Provisional High-Low width
// @param _ShowLabel TODO: Label display flag True: Displayed False: Not displayed
// @param _ShowHighLowBar TODO: High-Low bar display flag True:Show False:Hide
// @param _HighLowBarWidth TODO: High-Low bar width
// @param _HighLow_LabelSize TODO: Label Size
// @returns TODO: No return value
export ZigZag(
float[] _a_PHiLo, int[] _a_IHiLo,
int[] _a_FHiLo, float[] _a_DHiLo,
int _Histories,
float _Provisional_PHiLo, int _Provisional_IHiLo,
color _Color1, int _Width1,
color _Color2, int _Width2,
bool _ShowLabel, string _LabelSize,
bool _ShowHighLowBar, int _HighLowBarWidth) =>
string info =""
var line l =na
var line l_1 =na
var line l_2 =na
int i_1 =bar_index - _Histories
int i_2 =i_1
float p_1 =0., p_2 =0.
int f_1 =0 , f_2 =0
float d_1 =0., d_2 =0.
bool _ShowTrendLine =true
// for int i =_Histories - 1 to 0
for int i =0 to _Histories - 1
i_2 :=i_1
p_2 :=p_1
f_2 :=f_1
d_2 :=d_1
i_1 :=array.get(_a_IHiLo, i)
p_1 :=array.get(_a_PHiLo, i)
f_1 :=array.get(_a_FHiLo, i)
d_1 :=array.get(_a_DHiLo, i)
// if i !=_Histories - 1
if i !=0
l :=line.new(i_1, p_1, i_2, p_2, color =_Color1, width =_Width1)
if _ShowHighLowBar
l_1 :=line.new(i_1, p_1, i_1 + 50, p_1, color =color.new(GetColor(i), 40), width =_HighLowBarWidth, extend=extend.right)
if p_2 != 0.
l_2 :=line.new(i_2, p_2, i_2 + 50, p_2, color =color.new(GetColor(i + 1), 40), width =_HighLowBarWidth, extend=extend.right)
if _ShowLabel
string yloc1 =yloc.abovebar
string yloc2 =yloc.belowbar
string style1 =label.style_none
string style2 =label.style_none
color color1 =color.blue
color color2 =color.red
if f_1 == 2
yloc1 :=yloc.belowbar
yloc2 :=yloc.abovebar
color1 :=color.red
color2 :=color.blue
// info :=str.tostring(p_1)
info :=str.tostring(p_1) + "\n(" + str.tostring(d_1) + ")"
ShowLabel(info, i_1, p_1, style1, _LabelSize, yloc1, color1)
if p_2 != 0.
// info :=str.tostring(p_2)
info :=str.tostring(p_2) + "\n(" + str.tostring(d_2) + ")"
ShowLabel(info, i_2, p_2, style2, _LabelSize, yloc2, color2)
if not na(_Provisional_PHiLo)
if _Provisional_IHiLo > i_1
l :=line.new(i_1, p_1, _Provisional_IHiLo, _Provisional_PHiLo, color =_Color2, width =_Width2)
// @function TODO: Draw a Trend Line
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low INDEX array
// @param _Histories TODO: Array size (High-Low length)
// @param _MultiLine TODO: Draw a multiple Line.
// @param _StartWidth TODO: Line width start value
// @param _EndWidth TODO: Line width end value
// @param _IncreWidth TODO: Line width increment value
// @param _StartTrans TODO: Transparent rate start value
// @param _EndTrans TODO: Transparent rate finally
// @param _IncreTrans TODO: Transparent rate increase value
// @param _ColorMode TODO: 0:Nomal 1:Gradation
// @param _Color1_1 TODO: Gradation Color 1_1
// @param _Color1_2 TODO: Gradation Color 1_2
// @param _Color2_1 TODO: Gradation Color 2_1
// @param _Color2_2 TODO: Gradation Color 2_2
// @param _Top_High TODO: _Top_High Value for Gradation
// @param _Top_Low TODO: _Top_Low Value for Gradation
// @param _Bottom_High TODO: _Bottom_High Value for Gradation
// @param _Bottom_Low TODO: _Bottom_Low Value for Gradation
// @returns TODO: No return value
export TrendLine(
float[] _a_PHiLo, int[] _a_IHiLo,
int _Histories, bool _MultiLine,
float _StartWidth, float _EndWidth,
float _IncreWidth, int _StartTrans,
int _EndTrans, int _IncreTrans,
int _ColorMode, color _Color1_1,
color _Color1_2, color _Color2_1,
color _Color2_2, float _Top_High,
float _Top_Low, float _Bottom_High,
float _Bottom_Low) =>
var line l_1 =na
var line l_2 =na
var line l_3 =na
var line l_4 =na
var line l_5 =na
var line l_6 =na
int i_1 =bar_index - _Histories, i_2 =i_1, i_3 =i_1, i_4 =i_1
float p_1 =0., p_2 =0., p_3 =0., p_4 =0.
bool flg =array.get(_a_PHiLo, 0) >= array.get(_a_PHiLo, 1) // p_1 >= p_2 の時:True p_1 < p_2 の時:False
float width =0., trans =0.
int histories_1 =_Histories - 1
int histories_2 =_Histories - 1
// 偶数
if (histories_1) % 2 != 0
histories_1 := histories_1 - 1
// 奇数
if (histories_2) % 2 == 0
histories_2 := histories_2 - 1
float top_Hi =_Top_High
float top_Lo =_Top_Low
float bottom_Hi =_Bottom_High
float bottom_Lo =_Bottom_Low
color c1 =color.red
color c2 =color.blue
if _MultiLine
for int i =0 to _Histories - 1 by 2
i_1 :=array.get(_a_IHiLo, i)
p_1 :=array.get(_a_PHiLo, i)
width :=_StartWidth + (i * _IncreWidth)
if _IncreWidth > 0
if width > _EndWidth
width :=_EndWidth
else
if width < _EndWidth
width :=_EndWidth
trans :=_StartTrans + (i * _IncreTrans)
if _IncreTrans > 0
if trans > _EndTrans
trans :=_EndTrans
else
if trans < _EndTrans
trans :=_EndTrans
for int j =histories_1 to i by 2
if j < 0
break
ShowLabel("histories_1:" + str.tostring(histories_1) + "/j:" + str.tostring(j), bar_index, high, label.style_label_down, size.auto, yloc.abovebar, color.white)
i_3 :=array.get(_a_IHiLo, j)
p_3 :=array.get(_a_PHiLo, j)
if _ColorMode == 1
if flg // p_1 → p_3 が p_2 → p_4 より上の時
if p_1 >= p_3 // 上向き⤴
// c1 :=color.new(color.from_gradient(math.abs((p_1 - p_3) / 2), bottom_Hi, top_Hi, _Color1_1, _Color1_2), trans)
c1 :=color.new(color.from_gradient(p_1, bottom_Hi, top_Hi, _Color1_1, _Color1_2), trans)
else // 下向き⤵
// c1 :=color.new(color.from_gradient(math.abs((p_1 - p_3) / 2), bottom_Hi, top_Hi, _Color2_1, _Color2_2), trans)
c1 :=color.new(color.from_gradient(p_1, bottom_Hi, top_Hi, _Color2_1, _Color2_2), trans)
else
if p_1 >= p_3 // 上向き⤴
// c1 :=color.new(color.from_gradient(math.abs((p_1 - p_3) / 2), bottom_Lo, top_Lo, _Color1_1, _Color1_2), trans)
c1 :=color.new(color.from_gradient(p_1, bottom_Lo, top_Lo, _Color1_1, _Color1_2), trans)
else // 下向き⤵
// c1 :=color.new(color.from_gradient(math.abs((p_1 - p_3) / 2), bottom_Lo, top_Lo, _Color2_1, _Color2_2), trans)
c1 :=color.new(color.from_gradient(p_1, bottom_Lo, top_Lo, _Color2_1, _Color2_2), trans)
else
c1 :=color.new(GetColor(j), trans)
l_1 :=line.new(i_1, p_1 + width, i_3, p_3 + width, color =c1, width =1, extend =extend.right)
l_2 :=line.new(i_1, p_1, i_3, p_3, color =c1, width =1, extend =extend.right, style =line.style_dotted)
l_3 :=line.new(i_1, p_1 - width, i_3, p_3 - width, color =c1, width =1, extend =extend.right)
linefill.new(l_1, l_3, color.new(c1, 90))
for int i =1 to _Histories - 1 by 2
i_2 :=array.get(_a_IHiLo, i)
p_2 :=array.get(_a_PHiLo, i)
width :=_StartWidth + (i * _IncreWidth)
if _IncreWidth > 0
if width > _EndWidth
width :=_EndWidth
else
if width < _EndWidth
width :=_EndWidth
trans :=_StartTrans + (i * _IncreTrans)
if _IncreTrans > 0
if trans > _EndTrans
trans :=_EndTrans
else
if trans < _EndTrans
trans :=_EndTrans
for int j =histories_2 to i by 2
if j < 0
break
ShowLabel("histories_2:" + str.tostring(histories_2) + "/j:" + str.tostring(j), bar_index, low, label.style_label_up, size.auto, yloc.abovebar, color.white)
i_4 :=array.get(_a_IHiLo, j)
p_4 :=array.get(_a_PHiLo, j)
if _ColorMode == 1
if flg // p_1 → p_3 が p_2 → p_4 より上の時
if p_2 >= p_4 // 上向き⤴
c2 :=color.new(color.from_gradient(p_2, bottom_Lo, top_Lo, _Color1_1, _Color1_2), trans)
else // 下向き⤵
c2 :=color.new(color.from_gradient(p_2, bottom_Lo, top_Lo, _Color2_1, _Color2_2), trans)
else
if p_2 >= p_4 // 上向き⤴
c2 :=color.new(color.from_gradient(p_2, bottom_Hi, top_Hi, _Color1_1, _Color1_2), trans)
else // 下向き⤵
c2 :=color.new(color.from_gradient(p_2, bottom_Hi, top_Hi, _Color2_1, _Color2_2), trans)
else
c2 :=color.new(GetColor(j), trans)
l_4 :=line.new(i_2, p_2 + width, i_4, p_4 + width, color =c2, width =1, extend =extend.right)
l_5 :=line.new(i_2, p_2, i_4, p_4, color =c2, width =1, extend =extend.right, style =line.style_dotted)
l_6 :=line.new(i_2, p_2 - width, i_4, p_4 - width, color =c2, width =1, extend =extend.right)
linefill.new(l_4, l_6, color.new(c2, 90))
else
for int i =0 to _Histories - 1
i_4 :=i_3
p_4 :=p_3
i_3 :=i_2
p_3 :=p_2
i_2 :=i_1
p_2 :=p_1
i_1 :=array.get(_a_IHiLo, i)
p_1 :=array.get(_a_PHiLo, i)
width :=_StartWidth + (i * _IncreWidth)
if _IncreWidth > 0
if width > _EndWidth
width :=_EndWidth
else
if width < _EndWidth
width :=_EndWidth
trans :=_StartTrans + (i * _IncreTrans)
if _IncreTrans > 0
if trans > _EndTrans
trans :=_EndTrans
else
if trans < _EndTrans
trans :=_EndTrans
if p_4 !=0
if _ColorMode == 1
if p_1 > p_3
c1 :=color.new(color.from_gradient(p_1, bottom_Hi, top_Hi, _Color1_1, _Color1_2), trans)
else
c1 :=color.new(color.from_gradient(p_1, bottom_Hi, top_Hi, _Color2_1, _Color2_2), trans)
if p_2 > p_4
c2 :=color.new(color.from_gradient(p_2, bottom_Lo, top_Lo, _Color1_1, _Color1_2), trans)
else
c2 :=color.new(color.from_gradient(p_2, bottom_Lo, top_Lo, _Color2_1, _Color2_2), trans)
else
c1 :=color.new(GetColor(i), trans)
c2 :=color.new(GetColor(i + 1), trans)
l_1 :=line.new(i_1, p_1 + width, i_3, p_3 + width, color =c1, width =2, extend= extend.left)
l_2 :=line.new(i_1, p_1, i_3, p_3, color =c1, width =2, extend= extend.left, style =line.style_dotted)
l_3 :=line.new(i_1, p_1 - width, i_3, p_3 - width, color =c1, width =2, extend= extend.left)
l_4 :=line.new(i_2, p_2 + width, i_4, p_4 + width, color =c2, width =2, extend= extend.left)
l_5 :=line.new(i_2, p_2, i_4, p_4, color =c2, width =2, extend= extend.left, style =line.style_dotted)
l_6 :=line.new(i_2, p_2 - width, i_4, p_4 - width, color =c2, width =2, extend= extend.left)
linefill.new(l_1, l_3, color.new(c1, 90))
linefill.new(l_4, l_6, color.new(c2, 90))
// @function TODO: Draw a Fibonacci line
// @param _a_Fibonacci TODO: Fibonacci Percentage Array
// @param _a_PHiLo TODO: High-Low price array
// @param _Provisional_PHiLo TODO: Provisional High-Low price (when _Index is 0)
// @param _Index TODO: Where to draw the Fibonacci line
// @param _FrontMargin TODO: Fibonacci line front-margin
// @param _BackMargin TODO: Fibonacci line back-margin
// @returns TODO: No return value
export Fibonacci(
float[] _a_Fibonacci,
float[] _a_PHiLo,
float _Provisional_PHiLo, int _Index,
int _FrontMargin, int _BackMargin) =>
int i_1 =0 , i_2 =0
float p_1 =0., p_2 =0.
line l =na
line[] ls =array.new_line()
int index_1 =array.size(_a_PHiLo) - _Index
int index_2 =index_1 - 1
float dir =0.
float diff =0.
var label lbl1 = na
i_1 :=bar_index + _FrontMargin
i_2 :=bar_index + _BackMargin
if _Index == 0
p_1 :=_Provisional_PHiLo
else
p_1 :=array.get(_a_PHiLo, index_1)
p_2 :=array.get(_a_PHiLo, index_2)
// 上昇・下降判断用
dir :=p_1 - p_2
// 差の絶対値
diff :=math.abs(dir)
for i1 =0 to array.size(_a_Fibonacci) -1
float _f =0.
float _Fib =array.get(_a_Fibonacci, i1)
// 上昇
if dir > 0
_f :=p_1 - (diff * _Fib)
else
_f :=p_1 + (diff * _Fib)
l :=line.new(i_1, _f, i_2, _f, color =color.red, width =1)
array.push(ls, l)
lbl1 := label.new(x =i_1 + 7, y =_f, text =str.tostring(_Fib, "0.000") + " : " + str.tostring(_f, "0.000"), yloc = yloc.price, style =label.style_none) //, textalign =text.align_left)
for i2 =0 to array.size(ls) -2
if array.size(ls) >= 2
line l1 =array.get(ls, i2)
line l2 =array.get(ls, i2 + 1)
linefill.new(l1, l2, color.new(GetColor(i2), 90))
// @function TODO: Draw a Fibonacci line
// @param _a_Fibonacci TODO: Fibonacci Percentage Array
// @param _a_PHiLo TODO: High-Low price array
// @param _Provisional_PHiLo TODO: Provisional High-Low price (when _Index is 0)
// @param _Index1 TODO: Where to draw the Fibonacci line 1
// @param _FrontMargin1 TODO: Fibonacci line front-margin 1
// @param _BackMargin1 TODO: Fibonacci line back-margin 1
// @param _Transparent1 TODO: Transparent rate 1
// @param _Index2 TODO: Where to draw the Fibonacci line 2
// @param _FrontMargin2 TODO: Fibonacci line front-margin 2
// @param _BackMargin2 TODO: Fibonacci line back-margin 2
// @param _Transparent2 TODO: Transparent rate 2
// @returns TODO: No return value
export Fibonacci(
float[] _a_Fibonacci, float[] _a_PHiLo,
float _Provisional_PHiLo,
int _Index1, int _FrontMargin1,
int _BackMargin1, int _Transparent1,
int _Index2, int _FrontMargin2,
int _BackMargin2, int _Transparent2) =>
int i1_1 =0 , i1_2 =0 , i2_1 =0 , i2_2 =0
float p1_1 =0., p1_2 =0., p2_1 =0., p2_2 =0.
line l1 =na
line l2 =na
line[] ls1 =array.new_line(), ls2 =array.new_line()
int index1_1 =array.size(_a_PHiLo) - _Index1
int index1_2 =index1_1 - 1
int index2_1 =array.size(_a_PHiLo) - _Index2
int index2_2 =index2_1 - 1
float dir1 =0., dir2 =0.
float diff1 =0., diff2 =0.
var label lbl1 = na
var label lbl2 = na
i1_1 :=bar_index + _FrontMargin1
i1_2 :=bar_index + _BackMargin1
i2_1 :=bar_index + _FrontMargin2
i2_2 :=bar_index + _BackMargin2
if _Index1 == 0
p1_1 :=_Provisional_PHiLo
else
p1_1 :=array.get(_a_PHiLo, index1_1)
if _Index2 == 0
p2_1 :=_Provisional_PHiLo
else
p2_1 :=array.get(_a_PHiLo, index2_1)
p1_2 :=array.get(_a_PHiLo, index1_2)
p2_2 :=array.get(_a_PHiLo, index2_2)
// 上昇・下降判断用
dir1 :=p1_1 - p1_2
dir2 :=p2_1 - p2_2
// 差の絶対値
diff1 :=math.abs(dir1)
diff2 :=math.abs(dir2)
for i =0 to array.size(_a_Fibonacci) -1
float _f1 =0., _f2 =0.
float _Fib =array.get(_a_Fibonacci, i)
// 上昇
if dir1 > 0
_f1 :=p1_1 - (diff1 * _Fib)
else
_f1 :=p1_1 + (diff1 * _Fib)
if dir2 > 0
_f2 :=p2_1 - (diff2 * _Fib)
else
_f2 :=p2_1 + (diff2 * _Fib)
l1 :=line.new(i1_1, _f1, i1_2, _f1, color =color.red, width =1)
array.push(ls1, l1)
l2 :=line.new(i2_1, _f2, i2_2, _f2, color =color.red, width =1)
array.push(ls2, l2)
lbl1 := label.new(x =i1_1 + 7, y =_f1, text =str.tostring(_Fib, "0.000") + " : " + str.tostring(_f1, "0.000"), yloc = yloc.price, style =label.style_none) //, textcolor =color.red)
lbl2 := label.new(x =i2_1 + 7, y =_f2, text =str.tostring(_Fib, "0.000") + " : " + str.tostring(_f2, "0.000"), yloc = yloc.price, style =label.style_none) //, textcolor =color.red)
for i =0 to array.size(ls1) -2
if array.size(ls1) >= 2
line l1_1 =array.get(ls1, i)
line l1_2 =array.get(ls1, i + 1)
linefill.new(l1_1, l1_2, color.new(GetColor(i), _Transparent1))
if array.size(ls2) >= 2
line l2_1 =array.get(ls2, i)
line l2_2 =array.get(ls2, i + 1)
linefill.new(l2_1, l2_2, color.new(GetColor(i), _Transparent2))
// @function TODO: Judges High-Low
// @param _Length TODO: High-Low Confirmation Length
// @param _Extension TODO: Length of extension when the difference did not open
// @param _Difference TODO: Difference size
// @returns TODO: _HiLo=High-Low flag 0:Neither high nor low、1:High、2:Low、3:High-Low
// _PHi=high price、_PLo=low price、_IHi=High Price Index、_ILo=Low Price Index、
// _Cnt=count、_ECnt=Extension count、
// _DiffHi=Difference from Start(High)、_DiffLo=Difference from Start(Low)、
// _StartHi=Start value(High)、_StartLo=Start value(Low)
export High_Low_Judgment(
int _Length,
int _Extension,
float _Difference) =>
int _HiLo =0 // High-Lowフラグ
var float _PHi =-9999999999. // Price Hi
var float _PLo = 9999999999. // Price Lo
var int _IHi =0 // Index Hi
var int _ILo =0 // Index Lo
var int _Cnt =-1 // カウント変数
var int _ECnt =0 // Extカウント変数
var float _DiffHi =0. // Highの差
var float _DiffLo =0. // Lowの差
var float _StartHi =0. // Start時のHigh
var float _StartLo =0. // Start時のLow
_Cnt +=1 // カウントインクリ
if _Cnt == 0 // 初回の時
_PHi :=high // _PHiにhighを保管
_PLo :=low // _PLoにlowを保管
_StartHi :=_PHi // _StartHiに初回highを保管
_StartLo :=_PLo // _StartLoに初回lowを保管
_IHi :=bar_index // _IHiにインデックスを保存
_ILo :=bar_index // _ILoにインデックスを保存
else // 2回目以降の時
if _PHi < high // _PHiよりhighが大きい
_PHi :=high // _PHiをアップデート
_IHi :=bar_index // _IHiにインデックスを保存
if _PLo > low // _PLoよりlowが小さい
_PLo :=low // _PLoをアップデート
_ILo :=bar_index // _ILoにインデックスを保存
if _Cnt >= _Length // _Cntが_Length以上
_DiffHi :=_PHi - _StartHi // _StartHi(初回)と_PHiとの差
_DiffLo :=_StartLo - _PLo // _StartLo(初回)と_PLoとの差
if _DiffHi > _DiffLo // Highの方が差が大きい
if _DiffHi >= _Difference // _DiffHiが_Difference以上
_HiLo :=1 // High-Lowフラグに1をセット
_Cnt :=-1 // カウント変数リセット
_ECnt :=0 // Extカウント変数リセット
else if _DiffLo > _DiffHi // Lowの方が差が大きい
if _DiffLo >= _Difference // _DiffLoが_Difference以上
_HiLo :=2 // High-Lowフラグに2をセット
_Cnt :=-1 // カウント変数リセット
_ECnt :=0 // Extカウント変数リセット
else // High-Lowの差が同じ
if _DiffHi >= _Difference // _DiffLoが_Difference以上
_HiLo :=3 // High-Lowフラグに3をセット
_Cnt :=-1 // カウント変数リセット
_ECnt :=0 // Extカウント変数リセット
if _ECnt > _Extension // _ECntが_Extension以上
_Cnt :=-1 // カウント変数リセット
_ECnt :=0 // Extカウント変数リセット
if _HiLo == 0
if _DiffHi > _DiffLo // Highの方が大きい
_HiLo :=1 // High-Lowフラグに1をセット
else if _DiffLo > _DiffHi // Lowの方が大きい
_HiLo :=2 // High-Lowフラグに2をセット
else // High-Low同じ大きさ
_HiLo :=3 // High-Lowフラグに3をセット
else
_ECnt +=1
[_HiLo, _PHi, _PLo, _IHi, _ILo, _Cnt, _ECnt, _DiffHi, _DiffLo, _StartHi, _StartLo]
// @function TODO: Adds and updates High-Low related arrays from given parameters
// @param _HiLo TODO: High-Low flag
// @param _Histories TODO: Array size (High-Low length)
// @param _PHi TODO: Price Hi
// @param _PLo TODO: Price Lo
// @param _IHi TODO: Index Hi
// @param _ILo TODO: Index Lo
// @param _DiffHi TODO: Difference in High
// @param _DiffLo TODO: Difference in Low
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low INDEX array
// @param _a_FHiLo TODO: High-Low flag array 1:High 2:Low
// @param _a_DHiLo TODO: High-Low Price Differential Array
// @returns TODO: _PHiLo price array、_IHiLo indexed array、_FHiLo flag array、_DHiLo price-matching array、
// Provisional_PHiLo Provisional price、Provisional_IHiLo 暫定インデックス
export High_Low_Data_AddedAndUpdated(
int _HiLo, int _Histories,
float _PHi, float _PLo,
int _IHi, int _ILo,
float _DiffHi, float _DiffLo,
float[] _a_PHiLo, int[] _a_IHiLo,
int[] _a_FHiLo, float[] _a_DHiLo) =>
float Provisional_PHiLo =na // 暫定High-Low 価格
int Provisional_IHiLo =na // 暫定High-Low インデックス
if _HiLo != 0 // High-Low フラグ 0=初期値でない時
if array.get(_a_FHiLo, _Histories-1) == 1 // 前回High-Low フラグ 1=High(高値)の時
if _PHi >= array.get(_a_PHiLo, _Histories-1) // 前回High-Low 価格より現在High(高値)の方が高い(以上)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo, _PHi, _IHi, _DiffHi, _Histories) // 前回High-Low 価格、インデックス、価格差を置き換える
if _IHi <= _ILo // 前回High-Low 情報(High)を置き換えたので、HighインデックスよりLowインデックスの方が大きいか確認する
// ↑ちなみにHighは書き換え済みなので何もしない
if _HiLo == 2 // 今回がLowの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PLo, _ILo, _HiLo, _DiffLo) // 配列にLow値を追記する
else // 前回High-Low 価格より現在High(高値)の方が低い
if _HiLo == 2 // 今回がLowの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PLo, _ILo, _HiLo, _DiffLo) // 配列にLow値を追記する
else if _HiLo == 3 // 今回がHigh-Lowの時(HighでもLowでもある時)
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PLo, _ILo, 2, _DiffLo) // 前回がHighなので、配列にLow値から追記する
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PHi, _IHi, 1, _DiffHi) // 配列にLow値を追記したのでHigh値を追記する
if array.get(_a_FHiLo, _Histories-1) == 2 // 前回High-Low フラグ 2=Low(安値)の時
if _PLo <= array.get(_a_PHiLo, _Histories-1) // 前回High-Low 価格より現在Low(安値)の方が低い(以下)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo, _PLo, _ILo, _DiffLo, _Histories) // 前回High-Low 価格、インデックス、価格差を置き換える
if _ILo <= _IHi // 前回High-Low 情報(Low)を置き換えたので、LowインデックスよりHighインデックスの方が大きいか確認する
// ↑ちなみにLowは書き換え済みなので何もしない
if _HiLo == 1 // 今回がHighの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PHi, _IHi, _HiLo, _DiffHi) // 配列にHigh値を追記する
else
if _HiLo == 1 // 今回がHighの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PHi, _IHi, _HiLo, _DiffHi) // 配列にHigh値を追記する
else if _HiLo == 3 // 今回がHigh-Lowの時(HighでもLowでもある時)
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PHi, _IHi, 1, _DiffHi) // 前回Lowなので、配列にHigh値から追記する
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PLo, _ILo, 2, _DiffLo) // 配列にHigh値を追記したのでLow値を追記する
if array.get(_a_FHiLo, _Histories-1) == 0 // 前回High-Low フラグ 0=初回の時
if _HiLo == 1 // 今回がHighの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PHi, _IHi, _HiLo, _DiffHi) // 配列にHigh値を追記する
else if _HiLo == 2 // 今回がLowの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PLo, _ILo, _HiLo, _DiffLo) // 配列にLow値を追記する
else if _HiLo == 3 // 今回がHigh-Lowの時(HighでもLowでもある時)
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PHi, _IHi, 1, _DiffHi) // とりあえず、配列にHigh値から追記する
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _PLo, _ILo, 2, _DiffLo) // 配列にHigh値を追記したのでLow値を追記する
else // High-Low フラグ 0=初期値の時
float _price =array.get(_a_PHiLo, _Histories-1) // 前回価格の取得
if array.get(_a_FHiLo, _Histories-1) == 1 // 前回High-Low フラグ 1=High(高値)の時
if _price <= _PHi // 前回High-Low 価格より現在High(高値)の方が高い(以上)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo, _PHi, _IHi, _DiffHi, _Histories) // 前回High-Low 価格、インデックス、価格差を置き換える
else
Provisional_PHiLo :=_PLo // Lowとして暫定価格をセット
Provisional_IHiLo :=_ILo // Lowとして暫定インデックスをセット
if array.get(_a_FHiLo, _Histories-1) == 2 // 前回High-Low フラグ 2=Low(安値)の時
if _price >= _PLo // 前回High-Low 価格より現在Low(安値)の方が低い(以下)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo, _PLo, _ILo, _DiffLo, _Histories) // 前回High-Low 価格、インデックス、価格差を置き換える
else
Provisional_PHiLo :=_PHi // Highとして暫定価格をセット
Provisional_IHiLo :=_IHi // Highとして暫定インデックスをセット
[_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, Provisional_PHiLo, Provisional_IHiLo]
// @function TODO: Draw the contents of the High-Low array.
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low INDEX array
// @param _a_FHiLo TODO: High-Low flag sequence 1:High 2:Low
// @param _a_DHiLo TODO: High-Low Price Differential Array
// @param _a_Fibonacci TODO: Fibonacci Gnar Matching
// @param _Length TODO: Length of confirmation
// @param _Extension TODO: Extension Length of extension when the difference did not open
// @param _Difference TODO: Difference size
// @param _Histories TODO: High-Low Length
// @param _ShowZigZag TODO: ZigZag Display
// @param _ZigZagColor1 TODO: Colors of ZigZag1
// @param _ZigZagWidth1 TODO: Width of ZigZag1
// @param _ZigZagColor2 TODO: Colors of ZigZag2
// @param _ZigZagWidth2 TODO: Width of ZigZag2
// @param _ShowZigZagLabel TODO: ZigZagLabel Display
// @param _ShowHighLowBar TODO: High-Low Bar Display
// @param _ShowTrendLine TODO: Trend Line Display
// @param _TrendMultiLine TODO: Trend Multi Line Display
// @param _TrendStartWidth TODO: Line width start value
// @param _TrendEndWidth TODO: Line width end value
// @param _TrendIncreWidth TODO: Line width increment value
// @param _TrendStartTrans TODO: Starting transmittance value
// @param _TrendEndTrans TODO: Transmittance End Value
// @param _TrendIncreTrans TODO: Increased transmittance value
// @param _TrendColorMode TODO: color mode
// @param _TrendColor1_1 TODO: Trend Color 1_1
// @param _TrendColor1_2 TODO: Trend Color 1_2
// @param _TrendColor2_1 TODO: Trend Color 2_1
// @param _TrendColor2_2 TODO: Trend Color 2_2
// @param _ShowFibonacci1 TODO: Fibonacci1 Display
// @param _FibIndex1 TODO: Fibonacci1 Index No.
// @param _FibFrontMargin1 TODO: Fibonacci1 Front margin
// @param _FibBackMargin1 TODO: Fibonacci1 Back Margin
// @param _FibTransparent1 TODO: Fibonacci1 Transmittance
// @param _ShowFibonacci2 TODO: Fibonacci2 Display
// @param _FibIndex2 TODO: Fibonacci2 Index No.
// @param _FibFrontMargin2 TODO: Fibonacci2 Front margin
// @param _FibBackMargin2 TODO: Fibonacci2 Back Margin
// @param _FibTransparent2 TODO: Fibonacci2 Transmittance
// @param _ShowInfoTable1 TODO: InfoTable1 Display
// @param _TablePosition1 TODO: InfoTable1 position
// @param _ShowInfoTable2 TODO: InfoTable2 Display
// @param _TablePosition2 TODO: InfoTable2 position
// @returns TODO: 無し
export High_Low(
float[] _a_PHiLo, int[] _a_IHiLo,
int[] _a_FHiLo, float[] _a_DHiLo,
float[] _a_Fibonacci,
int _Length, int _Extension,
float _Difference, int _Histories,
bool _ShowZigZag,
color _ZigZagColor1, int _ZigZagWidth1,
color _ZigZagColor2, int _ZigZagWidth2,
bool _ShowZigZagLabel, string _ZigZagLabelSize,
bool _ShowHighLowBar, int _HighLowBarWidth,
bool _ShowTrendLine, bool _TrendMultiLine,
float _TrendStartWidth, float _TrendEndWidth,
float _TrendIncreWidth, int _TrendStartTrans,
int _TrendEndTrans, int _TrendIncreTrans,
int _TrendColorMode,
color _TrendColor1_1, color _TrendColor1_2,
color _TrendColor2_1, color _TrendColor2_2,
string _ShowFibonacci,
int _FibIndex1, int _FibFrontMargin1,
int _FibBackMargin1, int _FibTransparent1,
int _FibIndex2, int _FibFrontMargin2,
int _FibBackMargin2, int _FibTransparent2,
bool _ShowInfoTable1, string _TablePosition1,
bool _ShowInfoTable2, string _TablePosition2) =>
[rHiLo, rPHi, rPLo, rIHi, rILo, rCnt, rECnt, rDiffHi, rDiffLo, rStartHi, rStartLo]
=High_Low_Judgment(_Length, _Extension, _Difference)
[rPHiLo, rIHiLo, rFHiLo, rDHiLo, Provisional_PHiLo, Provisional_IHiLo]
=High_Low_Data_AddedAndUpdated(rHiLo, _Histories, rPHi, rPLo, rIHi, rILo, rDiffHi, rDiffLo, _a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo)
float top_Hi =ta.highest(high, _Histories) * 0.1
float top_Lo =ta.highest(low, _Histories) * 0.1
float bottom_Hi =ta.lowest (high, _Histories) * 0.1
float bottom_Lo =ta.lowest (low, _Histories) * 0.1
if _ShowInfoTable1
var table TBL_INFO_1 =na
// テーブル作成
TBL_INFO_1 :=table.new(Tbl_position(_TablePosition1), _Histories + 1, 3, border_width = 1)
//// テーブルに値セット
// 左タイトル
table.cell(TBL_INFO_1, 0, 0, "", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, 0, 1, "PRICE", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, 0, 2, "INDEX", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
for i =0 to _Histories - 1
// ヘッダー
table.cell(TBL_INFO_1, i + 1, 0, str.tostring(i), bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, i + 1, 1, str.tostring(array.get(_a_PHiLo, i), "0.000"), bgcolor =color.new(color.blue, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, i + 1, 2, str.tostring(array.get(_a_IHiLo, i)), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
if _ShowInfoTable2
var table TBL_INFO_2 =na
// テーブル作成
TBL_INFO_2 :=table.new(Tbl_position(_TablePosition2), 2, 12, border_width = 1)
// 左タイトル
table.cell(TBL_INFO_2, 0, 0, "HiLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 1, "PHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 2, "PLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 3, "IHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 4, "ILo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 5, "Cnt", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 6, "ECnt", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 7, "DiffHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 8, "DiffLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 9, "StartHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 10, "StartLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 11, "INDEX", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 0, str.tostring(rHiLo), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 1, str.tostring(rPHi, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 2, str.tostring(rPLo, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 3, str.tostring(rIHi), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 4, str.tostring(rILo), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 5, str.tostring(rCnt), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 6, str.tostring(rECnt), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 7, str.tostring(rDiffHi, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 8, str.tostring(rDiffLo, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 9, str.tostring(rStartHi, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 10, str.tostring(rStartLo, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 11, str.tostring(bar_index), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
if _ShowZigZag
ZigZag(rPHiLo, rIHiLo, rFHiLo, rDHiLo, _Histories, Provisional_PHiLo, Provisional_IHiLo,
_ZigZagColor1, _ZigZagWidth1, _ZigZagColor2, _ZigZagWidth2, _ShowZigZagLabel, _ZigZagLabelSize, _ShowHighLowBar, _HighLowBarWidth)
if _ShowTrendLine
TrendLine(_a_PHiLo, _a_IHiLo, _Histories, _TrendMultiLine, _TrendStartWidth, _TrendEndWidth, _TrendIncreWidth, _TrendStartTrans, _TrendEndTrans, _TrendIncreTrans, _TrendColorMode, _TrendColor1_1, _TrendColor1_2, _TrendColor2_1, _TrendColor2_2, top_Hi, top_Lo, bottom_Hi, bottom_Lo)
if _ShowFibonacci == "double"
Fibonacci(_a_Fibonacci, rPHiLo, Provisional_PHiLo, _FibIndex1, _FibFrontMargin1, _FibBackMargin1, _FibTransparent1, _FibIndex2, _FibFrontMargin2, _FibBackMargin2, _FibTransparent2)
else
Fibonacci(_a_Fibonacci, rPHiLo, Provisional_PHiLo, _FibIndex1, _FibFrontMargin1, _FibBackMargin1)
|
UtilityFunctions | https://www.tradingview.com/script/UU4SBVcv-UtilityFunctions/ | lyubo94 | https://www.tradingview.com/u/lyubo94/ | 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/
// © lyubo94
//@version=5
// @description Utility functions written by me
library("UtilityFunctions")
export empty() =>
1
// |
TR_HighLow_Lib | https://www.tradingview.com/script/9ZOwQn0C/ | Tommy_Rich | https://www.tradingview.com/u/Tommy_Rich/ | 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/
// © Tommy_Rich
//@version=5
// @description TODO: add library description here
library(title ="TR_HighLow_Lib",overlay =true)
////// //
//// local function group //// **********ローカル関数群**********
// //////
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]
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]
////// //
//// global function group //// **********グローバル関数群**********
// //////
// @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) Color of the label border and arrow
// @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 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: 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)
// @function TODO: Draw a zig-zag line.
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low INDEX array
// @param _a_FHiLo TODO: High-Low flag array sequence 1:High 2:Low
// @param _a_DHiLo TODO: High-Low Price Differential Array
// @param _Histories TODO: Array size (High-Low length)
// @param _Provisional_PHiLo TODO: Provisional High-Low Price
// @param _Provisional_IHiLo TODO: Provisional High-Low INDEX
// @param _Color1 TODO: Normal High-Low color
// @param _Width1 TODO: Normal High-Low width
// @param _Color2 TODO: Provisional High-Low color
// @param _Width2 TODO: Provisional High-Low width
// @param _ShowLabel TODO: Label display flag True: Displayed False: Not displayed
// @param _LabelSize TODO: Label Size
// @param _ShowHighLowBar TODO: High-Low bar display flag True:Show False:Hide
// @param _HighLowBarWidth TODO: High-Low bar width
// @returns TODO: No return value
export ZigZag(
float[] _a_PHiLo, int[] _a_IHiLo,
int[] _a_FHiLo, float[] _a_DHiLo,
int _Histories,
float _Provisional_PHiLo, int _Provisional_IHiLo,
color _Color1, int _Width1,
color _Color2, int _Width2,
bool _ShowLabel, string _LabelSize,
bool _ShowHighLowBar, int _HighLowBarWidth) =>
string info =""
var line l =na
var line l_1 =na
var line l_2 =na
int i_1 =bar_index - _Histories
int i_2 =i_1
float p_1 =0., p_2 =0.
int f_1 =0 , f_2 =0
float d_1 =0., d_2 =0.
bool _ShowTrendLine =true
for int i =0 to _Histories - 1
i_2 :=i_1
p_2 :=p_1
f_2 :=f_1
d_2 :=d_1
i_1 :=array.get(_a_IHiLo, i)
p_1 :=array.get(_a_PHiLo, i)
f_1 :=array.get(_a_FHiLo, i)
d_1 :=array.get(_a_DHiLo, i)
if i !=0
l :=line.new(i_1, p_1, i_2, p_2, color =_Color1, width =_Width1)
if _ShowHighLowBar
l_1 :=line.new(i_1, p_1, i_1 + 50, p_1, color =color.new(GetColor(i), 40), width =_HighLowBarWidth, extend=extend.right)
if p_2 != 0.
l_2 :=line.new(i_2, p_2, i_2 + 50, p_2, color =color.new(GetColor(i + 1), 40), width =_HighLowBarWidth, extend=extend.right)
if _ShowLabel
string yloc1 =yloc.abovebar
string yloc2 =yloc.belowbar
string style1 =label.style_none
string style2 =label.style_none
color color1 =color.blue
color color2 =color.red
if f_1 == 2
yloc1 :=yloc.belowbar
yloc2 :=yloc.abovebar
color1 :=color.red
color2 :=color.blue
info :=str.tostring(p_1) + "\n(" + str.tostring(d_1) + ")"
ShowLabel(info, i_1, p_1, style1, _LabelSize, yloc1, color1)
if p_2 != 0.
info :=str.tostring(p_2) + "\n(" + str.tostring(d_2) + ")"
ShowLabel(info, i_2, p_2, style2, _LabelSize, yloc2, color2)
if not na(_Provisional_PHiLo)
if _Provisional_IHiLo > i_1
l :=line.new(i_1, p_1, _Provisional_IHiLo, _Provisional_PHiLo, color =_Color2, width =_Width2)
// @function TODO: Draw a Trend Line
// @param _a_PHigh TODO: High price array
// @param _a_PLow TODO: Low price array
// @param _a_IHigh TODO: High INDEX array
// @param _a_ILow TODO: Low INDEX array
// @param _Histories TODO: Array size (High-Low length)
// @param _MultiLine TODO: Draw a multiple Line.
// @param _StartWidth TODO: Line width start value
// @param _EndWidth TODO: Line width end value
// @param _IncreWidth TODO: Line width increment value
// @param _StartTrans TODO: Transparent rate start value
// @param _EndTrans TODO: Transparent rate finally
// @param _IncreTrans TODO: Transparent rate increase value
// @param _ColorMode TODO: 0:Nomal 1:Gradation
// @param _Color1_1 TODO: Gradation Color 1_1
// @param _Color1_2 TODO: Gradation Color 1_2
// @param _Color2_1 TODO: Gradation Color 2_1
// @param _Color2_2 TODO: Gradation Color 2_2
// @returns TODO: No return value
export TrendLine(
float[] _a_PHigh, float[] _a_PLow,
int[] _a_IHigh, int[] _a_ILow,
int _Histories, bool _MultiLine,
float _StartWidth, float _EndWidth,
float _IncreWidth, int _StartTrans,
int _EndTrans, int _IncreTrans,
int _ColorMode, color _Color1_1,
color _Color1_2, color _Color2_1,
color _Color2_2) =>
var line l_1 =na
var line l_2 =na
var line l_3 =na
var line l_4 =na
var line l_5 =na
var line l_6 =na
int i_1 =bar_index - _Histories, i_2 =i_1, i_3 =i_1, i_4 =i_1
float p_1 =0., p_2 =0., p_3 =0., p_4 =0.
int f_1 =0, f_2 =0, f_3 =0, f_4 =0
float d_1 =0., d_2 =0., d_3 =0., d_4 =0.
float width =0., trans =0.
int histories_1 =array.size(_a_PHigh) -1
int histories_2 =array.size(_a_PLow) -1
float h_min = 999999999.
float h_max =-999999999.
float h_p1 =0., h_p2 =0.
for int i =0 to histories_1
h_p2 :=h_p1
h_p1 :=array.get(_a_PHigh, i)
if i > 0
if (h_p2 - h_p1) > h_max
h_max :=(h_p2 - h_p1)
if (h_p2 - h_p1) < h_min
h_min :=(h_p2 - h_p1)
float l_min = 999999999.
float l_max =-999999999.
float l_p1 =0., l_p2 =0.
for int i =0 to histories_2
l_p2 :=l_p1
l_p1 :=array.get(_a_PLow, i)
if i > 0
if (l_p2 - l_p1) > l_max
l_max :=(l_p2 - l_p1)
if (l_p2 - l_p1) < l_min
l_min :=(l_p2 - l_p1)
float top_Hi =array.max(_a_PHigh)
float top_Lo =array.min(_a_PHigh)
float bottom_Hi =array.max(_a_PLow)
float bottom_Lo =array.max(_a_PLow)
color c1 =na
color c2 =na
color c1d =color.new(color.from_gradient(5, 1, 10, _Color1_1, _Color1_2), 60)
color c2d =color.new(color.from_gradient(5, 1, 10, _Color2_1, _Color2_2), 60)
if _MultiLine
for int i =0 to histories_1
p_1 :=array.get(_a_PHigh, i)
i_1 :=array.get(_a_IHigh, i)
width :=_StartWidth + (i * _IncreWidth)
if _IncreWidth > 0
if width > _EndWidth
width :=_EndWidth
else
if width < _EndWidth
width :=_EndWidth
trans :=_StartTrans + (i * _IncreTrans)
if _IncreTrans > 0
if trans > _EndTrans
trans :=_EndTrans
else
if trans < _EndTrans
trans :=_EndTrans
for int j =histories_1 to i
if j < 0
break
p_3 :=array.get(_a_PHigh, j)
i_3 :=array.get(_a_IHigh, j)
if _ColorMode == 1
if p_1 >= p_3
c1 :=color.new(color.from_gradient(p_1 - p_3, h_min, h_max, _Color1_1, _Color1_2), trans)
else
c1 :=color.new(color.from_gradient(p_1 - p_3, h_min, h_max, _Color2_1, _Color2_2), trans)
else
c1 :=color.new(GetColor(j), trans)
l_1 :=line.new(i_1, p_1 + width, i_3, p_3 + width, color =c1, width =1, extend =extend.right)
l_2 :=line.new(i_1, p_1, i_3, p_3, color =c1d, width =1, extend =extend.right, style =line.style_dotted)
l_3 :=line.new(i_1, p_1 - width, i_3, p_3 - width, color =c1, width =1, extend =extend.right)
linefill.new(l_1, l_3, color.new(c1, trans))
for int i =0 to histories_2
p_2 :=array.get(_a_PLow, i)
i_2 :=array.get(_a_ILow, i)
width :=_StartWidth + (i * _IncreWidth)
if _IncreWidth > 0
if width > _EndWidth
width :=_EndWidth
else
if width < _EndWidth
width :=_EndWidth
trans :=_StartTrans + (i * _IncreTrans)
if _IncreTrans > 0
if trans > _EndTrans
trans :=_EndTrans
else
if trans < _EndTrans
trans :=_EndTrans
for int j =histories_2 to i
if j < 0
break
p_4 :=array.get(_a_PLow, j)
i_4 :=array.get(_a_ILow, j)
if _ColorMode == 1
if p_2 >= p_4
c2 :=color.new(color.from_gradient(p_2 - p_4, l_min, l_max, _Color1_1, _Color1_2), trans)
else
c2 :=color.new(color.from_gradient(p_2 - p_4, l_min, l_max, _Color2_1, _Color2_2), trans)
else
c2 :=color.new(GetColor(j), trans)
l_4 :=line.new(i_2, p_2 + width, i_4, p_4 + width, color =c2, width =1, extend =extend.right)
l_5 :=line.new(i_2, p_2, i_4, p_4, color =c2d, width =1, extend =extend.right, style =line.style_dotted)
l_6 :=line.new(i_2, p_2 - width, i_4, p_4 - width, color =c2, width =1, extend =extend.right)
linefill.new(l_4, l_6, color.new(c2, trans))
else
for int i =0 to histories_1
p_3 :=p_1
i_3 :=i_1
p_1 :=array.get(_a_PHigh, i)
i_1 :=array.get(_a_IHigh, i)
width :=_StartWidth + (i * _IncreWidth)
if _IncreWidth > 0
if width > _EndWidth
width :=_EndWidth
else
if width < _EndWidth
width :=_EndWidth
trans :=_StartTrans + (i * _IncreTrans)
if _IncreTrans > 0
if trans > _EndTrans
trans :=_EndTrans
else
if trans < _EndTrans
trans :=_EndTrans
if p_3 !=0
if _ColorMode == 1
if p_1 >= p_3
c1 :=color.new(color.from_gradient(p_1 - p_3, h_min, h_max, _Color1_1, _Color1_2), trans)
else
c1 :=color.new(color.from_gradient(p_1 - p_3, h_min, h_max, _Color2_1, _Color2_2), trans)
else
c1 :=color.new(GetColor(i), trans)
l_1 :=line.new(i_1, p_1 + width, i_3, p_3 + width, color =c1, width =1, extend =extend.left)
l_2 :=line.new(i_1, p_1, i_3, p_3, color =c1d, width =1, extend =extend.left, style =line.style_dotted)
l_3 :=line.new(i_1, p_1 - width, i_3, p_3 - width, color =c1, width =1, extend =extend.left)
linefill.new(l_1, l_3, color.new(c1, trans))
for int i =0 to histories_2
p_4 :=p_2
i_4 :=i_2
p_2 :=array.get(_a_PLow, i)
i_2 :=array.get(_a_ILow, i)
width :=_StartWidth + (i * _IncreWidth)
if _IncreWidth > 0
if width > _EndWidth
width :=_EndWidth
else
if width < _EndWidth
width :=_EndWidth
trans :=_StartTrans + (i * _IncreTrans)
if _IncreTrans > 0
if trans > _EndTrans
trans :=_EndTrans
else
if trans < _EndTrans
trans :=_EndTrans
if p_4 !=0
if _ColorMode == 1
if p_2 >= p_4
c2 :=color.new(color.from_gradient(p_2 - p_4, l_min, l_max, _Color1_1, _Color1_2), trans)
else
c2 :=color.new(color.from_gradient(p_2 - p_4, l_min, l_max, _Color2_1, _Color2_2), trans)
else
c2 :=color.new(GetColor(i), trans)
l_4 :=line.new(i_2, p_2 + width, i_4, p_4 + width, color =c2, width =1, extend =extend.left)
l_5 :=line.new(i_2, p_2, i_4, p_4, color =c2d, width =1, extend =extend.left, style =line.style_dotted)
l_6 :=line.new(i_2, p_2 - width, i_4, p_4 - width, color =c2, width =1, extend =extend.left)
linefill.new(l_4, l_6, color.new(c2, trans))
// @function TODO: Draw a fibonacci line
// @param _a_Fibonacci TODO: Fibonacci percentage array
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low index array
// @param _Provisional_PHiLo TODO: Provisional High-Low price (when _Index is 0)
// @param _Index TODO: Where to draw the Fibonacci line
// @param _FrontMargin TODO: Fibonacci line front-margin
// @param _BackMargin TODO: Fibonacci line back-margin
// @param _Transparent TODO: Transparent rate
// @param _TextColor TODO: Fibonacci text color
// @param _TextMargin TODO: Fibonacci text margin
// @param _LabelSize TODO: Fibonacci label size
// @param _Title TODO: Fibonacci title
// @param _TitleMargin TODO: Fibonacci title margin
// @param _ChangeColor TODO: Change the color of the corresponding trend line
// @param _TrendColor TODO: Color of trend line to be changed
// @param _TrendLineWidth TODO: Width of trend line to be changed
// @returns TODO: No return value
export Fibonacci(
float[] _a_Fibonacci,
float[] _a_PHiLo, int[] _a_IHiLo,
float _Provisional_PHiLo, int _Index,
int _FrontMargin, int _BackMargin,
int _Transparent, color _TextColor,
int _TextMargin, string _LabelSize,
string _Title, float _TitleMargin,
bool _ChangeColor, color _TrendColor,
int _TrendLineWidth) =>
int i_1 =0 , i_2 =0
float p_1 =0., p_2 =0.
line l =na
line[] ls =array.new_line()
int index_1 =array.size(_a_PHiLo) - _Index
int index_2 =index_1 - 1
float dir =0.
float diff =0.
float labelMargin =0.
int fib_size =array.size(_a_Fibonacci) -1
var label lbl1 = na
i_1 :=bar_index + _FrontMargin
i_2 :=bar_index + _BackMargin
if _Index == 0
p_1 :=_Provisional_PHiLo
else
p_1 :=array.get(_a_PHiLo, index_1)
p_2 :=array.get(_a_PHiLo, index_2)
// 上昇・下降判断用
dir :=p_1 - p_2
// 差の絶対値
diff :=math.abs(dir)
if dir > 0
labelMargin :=p_1 - diff * array.get(_a_Fibonacci, fib_size) - (_TitleMargin)
else
labelMargin :=p_1 - diff * array.get(_a_Fibonacci, 0) - (_TitleMargin)
lbl1 := label.new(x =i_1 + _TextMargin, y =labelMargin, text =_Title, yloc = yloc.price, style =label.style_none, textcolor =_TrendColor, size =_LabelSize)
if _ChangeColor
int x_1 =array.get(_a_IHiLo, index_1)
int x_2 =array.get(_a_IHiLo, index_2)
l :=line.new(x_1, p_1, x_2, p_2, color =_TrendColor, width =_TrendLineWidth)
for i1 =0 to array.size(_a_Fibonacci) -1
float _f =0.
float _Fib =array.get(_a_Fibonacci, i1)
// 上昇
if dir > 0
_f :=p_1 - (diff * _Fib)
else
_f :=p_1 + (diff * _Fib)
l :=line.new(i_1, _f, i_2, _f, color =color.red, width =1)
array.push(ls, l)
lbl1 := label.new(x =i_1 + _TextMargin, y =_f, text =str.tostring(_Fib, "0.000") + " : " + str.tostring(_f, "0.000"),
yloc = yloc.price, style =label.style_none, textcolor =_TextColor, size =_LabelSize)
for i2 =0 to array.size(ls) -2
if array.size(ls) >= 2
line l1 =array.get(ls, i2)
line l2 =array.get(ls, i2 + 1)
linefill.new(l1, l2, color.new(GetColor(i2), _Transparent))
// @function TODO: Draw a fibonacci line
// @param _a_Fibonacci TODO: Fibonacci percentage array
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low index array
// @param _Provisional_PHiLo TODO: Provisional High-Low price (when _Index is 0)
// @param _Index1 TODO: Where to draw the fibonacci line 1
// @param _FrontMargin1 TODO: Fibonacci line front-margin 1
// @param _BackMargin1 TODO: Fibonacci line back-margin 1
// @param _Transparent1 TODO: Transparent rate 1
// @param _TextColor1 TODO: Fibonacci text color 1
// @param _TextMargin1 TODO: Fibonacci text margin 1
// @param _LabelSize1 TODO: Fibonacci label size 1
// @param _Title1 TODO: Fibonacci title 1
// @param _TitleMargin1 TODO: Fibonacci title margin 1
// @param _ChangeColor1 TODO: Change the color of the corresponding trend line 1
// @param _TrendColor1 TODO: Color of trend line to be changed 1
// @param _TrendLineWidth1 TODO: Width of trend line to be changed 1
// @param _Index2 TODO: Where to draw the Fibonacci line 2
// @param _FrontMargin2 TODO: Fibonacci line front-margin 2
// @param _BackMargin2 TODO: Fibonacci line back-margin 2
// @param _Transparent2 TODO: Transparent rate 2
// @param _TextColor2 TODO: Fibonacci text color 2
// @param _TextMargin2 TODO: Fibonacci text margin 2
// @param _LabelSize2 TODO: Fibonacci label size 2
// @param _Title2 TODO: Fibonacci title 2
// @param _TitleMargin2 TODO: Fibonacci title margin 2
// @param _ChangeColor2 TODO: Change the color of the corresponding trend line 2
// @param _TrendColor2 TODO: Color of trend line to be changed 2
// @param _TrendLineWidth2 TODO: Width of trend line to be changed 2
// @returns TODO: No return value
export Fibonacci(
float[] _a_Fibonacci, float[] _a_PHiLo,
int[] _a_IHiLo, float _Provisional_PHiLo,
int _Index1, int _FrontMargin1,
int _BackMargin1, int _Transparent1,
color _TextColor1, int _TextMargin1,
string _LabelSize1,
string _Title1, float _TitleMargin1,
bool _ChangeColor1, color _TrendColor1,
int _TrendLineWidth1,
int _Index2, int _FrontMargin2,
int _BackMargin2, int _Transparent2,
color _TextColor2, int _TextMargin2,
string _LabelSize2,
string _Title2, float _TitleMargin2,
bool _ChangeColor2, color _TrendColor2,
int _TrendLineWidth2) =>
int i1_1 =0 , i1_2 =0 , i2_1 =0 , i2_2 =0
float p1_1 =0., p1_2 =0., p2_1 =0., p2_2 =0.
line l1 =na
line l2 =na
line[] ls1 =array.new_line(), ls2 =array.new_line()
int index1_1 =array.size(_a_PHiLo) - _Index1
int index1_2 =index1_1 - 1
int index2_1 =array.size(_a_PHiLo) - _Index2
int index2_2 =index2_1 - 1
float dir1 =0., dir2 =0.
float diff1 =0., diff2 =0.
float labelMargin1 =0., labelMargin2 =0.
int fib_size =array.size(_a_Fibonacci) -1
var label lbl1 = na
var label lbl2 = na
i1_1 :=bar_index + _FrontMargin1
i1_2 :=bar_index + _BackMargin1
i2_1 :=bar_index + _FrontMargin2
i2_2 :=bar_index + _BackMargin2
if _Index1 == 0
p1_1 :=_Provisional_PHiLo
else
p1_1 :=array.get(_a_PHiLo, index1_1)
if _Index2 == 0
p2_1 :=_Provisional_PHiLo
else
p2_1 :=array.get(_a_PHiLo, index2_1)
p1_2 :=array.get(_a_PHiLo, index1_2)
p2_2 :=array.get(_a_PHiLo, index2_2)
// 上昇・下降判断用
dir1 :=p1_1 - p1_2
dir2 :=p2_1 - p2_2
// 差の絶対値
diff1 :=math.abs(dir1)
diff2 :=math.abs(dir2)
if dir1 > 0
labelMargin1 :=p1_1 - diff1 * array.get(_a_Fibonacci, fib_size) - (_TitleMargin1)
else
labelMargin1 :=p1_1 - diff1 * array.get(_a_Fibonacci, 0) - (_TitleMargin1)
if dir2 > 0
labelMargin2 :=p2_1 - diff2 * array.get(_a_Fibonacci, fib_size) - (_TitleMargin2)
else
labelMargin2 :=p2_1 - diff2 * array.get(_a_Fibonacci, 0) - (_TitleMargin2)
lbl1 := label.new(x =i1_1 + _TextMargin1, y =labelMargin1, text =_Title1, yloc = yloc.price, style =label.style_none, textcolor =_TrendColor1, size =_LabelSize1)
lbl2 := label.new(x =i2_1 + _TextMargin2, y =labelMargin2, text =_Title2, yloc = yloc.price, style =label.style_none, textcolor =_TrendColor2, size =_LabelSize2)
if _ChangeColor1
int x1_1 =array.get(_a_IHiLo, index1_1)
int x1_2 =array.get(_a_IHiLo, index1_2)
l1 :=line.new(x1_1, p1_1, x1_2, p1_2, color =_TrendColor1, width =_TrendLineWidth1)
if _ChangeColor2
int x2_1 =array.get(_a_IHiLo, index2_1)
int x2_2 =array.get(_a_IHiLo, index2_2)
l2 :=line.new(x2_1, p2_1, x2_2, p2_2, color =_TrendColor2, width =_TrendLineWidth2)
for i =0 to fib_size
float _f1 =0., _f2 =0.
float _Fib =array.get(_a_Fibonacci, i)
// 上昇
if dir1 > 0
_f1 :=p1_1 - (diff1 * _Fib)
else
_f1 :=p1_1 + (diff1 * _Fib)
if dir2 > 0
_f2 :=p2_1 - (diff2 * _Fib)
else
_f2 :=p2_1 + (diff2 * _Fib)
l1 :=line.new(i1_1, _f1, i1_2, _f1, color =color.red, width =1)
array.push(ls1, l1)
l2 :=line.new(i2_1, _f2, i2_2, _f2, color =color.red, width =1)
array.push(ls2, l2)
lbl1 := label.new(x =i1_1 + _TextMargin1, y =_f1, text =str.tostring(_Fib, "0.000") + " : " + str.tostring(_f1, "0.000"),
yloc = yloc.price, style =label.style_none, textcolor =_TextColor1, size =_LabelSize1)
lbl2 := label.new(x =i2_1 + _TextMargin2, y =_f2, text =str.tostring(_Fib, "0.000") + " : " + str.tostring(_f2, "0.000"),
yloc = yloc.price, style =label.style_none, textcolor =_TextColor2, size =_LabelSize2)
for i =0 to array.size(ls1) -2
if array.size(ls1) >= 2
line l1_1 =array.get(ls1, i)
line l1_2 =array.get(ls1, i + 1)
linefill.new(l1_1, l1_2, color.new(GetColor(i), _Transparent1))
if array.size(ls2) >= 2
line l2_1 =array.get(ls2, i)
line l2_2 =array.get(ls2, i + 1)
linefill.new(l2_1, l2_2, color.new(GetColor(i), _Transparent2))
// @function TODO: Judges High-Low
// @param _High TODO: High Price Source
// @param _Low TODO: Low Price Source
// @param _Length TODO: High-Low Confirmation Length
// @param _Extension TODO: Length of extension when the difference did not open
// @param _Difference TODO: Difference size
// @returns TODO: _HiLo=High-Low flag 0:Neither high nor low、1:High、2:Low、3:High-Low
// _PHi=high price、_PLo=low price、_IHi=High Price Index、_ILo=Low Price Index、
// _Cnt=count、_ECnt=Extension count、
// _DiffHi=Difference from Start(High)、_DiffLo=Difference from Start(Low)、
// _StartHi=Start value(High)、_StartLo=Start value(Low)
export High_Low_Judgment(
float _High,
float _Low,
int _Length,
int _Extension,
float _Difference) =>
int hiLo =0 // High-Lowフラグ
var float pHi =-9999999999. // Price Hi
var float pLo = 9999999999. // Price Lo
var int iHi =0 // Index Hi
var int iLo =0 // Index Lo
var int cnt =-1 // カウント変数
var int eCnt =0 // Extカウント変数
var float diffHi =0. // Highの差
var float diffLo =0. // Lowの差
var float startHi =0. // Start時のHigh
var float startLo =0. // Start時のLow
cnt +=1 // カウントインクリ
if cnt == 0 // 初回の時
pHi :=_High // _PHiにhighを保管
pLo :=_Low // pLoにlowを保管
startHi :=pHi // _StartHiに初回highを保管
startLo :=pLo // _StartLoに初回lowを保管
iHi :=bar_index // _IHiにインデックスを保存
iLo :=bar_index // _ILoにインデックスを保存
else // 2回目以降の時
if pHi < _High // _PHiよりhighが大きい
pHi :=_High // _PHiをアップデート
iHi :=bar_index // iHiにインデックスを保存
if pLo > _Low // pLoよりlowが小さい
pLo :=_Low // pLoをアップデート
iLo :=bar_index // _ILoにインデックスを保存
if cnt >= _Length // _Cntが_Length以上
diffHi :=pHi - startHi // _StartHi(初回)と_PHiとの差
diffLo :=startLo - pLo // _StartLo(初回)とpLoとの差
if diffHi > diffLo // Highの方が差が大きい
if diffHi >= _Difference // _DiffHiが_Difference以上
hiLo :=1 // High-Lowフラグに1をセット
cnt :=-1 // カウント変数リセット
eCnt :=0 // Extカウント変数リセット
else if diffLo > diffHi // Lowの方が差が大きい
if diffLo >= _Difference // _DiffLoが_Difference以上
hiLo :=2 // High-Lowフラグに2をセット
cnt :=-1 // カウント変数リセット
eCnt :=0 // Extカウント変数リセット
else // High-Lowの差が同じ
if diffHi >= _Difference // _DiffLoが_Difference以上
hiLo :=3 // High-Lowフラグに3をセット
cnt :=-1 // カウント変数リセット
eCnt :=0 // Extカウント変数リセット
if eCnt > _Extension // _ECntが_Extension以上
cnt :=-1 // カウント変数リセット
eCnt :=0 // Extカウント変数リセット
if hiLo == 0
if diffHi > diffLo // Highの方が大きい
hiLo :=1 // High-Lowフラグに1をセット
else if diffLo > diffHi // Lowの方が大きい
hiLo :=2 // High-Lowフラグに2をセット
else // High-Low同じ大きさ
hiLo :=3 // High-Lowフラグに3をセット
else
eCnt +=1
[hiLo, pHi, pLo, iHi, iLo, cnt, eCnt, diffHi, diffLo, startHi, startLo]
// @function TODO: Adds and updates High-Low related arrays from given parameters
// @param _HiLo TODO: High-Low flag
// @param _Histories TODO: Array size (High-Low length)
// @param _PHi TODO: Price Hi
// @param _PLo TODO: Price Lo
// @param _IHi TODO: Index Hi
// @param _ILo TODO: Index Lo
// @param _DiffHi TODO: Difference in High
// @param _DiffLo TODO: Difference in Low
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low INDEX array
// @param _a_FHiLo TODO: High-Low flag array 1:High 2:Low
// @param _a_DHiLo TODO: High-Low Price Differential Array
// @param _a_PHigh TODO: High Price Differential Array
// @param _a_IHigh TODO: High INDEX array
// @param _a_PLow TODO: Low Price Differential Array
// @param _a_ILow TODO: Low INDEX array
// @returns TODO: _PHiLo price array、_IHiLo indexed array、_FHiLo flag array、_DHiLo price-matching array、
// Provisional_PHiLo Provisional price、Provisional_IHiLo 暫定インデックス
export High_Low_Data_AddedAndUpdated(
int _HiLo, int _Histories,
float _PHi, float _PLo,
int _IHi, int _ILo,
float _DiffHi, float _DiffLo,
float[] _a_PHiLo, int[] _a_IHiLo,
int[] _a_FHiLo, float[] _a_DHiLo,
float[] _a_PHigh, int[] _a_IHigh,
float[] _a_PLow, int[] _a_ILow) =>
float Provisional_PHiLo =na // 暫定High-Low 価格
int Provisional_IHiLo =na // 暫定High-Low インデックス
if _HiLo != 0 // High-Low フラグ 0=初期値でない時
if array.get(_a_FHiLo, _Histories-1) == 1 // 前回High-Low フラグ 1=High(高値)の時
if _PHi >= array.get(_a_PHiLo, _Histories-1) // 前回High-Low 価格より現在High(高値)の方が高い(以上)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo,
_PHi, _IHi, _DiffHi, _a_PHigh, _a_IHigh) // 前回High-Low 価格、インデックス、価格差を置き換える
if _IHi <= _ILo // 前回High-Low 情報(High)を置き換えたので、HighインデックスよりLowインデックスの方が大きいか確認する
// ↑ちなみにHighは書き換え済みなので何もしない
if _HiLo == 2 // 今回がLowの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PLo, _ILo, _HiLo, _DiffLo, _a_PLow, _a_ILow) // 配列にLow値を追記する
else // 前回High-Low 価格より現在High(高値)の方が低い
if _HiLo == 2 // 今回がLowの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PLo, _ILo, _HiLo, _DiffLo, _a_PLow, _a_ILow) // 配列にLow値を追記する
else if _HiLo == 3 // 今回がHigh-Lowの時(HighでもLowでもある時)
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PLo, _ILo, 2, _DiffLo, _a_PLow, _a_ILow) // 前回がHighなので、配列にLow値から追記する
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PHi, _IHi, 1, _DiffHi, _a_PHigh, _a_IHigh) // 配列にLow値を追記したのでHigh値を追記する
if array.get(_a_FHiLo, _Histories-1) == 2 // 前回High-Low フラグ 2=Low(安値)の時
if _PLo <= array.get(_a_PHiLo, _Histories-1) // 前回High-Low 価格より現在Low(安値)の方が低い(以下)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo,
_PLo, _ILo, _DiffLo, _a_PLow, _a_ILow) // 前回High-Low 価格、インデックス、価格差を置き換える
if _ILo <= _IHi // 前回High-Low 情報(Low)を置き換えたので、LowインデックスよりHighインデックスの方が大きいか確認する
// ↑ちなみにLowは書き換え済みなので何もしない
if _HiLo == 1 // 今回がHighの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PHi, _IHi, _HiLo, _DiffHi, _a_PHigh, _a_IHigh) // 配列にHigh値を追記する
else
if _HiLo == 1 // 今回がHighの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PHi, _IHi, _HiLo, _DiffHi, _a_PHigh, _a_IHigh) // 配列にHigh値を追記する
else if _HiLo == 3 // 今回がHigh-Lowの時(HighでもLowでもある時)
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PHi, _IHi, 1, _DiffHi, _a_PHigh, _a_IHigh) // 前回Lowなので、配列にHigh値から追記する
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PLo, _ILo, 2, _DiffLo, _a_PLow, _a_ILow) // 配列にHigh値を追記したのでLow値を追記する
if array.get(_a_FHiLo, _Histories-1) == 0 // 前回High-Low フラグ 0=初回の時
if _HiLo == 1 // 今回がHighの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PHi, _IHi, _HiLo, _DiffHi, _a_PHigh, _a_IHigh) // 配列にHigh値を追記する
else if _HiLo == 2 // 今回がLowの時
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PLo, _ILo, _HiLo, _DiffLo, _a_PLow, _a_ILow) // 配列にLow値を追記する
else if _HiLo == 3 // 今回がHigh-Lowの時(HighでもLowでもある時)
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PHi, _IHi, 1, _DiffHi, _a_PHigh, _a_IHigh) // とりあえず、配列にHigh値から追記する
SetHighLowArray(_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo,
_PLo, _ILo, 2, _DiffLo, _a_PLow, _a_ILow) // 配列にHigh値を追記したのでLow値を追記する
else // High-Low フラグ 0=初期値の時
float _price =array.get(_a_PHiLo, _Histories-1) // 前回価格の取得
if array.get(_a_FHiLo, _Histories-1) == 1 // 前回High-Low フラグ 1=High(高値)の時
if _price <= _PHi // 前回High-Low 価格より現在High(高値)の方が高い(以上)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo,
_PHi, _IHi, _DiffHi, _a_PHigh, _a_IHigh) // 前回High-Low 価格、インデックス、価格差を置き換える
else
Provisional_PHiLo :=_PLo // Lowとして暫定価格をセット
Provisional_IHiLo :=_ILo // Lowとして暫定インデックスをセット
if array.get(_a_FHiLo, _Histories-1) == 2 // 前回High-Low フラグ 2=Low(安値)の時
if _price >= _PLo // 前回High-Low 価格より現在Low(安値)の方が低い(以下)
ChangeHighLowArray(_a_PHiLo, _a_IHiLo, _a_DHiLo,
_PLo, _ILo, _DiffLo, _a_PLow, _a_ILow) // 前回High-Low 価格、インデックス、価格差を置き換える
else
Provisional_PHiLo :=_PHi // Highとして暫定価格をセット
Provisional_IHiLo :=_IHi // Highとして暫定インデックスをセット
[_a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, Provisional_PHiLo, Provisional_IHiLo]
// @function TODO: Draw the contents of the High-Low array.
// @param _High TODO: High Source
// @param _Low TODO: Low Source
// @param _a_PHiLo TODO: High-Low price array
// @param _a_IHiLo TODO: High-Low index array
// @param _a_FHiLo TODO: High-Low flag sequence 1:High 2:Low
// @param _a_DHiLo TODO: High-Low price differential array
// @param _a_PHigh TODO: High price array
// @param _a_PLow TODO: Low price array
// @param _a_IHigh TODO: High index array
// @param _a_ILow TODO: Low index array
// @param _a_Fibonacci TODO: Fibonacci gnar matching
// @param _Length TODO: Length of confirmation
// @param _Extension TODO: Extension length of extension when the difference did not open
// @param _Difference TODO: Difference size
// @param _Histories TODO: High-Low length
// @param _ShowZigZag TODO: ZigZag display
// @param _ZigZagColor1 TODO: Colors of ZigZag1
// @param _ZigZagWidth1 TODO: Width of ZigZag1
// @param _ZigZagColor2 TODO: Colors of ZigZag2
// @param _ZigZagWidth2 TODO: Width of ZigZag2
// @param _ShowZigZagLabel TODO: ZigZagLabel display
// @param _ShowHighLowBar TODO: High-Low bar display
// @param _ShowTrendLine TODO: Trend line display
// @param _TrendMultiLine TODO: Trend multi line display
// @param _TrendStartWidth TODO: Line width start value
// @param _TrendEndWidth TODO: Line width end value
// @param _TrendIncreWidth TODO: Line width increment value
// @param _TrendStartTrans TODO: Starting transmittance value
// @param _TrendEndTrans TODO: Transmittance end value
// @param _TrendIncreTrans TODO: Increased transmittance value
// @param _TrendColorMode TODO: color mode
// @param _TrendColor1_1 TODO: Trend color 1_1
// @param _TrendColor1_2 TODO: Trend color 1_2
// @param _TrendColor2_1 TODO: Trend color 2_1
// @param _TrendColor2_2 TODO: Trend color 2_2
// @param _ShowFibonacci1 TODO: Fibonacci1 display
// @param _FibIndex1 TODO: Fibonacci1 index no.
// @param _FibFrontMargin1 TODO: Fibonacci1 front margin
// @param _FibBackMargin1 TODO: Fibonacci1 back margin
// @param _FibTransparent1 TODO: Fibonacci1 transmittance
// @param _FibTextColor1 TODO: Fibonacci1 text color
// @param _FibTextMargin1 TODO: Fibonacci1 text margin
// @param _FibLabelSize1 TODO: Fibonacci1 label size
// @param _FibTitle1 TODO: Fibonacci1 title
// @param _FibTitleMargin1 TODO: Fibonacci1 title margin
// @param _FibChangeColor1 TODO: Fibonacci1 change the color of the trend line?
// @param _FibTrendColor1 TODO: Fibonacci1 trend line color
// @param _FibTrendLineWidth1 TODO: Fibonacci1 trend line width
// @param _ShowFibonacci2 TODO: Fibonacci2 display
// @param _FibIndex2 TODO: Fibonacci2 index no.
// @param _FibFrontMargin2 TODO: Fibonacci2 front margin
// @param _FibBackMargin2 TODO: Fibonacci2 back margin
// @param _FibTransparent2 TODO: Fibonacci2 transmittance
// @param _FibTextColor2 TODO: Fibonacci2 text color
// @param _FibTextMargin2 TODO: Fibonacci2 text margin
// @param _FibLabelSize2 TODO: Fibonacci2 label size
// @param _FibTitle2 TODO: Fibonacci2 title
// @param _FibTitleMargin2 TODO: Fibonacci2 title margin
// @param _FibChangeColor2 TODO: Fibonacci2 change the color of the trend line?
// @param _FibTrendColor2 TODO: Fibonacci2 trend line color
// @param _FibTrendLineWidth2 TODO: Fibonacci2 trend line width
// @param _ShowInfoTable1 TODO: InfoTable1 display
// @param _TablePosition1 TODO: InfoTable1 position
// @param _ShowInfoTable2 TODO: InfoTable2 display
// @param _TablePosition2 TODO: InfoTable2 position
// @returns TODO: 無し
export High_Low(
float _High, float _Low,
float[] _a_PHiLo, int[] _a_IHiLo,
int[] _a_FHiLo, float[] _a_DHiLo,
float[] _a_PHigh, float[] _a_PLow,
int[] _a_IHigh, int[] _a_ILow,
float[] _a_Fibonacci,
int _Length, int _Extension,
float _Difference, int _Histories,
bool _ShowZigZag,
color _ZigZagColor1, int _ZigZagWidth1,
color _ZigZagColor2, int _ZigZagWidth2,
bool _ShowZigZagLabel, string _ZigZagLabelSize,
bool _ShowHighLowBar, int _HighLowBarWidth,
bool _ShowTrendLine, bool _TrendMultiLine,
float _TrendStartWidth, float _TrendEndWidth,
float _TrendIncreWidth, int _TrendStartTrans,
int _TrendEndTrans, int _TrendIncreTrans,
int _TrendColorMode,
color _TrendColor1_1, color _TrendColor1_2,
color _TrendColor2_1, color _TrendColor2_2,
string _ShowFibonacci,
int _FibIndex1, int _FibFrontMargin1,
int _FibBackMargin1, int _FibTransparent1,
color _FibTextColor1, int _FibTextMargin1,
string _FibLabelSize1,
string _FibTitle1, float _FibTitleMargin1,
bool _FibChangeColor1,
color _FibTrendColor1, int _FibTrendLineWidth1,
int _FibIndex2, int _FibFrontMargin2,
int _FibBackMargin2, int _FibTransparent2,
color _FibTextColor2, int _FibTextMargin2,
string _FibLabelSize2,
string _FibTitle2, float _FibTitleMargin2,
bool _FibChangeColor2,
color _FibTrendColor2, int _FibTrendLineWidth2,
bool _ShowInfoTable1, string _TablePosition1,
bool _ShowInfoTable2, string _TablePosition2) =>
[rHiLo, rPHi, rPLo, rIHi, rILo, rCnt, rECnt, rDiffHi, rDiffLo, rStartHi, rStartLo]
=High_Low_Judgment(_High, _Low, _Length, _Extension, _Difference)
[rPHiLo, rIHiLo, rFHiLo, rDHiLo, Provisional_PHiLo, Provisional_IHiLo]
=High_Low_Data_AddedAndUpdated(rHiLo, _Histories, rPHi, rPLo, rIHi, rILo, rDiffHi, rDiffLo, _a_PHiLo, _a_IHiLo, _a_FHiLo, _a_DHiLo, _a_PHigh, _a_IHigh, _a_PLow, _a_ILow)
if _ShowInfoTable1
var table TBL_INFO_1 =na
// テーブル作成
TBL_INFO_1 :=table.new(Tbl_position(_TablePosition1), _Histories + 1, 3, border_width = 1)
//// テーブルに値セット
// 左タイトル
table.cell(TBL_INFO_1, 0, 0, "", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, 0, 1, "PRICE", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, 0, 2, "INDEX", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
for i =0 to _Histories - 1
// ヘッダー
table.cell(TBL_INFO_1, i + 1, 0, str.tostring(i), bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, i + 1, 1, str.tostring(array.get(_a_PHiLo, i), "0.000"), bgcolor =color.new(color.blue, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_1, i + 1, 2, str.tostring(array.get(_a_IHiLo, i)), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
if _ShowInfoTable2
var table TBL_INFO_2 =na
// テーブル作成
TBL_INFO_2 :=table.new(Tbl_position(_TablePosition2), 2, 12, border_width = 1)
// 左タイトル
table.cell(TBL_INFO_2, 0, 0, "HiLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 1, "PHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 2, "PLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 3, "IHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 4, "ILo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 5, "Cnt", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 6, "ECnt", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 7, "DiffHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 8, "DiffLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 9, "StartHi", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 10, "StartLo", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 0, 11, "INDEX", bgcolor =color.new(color.lime, 0), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 0, str.tostring(rHiLo), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 1, str.tostring(rPHi, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 2, str.tostring(rPLo, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 3, str.tostring(rIHi), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 4, str.tostring(rILo), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 5, str.tostring(rCnt), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 6, str.tostring(rECnt), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 7, str.tostring(rDiffHi, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 8, str.tostring(rDiffLo, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 9, str.tostring(rStartHi, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 10, str.tostring(rStartLo, "0.000"), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
table.cell(TBL_INFO_2, 1, 11, str.tostring(bar_index), bgcolor =color.new(color.red, 80), text_color =color.black, text_size =size.auto)
if _ShowZigZag
ZigZag(rPHiLo, rIHiLo, rFHiLo, rDHiLo, _Histories, Provisional_PHiLo, Provisional_IHiLo,
_ZigZagColor1, _ZigZagWidth1, _ZigZagColor2, _ZigZagWidth2, _ShowZigZagLabel, _ZigZagLabelSize, _ShowHighLowBar, _HighLowBarWidth)
if _ShowTrendLine
TrendLine(_a_PHigh, _a_PLow, _a_IHigh, _a_ILow, _Histories,
_TrendMultiLine, _TrendStartWidth, _TrendEndWidth, _TrendIncreWidth, _TrendStartTrans, _TrendEndTrans, _TrendIncreTrans,
_TrendColorMode, _TrendColor1_1, _TrendColor1_2, _TrendColor2_1, _TrendColor2_2)
if _ShowFibonacci == "double"
Fibonacci(_a_Fibonacci, rPHiLo, rIHiLo, Provisional_PHiLo,
_FibIndex1, _FibFrontMargin1, _FibBackMargin1, _FibTransparent1, _FibTextColor1, _FibTextMargin1, _FibLabelSize1,
_FibTitle1, _FibTitleMargin1, _FibChangeColor1, _FibTrendColor1, _FibTrendLineWidth1,
_FibIndex2, _FibFrontMargin2, _FibBackMargin2, _FibTransparent2, _FibTextColor2, _FibTextMargin2, _FibLabelSize2,
_FibTitle2, _FibTitleMargin2, _FibChangeColor2, _FibTrendColor2, _FibTrendLineWidth2)
else
Fibonacci(_a_Fibonacci, rPHiLo, rIHiLo, Provisional_PHiLo, _FibIndex1, _FibFrontMargin1, _FibBackMargin1, _FibTransparent1, _FibTextColor1, _FibTextMargin1, _FibLabelSize1,
_FibTitle1, _FibTitleMargin1, _FibChangeColor1, _FibTrendColor1, _FibTrendLineWidth1)
|
loxxmas - moving averages used in Loxx's indis & strats | https://www.tradingview.com/script/Qc1LnCik-loxxmas-moving-averages-used-in-Loxx-s-indis-strats/ | loxx | https://www.tradingview.com/u/loxx/ | 29 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
// @description TODO:loxx moving averages used in indicators
library("loxxmas", overlay = true)
// @function KAMA Kaufman adaptive moving average
// @param src float
// @param len int
// @param kamafastend int
// @param kamaslowend int
// @returns array
export kama(float src, int len, int kamafastend, int kamaslowend) =>
xvnoise = math.abs(src - src[1])
nfastend = kamafastend
nslowend = kamaslowend
nsignal = math.abs(src - src[len])
nnoise = math.sum(xvnoise, len)
nefratio = nnoise != 0 ? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA = 0.0
nAMA := nz(nAMA[1]) + nsmooth * (src - nz(nAMA[1]))
nAMA
// @function AMA, adaptive moving average
// @param src float
// @param len int
// @param fl int
// @param sl int
// @returns array
export ama(float src, int len, int fl, int sl)=>
flout = 2/(fl + 1)
slout = 2/(sl + 1)
hh = ta.highest(len + 1)
ll = ta.lowest(len + 1)
mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0
ssc = mltp * (flout - slout) + slout
ama = 0.
ama := nz(ama[1]) + math.pow(ssc, 2) * (src - nz(ama[1]))
ama
// @function T3 moving average, adaptive moving average
// @param src float
// @param len int
// @returns array
export t3(float src, int len) =>
xe11 = ta.ema(src, len)
xe21 = ta.ema(xe11, len)
xe31 = ta.ema(xe21, len)
xe41 = ta.ema(xe31, len)
xe51 = ta.ema(xe41, len)
xe61 = ta.ema(xe51, len)
b1 = 0.7
c11 = -b1 * b1 * b1
c21 = 3 * b1 * b1 + 3 * b1 * b1 * b1
c31 = -6 * b1 * b1 - 3 * b1 - 3 * b1 * b1 * b1
c41 = 1 + 3 * b1 + b1 * b1 * b1 + 3 * b1 * b1
nT3Average = c11 * xe61 + c21 * xe51 + c31 * xe41 + c41 * xe31
nT3Average
// @function ADXvma - Average Directional Volatility Moving Average
// @param src float
// @param len int
// @returns array
export adxvma(float src, int len)=>
tpdm = 0., tmdm = 0.
pdm = 0., mdm = 0., pdi = 0., mdi = 0., out = 0., val = 0.
tpdi = 0., tmdi = 0., thi = 0., tlo = 0., tout = 0., vi = 0.
diff = src - nz(src[1])
tpdm := diff > 0 ? diff : tpdm
tmdm := diff > 0 ? tmdm : -diff
pdm := ((len- 1.0) * nz(pdm[1]) + tpdm) / len
mdm := ((len- 1.0) * nz(mdm[1]) + tmdm) / len
trueRange = pdm + mdm
tpdi := nz(pdm / trueRange)
tmdi := nz(mdm / trueRange)
pdi := ((len- 1.0) * nz(pdi[1]) + tpdi) / len
mdi := ((len- 1.0) * nz(mdi[1]) + tmdi) / len
tout := (pdi + mdi) > 0 ? math.abs(pdi - mdi) / (pdi + mdi) : tout
out := ((len- 1.0) * nz(out[1]) + tout) / len
thi := math.max(out, nz(out[1]))
tlo := math.min(out, nz(out[1]))
for j = 2 to len
thi := math.max(nz(out[j]), thi)
tlo := math.min(nz(out[j]), tlo)
vi := (thi - tlo) > 0 ? (out - tlo) / (thi - tlo) : vi
val := ((len- vi) * nz(val[1]) + vi * src) / len
[val, val[1], false]
// @function Ahrens Moving Average
// @param src float
// @param len int
// @returns array
export ahrma(float src, int len)=>
ahrma = 0.
medMA = (nz(ahrma[1]) + nz(ahrma[len])) / 2.0
ahrma := nz(ahrma[1]) + ((src - medMA) / len)
[ahrma, ahrma[1], false]
// @function Alexander Moving Average - ALXMA
// @param src float
// @param len int
// @returns array
export alxma(float src, int len)=>
sumw = len - 2
sum = sumw * src
for k = 1 to len
weight = len - k - 2
sumw += weight
sum += weight * nz(src[k])
out = len < 4 ? src : sum/sumw
[out, out[1], false]
// @function Double Exponential Moving Average - DEMA
// @param src float
// @param len int
// @returns array
export dema(float src, simple int len)=>
e1 = ta.ema(src, len)
e2 = ta.ema(e1, len)
dema = 2 * e1 - e2
[dema, dema[1], false]
// @function Double Smoothed Exponential Moving Average - DSEMA
// @param src float
// @param len int
// @returns array
export dsema(float src, int len)=>
alpha = 2.0 / (1.0 + math.sqrt(len))
ema1 = 0., ema2 = 0.
ema1 := nz(ema1[1]) + alpha * (src - nz(ema1[1]))
ema2 := nz(ema2[1]) + alpha * (ema1 - nz(ema2[1]))
[ema2, ema2[1], false]
// @function Exponential Moving Average - EMA
// @param src float
// @param len int
// @returns array
export ema(float src, simple int len)=>
out = ta.ema(src, len)
[out, out[1], false]
// @function Fast Exponential Moving Average - FEMA
// @param src float
// @param len int
// @returns array
export fema(float src, int len)=>
alpha = (2.0 / (2.0 + (len - 1.0) / 2.0))
out = 0.
out := nz(out[1]) + alpha * (src - nz(out[1]))
[out, out[1], false]
// @function Hull moving averge
// @param src float
// @param len int
// @returns array
export hma(float src, simple int len)=>
out = ta.hma(src, len)
[out, out[1], false]
// @function Early T3 by Tim Tilson
// @param src float
// @param len int
// @returns array
export ie2(float src, int len)=>
sumx=0., sumxx=0., sumxy=0., sumy=0.
for k = 0 to len - 1
price = nz(src[k])
sumx += k
sumxx += k * k
sumxy += k * price
sumy += price
slope = (len * sumxy - sumx * sumy) / (sumx * sumx - len * sumxx)
average = sumy/len
out = (((average + slope) + (sumy + slope * sumx) / len) / 2.0)
[out, out[1], false]
// @function Fractal Adaptive Moving Average - FRAMA
// @param src float
// @param len int
// @param FC int
// @param SC int
// @returns array
export frama(float src, int len, int FC, int SC) =>
len1 = len / 2
e = math.e
w = math.log(2 / (SC + 1)) / math.log(e) // Natural logarithm (ln(2/(SC+1))) workaround
H1 = ta.highest(high, len1)
L1 = ta.lowest(low, len1)
N1 = (H1 - L1) / len1
H2 = ta.highest(high, len1)[len1]
L2 = ta.lowest(low, len1)[len1]
N2 = (H2 - L2) / len1
H3 = ta.highest(high, len)
L3 = ta.lowest(low, len)
N3 = (H3 - L3) / len
dimen1 = (math.log(N1 + N2) - math.log(N3)) / math.log(2)
dimen = N1 > 0 and N2 > 0 and N3 > 0 ? dimen1 : nz(dimen1[1])
alpha1 = math.exp(w * (dimen - 1))
oldalpha = alpha1 > 1 ? 1 : alpha1 < 0.01 ? 0.01 : alpha1
oldN = (2 - oldalpha) / oldalpha
N = (SC - FC) * (oldN - 1) / (SC - 1) + FC
alpha_ = 2 / (N + 1)
alpha = alpha_ < 2 / (SC + 1) ? 2 / (SC + 1) : alpha_ > 1 ? 1 : alpha_
out = 0.0
out := (1 - alpha) * nz(out[1]) + alpha * src
[out, out[1], false]
// @function Instantaneous Trendline
// @param src float
// @param float alpha
// @returns array
export instant(float src, float alpha) =>
itrend = 0.0
itrend := bar_index < 7 ? (src + 2 * nz(src[1]) + nz(src[2])) / 4 :
(alpha - math.pow(alpha, 2) / 4) * src + 0.5 * math.pow(alpha, 2) * nz(src[1]) - (alpha - 0.75 * math.pow(alpha, 2)) * nz(src[2]) + 2 * (1 - alpha) * nz(itrend[1]) - math.pow(1 - alpha, 2) * nz(itrend[2])
trigger = 2 * itrend - nz(itrend[2])
[trigger, itrend, false]
// @function Integral of Linear Regression Slope - ILRS
// @param src float
// @param int len
// @returns array
export ilrs(float src, int len)=> // Integral of linear regression slope
sum = len * (len -1) * 0.5
sum2 = (len - 1) * len * (2 * len - 1) / 6.0
sum1 = 0., sumy = 0., slope = 0.
for i = 0 to len - 1
sum1 += i * nz(src[i])
sumy += nz(src[i])
num1 = len * sum1 - sum * sumy
num2 = sum * sum - len * sum2
slope := num2 != 0. ? num1/num2 : 0.
ilrs = slope + ta.sma(src, len)
[ilrs, ilrs[1], false]
// @function Laguerre Filter
// @param src float
// @param float alpha
// @returns array
export laguerre(float src, float alpha)=>
L0 = 0.0, L1 = 0.0, L2 = 0.0, L3 = 0.0
L0 := alpha * src + (1 - alpha) * nz(L0[1])
L1 := -(1 - alpha) * L0 + nz(L0[1]) + (1 - alpha) * nz(L1[1])
L2 := -(1 - alpha) * L1 + nz(L1[1]) + (1 - alpha) * nz(L2[1])
L3 := -(1 - alpha) * L2 + nz(L2[1]) + (1 - alpha) * nz(L3[1])
lf = (L0 + 2 * L1 + 2 * L2 + L3) / 6
[lf, lf[1], false]
// @function Leader Exponential Moving Average
// @param src float
// @param int len
// @returns array
export leader(float src, int len)=>
alpha = 2.0/(len + 1.0)
ldr = 0.,ldr2 = 0.
ldr := nz(ldr[1]) + alpha * (src - nz(ldr[1]))
ldr2 := nz(ldr2[1]) + alpha * (src - ldr - nz(ldr2[1]))
out = ldr + ldr2
[out, out[1], false]
// @function Linear Regression Value - LSMA (Least Squares Moving Average)
// @param src float
// @param int len
// @param int offset
// @returns array
export lsma(float src, simple int len, simple int offset)=>
out = ta.linreg(src, len, offset)
[out, out[1], false]
// @function Linear Weighted Moving Average - LWMA
// @param src float
// @param int len
// @returns array
export lwma(float src, int len)=>
out = ta.wma(src, len)
[out, out[1], false]
// @function McGinley Dynamic
// @param src float
// @param int len
// @returns array
export mcginley(float src, simple int len)=>
mg = 0.0
t = ta.ema(src, len)
mg := na(mg[1]) ? t : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
[mg, mg[1], false]
// @function McNicholl EMA
// @param src float
// @param int len
// @returns array
export mcNicholl(float src, simple int len)=>
alpha = 2 / (len + 1)
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
out = ((2 - alpha) * ema1 - ema2) / (1 - alpha)
[out, out[1], false]
// @function Non-lag moving average
// @param src float
// @param int len
// @returns array
export nonlagma(float src, int len)=>
cycle = 4.0
coeff = 3.0 * math.pi
phase = len - 1.0
_len = int(len * cycle + phase)
weight = 0., alfa = 0., out = 0.
alphas = array.new_float(_len, 0)
for k = 0 to _len - 1
t = 0.
t := k <= phase - 1 ? 1.0 * k / (phase - 1) : 1.0 + (k - phase + 1) * (2.0 * cycle - 1.0) / (cycle * len -1.0)
beta = math.cos(math.pi * t)
g = 1.0/(coeff * t + 1)
g := t <= 0.5 ? 1 : g
array.set(alphas, k, g * beta)
weight += array.get(alphas, k)
if (weight > 0)
sum = 0.
for k = 0 to _len - 1
sum += array.get(alphas, k) * nz(src[k])
out := (sum / weight)
[out, out[1], false]
// @function Parabolic Weighted Moving Average
// @param src float
// @param int len
// @param float pwr
// @returns array
export pwma(float src, int len, float pwr)=>
sum = 0.0, weightSum = 0.0
for i = 0 to len - 1 by 1
weight = math.pow(len - i, pwr)
sum += nz(src[i]) * weight
weightSum += weight
weightSum
out = sum / weightSum
[out, out[1], false]
// @function Recursive Moving Trendline
// @param src float
// @param int len
// @returns array
export rmta(float src, int len)=>
alpha = 2 / (len + 1)
b = 0.0
b := (1 - alpha) * nz(b[1], src) + src
rmta = 0.0
rmta := (1 - alpha) * nz(rmta[1], src) + alpha * (src + b - nz(b[1]))
[rmta, rmta[1], false]
// @function Simple decycler - SDEC
// @param src float
// @param int len
// @returns array
export decycler(float src, int len)=>
alphaArg = 2 * math.pi / (len * math.sqrt(2))
alpha = 0.0
alpha := math.cos(alphaArg) != 0 ? (math.cos(alphaArg) + math.sin(alphaArg) - 1) / math.cos(alphaArg) : nz(alpha[1])
hp = 0.0
hp := math.pow(1 - alpha / 2, 2) * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * (1 - alpha) * nz(hp[1]) - math.pow(1 - alpha, 2) * nz(hp[2])
decycler = src - hp
[decycler, decycler[1], false]
// @function Simple Moving Average
// @param src float
// @param int len
// @returns array
export sma(float src, int len)=>
out = ta.sma(src, len)
[out, out[1], false]
// @function Sine Weighted Moving Average
// @param src float
// @param int len
// @returns array
export swma(float src, int len)=>
sum = 0.0, weightSum = 0.0
for i = 0 to len - 1 by 1
weight = math.sin((i + 1) * math.pi / (len + 1))
sum += nz(src[i]) * weight
weightSum += weight
weightSum
swma = sum / weightSum
[swma, swma[1], false]
// @function linear weighted moving average
// @param src float
// @param int len
// @returns array
export slwma(float src, int len)=>
out = ta.wma(ta.wma(src, len), math.floor(math.sqrt(len)))
[out, out[1], false]
// @function Smoothed Moving Average - SMMA
// @param src float
// @param int len
// @returns array
export smma(float src, simple int len)=>
out = ta.rma(src, len)
[out, out[1], false]
// @function Ehlers super smoother
// @param src float
// @param int len
// @returns array
export super(float src, int len) =>
f = (1.414 * math.pi)/len
a = math.exp(-f)
c2 = 2 * a * math.cos(f)
c3 = -a*a
c1 = 1-c2-c3
smooth = 0.0
smooth := c1*(src+src[1])*0.5+c2*nz(smooth[1])+c3*nz(smooth[2])
[smooth, smooth[1], false]
// @function Smoother filter
// @param src float
// @param int len
// @returns array
export smoother(float src, int len)=>
wrk = src, wrk2 = src, wrk4 = src
wrk0 = 0., wrk1 = 0., wrk3 = 0.
alpha = 0.45 * (len - 1.0) / (0.45 * (len - 1.0) + 2.0)
wrk0 := src + alpha * (nz(wrk[1]) - src)
wrk1 := (src - wrk) * (1 - alpha) + alpha * nz(wrk1[1])
wrk2 := wrk0 + wrk1
wrk3 := (wrk2 - nz(wrk4[1])) * math.pow(1.0 - alpha, 2) + math.pow(alpha, 2) * nz(wrk3[1])
wrk4 := wrk3 + nz(wrk4[1])
[wrk4, wrk4[1], false]
// @function Triangular moving average - TMA
// @param src float
// @param int len
// @returns array
export tma(float src, int len)=>
filt = 0.0, coef = 0.0, l2 = len / 2.0
for i = 1 to len
c = i < l2 ? i : i > l2 ? len + 1 - i : l2
filt := filt + (c * nz(src[i - 1]))
coef := coef + c
filt := coef != 0 ? filt / coef : 0
[filt, filt[1], false]
// @function Tripple exponential moving average - TEMA
// @param src float
// @param int len
// @returns array
export tema(float src, simple int len)=>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
out = 3 * (ema1 - ema2) + ema3
[out, out[1], false]
// @function Volume weighted ema - VEMA
// @param src float
// @param int len
// @returns array
export vwema(float src, simple int len) =>
p = ta.ema(volume * src, len)
v = ta.ema(volume, len)
vwema = p / v
[vwema, vwema[1], false]
// @function Volume weighted moving average - VWMA
// @param src float
// @param int len
// @returns array
export vwma(float src, simple int len)=>
ma = ta.vwma(src, len)
[ma, ma[1], false]
// @function Zero-lag dema
// @param src float
// @param int len
// @returns array
export zlagdema(float src, simple int len)=>
zdema1 = ta.ema(src, len)
zdema2 = ta.ema(zdema1, len)
dema1 = 2 * zdema1 - zdema2
zdema12 = ta.ema(dema1, len)
zdema22 = ta.ema(zdema12, len)
demaout = 2 * zdema12 - zdema22
[demaout, demaout[1], false]
// @function Zero-lag moving average
// @param src float
// @param int len
// @returns array
export zlagma(float src, int len)=>
alpha = 2.0/(1.0 + len)
per = math.ceil((len - 1.0) / 2.0 )
zlagma = 0.
zlagma := nz(zlagma[1]) + alpha * (2.0 * src - nz(zlagma[per]) - nz(zlagma[1]))
[zlagma, zlagma[1], false]
// @function Zero-lag tema
// @param src float
// @param int len
// @returns array
export zlagtema(float src, simple int len)=>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
out = 3 * (ema1 - ema2) + ema3
ema1a = ta.ema(out, len)
ema2a = ta.ema(ema1a, len)
ema3a = ta.ema(ema2a, len)
outf = 3 * (ema1a - ema2a) + ema3a
[outf, outf[1], false]
// @function Three-pole Ehlers Butterworth
// @param src float
// @param int len
// @returns array
export threepolebuttfilt(float src, int len)=>
a1 = 0., b1 = 0., c1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0., coef4 = 0.
bttr = 0., trig = 0.
a1 := math.exp(-math.pi / len)
b1 := 2 * a1 * math.cos(1.738 * math.pi / len)
c1 := a1 * a1
coef2 := b1 + c1
coef3 := -(c1 + b1 * c1)
coef4 := c1 * c1
coef1 := (1 - b1 + c1) * (1 - c1) / 8
bttr := coef1 * (src + 3 * nz(src[1]) + 3 * nz(src[2]) + nz(src[3])) + coef2 * nz(bttr[1]) + coef3 * nz(bttr[2]) + coef4 * nz(bttr[3])
bttr := bar_index < 4 ? src : bttr
trig := nz(bttr[1])
[bttr, trig, true]
// @function Three-pole Ehlers smoother
// @param src float
// @param int len
// @returns array
export threepolesss(float src, int len)=>
a1 = 0., b1 = 0., c1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0., coef4 = 0.
filt = 0., trig = 0.
a1 := math.exp(-math.pi / len)
b1 := 2 * a1 * math.cos(1.738 * math.pi / len)
c1 := a1 * a1
coef2 := b1 + c1
coef3 := -(c1 + b1 * c1)
coef4 := c1 * c1
coef1 := 1 - coef2 - coef3 - coef4
filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2]) + coef4 * nz(filt[3])
filt := bar_index < 4 ? src : filt
trig := nz(filt[1])
[filt, trig, true]
// @function Two-pole Ehlers Butterworth
// @param src float
// @param int len
// @returns array
export twopolebutter(float src, int len)=>
a1 = 0., b1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0.
bttr = 0., trig = 0.
a1 := math.exp(-1.414 * math.pi / len)
b1 := 2 * a1 * math.cos(1.414 * math.pi / len)
coef2 := b1
coef3 := -a1 * a1
coef1 := (1 - b1 + a1 * a1) / 4
bttr := coef1 * (src + 2 * nz(src[1]) + nz(src[2])) + coef2 * nz(bttr[1]) + coef3 * nz(bttr[2])
bttr := bar_index < 3 ? src : bttr
trig := nz(bttr[1])
[bttr, trig, true]
// @function Two-pole Ehlers smoother
// @param src float
// @param int len
// @returns array
export twopoless(float src, int len)=>
a1 = 0., b1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0.
filt = 0., trig = 0.
a1 := math.exp(-1.414 * math.pi / len)
b1 := 2 * a1 * math.cos(1.414 * math.pi / len)
coef2 := b1
coef3 := -a1 * a1
coef1 := 1 - coef2 - coef3
filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2])
filt := bar_index < 3 ? src : filt
trig := nz(filt[1])
[filt, trig, true]
//exmaple useage
[out, _, _] = ema(close, 25)
plot(out)
|
loxxexpandedsourcetypes | https://www.tradingview.com/script/yTwtoFhz-loxxexpandedsourcetypes/ | loxx | https://www.tradingview.com/u/loxx/ | 27 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
library("loxxexpandedsourcetypes", overlay = true)
_ama(src, len, fl, sl)=>
flout = 2/(fl + 1)
slout = 2/(sl + 1)
hh = ta.highest(len + 1)
ll = ta.lowest(len + 1)
mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0
ssc = mltp * (flout - slout) + slout
ama = 0.
ama := nz(ama[1]) + math.pow(ssc, 2) * (src - nz(ama[1]))
ama
_t3(src, len) =>
xe1_1 = ta.ema(src, len)
xe2_1 = ta.ema(xe1_1, len)
xe3_1 = ta.ema(xe2_1, len)
xe4_1 = ta.ema(xe3_1, len)
xe5_1 = ta.ema(xe4_1, len)
xe6_1 = ta.ema(xe5_1, len)
b_1 = 0.7
c1_1 = -b_1 * b_1 * b_1
c2_1 = 3 * b_1 * b_1 + 3 * b_1 * b_1 * b_1
c3_1 = -6 * b_1 * b_1 - 3 * b_1 - 3 * b_1 * b_1 * b_1
c4_1 = 1 + 3 * b_1 + b_1 * b_1 * b_1 + 3 * b_1 * b_1
nT3Average = c1_1 * xe6_1 + c2_1 * xe5_1 + c3_1 * xe4_1 + c4_1 * xe3_1
nT3Average
_kama(src, len, kama_fastend, kama_slowend) =>
xvnoise = math.abs(src - src[1])
nfastend = kama_fastend
nslowend = kama_slowend
nsignal = math.abs(src - src[len])
nnoise = math.sum(xvnoise, len)
nefratio = nnoise != 0 ? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA = 0.0
nAMA := nz(nAMA[1]) + nsmooth * (src - nz(nAMA[1]))
nAMA
_trendreg(o, h, l, c)=>
compute = 0.
if (c > o)
compute := ((h + c)/2.0)
else
compute := ((l + c)/2.0)
compute
_trendext(o, h, l, c) =>
compute = 0.
if (c > o)
compute := h
else if (c < o)
compute := l
else
compute := c
compute
// @function rClose: regular close
// @returns float
export rclose() => close
// @function rClose: regular open
// @returns float
export ropen() => open
// @function rClose: regular high
// @returns float
export rhigh() => high
// @function rClose: regular low
// @returns float
export rlow() => low
// @function rClose: regular hl2
// @returns float
export rmedian() => hl2
// @function rClose: regular hlc3
// @returns float
export rtypical() => hlc3
// @function rClose: regular hlcc4
// @returns float
export rweighted() => hlcc4
// @function rClose: regular ohlc4
// @returns float
export raverage() => ohlc4
// @function rClose: median body
// @returns float
export ravemedbody() => (open + close)/2
// @function rClose: trend regular
// @returns float
export rtrendb() => _trendreg(ropen(), rhigh(), rlow(), rclose())
// @function rClose: trend extreme
// @returns float
export rtrendbext() => _trendext(ropen(), rhigh(), rlow(), rclose())
//heiken-ashi regular
// @function haclose: heiken-ashi close
// @param haclose float
// @returns float
export haclose(float haclose) => haclose
// @function haopen: heiken-ashi open
// @param haopen float
// @returns float
export haopen(float haopen) => haopen
// @function hahigh: heiken-ashi high
// @param hahigh float
// @returns float
export hahigh(float hahigh) => hahigh
// @function halow: heiken-ashi low
// @param halow float
// @returns float
export halow(float halow) => halow
// @function hamedian: heiken-ashi median
// @param hamedian float
// @returns float
export hamedian(float hamedian) => hamedian
// @function hatypical: heiken-ashi typical
// @param hatypical float
// @returns float
export hatypical(float hatypical) => hatypical
// @function haweighted: heiken-ashi weighted
// @param haweighted float
// @returns float
export haweighted(float haweighted) => haweighted
// @function haaverage: heiken-ashi average
// @param haweighted float
// @returns float
export haaverage(float haweighted) => haweighted
// @function haavemedbody: heiken-ashi median body
// @param haclose float
// @param haopen float
// @returns float
export haavemedbody(float haclose, float haopen) => (haopen(haopen) + haclose(haclose))/2
// @function hatrendb: heiken-ashi trend
// @param haclose float
// @param haopen float
// @param hahigh float
// @param halow float
// @returns float
export hatrendb(float haclose, float haopen, float hahigh, float halow) => _trendreg(haopen(haopen), hahigh(hahigh), halow(halow), haclose(haclose))
// @function hatrendext: heiken-ashi trend extreme
// @param haclose float
// @param haopen float
// @param hahigh float
// @param halow float
// @returns float
export hatrendbext(float haclose, float haopen, float hahigh, float halow) => _trendext(haopen(haopen), hahigh(hahigh), halow(halow), haclose(haclose))
//heiken-ashi better
_habingest() =>
out = (ropen() + rclose())/2 + (((rclose() - ropen())/(rhigh() - rlow())) * math.abs((rclose() - ropen())/2))
out := na(out) ? rclose() : out
out
// @function habclose: heiken-ashi better open
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habclose(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
amaout = _ama(_habingest(), 2, amafl, amasl)
t3out = _t3(_habingest(), 3)
kamaout = _kama(_habingest(), 2, kfl, ksl)
smthtype == "AMA" ? amaout : smthtype == "T3" ? t3out : kamaout
// @function habopen: heiken-ashi better open
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habopen(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
habopen = 0.
habopen := na(habopen[1]) ? (nz(habopen) + nz(habclose(smthtype, amafl, amasl, kfl, ksl)[1]))/2 : (nz(habopen[1]) + nz(habclose(smthtype, amafl, amasl, kfl, ksl)[1]))/2
habopen
// @function habhigh: heiken-ashi better high
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habhigh(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
math.max(rhigh(), habopen(smthtype, amafl, amasl, kfl, ksl), habclose(smthtype, amafl, amasl, kfl, ksl))
// @function hablow: heiken-ashi better low
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export hablow(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
math.min(rlow(), habopen(smthtype, amafl, amasl, kfl, ksl), habclose(smthtype, amafl, amasl, kfl, ksl))
// @function habmedian: heiken-ashi better median
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habmedian(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
(habhigh(smthtype, amafl, amasl, kfl, ksl) + hablow(smthtype, amafl, amasl, kfl, ksl))/2
// @function habtypical: heiken-ashi better typical
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habtypical(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
(habhigh(smthtype, amafl, amasl, kfl, ksl) + hablow(smthtype, amafl, amasl, kfl, ksl) + habclose(smthtype, amafl, amasl, kfl, ksl))/3
// @function habweighted: heiken-ashi better weighted
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habweighted(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
(habhigh(smthtype, amafl, amasl, kfl, ksl) + hablow(smthtype, amafl, amasl, kfl, ksl) + habclose(smthtype, amafl, amasl, kfl, ksl) + habclose(smthtype, amafl, amasl, kfl, ksl))/4
// @function habaverage: heiken-ashi better average
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habaverage(string smthtype, int amafl, int amasl, float kfl, float ksl) => //ohlc4
(habopen(smthtype, amafl, amasl, kfl, ksl) + habhigh(smthtype, amafl, amasl, kfl, ksl) + hablow(smthtype, amafl, amasl, kfl, ksl) + habclose(smthtype, amafl, amasl, kfl, ksl))/4
// @function habavemedbody: heiken-ashi better median body
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habavemedbody(string smthtype, int amafl, int amasl, float kfl, float ksl) => //oc2
(habopen(smthtype, amafl, amasl, kfl, ksl) + habclose(smthtype, amafl, amasl, kfl, ksl))/2
// @function habtrendb: heiken-ashi better trend
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habtrendb(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
_trendreg(habopen(smthtype, amafl, amasl, kfl, ksl), habhigh(smthtype, amafl, amasl, kfl, ksl), hablow(smthtype, amafl, amasl, kfl, ksl), habclose(smthtype, amafl, amasl, kfl, ksl))
// @function habtrendbext: heiken-ashi better trend extreme
// @param smthtype string
// @param amafl int
// @param amasl int
// @param kfl int
// @param ksl int
// @returns float
export habtrendbext(string smthtype, int amafl, int amasl, float kfl, float ksl) =>
_trendext(habopen(smthtype, amafl, amasl, kfl, ksl), habhigh(smthtype, amafl, amasl, kfl, ksl), hablow(smthtype, amafl, amasl, kfl, ksl), habclose(smthtype, amafl, amasl, kfl, ksl))
//example ussage
habcloser = habclose("AMA", 6, 20, 5, 25)
plot(habcloser)
|
loxxpaaspecial | https://www.tradingview.com/script/eLk4ghlC-loxxpaaspecial/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description loxxpaaspecial: Ehles Phase Accumulation Dominant Cycle Period with Multipler and Fitler
library("loxxpaaspecial", overlay = false)
calcComp(src, period)=>
out = (
(0.0962 * src +
0.5769 * src[2] -
0.5769 * src[4] -
0.0962 * src[6]) * (0.075 * src[1] + 0.54))
out
// @function (src, mult, filt)
// @param src float
// @param mult float
// @param filt float
// @returns result float
export paa(float src, float mult, float filt)=>
Smooth = 0., Detrender = 0.
I1 = 0., Q1 = 0., Period = 0., DeltaPhase = 0., InstPeriod = 0.
PhaseSum = 0., Phase = 0., _period = 0.
Smooth := bar_index > 5 ? (4 * src + 3 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 10 : Smooth
ts = calcComp(Smooth, Period)
Detrender := bar_index > 5 ? ts : Detrender
qs = calcComp(Detrender, Period)
Q1 := bar_index > 5 ? qs : Q1
I1 := bar_index > 5 ? nz(Detrender[3]) : I1
I1 := .15 * I1 + .85 * nz(I1[1])
Q1 := .15 * Q1 + .85 * nz(Q1[1])
Phase := nz(Phase[1])
Phase := math.abs(I1) > 0 ? 180.0 / math.pi * math.atan(math.abs(Q1 / I1)) : Phase
Phase := I1 < 0 and Q1 > 0 ? 180 - Phase : Phase
Phase := I1 < 0 and Q1 < 0 ? 180 + Phase : Phase
Phase := I1 > 0 and Q1 < 0 ? 360 - Phase : Phase
DeltaPhase := nz(Phase[1]) - Phase
DeltaPhase := nz(Phase[1]) < 90 and Phase > 270 ? 360 + nz(Phase[1]) - Phase : DeltaPhase
DeltaPhase := math.max(math.min(DeltaPhase, 60), 7)
InstPeriod := nz(InstPeriod[1])
PhaseSum := 0
count = 0
while (PhaseSum < mult * 360 and count < 4500)
PhaseSum += nz(DeltaPhase[count])
count := count + 1
InstPeriod := count > 0 ? count : InstPeriod
alpha = 2.0 / (1.0 + math.max(filt, 1))
_period := nz(_period[1]) + alpha * (InstPeriod - nz(_period[1]))
_period := math.floor(_period) < 1 ? 1 : math.floor(_period)
math.floor(_period)
//example useage
int fout = math.floor(paa(close, 1., 0.))
plot(fout)
|
functionStringToMatrix | https://www.tradingview.com/script/48OB7p0o-functionStringToMatrix/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 31 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Provides unbound methods (no error checking) to parse a string into a float or int matrix.
library(title='functionStringToMatrix')
import RicardoSantos/DebugConsole/10 as console
[_T, _C] = console.init()
// @function Parse a string into a float matrix.
// @param str , string, the formated string to parse.
// @param interval_sep , string, cell interval separator token.
// @param start_tk , string, row start token.
// @param end_tk , string, row end token.
// @returns matrix<float>, parsed float matrix.
export to_matrix_float (
string str,
string interval_sep=',',
string start_tk='[',
string end_tk=']'
) => //{
//
// remove spaces, new lines and block initializing tokens
string _cleaned = str.replace_all(str.replace_all(str.replace_all(str, start_tk, ''), '\n', ''), ' ', '')
array<string> _str_rows = str.split(_cleaned, end_tk)
array.pop(_str_rows)//remove the end token
int _size_cols = array.size(str.split(array.get(_str_rows, 0), interval_sep))
matrix<float> _M = matrix.new<float>(array.size(_str_rows), _size_cols)
for [_i, _row] in _str_rows
array<string> _s = str.split(_row, interval_sep)
for [_j, _e] in _s
matrix.set(_M, _i, _j, str.tonumber(_e))
_M
//}
// @function Parse a string into a int matrix.
// @param str , string, the formated string to parse.
// @param interval_sep , string, cell interval separator token.
// @param start_tk , string, row start token.
// @param end_tk , string, row end token.
// @returns matrix<int>, parsed int matrix.
export to_matrix_int (
string str,
string interval_sep=',',
string start_tk='[',
string end_tk=']'
) => //{
//
// remove spaces, new lines and block initializing tokens
string _cleaned = str.replace_all(str.replace_all(str.replace_all(str, start_tk, ''), '\n', ''), ' ', '')
array<string> _str_rows = str.split(_cleaned, end_tk)
array.pop(_str_rows)//remove the end token
int _size_cols = array.size(str.split(array.get(_str_rows, 0), interval_sep))
matrix<int> _M = matrix.new<int>(array.size(_str_rows), _size_cols)
for [_i, _row] in _str_rows
array<string> _s = str.split(_row, interval_sep)
for [_j, _e] in _s
matrix.set(_M, _i, _j, int(str.tonumber(_e)))
_M
//}
// @function Parse a string into a string matrix.
// @param str , string, the formated string to parse.
// @param interval_sep , string, cell interval separator token.
// @param start_tk , string, row start token.
// @param end_tk , string, row end token.
// @returns matrix<string>, parsed string matrix.
export to_matrix_string (
string str,
string interval_sep=',',
string start_tk='[',
string end_tk=']'
) => //{
//
// remove spaces, new lines and block initializing tokens
string _cleaned = str.replace_all(str.replace_all(str.replace_all(str, start_tk, ''), '\n', ''), ' ', '')
array<string> _str_rows = str.split(_cleaned, end_tk)
array.pop(_str_rows)//remove the end token
int _size_cols = array.size(str.split(array.get(_str_rows, 0), interval_sep))
matrix<string> _M = matrix.new<string>(array.size(_str_rows), _size_cols)
for [_i, _row] in _str_rows
array<string> _s = str.split(_row, interval_sep)
for [_j, _e] in _s
matrix.set(_M, _i, _j, _e)
_M
//}
string s0 = input.text_area('[[-0,1,2.1][-0,1,2.2][-0,1,2.3]]')
string s1 = input.text_area('-0,1,2.1 | -0,1,2.2 | -0,1,2.3|')
string s2 = input.text_area('-0,1,2.1;-0,1,2.2;-0,1,2.3;')
string s3 = input.text_area('((-0,1,2.1)(-0,1,2.2)(-0,1,2.3))')
string s4 = input.text_area('[[a,b,c.d][a,b,c.d][a,b,c.d]]')
console.queue_one(_C, str.format('"{0}":\n{1}', s0, str.tostring(to_matrix_float(s0))))
console.queue_one(_C, str.format('"{0}":\n{1}', s1, str.tostring(to_matrix_float(s1, ',', '', '|'))))
console.queue_one(_C, str.format('"{0}":\n{1}', s2, str.tostring(to_matrix_float(s2, ',', '', ';'))))
console.queue_one(_C, str.format('"{0}":\n{1}', s3, str.tostring(to_matrix_int(s3, ',', '(', ')'))))
console.queue_one(_C, str.format('"{0}":\n{1}', s4, str.tostring(to_matrix_string(s4))))
console.update(_T, _C) |
loxxfsrrdspfilts | https://www.tradingview.com/script/8T2g9amR-loxxfsrrdspfilts/ | loxx | https://www.tradingview.com/u/loxx/ | 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/
// © loxx
//@version=5
// @description loxxfsrrdspfilts : FATL, SATL, RFTL, & RSTL Digital Signal Filters
library("loxxfsrrdspfilts", overlay = true)
// @function fatl
// @param src float
// @returns result float
export fatl(float src) =>
fatl_val = 0.4360409450 *
src + 0.3658689069 *
src[1] + 0.2460452079 *
src[2] + 0.1104506886 *
src[3] - 0.0054034585 *
src[4] - 0.0760367731 *
src[5] - 0.0933058722 *
src[6] - 0.0670110374 *
src[7] - 0.0190795053 *
src[8] + 0.0259609206 *
src[9] + 0.0502044896 *
src[10] + 0.0477818607 *
src[11] + 0.0249252327 *
src[12] - 0.0047706151 *
src[13] - 0.0272432537 *
src[14] - 0.0338917071 *
src[15] - 0.0244141482 *
src[16] - 0.0055774838 *
src[17] + 0.0128149838 *
src[18] + 0.0226522218 *
src[19] + 0.0208778257 *
src[20] + 0.0100299086 *
src[21] - 0.0036771622 *
src[22] - 0.0136744850 *
src[23] - 0.0160483392 *
src[24] - 0.0108597376 *
src[25] - 0.0016060704 *
src[26] + 0.0069480557 *
src[27] + 0.0110573605 *
src[28] + 0.0095711419 *
src[29] + 0.0040444064 *
src[30] - 0.0023824623 *
src[31] - 0.0067093714 *
src[32] - 0.0072003400 *
src[33] - 0.0047717710 *
src[34] + 0.0005541115 *
src[35] + 0.0007860160 *
src[36] + 0.0130129076 *
src[37] + 0.0040364019 *
src[38]
fatl_val
// @function rftl
// @param src float
// @returns result float
export rftl(float src) =>
rftl_val = -0.0025097319 *
src + 0.0513007762 *
src[1] + 0.1142800493 *
src[2] + 0.1699342860 *
src[3] + 0.2025269304 *
src[4] + 0.2025269304 *
src[5] + 0.1699342860 *
src[6] + 0.1142800493 *
src[7] + 0.0513007762 *
src[8] - 0.0025097319 *
src[9] - 0.0353166244 *
src[10] - 0.0433375629 *
src[11] - 0.0311244617 *
src[12] - 0.0088618137 *
src[13] + 0.0120580088 *
src[14] + 0.0233183633 *
src[15] + 0.0221931304 *
src[16] + 0.0115769653 *
src[17] - 0.0022157966 *
src[18] - 0.0126536111 *
src[19] - 0.0157416029 *
src[20] - 0.0113395830 *
src[21] - 0.0025905610 *
src[22] + 0.0059521459 *
src[23] + 0.0105212252 *
src[24] + 0.0096970755 *
src[25] + 0.0046585685 *
src[26] - 0.0017079230 *
src[27] - 0.0063513565 *
src[28] - 0.0074539350 *
src[29] - 0.0050439973 *
src[30] - 0.0007459678 *
src[31] + 0.0032271474 *
src[32] + 0.0051357867 *
src[33] + 0.0044454862 *
src[34] + 0.0018784961 *
src[35] - 0.0011065767 *
src[36] - 0.0031162862 *
src[37] - 0.0033443253 *
src[38] - 0.0022163335 *
src[39] + 0.0002573669 *
src[40] + 0.0003650790 *
src[41] + 0.0060440751 *
src[42] + 0.0018747783 *
src[43]
rftl_val
// @function satl
// @param src float
// @returns result float
export satl(float src) =>
satl_val = 0.0982862174 *
src + 0.0975682269 *
src[1] + 0.0961401078 *
src[2] + 0.0940230544 *
src[3] + 0.0912437090 *
src[4] + 0.0878391006 *
src[5] + 0.0838544303 *
src[6] + 0.0793406350 *
src[7] + 0.0743569346 *
src[8] + 0.0689666682 *
src[9] + 0.0632381578 *
src[10] + 0.0572428925 *
src[11] + 0.0510534242 *
src[12] + 0.0447468229 *
src[13] + 0.0383959950 *
src[14] + 0.0320735368 *
src[15] + 0.0258537721 *
src[16] + 0.0198005183 *
src[17] + 0.0139807863 *
src[18] + 0.0084512448 *
src[19] + 0.0032639979 *
src[20] - 0.0015350359 *
src[21] - 0.0059060082 *
src[22] - 0.0098190256 *
src[23] - 0.0132507215 *
src[24] - 0.0161875265 *
src[25] - 0.0186164872 *
src[26] - 0.0205446727 *
src[27] - 0.0219739146 *
src[28] - 0.0229204861 *
src[29] - 0.0234080863 *
src[30] - 0.0234566315 *
src[31] - 0.0231017777 *
src[32] - 0.0223796900 *
src[33] - 0.0213300463 *
src[34] - 0.0199924534 *
src[35] - 0.0184126992 *
src[36] - 0.0166377699 *
src[37] - 0.0147139428 *
src[38] - 0.0126796776 *
src[39] - 0.0105938331 *
src[40] - 0.0084736770 *
src[41] - 0.0063841850 *
src[42] - 0.0043466731 *
src[43] - 0.0023956944 *
src[44] - 0.0005535180 *
src[45] + 0.0011421469 *
src[46] + 0.0026845693 *
src[47] + 0.0040471369 *
src[48] + 0.0052380201 *
src[49] + 0.0062194591 *
src[50] + 0.0070340085 *
src[51] + 0.0076266453 *
src[52] + 0.0080376628 *
src[53] + 0.0083037666 *
src[54] + 0.0083694798 *
src[55] + 0.0082901022 *
src[56] + 0.0080741359 *
src[57] + 0.0077543820 *
src[58] + 0.0073260526 *
src[59] + 0.0068163569 *
src[60] + 0.0062325477 *
src[61] + 0.0056078229 *
src[62] + 0.0049516078 *
src[63] + 0.0161380976 *
src[64]
satl_val
// @function rstl
// @param src float
// @returns result float
export rstl(float src) =>
rstl_val = -0.0074151919 *
src - 0.0060698985 *
src[1] - 0.0044979052 *
src[2] - 0.0027054278 *
src[3] - 0.0007031702 *
src[4] + 0.0014951741 *
src[5] + 0.0038713513 *
src[6] + 0.0064043271 *
src[7] + 0.0090702334 *
src[8] + 0.0118431116 *
src[9] + 0.0146922652 *
src[10] + 0.0175884606 *
src[11] + 0.0204976517 *
src[12] + 0.0233865835 *
src[13] + 0.0262218588 *
src[14] + 0.0289681736 *
src[15] + 0.0315922931 *
src[16] + 0.0340614696 *
src[17] + 0.0363444061 *
src[18] + 0.0384120882 *
src[19] + 0.0402373884 *
src[20] + 0.0417969735 *
src[21] + 0.0430701377 *
src[22] + 0.0440399188 *
src[23] + 0.0446941124 *
src[24] + 0.0450230100 *
src[25] + 0.0450230100 *
src[26] + 0.0446941124 *
src[27] + 0.0440399188 *
src[28] + 0.0430701377 *
src[29] + 0.0417969735 *
src[30] + 0.0402373884 *
src[31] + 0.0384120882 *
src[32] + 0.0363444061 *
src[33] + 0.0340614696 *
src[34] + 0.0315922931 *
src[35] + 0.0289681736 *
src[36] + 0.0262218588 *
src[37] + 0.0233865835 *
src[38] + 0.0204976517 *
src[39] + 0.0175884606 *
src[40] + 0.0146922652 *
src[41] + 0.0118431116 *
src[42] + 0.0090702334 *
src[43] + 0.0064043271 *
src[44] + 0.0038713513 *
src[45] + 0.0014951741 *
src[46] - 0.0007031702 *
src[47] - 0.0027054278 *
src[48] - 0.0044979052 *
src[49] - 0.0060698985 *
src[50] - 0.0074151919 *
src[51] - 0.0085278517 *
src[52] - 0.0094111161 *
src[53] - 0.0100658241 *
src[54] - 0.0104994302 *
src[55] - 0.0107227904 *
src[56] - 0.0107450280 *
src[57] - 0.0105824763 *
src[58] - 0.0102517019 *
src[59] - 0.0097708805 *
src[60] - 0.0091581551 *
src[61] - 0.0084345004 *
src[62] - 0.0076214397 *
src[63] - 0.0067401718 *
src[64] - 0.0058083144 *
src[65] - 0.0048528295 *
src[66] - 0.0038816271 *
src[67] - 0.0029244713 *
src[68] - 0.0019911267 *
src[69] - 0.0010974211 *
src[70] - 0.0002535559 *
src[71] + 0.0005231953 *
src[72] + 0.0012297491 *
src[73] + 0.0018539149 *
src[74] + 0.0023994354 *
src[75] + 0.0028490136 *
src[76] + 0.0032221429 *
src[77] + 0.0034936183 *
src[78] + 0.0036818974 *
src[79] + 0.0038037944 *
src[80] + 0.0038338964 *
src[81] + 0.0037975350 *
src[82] + 0.0036986051 *
src[83] + 0.0035521320 *
src[84] + 0.0033559226 *
src[85] + 0.0031224409 *
src[86] + 0.0028550092 *
src[87] + 0.0025688349 *
src[88] + 0.0022682355 *
src[89] + 0.0073925495 *
src[90]
rstl_val
//example usage
out = rstl(close)
plot(out)
|
VisibleChart | https://www.tradingview.com/script/j7vCseM2-VisibleChart/ | PineCoders | https://www.tradingview.com/u/PineCoders/ | 340 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PineCoders
//@version=5
// @description This library is a Pine programmer’s tool containing functions that return values from visible chart bars.
library("VisibleChart", true)
// VisibleChart Library
// v4, 2022.08.17
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
// ———————————————————— Library functions {
// @function Condition to determine if a given bar is visible on the chart.
// @returns (bool) True if the current bar is visible.
export barIsVisible() =>
bool result = time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
// @function Condition to determine if a bar is the first visible bar.
// @returns (bool) True if the current bar is the first visible bar.
export isFirstVisibleBar() =>
bool result = time == chart.left_visible_bar_time
// @function Condition to determine if a bar is the last visible bar.
// @returns (bool) True if the current bar is the last visible bar.
export isLastVisibleBar() =>
bool result = 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.
export high() =>
var float result = na
if barIsVisible() and high >= nz(result, high)
result := high
result
// @function Determines the `bar_index` of the highest `high` in visible bars.
// @returns (int) The `bar_index` of the `high()`.
export highBarIndex() =>
var float chartHigh = na
var int highBar = na
if barIsVisible() and high >= nz(chartHigh, high)
highBar := bar_index
chartHigh := high
int result = highBar
// @function Determines the bar time of the highest `high` in visible bars.
// @returns (int) The `time` of the `high()`.
export highBarTime() =>
var float chartHigh = na
var int highTime = na
if barIsVisible() and high >= nz(chartHigh, high)
highTime := time
chartHigh := high
int result = highTime
// @function Determines the value of the lowest `low` in visible bars.
// @returns (float) The minimum low value of visible chart bars.
export low() =>
var float result = na
if barIsVisible() and low <= nz(result, low)
result := low
result
// @function Determines the `bar_index` of the lowest `low` in visible bars.
// @returns (int) The `bar_index` of the `low()`.
export lowBarIndex() =>
var float chartLow = na
var int lowBar = na
if barIsVisible() and low <= nz(chartLow, low)
lowBar := bar_index
chartLow := low
int result = lowBar
// @function Determines the bar time of the lowest `low` in visible bars.
// @returns (int) The `time` of the `low()`.
export lowBarTime() =>
var float chartLow = na
var int lowTime = na
if barIsVisible() and low <= nz(chartLow, low)
lowTime := time
chartLow := low
int result = lowTime
// @function Determines the value of the opening price in the visible chart time range.
// @returns (float) The `open` of the leftmost visible chart bar.
export open() =>
var float result = na
if time == chart.left_visible_bar_time
result := open
result
// @function Determines the value of the closing price in the visible chart time range.
// @returns (float) The `close` of the rightmost visible chart bar.
export close() =>
var float result = na
if barIsVisible()
result := close
result
// @function Determines the `bar_index` of the leftmost visible chart bar.
// @returns (int) A `bar_index`.
export leftBarIndex() =>
var int result = na
if time == chart.left_visible_bar_time
result := bar_index
result
// @function Determines the `bar_index` of the rightmost visible chart bar.
// @returns (int) A `bar_index`
export rightBarIndex() =>
var int result = na
if barIsVisible()
result := bar_index
result
// @function Determines the number of visible chart bars.
// @returns (int) The number of bars.
export bars() =>
var int result = 0
if barIsVisible()
result += 1
result
// @function Determines the sum of volume of all visible chart bars.
// @returns (float) The cumulative sum of volume.
export volume() =>
var float result = 0
if barIsVisible()
result += volume
result
// @function Determines the open, high, low, close, and volume sum of the visible bar time range.
// @returns ([float, float, float, float, float]) A tuple of the OHLCV values for the visible chart bars. Example: open is chart left, high is the highest visible high, etc.
export ohlcv() =>
var float chartOpen = na
var float chartHigh = na
var float chartLow = na
var float chartClose = na
var float chartVolume = na
if time == chart.left_visible_bar_time
chartOpen := open
chartHigh := high
chartLow := low
chartClose := close
chartVolume := volume
else if barIsVisible()
chartHigh := math.max(high, chartHigh)
chartLow := math.min(low, chartLow)
chartClose := close
chartVolume += volume
[chartOpen, chartHigh, chartLow, chartClose, chartVolume]
// @function Determines a price level as a percentage of the visible bar price range, which depends on the chart's top/bottom margins in "Settings/Appearance".
// @param pct (series float) Percentage of the visible price range (50 is 50%). Negative values are allowed.
// @returns (float) A price level equal to the `pct` of the price range between the high and low of visible chart bars. Example: 50 is halfway between the visible high and low.
export chartYPct(series float pct) =>
float result = low() + ((high() - low()) * (pct / 100))
// @function Determines a time as a percentage of the visible bar time range.
// @param pct (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
// @returns (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
export chartXTimePct(series float pct) =>
int result = chart.left_visible_bar_time + int((chart.right_visible_bar_time - chart.left_visible_bar_time) * (pct / 100))
// @function Determines a `bar_index` as a percentage of the visible bar time range.
// @param pct (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
// @returns (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
export chartXIndexPct(series float pct) =>
int leftBarIndex = leftBarIndex()
int rightBarIndex = rightBarIndex()
int result = leftBarIndex + int((rightBarIndex - leftBarIndex) * (pct / 100))
// @function Creates an array containing the `length` last `src` values where `whenCond` is true for visible chart bars.
// @param src (series int/float) The source of the values to be included.
// @param whenCond (series bool) The condition determining which values are included. Optional. The default is `true`.
// @param length (simple int) The number of last values to return. Optional. The default is all values.
// @returns (float[]) The array ID of the accumulated `src` values.
export whenVisible(series float src, series bool whenCond = true, simple int length = na) =>
var float[] values = array.new_float(0)
int cappedLen = math.max(1, length)
if barIsVisible() and whenCond
array.push(values, src)
if not na(cappedLen) and array.size(values) > cappedLen
array.shift(values)
float[] result = values
// @function Gathers values of the source over visible chart bars and averages them.
// @param src (series int/float) The source of the values to be averaged. Optional. Default is `close`.
// @returns (float) A cumulative average of values for the visible time range.
export avg(series float src = close) =>
bool visible = barIsVisible()
float cumTotal = ta.cum(visible ? src : 0)
float cumCount = ta.cum(visible ? 1 : 0)
float result = cumTotal / cumCount
// @function Calculates the median of a source over visible chart bars.
// @param src (series int/float) The source of the values. Optional. Default is `close`.
// @returns (float) The median of the `src` for the visible time range.
export median(series float src = close) =>
float result = array.median(whenVisible(src))
// @function Calculates a volume-weighted average for visible chart bars.
// @param src (series int/float) Source used for the VWAP calculation. Optional. Default is `hlc3`.
// @returns (float) The VWAP for the visible time range.
export vVwap(series float src = hlc3) =>
bool startTime = time == chart.left_visible_bar_time
float result = ta.vwap(src, startTime)
// }
// ———————————————————— Example Code {
// !!!!! WARNING
// !!!!! All functions must be called on each bar to return correct results.
// Chart's high and low values and their time x-coordinate.
float chartHigh = high()
float chartLow = low()
int highTime = highBarTime()
int lowTime = lowBarTime()
int leftTime = math.min(highTime, lowTime)
int rightTime = math.max(highTime, lowTime)
bool isBull = lowTime < highTime
int bars = bars()
float vol = volume()
// Function to manage fib lines. It declares fib lines and label the first time it is called, then sets their properties on subsequent calls.
fibLine(series color fibColor, series float fibLevel) =>
float fibRatio = fibLevel / 100
float fibPrice = isBull ? chartLow + ((chartHigh - chartLow) * fibRatio) :
chartHigh - ((chartHigh - chartLow) * fibRatio)
var line fibLine = line.new(na, na, na, na, xloc.bar_time, extend.none, fibColor, line.style_solid, 1)
var line fibLine2 = line.new(na, na, na, na, xloc.bar_time, extend.none, fibColor, line.style_dotted, 1)
var label fibLabel = label.new(na, na, "", xloc.bar_time, yloc.price, color(na), label.style_label_up, fibColor)
line.set_xy1(fibLine, leftTime, fibPrice)
line.set_xy2(fibLine, rightTime, fibPrice)
line.set_xy1(fibLine2, rightTime, fibPrice)
line.set_xy2(fibLine2, time, fibPrice)
label.set_xy(fibLabel, int(math.avg(leftTime, rightTime)), fibPrice)
label.set_text(fibLabel, str.format("{0, number, #.###} ({1})", fibRatio, str.tostring(fibPrice, format.mintick)))
// 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
// ————— Table displaying visible bars and volume.
// Declare the table once.
var table display = table.new(position.top_right, 1, 1)
// String for table showing the cumulative volume and number of visible chart bars.
string displayString = "Total Visible Bars: " + str.tostring(bars)
+ "\nTotal Visible Volume: " + str.tostring(vol, format.volume)
// Populate table on last bar.
table.cell(display, 0, 0, displayString, bgcolor = color.yellow, text_color = color.black, text_size = size.normal)
// ————— Labels displaying hi/lo points and time.
// Declare basic labels once.
var label hiLabel = label.new(na, na, na, xloc.bar_time, yloc.price, color.new(color.lime, 80), label.style_label_down, color.lime)
var label loLabel = label.new(na, na, na, xloc.bar_time, yloc.price, color.new(color.fuchsia, 80), label.style_label_up, color.fuchsia)
// Update label for changes to location, and text.
label.set_xy(hiLabel, highTime, chartHigh)
label.set_xy(loLabel, lowTime, chartLow)
label.set_text(hiLabel, str.format("{0}\n{1,time, dd/MM/yy @ HH:mm:ss}", str.tostring(chartHigh, format.mintick), highTime))
label.set_text(loLabel, str.format("{0}\n{1,time, dd/MM/yy @ HH:mm:ss}", str.tostring(chartLow, format.mintick), lowTime))
// ————— Fib lines
// Declare fib lines and labels once, then set properties on each bar.
fibLine(color.gray, 100)
fibLine(#64b5f6, 78.6)
fibLine(#089981, 61.8)
fibLine(color.green, 50)
fibLine(#81c784, 38.2)
fibLine(color.red, 23.6)
fibLine(color.gray, 0)
// ————— Dashed line between hi/lo.
// Declare line once.
var line hiLoLine = line.new(na, na, na, na, xloc.bar_time, extend.none, color.gray, line.style_dashed, 1)
// Re-position line on each update.
line.set_xy1(hiLoLine, highTime, chartHigh)
line.set_xy2(hiLoLine, lowTime, chartLow)
// } |
threengine_global_automation_library | https://www.tradingview.com/script/BJk6hZD6-threengine-global-automation-library/ | jordanfray | https://www.tradingview.com/u/jordanfray/ | 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/
// © jordanfray
//@version=5
// @description A collection of functions used for trade automation
library("threengine_global_automation_library")
// @function Gets the base currency for the chart's ticker. Supported trade pairs are USD, USDT, USDC, BTC, and PERP.
// @returns Base currency as a string
export getBaseCurrency() =>
var ticker = syminfo.ticker
var string base_currency = na
if str.endswith(ticker, "USDT")
base_currency := "USDT"
else
if str.endswith(ticker, "USDT.P")
base_currency := "USDT"
else
if str.endswith(ticker, "USDC")
base_currency := "USDC"
else
if str.endswith(ticker, "BUSD")
base_currency := "BUSD"
else
if str.endswith(ticker, "BTC")
base_currency := "BTC"
else
if str.endswith(ticker, "PERP")
base_currency := "PERP"
else
if str.endswith(ticker, "USD")
base_currency := "USD"
else
if str.endswith(ticker, "USD.P")
base_currency := "USD"
else
base_currency := "USD"
base_currency
// @function Get the current chart's symbol without the base currency appended to it. Supported trade paris are USD, USDT, USDC, BTC, and PERP.
// @returns Ssymbol and base currency
export getChartSymbol() =>
var ticker = syminfo.ticker
trade_pair_parts = array.new_string()
var string trade_pair = na
if str.endswith(ticker, "USDT")
trade_pair_parts := str.split(ticker, "USDT")
trade_pair := array.get(trade_pair_parts,0)
else
if str.endswith(ticker, "USDT.P")
trade_pair_parts := str.split(ticker, "USDT.P")
trade_pair := array.get(trade_pair_parts,0)
else
if str.endswith(ticker, "USDC")
trade_pair_parts := str.split(ticker, "USDC")
trade_pair := array.get(trade_pair_parts,0)
else
if str.endswith(ticker, "BUSD")
trade_pair_parts := str.split(ticker, "BUSD")
trade_pair := array.get(trade_pair_parts,0)
else
if str.endswith(ticker, "BTC")
trade_pair_parts := str.split(ticker, "BTC")
trade_pair := array.get(trade_pair_parts,0)
else
if str.endswith(ticker, "PERP")
trade_pair_parts := str.split(ticker, "PERP")
trade_pair := array.get(trade_pair_parts,0)
else
if str.endswith(ticker, "USD")
trade_pair_parts := str.split(ticker, "USD")
trade_pair := array.get(trade_pair_parts,0)
else
if str.endswith(ticker, "USD.P")
trade_pair_parts := str.split(ticker, "USD.P")
trade_pair := array.get(trade_pair_parts,0)
else
trade_pair := ticker
trade_pair
// @function Calculates how many decimals are on the quote price of the current market
// @returns The current deimal places on the market quote price
export getDecimals() => math.abs(math.log(syminfo.mintick)/ math.log(10))
// @function Plot a string as a label on the chart to test variable value. Use str.tostring() for any variable that isn't a string.
// @returns Label with stringified variable
export checkVar(int y_offset, string variable) =>
var label lb = na
label.delete(lb)
lb := label.new(
x=time + 20000000,
xloc=xloc.bar_time,
y=hl2 + y_offset,
style=label.style_none,
size=size.normal,
textcolor=color.new(color.blue, 0),
textalign = text.align_left,
text=str.tostring(variable))
// @function Gets you the right divider needed between the symbol and base currency depending on the exhange you want to use. Supports "FTX.us" and "Bybit" currently
// @returns string containing the divider needed between the symbol and base currency
export getPairDividerForExchange(string exchangeName) =>
pairDivider = switch exchangeName
"FTX.us" => "/"
"ByBit" => ""
=> na
pairDivider
// @function Generates stringified JSON for a limit order that can be passed to the strategy alert_message for a long entry.
// @returns Stringifed JSON for a long entry
export getStrategyAlertMessage(string secret, string symbol, string base_currency, string side, float orderTriggerPrice, float orderLimitPrice, string orderSize, float profitTriggerPrice, float profitLimitPrice, float stopLossTriggerPrice, float stopLossLimitPrice, bool cancelExistingUnfilledOrders) =>
close_side = if side == "buy"
"sell"
else
"buy"
'{' +
'"secret" : "' + str.tostring(secret) + '", ' +
'"symbol" : "' + str.tostring(symbol) + '", ' +
'"baseCurrency" : "' + str.tostring(base_currency) + '", ' +
'"cancelExistingUnfilledOrders" : ' + str.tostring(cancelExistingUnfilledOrders) + ', ' +
'"order" : {' +
'"side" : "' + str.tostring(side) + '", ' +
'"triggerPrice" : ' + str.tostring(orderTriggerPrice) + ', ' +
'"limitPrice" : ' + str.tostring(orderLimitPrice) + ', ' +
'"size" : "' + str.tostring(orderSize) + '"' +
'}, "takeProfit" : {' +
'"side" : "' + str.tostring(close_side) + '", ' +
'"triggerPrice" : ' + str.tostring(profitTriggerPrice) + ', ' +
'"limitPrice" : ' + str.tostring(profitLimitPrice) + ', ' +
'"size" : "100%p"' +
'}, "stopLoss" : {' +
'"side" : "' + str.tostring(close_side) + '", ' +
'"triggerPrice" : ' + str.tostring(stopLossTriggerPrice) + ', ' +
'"limitPrice" : ' + str.tostring(stopLossLimitPrice) + ', ' +
'"size" : "100%p"' +
'},"chartInfo" : {' +
'"barIndex" : "' + str.tostring(bar_index + 1) + '", ' +
'"time" : "' + str.tostring(time) + '", ' +
'"decimals" : "' + str.tostring(getDecimals()) + '"' +
'}' +
'}'
// @function Generates stringified JSON for a limit order that can be passed to the strategy alert_message for an entry.
// @returns Stringifed JSON for an entry
export getAlertatronEntryMessage(string strategyName, string secret, int leverage, string leverageType, string symbol, string baseCurrency, string pairDivider, string side, float orderPrice, string orderSize, float stopLossPrice, bool cancelExistingUnfilledOrders) =>
closeSide = side == "buy" ? "sell" : "buy"
string initializeOrder = str.tostring(secret) + "(" + str.tostring(symbol) + pairDivider + str.tostring(baseCurrency) + ") { "
string exchangeSettings = "exchangeSettings(leverage=" + str.tostring(leverage) + "); " + "exchangeSettings(leverage=" + str.lower(leverageType) + "); "
string cancelOrders = cancelExistingUnfilledOrders ? "cancel(which=all); " : ""
string limit = "limit(side=" + str.tostring(side) + ", amount=" + str.tostring(orderSize) + ", offset=@" + str.tostring(orderPrice) + "); "
string stopLoss = "stopOrder(side=" + str.tostring(closeSide) + ", amount=" + str.tostring(orderSize) + ", offset=@" + str.tostring(stopLossPrice) + ", trigger=last, reduceOnly=true); "
string messageEnd = "} #bot "
string comment = "// Alert Source: " + str.tostring(strategyName)
webhookEntryMessage = initializeOrder + exchangeSettings + cancelOrders + limit + stopLoss + messageEnd + comment
// @function Generates stringified JSON for a limit Exit that can be passed to the strategy alert_message for a long entry.
// @returns Stringifed JSON for a exit entry
export getAlertatronExitMessage(string strategyName, string secret, string symbol, string baseCurrency, string pairDivider, string side, float orderPrice, string orderSize, bool cancelExistingUnfilledOrders) =>
string initializeOrder = str.tostring(secret) + "(" + str.tostring(symbol) + pairDivider + str.tostring(baseCurrency) + ") { "
string cancelOrders = cancelExistingUnfilledOrders ? "cancel(which=all); " : ""
string limit = "limit(side=" + str.tostring(side) + ", amount=" + str.tostring(orderSize) + ", offset=@" + str.tostring(orderPrice) + ", reduceOnly=true); "
string messageEnd = "} #bot "
string comment = "// Alert Source: " + str.tostring(strategyName)
webhookExitMessage = initializeOrder + cancelOrders + limit + messageEnd + comment
// @function Generates a string for a limit order that can be passed to the strategy alert_message for an entry.
// @returns string that represents a block of entries for alertatron
export getAlertatronEntryMessageV2(string tag, string secret, int leverage, string leverageType, string symbol, string baseCurrency, string pairDivider, string side, string entryPrices, string entrySizes, string profitTargetPrices, string profitTargetSizes, float stopLossPrice, bool cancelExistingUnfilledOrders) =>
string closeSide = side == "buy" ? "sell" : "buy"
entryPricesArray = str.split(entryPrices,",")
entrySizessArray = str.split(entrySizes,",")
profitTargetPricesArray = str.split(profitTargetPrices,",")
profitTargetSizesArray = str.split(profitTargetSizes,",")
string webhookEntryMessages = ""
for i = 0 to array.size(entryPricesArray) - 1 by 1
string initializeOrder = str.tostring(secret) + "(" + str.tostring(symbol) + pairDivider + str.tostring(baseCurrency) + ") { "
string exchangeSettings = "exchangeSettings(leverage=" + str.tostring(leverage) + "); " + "exchangeSettings(leverage=" + str.lower(leverageType) + "); "
string cancelOrders = cancelExistingUnfilledOrders ? "cancel(which=tagged, tag=" + tag + "); " : ""
string waitingLimit = "waitingLimit(side=" + str.tostring(side) + ", amount=" + str.tostring(array.get(entrySizessArray,i)) + ", offset=@" + str.tostring(array.get(entryPricesArray,i)) + ", tag='" + tag + "'); "
string profitTargets = ""
for x = 0 to array.size(profitTargetPricesArray) - 1 by 1
profitTarget = "limit(side=" + closeSide + ", amount=" + str.tostring(array.get(profitTargetSizesArray,x)) + ", offset=@" + str.tostring(array.get(profitTargetPricesArray,x)) + ", reduceOnly=true, tag='" + tag + "'); "
profitTargets := profitTargets + profitTarget
string stopLoss = "stopOrder(side=" + str.tostring(closeSide) + ", amount=" + str.tostring(array.get(profitTargetSizesArray,i)) + ", offset=@" + str.tostring(stopLossPrice) + ", trigger=last, reduceOnly=true, tag='" + tag + "'); "
string messageEnd = "} #bot "
webhookEntryMessage = initializeOrder + exchangeSettings + cancelOrders + waitingLimit + profitTargets + stopLoss + messageEnd
webhookEntryMessages := webhookEntryMessages + webhookEntryMessage
// @function Calculates the Average Directional Index
// @returns The value of ADX as a float
export taGetAdx(int diLength, int smoothing) =>
up = ta.change(high)
down = -ta.change(low)
plusDm = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDm = na(down) ? na : (down > up and down > 0 ? down : 0)
trueRange = ta.rma(ta.tr, diLength)
plus = fixnan(100 * ta.rma(plusDm, diLength) / trueRange)
minus = fixnan(100 * ta.rma(minusDm, diLength) / trueRange)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), smoothing)
adx
// @function Calculates the Plust and Minus Directional Index and the distance betwen the two
// @returns The value of DI Plus, DI Minus, & Distance between them
export taGetDirectionalIndex(int length) =>
TrueRange = math.max(math.max(high-low, math.abs(high-nz(close[1]))), math.abs(low-nz(close[1])))
DirectionalMovementPlus = high-nz(high[1]) > nz(low[1])-low ? math.max(high-nz(high[1]), 0): 0
DirectionalMovementMinus = nz(low[1])-low > high-nz(high[1]) ? math.max(nz(low[1])-low, 0): 0
SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1])/length) + TrueRange
SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - (nz(SmoothedDirectionalMovementPlus[1])/length) + DirectionalMovementPlus
SmoothedDirectionalMovementMinus = 0.0
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1])/length) + DirectionalMovementMinus
DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
distanceBetweenDi = (DIPlus - DIMinus) < 0 ? (DIPlus - DIMinus)*-1 : (DIPlus - DIMinus)
[DIPlus, DIMinus, distanceBetweenDi]
// @function Calculates the Directional Index based on a DI Length
// @returns directional index (float)
export taGetDirectionalIndex(float diLength) =>
TrueRange = math.max(math.max(high-low, math.abs(high-nz(close[1]))), math.abs(low-nz(close[1])))
DirectionalMovementPlus = high-nz(high[1]) > nz(low[1])-low ? math.max(high-nz(high[1]), 0): 0
DirectionalMovementMinus = nz(low[1])-low > high-nz(high[1]) ? math.max(nz(low[1])-low, 0): 0
SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1])/diLength) + TrueRange
SmoothedDiMovementPlus = 0.0
SmoothedDiMovementPlus := nz(SmoothedDiMovementPlus[1]) - (nz(SmoothedDiMovementPlus[1])/diLength) + DirectionalMovementPlus
SmoothedDiMovementMinus = 0.0
SmoothedDiMovementMinus := nz(SmoothedDiMovementMinus[1]) - (nz(SmoothedDiMovementMinus[1])/diLength) + DirectionalMovementMinus
DiPlus = SmoothedDiMovementPlus / SmoothedTrueRange * 100
DiMinus = SmoothedDiMovementMinus / SmoothedTrueRange * 100
DX = math.abs(DiPlus-DiMinus) / (DiPlus+DiMinus)*100
[DiPlus, DiMinus]
// @function Calculates the EMA based on a type, source, and length. Supported types are EMA, SMA, RMA, and WMA.
// @returns The value of the selected EMA
export taGetEma(simple string type, series float source, simple int length) =>
ema = switch type
"EMA" => ta.ema(source, length)
"SMA" => ta.sma(source, length)
"RMA" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
=> na
ema
// @function Calculates VWAP based on provided src, anchor, and multiplier
// @returns VWAP, lower band, and upper band
export taGetVwap(float src, string anchor, float multiplier) =>
isNewPeriod = switch anchor
"Session" => ta.change(time("D"))
"Week" => ta.change(time("W"))
"Month" => ta.change(time("M"))
"Quarter" => ta.change(time("3M"))
"Year" => ta.change(time("12M"))
=> false
var float sumSrcVol = na
var float sumVol = na
var float sumSrcSrcVol = na
sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1]
sumVol := isNewPeriod ? volume : volume + sumVol[1]
sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1]
vwap = sumSrcVol / sumVol
variance = sumSrcSrcVol / sumVol - math.pow(vwap, 2)
variance := variance < 0 ? 0 : variance
standardDeviation = math.sqrt(variance)
lowerBandValue = vwap - standardDeviation * multiplier
upperBandValue = vwap + standardDeviation * multiplier
[vwap, lowerBandValue, upperBandValue]
// @function Calculates a smoothed VWAP based on provided src, anchor, multiplier, and smoothing length
// @returns VWAP, lower band, and upper band
export taGetSmoothedVwap(float src, string anchor, float multiplier, int smoothingLength) =>
isNewPeriod = switch anchor
"Session" => ta.change(time("D"))
"Week" => ta.change(time("W"))
"Month" => ta.change(time("M"))
"Quarter" => ta.change(time("3M"))
"Year" => ta.change(time("12M"))
=> false
var float sumSrcVol = na
var float sumVol = na
var float sumSrcSrcVol = na
sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1]
sumVol := isNewPeriod ? volume : volume + sumVol[1]
sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1]
vwap = sumSrcVol / sumVol
variance = sumSrcSrcVol / sumVol - math.pow(vwap, 2)
variance := variance < 0 ? 0 : variance
standardDeviation = math.sqrt(variance)
lowerBandValue = vwap - standardDeviation * multiplier
upperBandValue = vwap + standardDeviation * multiplier
vwap := ta.sma(vwap, smoothingLength)
lowerBandValue := ta.sma(lowerBandValue, smoothingLength)
upperBandValue := ta.sma(upperBandValue, smoothingLength)
[vwap, lowerBandValue, upperBandValue]
// @function Calculates and average, min, and max for provided series using a lookback period and sample size
// @returns Min, Max, and Average values
export taGetExtremes(float value, string direction, int lookbackPeriod, int sampleSize) =>
extremes = array.new_float()
for i=0 to lookbackPeriod - 1 by 1
array.push(extremes, value[i])
topExtremes = array.new_float()
for i=0 to sampleSize - 1 by 1
float etremeAtN = na
if direction == "high"
etremeAtN := array.get(extremes, array.indexof(extremes, array.max(extremes,i)))
else
if direction == "low"
etremeAtN := array.get(extremes, array.indexof(extremes, array.min(extremes,i)))
else
runtime.error("You must slect either 'high' or 'low' for the 'direction' when using taGetExtremes.")
array.push(topExtremes, etremeAtN)
minExtreme = array.min(topExtremes)
avgExtreme = array.avg(topExtremes)
maxExtreme = array.max(topExtremes)
[minExtreme, avgExtreme, maxExtreme]
// @function Calculate the pivot low (support) using a look back/ahead window
// @returns float value of the pivot low
export taGetSupport(int lookback, int lookahead) =>
support = fixnan(ta.pivotlow(lookback, lookahead)[1])
support
// @function Calculate the pivot high (support) using a look back/ahead window
// @returns float value of the pivot high
export taGetResistance(int lookback, int lookahead) =>
resistance = fixnan(ta.pivothigh(lookback, lookahead)[1])
resistance
// @function Calculate the percent difference between two numbers
// @returns the percentage difference between the two numbers
export taGetPercentDif(float number1, float number2) =>
difRaw = number1 - number2
dif = difRaw < 0 ? difRaw * -1 : difRaw
avg = (number1 + number2) / 2
percentDif = (dif / avg) * 100
// @function Calculates Wavetrend
// @returns Tupple [waveTrend1, waveTrend2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown]
export wavetrend(float source, int channelLength, int avg, int movingAverageLength, int oversoldLevel, int overboughtLevel) =>
esa = ta.ema(source, channelLength)
de = ta.ema(math.abs(source - esa), channelLength)
ci = (source - esa) / (0.015 * de)
waveTrend1 = ta.ema(ci, avg)
waveTrend2 = ta.sma(waveTrend1, movingAverageLength)
wtOversold = waveTrend2 <= oversoldLevel
wtOverbought = waveTrend2 >= overboughtLevel
wtCross = ta.cross(waveTrend1, waveTrend2)
wtCrossUp = ta.crossover(waveTrend1, waveTrend2)
wtCrossDown = ta.crossunder(waveTrend1, waveTrend2)
[waveTrend1, waveTrend2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown]
// @function Checks to see if within a rage based on two times
// @returns true/false boolean
export isBetweenTwoTimes(simple string session, simple string timezone) =>
na(time(timeframe.period, session, timezone)) == false
// @function This gets all closed trades and open trades
// @returns an array of all open and closed trade ID's
export getAllTradeIDs() =>
closed_orders = array.new_string()
open_orders = array.new_string()
all_orders = array.new_string()
currentlyInAPosition = strategy.position_size != 0
open_order_count = strategy.opentrades - 1
for i = 0 to strategy.closedtrades by 1
id = strategy.closedtrades.entry_id(i)
array.push(closed_orders, id)
if currentlyInAPosition
for i = 0 to open_order_count by 1
id = strategy.opentrades.entry_id(i)
array.push(open_orders, id)
array.concat(all_orders, closed_orders)
array.concat(all_orders, open_orders)
all_orders
// @function This gets all closed trades since a provided bar number
// @returns two arrays: closing bar index, and closing price
export getClosedTradeSince(int barNumberToCompare) =>
closedOrderBarNumbers = array.new_int()
closedOrderPrices = array.new_int()
for i = 0 to strategy.closedtrades - 1 by 1
bar = strategy.closedtrades.exit_bar_index(i)
price = strategy.closedtrades.exit_price(i)
if bar > barNumberToCompare
array.push(closedOrderBarNumbers, bar)
array.push(closedOrderPrices, bar)
[closedOrderBarNumbers, closedOrderPrices]
// @function This gets the count of closed trades since a provided bar index
// @returns integer of number of closed trades since provided bar index
export getCountOfClosedTradeSince(int barNumberToCompare) =>
int count = 0
if strategy.position_size != 0
for i = 0 to strategy.closedtrades - 1 by 1
bar = strategy.closedtrades.exit_bar_index(i)
if bar > barNumberToCompare
count += 1
count
else
count += 0
count
// @function Checks to see if a trade has already closed since a past bar number
// @returns boolean of whether provided trade id has already closed since provided bar number
export orderAlreadyClosedSince(string exitId, int barNumberToCompare) =>
closedOrderIds = array.new_string()
currentlyInAPosition = strategy.position_size != 0
if currentlyInAPosition
for i = 0 to strategy.closedtrades - 1 by 1
bar = strategy.closedtrades.exit_bar_index(i)
price = strategy.closedtrades.exit_price(i)
id = strategy.closedtrades.exit_id(i)
if bar > barNumberToCompare
array.push(closedOrderIds, id)
alreadyClosed = array.includes(closedOrderIds, exitId)
// @function This gets all open trades
// @returns an array of all open trade ID's
export getOpenTradeIDs() =>
open_orders = array.new_string()
open_order_count = strategy.opentrades
if open_order_count > 0
for i = 0 to open_order_count - 1 by 1
id = strategy.opentrades.entry_id(i)
array.push(open_orders, id)
open_orders
// @function This checks to see if a provided order id uses the getAllTradeIDs() function to check
// @returns an array of all open and closed trade ID's
export orderAlreadyExists(string order_id) =>
array.includes(getAllTradeIDs(), order_id) ? true : false
// @function This checks to see if a provided order id uses the getAllTradeIDs() function to check
// @returns an array of all open and closed trade ID's
export orderCurrentlyExists(string order_id) =>
array.includes(getOpenTradeIDs(), order_id) ? true : false
// @function Detect when the ladder has started to fill so that the ladder start can be locked to the initial strategy entry price. After trades close, reset it back to zero.
// @returns Locked ladder start price and the bar number that the first ladder was filled on
export getLockedLadderStart(float startingLadderPrice) =>
var float ladderInStart = startingLadderPrice
var bool ladderInActive = false
var int firstLadderOpenedOnBar = 0
bool currentlyInAPosition = strategy.position_size != 0
if currentlyInAPosition and not ladderInActive
ladderInStart := strategy.opentrades.entry_price(0)
firstLadderOpenedOnBar := strategy.opentrades.entry_bar_index(0)
ladderInActive := true
else
if not currentlyInAPosition
ladderInStart := startingLadderPrice
firstLadderOpenedOnBar := 0
ladderInActive := false
[ladderInStart, firstLadderOpenedOnBar]
// @function Keeps count of the number of ladder orders that have been filled for an strategy entry
// @returns maximum number of ladder orders filled
export getAveragePriceOfFilledLadders() =>
var float avgPrice = na
var int mostOpenTradesSinceFirstLadderFilled = 0
bool currentlyInAPosition = strategy.position_size != 0
if currentlyInAPosition and strategy.opentrades > mostOpenTradesSinceFirstLadderFilled
mostOpenTradesSinceFirstLadderFilled := strategy.opentrades
avgPrice := strategy.position_avg_price
else
if not currentlyInAPosition
mostOpenTradesSinceFirstLadderFilled := 0
avgPrice := na
avgPrice
// @function calulates the number of contracts you can buy with a set amount of capital and a limit price
// @returns number of contracts you can buy based on amount of capital you want to use and a price
export getContractCount(string amount, float price) =>
float contractCount = 0.00
accountBalance = strategy.equity
if str.contains(amount,"%a") and accountBalance > 0
percentAmount = str.split(amount,"%")
contractCount := (str.tonumber(array.get(percentAmount,0))/100 * accountBalance) /price
else
contractCount := str.tonumber(amount)/price
contractCount
// @function Constructs arrays used for creating strategy entry orders via a for loop
// @returns array of ladder entry prices and amounts based on total amount you want to invest across all ladder rungs and either a range between ladderStart and LadderStop based on specificed number of ladderRungs OR ladderStart, ladderRungs, and LadderSpacingPercent
export getLadderInSteps(string side, float amount, string amountType, int ladderRungs, float ladderStart, float ladderStop, float stepSpacingPercent, int roundTo) =>
entryPrices = array.new_float() // For Alertatron and TradingView
contractCounts = array.new_float() // For TradingView
entryAmounts = array.new_float() // For Alertatron
orderNames = array.new_string() // For TradingView
float ladderSpacing = na
float contractCount = na
float entryAmount = na
if ladderStart and ladderStop and not stepSpacingPercent
ladderSpacing := (ladderStart - ladderStop) / ladderRungs // float returns the dollar amount between each rung of the ladder
else
ladderSpacing := ladderStart * (stepSpacingPercent/100)
if ladderStart and ladderSpacing
for i = 0 to ladderRungs - 1 by 1
price = side == "buy" ? ladderStart - (ladderSpacing * i) : ladderStart + (ladderSpacing * i)
orderName = side =="buy" ? "Long - " + str.tostring(i+1) : "Short - " + str.tostring(i+1)
if amountType == "Percent Of Account"
contractCount := math.round(((amount/100) * strategy.equity)/price, roundTo) // For TradingView
entryAmount := math.round(amount, roundTo) // For Alertatron
if amountType == "Dollars"
contractCount := math.round(amount/price, roundTo) // For TradingView
entryAmount := math.round(amount, roundTo) // For Alertatron
if amountType == "Contracts"
contractCount := math.round(amount, roundTo) // For TradingView
entryAmount := math.round(amount, roundTo) // For Alertatron
array.push(entryPrices, price)
array.push(contractCounts, contractCount)
array.push(entryAmounts, entryAmount)
array.push(orderNames, orderName)
[entryPrices, contractCounts, entryAmounts, orderNames]
// @function Constructs arrays used for creating strategy exit orders via a for loop
// @returns array of ladder entry prices and amounts based on total amount you want to invest across all ladder rungs and either a range between ladderStart and LadderStop based on specificed number of ladderRungs OR ladderStart, ladderRungs, and LadderSpacingPercent
export getLadderOutSteps(string side, float ladderStart, int ladderRungs, float stepSpacingPercent, int roundTo) =>
prices = array.new_float()
quantityPercents = array.new_float()
orderNames = array.new_string()
float ladderSpacing = ladderStart * (stepSpacingPercent/100)
int quantityPercent = math.floor(100/ladderRungs)
int remainingPercent = 100
int percentToClose = na
for i = 0 to ladderRungs - 1 by 1
price = math.round(side == "sell" ? ladderStart + (ladderSpacing * i) : ladderStart - (ladderSpacing * i), roundTo)
orderName = "Ladder Out - " + str.tostring(i+1)
if i == ladderRungs -1
percentToClose := remainingPercent
else
percentToClose := quantityPercent
remainingPercent -= percentToClose
array.push(prices, price)
array.push(quantityPercents, percentToClose)
array.push(orderNames, orderName)
[prices, quantityPercents, orderNames]
// @function Calulates the rate of change of a series based on a look back length
// @returns the rate of change as a float
export getRateOfChange(float source, int length) =>
float rateOfChange = 100 * (source - source[length])/source[length]
rateOfChange
// @function Constructs arrays used for creating strategy exit orders via a for loop
// @returns array of ladder entry prices and amounts based on total amount you want to invest across all ladder rungs and either a range between ladderStart and LadderStop based on specificed number of ladderRungs OR ladderStart, ladderRungs, and LadderSpacingPercent
export closeUnfilledEntriesAfter(int cancelUnfilledOrdersAfter, string cancelUnfilledOrdersType, int startingBar) =>
int chartTimeframeMinutes = timeframe.in_seconds(timeframe.period) / 60
bool currentlyInAPosition = strategy.position_size != 0
bool cancelUnfilledEntries = false
int numberOfClosedTrades = getCountOfClosedTradeSince(startingBar)
int cancelOnBar = na
if currentlyInAPosition
cancelUnfilledEntries := switch cancelUnfilledOrdersType
"exits" => numberOfClosedTrades >= cancelUnfilledOrdersAfter
"bars" => bar_index >= (startingBar + cancelUnfilledOrdersAfter)
"days" => bar_index >= (startingBar + ((cancelUnfilledOrdersAfter * 1440)/chartTimeframeMinutes))
"hours" => bar_index >= (startingBar + ((cancelUnfilledOrdersAfter * 60)/chartTimeframeMinutes))
"minutes" => bar_index >= (startingBar + (cancelUnfilledOrdersAfter/chartTimeframeMinutes))
cancelOnBar := switch cancelUnfilledOrdersType
"exits" => numberOfClosedTrades >= cancelUnfilledOrdersAfter ? strategy.closedtrades.exit_bar_index(0) : na
"bars" => startingBar + cancelUnfilledOrdersAfter
"days" => startingBar + ((cancelUnfilledOrdersAfter * 1440)/chartTimeframeMinutes)
"hours" => startingBar + ((cancelUnfilledOrdersAfter * 60)/chartTimeframeMinutes)
"minutes" => startingBar + (cancelUnfilledOrdersAfter/chartTimeframeMinutes)
else
cancelUnfilledEntries := false
cancelOnBar := na
[cancelUnfilledEntries, cancelOnBar]
// @function Gets an array of entry names for number of desired entries
// @returns array of entry name strings
export getEntryNames(int numberOfEntries, string side) =>
entryNamesArray = array.new_string(numberOfEntries)
for i = 0 to numberOfEntries - 1 by 1
entryName = side == "buy" ? "Long - " + str.tostring(i + 1) : "Short - " + str.tostring(i + 1)
array.insert(entryNamesArray, i, entryName)
array.from(side == "buy" ? "Long" + " - 1" : "Short" + " - 1", side == "buy" ? "Long" + " - 2" : "Short" + " - 2", side == "buy" ? "Long" + " - 3" : "Short" + " - 3", side == "buy" ? "Long" + " - 4" : "Short" + " - 4", side == "buy" ? "Long" + " - 5" : "Short" + " - 5", side == "buy" ? "Long" + " - 6" : "Short" + " - 6")
entryNamesArray
// @function Formats array of entry prices to supported format
// @returns CSV string of properly formated entry prices
export formatEntryPrices(string entryPrices) =>
entryPricesArray = str.split(entryPrices, ",")
string entryPricesString = na
for i = 0 to array.size(entryPricesArray) - 1 by 1
entryPricesString += str.format("{0,number,currency}", array.get(entryPricesArray,i))
if i != array.size(entryPricesArray) - 1
entryPricesString += ","
entryPricesString
// This next section includes all of the functions needed for Alertatron webhook messages. Not all functions are exported. Some are just helper functions to make the bottom exported function cleaner.
getProfitTargetAmount(string amount) =>
string profitTargetAmount = na
if str.contains(amount,"%")
profitTargetAmount := amount + "p"
else
runtime.error("The profit target amount must be represented as a % of the position. Update 'profitTargetAmounts' to be a CSV string of percentages like '3%, 4%, 5%'")
profitTargetAmount
getProfitTarget(string target, int symbolMaxDecimals) =>
string profitTarget = na
if str.contains(target,"$")
targetSplit = str.split(target,"$")
roundedPrice = math.round(str.tonumber(array.get(targetSplit,1)),symbolMaxDecimals)
profitTarget := "@" + str.tostring(roundedPrice)
else
if str.contains(target,"%")
profitTarget := target + "p"
else
runtime.error("The profit target must be represented as a % or price. Update 'profitTargets' to be a CSV string of percentages like '3%, 4%, 5%' or prices like '$20000.00, 21000.00, 22000.00'")
profitTarget
// Converts incoming entry amounts into % of account or contracts
getEntryPrices(float[] array, int roundTo) =>
roundedArray = array.new_string(0)
for i = 0 to array.size(array) - 1 by 1
roundedVal = math.round(array.get(array,i),roundTo)
array.push(roundedArray, str.tostring(roundedVal))
roundedArray
// @function Calulates the contract count and entry amount for strategy entries and for alertatron alert messages
// @returns Tupple including the contract count (to be used in TV) and entry amount (to be used in alert messages)
export getLotSize(string type, float amount, float leverage, int roundTo) =>
float contractCount = na
float entryAmount = na
if type == "Percent Of Account"
contractCount := math.round(((amount/100) * strategy.equity)/close, roundTo) * leverage
entryAmount := math.round(amount, roundTo)
if type == "Dollars"
contractCount := math.round(amount/close, roundTo) * leverage
entryAmount := math.round(amount, roundTo)
if type == "Contracts"
contractCount := math.round(amount, roundTo) * leverage
entryAmount := math.round(amount, roundTo)
[contractCount,entryAmount]
// @function Sets the alertatron symbol and base currency based on provided overrides in strategy settings
// @returns Tupple including the symbol and base currency
export getPairOverrides(string symbolOverride, string currencyOverride) =>
string baseCurrency = na
string symbol = na
if currencyOverride != ""
baseCurrency := currencyOverride
else
baseCurrency := getBaseCurrency()
if symbolOverride != ""
symbol := symbolOverride
else
symbol := getChartSymbol()
[symbol,baseCurrency]
getEntryQuantity(float entryAmount, string type, float price, int roundTo, float leverage) =>
string entryQuantity = na
float leveragedPercentAmount = na
if type == "Contracts"
entryQuantity := str.tostring(math.round(entryAmount, roundTo))
else
if type == "Percent Of Account"
if leverage > 1
leveragedPercentAmount := (entryAmount * leverage)
else
leveragedPercentAmount := (entryAmount * leverage)
entryQuantity := str.tostring(math.round(leveragedPercentAmount, roundTo)) + "%a"
else
if type == "Dollars"
entryQuantity := str.tostring(math.round(entryAmount/price, roundTo))
entryQuantity
// Converts incoming profit target amounts into % of position or contracts
getProfitTargets(float[] array, string type, int roundTo) =>
int inputSize = array.size(array) - 1
output = array.new_string(0) // Create empty array of sting type
string target = na
float remainingPercentage = 100.00
for i = 0 to inputSize by 1
float percent = 0.00
bool lastTarget = i == inputSize
if type == "percent"
if lastTarget
percent := remainingPercentage
else
percent := math.round(array.get(array,i), roundTo)
remainingPercentage -= percent
target := "e" + str.tostring(percent) + "%"
else
if type == "price"
target := "@" + str.tostring(math.round(array.get(array,i), roundTo))
else
runtime.error('The "profitTargetType must be "percent" or "price".')
array.push(output, target)
output
getProfitTargetAmounts(float[] array, int roundTo) =>
output = array.new_string(0) // Create empty array of sting type
float remainingPercentage = 100.00
float targetPercentage = 0.00
for i = 0 to array.size(array) - 1 by 1
if i == array.size(array) - 1
targetPercentage := remainingPercentage
else
targetPercentage := math.round(array.get(array,i),roundTo)
remainingPercentage -= targetPercentage
array.push(output, str.tostring(targetPercentage) + "%p")
output
getStop(string side, string stopTriggerType, float stopTrigger, float stopLimitOffset, int roundTo) =>
string stopTriggerVal = na
string stopLimitOffsetVal = na
if stopTriggerType == "percent"
stopTriggerVal := "e" + str.tostring(math.round(stopTrigger,roundTo)) + "%"
stopLimitOffsetVal := "e" + str.tostring(math.round(side == "buy" ? (stopTrigger - (stopTrigger * (stopLimitOffset/100))) : (stopTrigger + (stopTrigger * (stopLimitOffset/100))),roundTo)) + "%"
if stopTriggerType == "price"
stopTriggerVal := "@" + str.tostring(math.round(stopTrigger,roundTo))
stopLimitOffsetVal := "@" + str.tostring(math.round(side == "buy" ? (stopTrigger + (stopTrigger * (stopLimitOffset/100))) : (stopTrigger - (stopTrigger * (stopLimitOffset/100))),roundTo))
[stopTriggerVal, stopLimitOffsetVal]
getProfit(string side, string profitTriggerType, float profitTrigger, float profitLimitOffset, int roundTo) =>
string profitTriggerVal = na
string profitLimitOffsetVal = na
if profitTriggerType == "percent"
profitTriggerVal := "e" + str.tostring(math.round(profitTrigger,roundTo)) + "%"
profitLimitOffsetVal := "e" + str.tostring(math.round(side == "buy" ? (profitTrigger - (profitTrigger * (profitLimitOffset/100))) : (profitTrigger + (profitTrigger * (profitLimitOffset/100))),roundTo)) + "%"
if profitTriggerType == "price"
profitTriggerVal := "@" + str.tostring(math.round(profitTrigger,roundTo))
profitLimitOffsetVal := "@" + str.tostring(math.round(side == "buy" ? (profitTrigger - (profitTrigger * (profitLimitOffset/100))) : (profitTrigger + (profitTrigger * (profitLimitOffset/100))),roundTo))
[profitTriggerVal, profitLimitOffsetVal]
// @function Generates Alertatron Order Management strings for 1) Entry, Take Profit, and Stop Loss, 2) Cancel Unfilled Entries, and 3) Trailing Stop
// @returns 1) array of order messages, 2) string for Canceling Unfilled Entries, and 3) string for Intiating the Trailing Stop
export getAlertatrongAlertMessages(string tag, string secret, string symbol, string baseCurrency, string pairDivider, string side, int symbolMaxDecimals, int leverage, string leverageType, float[] entryPrices, float[] entryAmounts, string entryAmountType, float[] profitTargets, string profitTargetType, float[] profitTargetAmounts, float stopTrigger, string stopTriggerType, float stopLimitOffset, float trailingStopTrigger, string trailingStopTriggerType, float trailingStopLimitOffset) =>
// Global Variables
closeSide = side == "buy" ? "sell" : "buy"
initializeOrder = secret + "(" + symbol + pairDivider + baseCurrency + ") {" + "\n"
messageEnd = "} #bot"
// Entry, Take Profit, and Stop Loss
entryPricesFormatted = getEntryPrices(array=entryPrices, roundTo=symbolMaxDecimals)
profitTargetsFormatted = getProfitTargets(array=profitTargets, type=profitTargetType, roundTo=symbolMaxDecimals)
profitTargetAmountsFormatted = getProfitTargetAmounts(array=profitTargetAmounts, roundTo=symbolMaxDecimals)
[stopTriggerFormatted, stopTriggerOffestFormatted] = getStop(closeSide, stopTriggerType, stopTrigger, stopLimitOffset, roundTo=symbolMaxDecimals)
settingsLeverageType = "exchangeSettings(leverage=" + str.lower(leverageType) + ");" + "\n"
settingsLeverageAmount = "exchangeSettings(leverage=" + str.tostring(leverage) + "); " + "\n"
entryOrders = array.new_string(0)
for i = 0 to array.size(entryPricesFormatted) - 1 by 1
waitingLimit = "waitingLimit(side=" + side + ", amount=" + getEntryQuantity(entryAmount=array.get(entryAmounts,i), type=entryAmountType, price=array.get(entryPrices,i), leverage=leverage, roundTo=symbolMaxDecimals) + ", offset=@" + array.get(entryPricesFormatted,i) + ", tag=" + tag + "-entry);" + "\n"
profitTargets = ""
for x = 0 to array.size(profitTargetsFormatted) - 1 by 1
profitTarget = "limit(side=" + closeSide + ", amount=" + array.get(profitTargetAmountsFormatted,x) + ", offset=" + array.get(profitTargetsFormatted,x) + ", reduceOnly=true, tag=" + tag + ");" + "\n"
profitTargets += profitTarget
stopOrder = "stopOrder(side=" + closeSide + ", amount=100%p, offset=" + stopTriggerFormatted + ", limitOffset=" + stopTriggerOffestFormatted + ", trigger=last, reduceOnly=true, tag=" + tag + ");" + "\n"
entryOrder = initializeOrder + settingsLeverageType + settingsLeverageAmount + waitingLimit + profitTargets + stopOrder + messageEnd
array.push(entryOrders, entryOrder)
// Cancel Unfilled Entries
cancelUnfilledEntries = "cancel(which=tagged, tag=" + tag + "-entry);" + "\n"
cancelEverythingElse = "cancel(which=tagged, tag=" + tag + ");" + "\n"
cancelEntriesMessage = initializeOrder + cancelUnfilledEntries + messageEnd
// Trailing Stop
[trailingStopTriggerFormatted, trailingStopTriggerOffestFormatted] = getStop(side=closeSide, stopTriggerType=trailingStopTriggerType, stopTrigger=trailingStopTrigger, stopLimitOffset=trailingStopLimitOffset, roundTo=symbolMaxDecimals)
trailingStop = "trailingStop(side=" + closeSide + ", amount=100%p, offset=" + trailingStopTriggerFormatted + ", limitOffset=" + trailingStopTriggerOffestFormatted + ", trigger=last, trailingMethod=continuous, reduceOnly=true, tag=" + tag + ");" + "\n"
trailingStopMessage = initializeOrder + cancelUnfilledEntries + cancelEverythingElse + trailingStop + messageEnd
[entryOrders, cancelEntriesMessage, trailingStopMessage]
// @function Generates Alertatron alert message for a market entry
// @returns string of instructions for Alertatron to market enter
export getAlertatronMarketEntryMessage(string strategyKey, string secret, string symbol, string baseCurrency, string pairDivider, string side, int symbolMaxDecimals, int leverage, string leverageType, float entryPrice, float amount, string amountType, float stopTrigger, string stopTriggerType, float stopLimitOffset) =>
closeSide = side == "buy" ? "sell" : "buy"
qty = getEntryQuantity(entryAmount=amount, type=amountType, leverage=leverage, price=entryPrice, roundTo=symbolMaxDecimals)
[stopTriggerFormatted, stopTriggerOffestFormatted] = getStop(closeSide, stopTriggerType, stopTrigger, stopLimitOffset, roundTo=symbolMaxDecimals)
tradePair = symbol + pairDivider + baseCurrency
initializeOrder = secret + "(" + tradePair + ") {" + "\n"
settingsLeverageType = "exchangeSettings(leverage=" + str.lower(leverageType) + ");" + "\n"
settingsLeverageAmount = "exchangeSettings(leverage=" + str.tostring(leverage) + "); " + "\n"
cancelExistingOrders = "cancel(which=tagged, tag=" + tradePair + ");" + "\n"
market = "market(side=" + side + ", amount=" + qty + ", tag=" + strategyKey + "/" + tradePair + ");" + "\n"
stopOrder = "stopOrder(side=" + closeSide + ", amount=100%p, offset=" + stopTriggerFormatted + ", limitOffset=" + stopTriggerOffestFormatted + ", trigger=last, reduceOnly=true);" + "\n"
messageEnd = "} #bot"
marketEntryMessage = initializeOrder + settingsLeverageType + settingsLeverageAmount + cancelExistingOrders + market + stopOrder + messageEnd
// @function Generates Alertatron alert message for a market entry with a stop loss and profit target
// @returns string of instructions for Alertatron to create an OCO order
export getAlertatronOcoMessage(string secret, string symbol, string baseCurrency, string pairDivider, string side, int symbolMaxDecimals, int leverage, string leverageType, float entryPrice, float amount, string amountType, float stopTrigger, string stopTriggerType, float stopLimitOffset, float profitTrigger, string profitTriggerType, float profitLimitOffset) =>
closeSide = side == "buy" ? "sell" : "buy"
qty = getEntryQuantity(entryAmount=amount, type=amountType, leverage=leverage, price=entryPrice, roundTo=symbolMaxDecimals)
[stopTriggerFormatted, stopTriggerOffestFormatted] = getStop(closeSide, stopTriggerType, stopTrigger, stopLimitOffset, roundTo=symbolMaxDecimals)
[profitTargetFormatted, profitTriggerOffsetFormatted] = getProfit(closeSide, profitTriggerType, profitTrigger, profitLimitOffset, roundTo=symbolMaxDecimals)
tradePair = symbol + pairDivider + baseCurrency
initializeOrder = secret + "(" + tradePair + ") {" + "\n"
settingsLeverageType = "exchangeSettings(leverage=" + str.lower(leverageType) + ");" + "\n"
settingsLeverageAmount = "exchangeSettings(leverage=" + str.tostring(leverage) + "); " + "\n"
cancelExistingOrders = "cancel(which=tagged, tag=" + tradePair + ");" + "\n"
market = "market(side=" + side + ", amount=" + qty + ", tag=" + tradePair + ");" + "\n"
stopOrder = "stopOrder(side=" + closeSide + ", amount=100%p, offset=" + stopTriggerFormatted + ", limitOffset=" + stopTriggerOffestFormatted + ", trigger=last, reduceOnly=true);" + "\n"
profitOrder = "stopOrder(side=" + closeSide + ", amount=100%p, offset=" + profitTargetFormatted + ", limitOffset=" + profitTriggerOffsetFormatted + ", trigger=last, reduceOnly=true);" + "\n"
messageEnd = "} #bot"
marketEntryMessage = initializeOrder + settingsLeverageType + settingsLeverageAmount + cancelExistingOrders + market + stopOrder + profitOrder + messageEnd
// @function Generates Alertatron alert message for a market exit
// @returns string of instructions for Alertatron to market close a position
export getAlertatronMarketExitMessage(string strategyKey, string secret, string symbol, string baseCurrency, string pairDivider, string side) =>
tradePair = symbol + pairDivider + baseCurrency
initializeOrder = secret + "(" + tradePair + ") {" + "\n"
cancelExistingOrders = "cancel(which=tagged, tag=" + strategyKey + "/" + tradePair + ");" + "\n"
market = "market(side=" + side + ", amount=100%p, reduceOnly=true);" + "\n"
messageEnd = "} #bot"
marketExitMessage = initializeOrder + cancelExistingOrders + market + messageEnd
// @function Generates Alertatron alert message for to market exit a percentage of an open position
// @returns string of instructions for Alertatron to market close a a percentage of an open position
export getAlertatronAlertMessageMarketClosePercentOfPosition(string secret, string symbol, string baseCurrency, string pairDivider, int percent, string side) =>
initializeOrder = secret + "(" + symbol + pairDivider + baseCurrency + ") {" + "\n"
cancelExistingOrders = "cancel(which=all);" + "\n"
market = "market(side=" + side + ", amount=" + str.tostring(percent) + "%p, reduceOnly=true);" + "\n"
messageEnd = "} #bot"
marketExitMessage = initializeOrder + cancelExistingOrders + market + messageEnd
// @function Converts a timeframe into a pretty string
// @returns string representation of timeframe
export convertTimeframeToString(string timeframe) =>
string timeToConvert = na
if timeframe == timeframe.period
timeToConvert := timeframe.period
else
timeToConvert := timeframe
printTime = switch timeToConvert
"1" => "1m"
"3" => "3m"
"5" => "5m"
"15" => "15m"
"30" => "30m"
"45" => "45m"
"60" => "1h"
"120" => "2h"
"180" => "3h"
"240" => "4h"
"720" => "12h"
"1D" => "1D"
"3D" => "3D"
"1W" => "1W"
"1M" => "1M"
"6M" => "6M"
printTime
|
loxxrsx | https://www.tradingview.com/script/us2myKcI-loxxrsx/ | 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 TODO: add library description here
library("loxxrsx", overlay = false)
// @function rsx
// @param src float
// @param len int
// @returns result float
export rsx(float src, int len)=>
src_out = 100 * src
mom0 = ta.change(src_out)
moa0 = math.abs(mom0)
Kg = 3 / (len + 2.0)
Hg = 1 - Kg
//mom
f28 = 0.0, f30 = 0.0
f28 := Kg * mom0 + Hg * nz(f28[1])
f30 := Hg * nz(f30[1]) + Kg * f28
mom1 = f28 * 1.5 - f30 * 0.5
f38 = 0.0, f40 = 0.0
f38 := Hg * nz(f38[1]) + Kg * mom1
f40 := Kg * f38 + Hg * nz(f40[1])
mom2 = f38 * 1.5 - f40 * 0.5
f48 = 0.0, f50 = 0.0
f48 := Hg * nz(f48[1]) + Kg * mom2
f50 := Kg * f48 + Hg * nz(f50[1])
mom_out = f48 * 1.5 - f50 * 0.5
//moa
f58 = 0.0, f60 = 0.0
f58 := Hg * nz(f58[1]) + Kg * moa0
f60 := Kg * f58 + Hg * nz(f60[1])
moa1 = f58 * 1.5 - f60 * 0.5
f68 = 0.0, f70 = 0.0
f68 := Hg * nz(f68[1]) + Kg * moa1
f70 := Kg * f68 + Hg * nz(f70[1])
moa2 = f68 * 1.5 - f70 * 0.5
f78 = 0.0, f80 = 0.0
f78 := Hg * nz(f78[1]) + Kg * moa2
f80 := Kg * f78 + Hg * nz(f80[1])
moa_out = f78 * 1.5 - f80 * 0.5
rsiout = math.max(math.min((mom_out / moa_out + 1.0) * 50.0, 100.00), 0.00)
rsiout
//example usage
out = rsx(close, 30)
plot(out) |
McNichollBands | https://www.tradingview.com/script/gpZTk9RM/ | EduardoMattje | https://www.tradingview.com/u/EduardoMattje/ | 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/
// © EduardoMattje
//@version=5
// @description This is a library which only functions to make the McNicholl's Bollinger Bands modifications. It's also my first library, so I'll probably screw some things up.
// I know that global variables are evil, but damn, do I want to use them. Maybe I could do a "gambiarra", but I'll be a good boy and do the right thing. For now.
library("McNichollBands")
calcEMA(float alpha, float modifier) =>
var lastValue = 0.0
newValue = alpha * modifier + (1 - alpha) * lastValue
lastValue := newValue
newValue
expIfLog(bool useLogScale, float value) =>
if useLogScale
math.exp(value)
else
value
calcBand(bool useLogScale, float centerLine, float widthMultiplier, float bCenterLine, int sign) =>
band = centerLine + widthMultiplier * bCenterLine * sign
expIfLog(useLogScale, band)
calcCenterLine(float alpha, float m, float u) =>
((2 - alpha) * m - u) /
(1 - alpha)
// @function Calculates the McNicholl's Bollinger Bands modifications.
// @param alpha The alpha constant to be used on the EMA calculations.
// @param useLogScale Whether to use the log version of the prices or not.
// @param widthMultiplier The number that shall be multiplied by the volatility to form the bands.
// @returns A tuple containing the lower band, the center line, and the upper band.
export mcNichollBands(float alpha, float widthMultiplier, bool useLogScale) =>
// Getting the right close
rClose = useLogScale ? math.log(close) : close
// Getting the bands
M = calcEMA(alpha, rClose)
U = calcEMA(alpha, M)
centerLine = calcCenterLine(alpha, M, U)
bM = calcEMA(alpha, math.abs(rClose - M))
bU = calcEMA(alpha, bM)
bCenterLine = calcCenterLine(alpha, bM, bU)
upperBand = calcBand(useLogScale, centerLine, widthMultiplier, bCenterLine, 1)
lowerBand = calcBand(useLogScale, centerLine, widthMultiplier, bCenterLine, -1)
centerLineLog = expIfLog(useLogScale, centerLine)
// Returning
[lowerBand, centerLineLog, upperBand]
|
FunctionArrayUnique | https://www.tradingview.com/script/PN1mL4cK-FunctionArrayUnique/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 27 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Method for retrieving the unique elements in a array.
// for example [1, 2, 1, 1, 2] would retrieve a array with [1, 2],
// the elements retrieved will be sorted by its first seen index in
// parent array.
// note: float values have no precision option.
library("FunctionArrayUnique")
// Helper method for the unique() function
_unique (a) => //{
int _size = array.size(a)
if _size > 0
_dict = array.from(array.get(a, 0)) // type detection
for _i = 1 to _size-1
_value = array.get(a, _i)
if array.indexof(_dict, _value) < 0
array.push(_dict, _value)
_dict
else
runtime.error('array must have atleast one element.')
array.copy(a)
//}
// @function method for retrieving the unique elements in a array.
// @param source array<float> source array to extract elements.
// @returns array<float> unique elements in the source array.
export unique (array<float> source) => _unique(source)
// @function method for retrieving the unique elements in a array.
// @param source array<int> source array to extract elements.
// @returns array<int> unique elements in the source array.
export unique (array<int> source) => _unique(source)
// @function method for retrieving the unique elements in a array.
// @param source array<string> source array to extract elements.
// @returns array<string> unique elements in the source array.
export unique (array<string> source) => _unique(source)
import RicardoSantos/DebugConsole/8 as console
a0 = array.from(1,2,3,1,3,5,4,1,2,4,-1,-0,1,-6,99999)
a1 = array.from('a', 'b', 'a', 'c', 'b')
b0 = str.tostring(unique(a0))
b1 = str.tostring(unique(a1))
console.log(bar_index%2==0?b0:b1) |
DeleteArrayObject | https://www.tradingview.com/script/dhx2QoYA-DeleteArrayObject/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description TODO: Delete array object according to array size
library('DeleteArrayObject')
// 0. Delete array label[]
// 1. Delete array line[]
// 2. Delete array linefill[]
// 3. Delete array box[]
// 4. Delete array table[]
// 5. Examples
// ————————————————————————————————————————————————————————————————————————————— 0. Delete array label[] {
export delete(simple label[] _id) =>
for x = 0 to array.size(_id) - 1
label.delete(array.get(_id, x))
// }
// ————————————————————————————————————————————————————————————————————————————— 1. Delete array line[] {
export delete(simple line[] _id) =>
for x = 0 to array.size(_id) - 1
line.delete(array.get(_id, x))
// }
// ————————————————————————————————————————————————————————————————————————————— 2. Delete array linefill[] {
export delete(simple linefill[]_id) =>
for x = 0 to array.size(_id) - 1
linefill.delete(array.get(_id, x))
// }
// ————————————————————————————————————————————————————————————————————————————— 3. Delete array box[] {
export delete(simple box[] _id) =>
for x = 0 to array.size(_id) - 1
box.delete(array.get(_id, x))
// }
// ————————————————————————————————————————————————————————————————————————————— 4. Delete array table[] {
export delete(simple table[] _id) =>
for x = 0 to array.size(_id) - 1
table.delete(array.get(_id, x))
// }
// ————————————————————————————————————————————————————————————————————————————— 5. Examples {
var array_label = array.new_label(6), delete(array_label)
var array_line = array.new_line(6), delete(array_line)
var array_linefill = array.new_linefill(5), delete(array_linefill)
var array_box = array.new_box(4), delete(array_box)
var array_table = array.new_table(4), delete(array_table)
// } |
Heikin Ashi Candles | https://www.tradingview.com/script/jnUA4DB8-Heikin-Ashi-Candles/ | layth7ussein | https://www.tradingview.com/u/layth7ussein/ | 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/
// © layth7ussein
//@version=5
library("heikin_ashi_candles")
export _close() =>
1.01*(open+close+high+low)/4.01
export _open() =>
(open[1]+close[1])/2
export _high() =>
math.max(high, _close(), _open())
export _low() =>
math.min(low, _close(), _open())
export _ohlc4() =>
(_close()+_open()+_high()+_low())/4
export _hlcc4() =>
(2*_close()+_high()+_low())/4
export _hlc3() =>
(_close()+_high()+_low())/3
export _hl2() =>
(_high()+_low())/2
plotcandle(_open(), _high(), _low(), _close(), color= _open()>_close() ? color.red : color.green) |
HarmonicDB | https://www.tradingview.com/script/pyxi0Oes-HarmonicDB/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description TODO: Database of Harmonic Pattern Specifications
library('HarmonicDB', overlay = true)
// 0. animal_db
// 1. example
// ————————————————————————————————————————————————————————————————————————————— 0. animal_db {
// @function TODO: export animal_db
// @param x TODO: float value is set to default if not necessary
// @returns TODO: [animal_name, spec_B_XA_min, spec_B_XA_max, spec_C_AB_min, spec_C_AB_max, spec_D_BC_min, spec_D_BC_max, spec_D_XA_nom, spec_E_SL_nom]
export animal_db(float prz_crab = 1.618, float prz_gart = 0.786, float prz_shark = 0.886) =>
p0 = math.round(math.rphi, 3)
p1 = math.round(math.phi, 3)
p2 = p0 + 2
p3 = p0 + 3
[bc1_gart, bc2_gart, sl_gart] = switch prz_gart
// Output => bc1_gart, bc2_gart, sl_gart
.786 => [ 1.13 , p1, 1. ]
.886 => [ p1, p2, 1.13]
float sl_shark = switch prz_shark
0.886 => 1.13
1.130 => 1.27
// Credits to Scott M Carney, author of Harmonic Trading : Volume Three
// Page 101, 98, 104, 92, 113, 107, 119 - 220
// Index 0 1 2 3 4 5 6
animal_name = array.from('ALT BAT', 'BAT', 'CRAB', 'GARTLEY', 'BUTTERFLY', 'DEEP CRAB', 'SHARK')
spec_B_XA_min = array.from( .371, .382, .382, .599, .762, .886, .382) // B = XA ==|=> Trade Identification
spec_B_XA_max = array.from( .382, .5 , p0, .637, .81 , .93 , p0) // |
spec_C_AB_min = array.from( .382, .382, .382, .382, .382, .382, 1.13 ) // C = AB |
spec_C_AB_max = array.from( .886, .886, .886, .886, .886, .886, p1) // ==|
spec_D_BC_min = array.from( 2. , p1, p2, bc1_gart, p1, 2. , p1) // D = BC ==|=> Trade Execution - PRZ (Potential Reversal Zone)
spec_D_BC_max = array.from( p3, p2, p3, bc2_gart, 2.24 , p3, 2.24 ) // |
spec_D_XA_nom = array.from( 1.13 , .886, prz_crab, prz_gart, 1.27 , prz_crab, prz_shark) // D = XA ==|
spec_E_SL_nom = array.from( 1.27 , 1.13 , 2. , sl_gart, 1.414, 2. , sl_shark) // Stop Loss => Trade Management (Page 174)
[animal_name, spec_B_XA_min, spec_B_XA_max, spec_C_AB_min, spec_C_AB_max, spec_D_BC_min, spec_D_BC_max, spec_D_XA_nom, spec_E_SL_nom]
// }
// ————————————————————————————————————————————————————————————————————————————— 1. example {
T0 = 'Small font size recommended for mobile app or multiple layout'
i_s_font = input.string('large', 'Font size', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T0)
[animal_name, spec_B_XA_min, spec_B_XA_max, spec_C_AB_min, spec_C_AB_max, spec_D_BC_min, spec_D_BC_max, spec_D_XA_nom, spec_E_SL_nom] = animal_db()
var testTable = table.new(position.middle_center, 10, 10, bgcolor = color.white, border_color = color.black, border_width = 1)
if barstate.islast
table.cell(testTable, 0, 0, 'ANIMAL', text_size = i_s_font), table.merge_cells(testTable, 0, 0, 0, 1)
table.cell(testTable, 1, 0, 'B = XA', text_size = i_s_font), table.merge_cells(testTable, 1, 0, 2, 0)
table.cell(testTable, 1, 1, 'MIN', text_size = i_s_font)
table.cell(testTable, 2, 1, ' MAX', text_size = i_s_font)
table.cell(testTable, 3, 0, 'C = AB', text_size = i_s_font), table.merge_cells(testTable, 3, 0, 4, 0)
table.cell(testTable, 3, 1, 'MIN', text_size = i_s_font)
table.cell(testTable, 4, 1, 'MAX', text_size = i_s_font)
table.cell(testTable, 5, 0, 'D = BC', text_size = i_s_font), table.merge_cells(testTable, 5, 0, 6, 0)
table.cell(testTable, 5, 1, 'MIN', text_size = i_s_font)
table.cell(testTable, 6, 1, 'MAX', text_size = i_s_font)
table.cell(testTable, 7, 0, 'D = XA', text_size = i_s_font), table.merge_cells(testTable, 7, 0, 7, 1)
table.cell(testTable, 8, 0, 'SL = XA', text_size = i_s_font), table.merge_cells(testTable, 8, 0, 8, 1)
for x = 0 to 6
table.cell(testTable, 0, x + 2, array.get(animal_name, x), bgcolor = array.get(spec_D_XA_nom, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 1, x + 2, str.tostring(array.get(spec_B_XA_min, x), '0.000'), bgcolor = array.get(spec_B_XA_min, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 2, x + 2, str.tostring(array.get(spec_B_XA_max, x), '0.000'), bgcolor = array.get(spec_B_XA_max, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 3, x + 2, str.tostring(array.get(spec_C_AB_min, x), '0.000'), bgcolor = array.get(spec_C_AB_min, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 4, x + 2, str.tostring(array.get(spec_C_AB_max, x), '0.000'), bgcolor = array.get(spec_C_AB_max, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 5, x + 2, str.tostring(array.get(spec_D_BC_min, x), '0.000'), bgcolor = array.get(spec_D_BC_min, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 6, x + 2, str.tostring(array.get(spec_D_BC_max, x), '0.000'), bgcolor = array.get(spec_D_BC_max, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 7, x + 2, str.tostring(array.get(spec_D_XA_nom, x), '0.000'), bgcolor = array.get(spec_D_XA_nom, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
table.cell(testTable, 8, x + 2, str.tostring(array.get(spec_E_SL_nom, x), '0.000'), bgcolor = array.get(spec_E_SL_nom, x) <= 1 ? color.red : color.blue, text_size = i_s_font)
// } |
HarmonicCalculation | https://www.tradingview.com/script/j8t5IkYF-HarmonicCalculation/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description TODO: library for HarmonicCalculation
library('HarmonicCalculation')
// 0. PriceDiff
// 1. TimeDiff
// 2. ReturnIndexOf3Arrays
// 3. AbsoluteRange
// 4. PriceAverage
// 5. TimeAverage
// 6. StringBool
// 7. PricePercent
// 8. BoolCurrency
// 9. RatioText
// 10. RangeText
// 11. PriceCurrency
// ————————————————————————————————————————————————————————————————————————————— 0. PriceDiff {
// @function : Price Difference
// @param : price_1, price_2
// @returns : PriceDiff
export PriceDiff(float price_1, float price_2) =>
price_1 - price_2
// }
// ————————————————————————————————————————————————————————————————————————————— 1. TimeDiff {
// @function : Time Difference
// @param : time_1, time_2
// @returns : TimeDiff
export TimeDiff(int time_1, int time_2) =>
time_1 - time_2
// }
// ————————————————————————————————————————————————————————————————————————————— 2. ReturnIndexOf3Arrays {
// @function : Return Index Of 3 Arrays
// @param : id1, id2, id3, _int
// @returns : ReturnIndexOf3Arrays
export ReturnIndexOf3Arrays(simple float[] id1, simple float[] id2, simple float[] id3, int _int) =>
a = array.get(id1, _int)
b = array.get(id2, _int)
c = array.get(id3, _int)
[a, b, c]
// }
// ————————————————————————————————————————————————————————————————————————————— 3. AbsoluteRange {
// @function : Price Difference
// @param : price, y, point
// @returns : AbsoluteRange
export AbsoluteRange(float price, float y, float point) =>
math.abs(price - (y * point))
// }
// ————————————————————————————————————————————————————————————————————————————— 4. PriceAverage {
// @function : To calculate average of 2 prices
// @param : price_1, price_2
// @returns : PriceAverage
export PriceAverage(float price_1, float price_2) =>
math.avg(price_1, price_2)
// }
// ————————————————————————————————————————————————————————————————————————————— 5. TimeAverage {
// @function : To calculate average of 2 times
// @param : time_1, time_2
// @returns : TimeAverage
export TimeAverage( int time_1, int time_2) =>
int(math.avg( time_1, time_2))
// }
// ————————————————————————————————————————————————————————————————————————————— 6. StringBool {
// @function : To show ratio in 3 decimals format
// @param : _value, _bool, _text
// @returns : StringBool
export StringBool(float _value, bool _bool = false, string _text = '') =>
if _bool
string str = ' ' + _text
str.tostring(_value, '0.000') + str
else
str.tostring(_value, '0.000')
// }
// ————————————————————————————————————————————————————————————————————————————— 7. PricePercent {
// @function : To show Price in percent format
// @param : _price, PriceRef, str_dir
// @returns : PricePercent
export PricePercent(float _price, float PriceRef, string str_dir) =>
string percent = na
bear_bool = ( _price - PriceRef) / PriceRef > 0 ? ' ▼' : ( _price - PriceRef) / PriceRef > 0 ? ' ▲' : ''
bull_bool = -(PriceRef - _price) / PriceRef > 0 ? ' ▲' : -(PriceRef - _price) / PriceRef < 0 ? ' ▼' : ''
if str_dir == 'BEARISH'
percent := str.tostring( ( _price - PriceRef) / PriceRef, '##.## %') + bear_bool
else
percent := str.tostring(-(PriceRef - _price) / PriceRef, '##.## %') + bull_bool
percent
// }
// ————————————————————————————————————————————————————————————————————————————— 8. BoolCurrency {
// @function : To show syminfo.currency
// @param : _bool
// @returns : BoolCurrency
export BoolCurrency(bool _bool) =>
currency = switch _bool
true => syminfo.currency + ' '
=> ''
currency
// }
// ————————————————————————————————————————————————————————————————————————————— 9. RatioText {
// @function : To show RatioText in 3 decimals format
// @param : _value, _text
// @returns : RatioText
export RatioText(float _value, string _text) =>
str.tostring(math.abs(_value), '0.000 ') + _text
// }
// ————————————————————————————————————————————————————————————————————————————— 10. RangeText {
// @function : To display RangeText in Harmonic Range Format
// @param : _id1, _id2, _int, _text
// @returns : RangeText
export RangeText(simple float[] _id1, simple float[] _id2, int _int, string _text) =>
RatioText(array.get(_id1, _int), '; ') + RatioText(array.get(_id2, _int), _text)
// }
// ————————————————————————————————————————————————————————————————————————————— 11. PriceCurrency {
// @function : To show Currency in Price Format
// @param : _bool, _value
// @returns : PriceCurrency
export PriceCurrency(bool _bool, float _value) =>
BoolCurrency(_bool) + str.tostring(math.abs(_value), '0.000')
// } |
srcCalc | https://www.tradingview.com/script/8XUiFDY1-srcCalc/ | LamboLimbo | https://www.tradingview.com/u/LamboLimbo/ | 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/
// © LamboLimbo
//@version=5
// @description Provides functions for converting input strings 'open','high','low','close','hl2','hlc3','ohlc4','hlcc4' to corresponding source values.
library("srcCalc")
src1_str = input.string('high', 'Source 1', options=['open', 'high', 'low', 'close', 'hl2', 'hlc3', 'ohlc4', 'hlcc4'])
src2_str = input.string('low', 'Source 2', options=['open', 'high', 'low', 'close', 'hl2', 'hlc3', 'ohlc4', 'hlcc4'])
ext_src = input.source(close, 'External Source')
ext_long_op = input.string('>', 'Operator', options=['>','>=','==','<=','<','!='], group='Ext Src Long Condition', inline='l2')
ext_long_val = input.float(0, 'Value', group='Ext Src Long Condition', inline='l2')
ext_short_op = input.string('<', 'Operator', options=['>','>=','==','<=','<','!='], group='Ext Src Short Condition', inline='l3')
ext_short_val = input.float(0, 'Value', group='Ext Src Short Condition', inline='l3')
// @function Converts string to source float value
// @param src String to use (`close` is used if no argument is supplied).
// @returns Returns the float value of the string
export get_src(string src='close') =>
switch src
'open' => open
'high' => high
'low' => low
'close' => close
'hl2' => hl2
'hlc3' => hlc3
'ohlc4' => ohlc4
'hlcc4' => hlcc4
'' => na
// @function Evaluates a conditional expression of 2 values given a string of the conditional operator.
// @param op Conditional operator string to use. (options: '>','>=','==','<=','<','!=')(default: '==')
// @param left_val Left value of expression. (default: float 0.0)
// @param right_val Right value of expression. (default: float 0.0)
// @returns Returns the boolean value of conditional expression
export return_bool(string op='==', float left_val=0.0, float right_val=0.0) =>
switch op
'>' => left_val > right_val
'>=' => left_val >= right_val
'==' => left_val == right_val
'<=' => left_val <= right_val
'<' => left_val < right_val
'!=' => left_val != right_val
'' => na
src1 = get_src(src1_str)
src2 = get_src(src2_str)
ext_longCond = return_bool(ext_long_op, ext_src, ext_long_val)
ext_shortCond = return_bool(ext_short_op, ext_src, ext_short_val)
plot(src1, 'source 1: input', color.red)
plot(src2, 'source 2: input', color.maroon)
bgcolor(ext_longCond ? color.new(color.green,90) : ext_shortCond ? color.new(color.red,90) : na)
// debugging to data window
plotchar(ext_src, 'ext src: input', '')
plotchar(ext_longCond, 'ext_longCond','')
plotchar(ext_shortCond, 'ext_shortCond','') |
xor logical operator | https://www.tradingview.com/script/76H016CG/ | TheSocialCryptoClub | https://www.tradingview.com/u/TheSocialCryptoClub/ | 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/
// © TheSocialCryptoClub
//@version=5
// @description: this library provides xor logical operator to Pine Script
library("xor")
// @function xor: Exclusive or, or exclusive disjunction is a logical operation that is true if and only if its arguments differ (one is true, the other is false).
// @param a first argument
// @param b second argument
// @returns returns xor (true only if a and b are true, but not both)
export xor(bool a, bool b) =>
(a and not b) or (not a and b)
|
CommonMarkup | https://www.tradingview.com/script/X3r6W8fY-CommonMarkup/ | foosmoo | https://www.tradingview.com/u/foosmoo/ | 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/
// © foosmoo
//@version=5
// @description Provides functions for chart markup, such as indicating recession bands.
library("CommonMarkup")
markRecessionBands(string title, int start, int end, float y) =>
if (time >= start and time <= end)
var line0a = line.new(start, 0, start, 0, xloc=xloc.bar_time, color = color.new(color.gray, 35), width = 2, extend = extend.both, style=line.style_dotted)
var line0b = line.new(end, 0, end, 0, xloc=xloc.bar_time, color = color.new(color.gray, 35), width = 2, extend = extend.both, style=line.style_dotted)
var l0 = label.new(end, y, xloc = xloc.bar_time, text = title, textalign = text.align_left, size=size.small, color = color.orange, style = label.style_label_left, tooltip = title)
// @function Mark vertical bands and show recession band labels if argument showBands is true. Example "markRecessionBands(bar_index[0],3.0"
// @param showBands - show vertical recession bands when true. Functionally equiv to no op when false
// @param twoQrtsOfNegativeGDPIsRecession - if true, then periods with two consecutive quarters of negative GDP is considered a recession. Defaut is false.
// @param labelY - y-axis value for label positioning
// @return true - always answers the value of showBands
export markRecessionBands(bool showBands, bool twoQrtsOfNegativeGDPIsRecession, float labelY) =>
if showBands
// 2001 recession band
var r0s = timestamp("UTC", 2001, 1, 1, 00, 00, 00)
var r0e = timestamp("UTC", 2001, 6, 30, 23, 59, 59)
if (time >= r0s and time <= r0e)
markRecessionBands("2001", r0s, r0e, labelY)
// 2009 recession band
var r1s = timestamp("UTC", 2008, 1, 1, 00, 00, 00)
var r1e = timestamp("UTC", 2009, 6, 30, 23, 59, 59)
if (time >= r1s and time <= r1e)
markRecessionBands("2009", r1s, r1e, labelY)
// 2020 recession band. -5.1 Q1, -31.2, Q2
var r2s = timestamp("UTC", 2020, 1, 1, 00, 00, 00)
var r2e = timestamp("UTC", 2020, 6, 30, 23, 59, 59)
if (time >= r2s and time <= r2e)
markRecessionBands("2020", r2s, r2e, labelY)
// 2022 recession band. -1.6 Q1, -0.9 Q2
var r3s = timestamp("UTC", 2022, 1, 1, 00, 00, 00)
var r3e = timestamp("UCT", 2022, 6, 30, 23, 59, 59)
if (twoQrtsOfNegativeGDPIsRecession and time >= r3s and time <= r3e)
markRecessionBands("2022", r3s, r3e, labelY)
showBands
|
Object: object oriented programming made possible! | https://www.tradingview.com/script/uQNIj9rc-Object-object-oriented-programming-made-possible/ | NeoDaNomad | https://www.tradingview.com/u/NeoDaNomad/ | 22 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NeoDaNomad
//@version=5
library("Object",overlay=true)
//flags
//collision flag comes before type flags
string f_collision = "C!"
string f_string = "S."
string f_float = "F."
string f_bool = "B."
string f_int = "I."
//separators
string keyVal = ":"
string comma = ","
string undr = "_"
string clsn = "|"
//format properties so that data can be output in the same type it as input (not a string you would have to convert)
export prop_string(string key, string val)=>
//string flag added
key+keyVal+f_string+val
export prop_float(string key, float val)=>
//float flag added
key+keyVal+f_float+str.tostring(val)
export prop_bool(string key, bool val)=>
//bool flag added
key+keyVal+f_bool+str.tostring(val)
export prop_int(string key, int val)=>
//int flag added
key+keyVal+f_int+str.tostring(val)
//only intended for use by Object methods but it's here
export ___HASH(string[] tableID, string str, bool isKeyVal)=>
//all hash table state kept at index 0, cannont be overwritten
string[] state = str.split(array.get(tableID,0),undr)
//predetermined table sizes for consistent scaling
string primeSequence = array.get(state,0)
//the current index corresponding to the table size
int currPrimeIndex = int(str.tonumber(array.get(state,1)))
//the next table size in the prime sequence
float nextPrime = str.tonumber(array.get(str.split(primeSequence, comma), currPrimeIndex + 1))
//actual table size
int tableSize=array.size(tableID)
//used to calculate load factor
string bucketsUsed = array.get(state,2)
int entries = str.length(bucketsUsed) > 1 ? array.size(str.split(bucketsUsed, comma)) : 1
int buckets = int(str.tonumber(array.get(str.split(primeSequence, comma),currPrimeIndex)))
float loadFactor = entries/buckets
// hash init
int hash=7
//checks for correct key:val format, if just a key is necessary, throws error if format isn't correct
string key = ""
string[] keyIterator = array.new_string()
string val = ""
if isKeyVal == true and str.contains(str,keyVal)
key := array.get(str.split(str,keyVal),0)
keyIterator := str.split(key,"")
val := array.get(str.split(str,keyVal),1)
else if isKeyVal == false
key := str
keyIterator := str.split(key,"")
else
runtime.error("string must contain key:value pair separated by ':'!")
// resizes hash table if load factor reaches threshold
if loadFactor > 0.67
while tableSize < nextPrime
array.push(tableID, na)
//updates state for resized hash table
array.set(tableID,0,primeSequence+undr+str.tostring(currPrimeIndex + 1)+undr+bucketsUsed)
for char in keyIterator
charset_str = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
chars = str.split(charset_str, "")
code_base = 32
i = array.indexof(chars, char)
code = i >= 0 ? code_base + i : na
//hash initialized as a static prime number, then multiplied by the char code for each character in the "key" string
hash := hash * code
//applies constraints: hash < tableSize & hash > 0 (state is stored at index 0)
hash := hash % tableSize == tableSize - 1 ? hash % tableSize : hash % tableSize + 1
h = str.tostring(hash)
[_h,_k,_val] = if isKeyVal == true
[h,key,val]
else
[h,na,na]
export new()=>
string primeSequence = "113,229,463,863,1733,3511,7103,9973"
string currPrimeIndex = "0"
string prime = array.get(str.split(primeSequence, comma), int(str.tonumber(currPrimeIndex)))
init = array.new_string(int(str.tonumber(prime)),na)
string bucketsUsed = "0"
string state = primeSequence+undr+currPrimeIndex+undr+bucketsUsed
array.set(init,0,state)
map = init
export set(string[] ID, string str)=>
string[] state = str.split(array.get(ID,0),undr)
string primeSequence = array.get(state,0)
string currPrimeIndex = array.get(state,1)
string bucketsUsed = array.get(state,2)
string newBuckets = ""
[hashString,key,val] = ___HASH(ID, str, true)
hash = int(str.tonumber(hashString))
// value currently stored at hash index (most likely na)
string val1 = array.get(ID, hash)
//checks for collision (more than one entry at same hash index)
if val1 != na
// checks if collision is the first instance
if str.match(val1, clsn) == na
array.set(ID, hash, f_collision+val1+clsn+key+keyVal+val)
//collision flag added if collision is the first instance
newBuckets := str.format("{{0},{1}{2}",bucketsUsed,f_collision,hash)
else
//if not the collision flag will already be present and collided entry will be chained to all other entries at hash index of table using "clsn" separator
array.set(ID, hash, val1+clsn+key+keyVal+val)
newBuckets := str.format("{{0},{1}{2}",bucketsUsed,f_collision,hash)
else
array.set(ID,hash,key+keyVal+val)
newBuckets := str.format("{0},{1}",bucketsUsed,hash)
array.set(ID, 0, primeSequence+undr+currPrimeIndex+undr+newBuckets)
export get_f(string[] ID, string key)=>
[hashString,_,__] = ___HASH(ID, key, false)
hash = int(str.tonumber(hashString))
//check for key in hash table
val = array.get(ID,hash)
props = array.new_string(0)
//init extraction variables
f_collision_split = array.new_string(0)
_prop = array.new_string(0)
vt = array.new_string(0)
shell = ""
v = ""
type = ""
_val = ""
_key = ""
if val == na
runtime.error(str.format("key: '{0}' is invalid! Check spelling and try again.", key))
//check for collision at hash index
else if str.startswith(val, f_collision)
f_collision_split := str.split(val, f_collision)
shell := array.get(f_collision_split,1)
props := str.split(shell,clsn)
else
array.push(props, val)
for property in props
_prop := str.split(property, keyVal)
_key := array.get(_prop, 0)
if key != _key
continue
v := array.get(_prop, 1)
vt := str.split(v, ".")
type := array.get(vt, 0)
_val := array.get(vt, 1)
break
//return original-typed value
switch
type == "B" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "f"))
type == "S" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "f"))
type == "I" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "f"))
res = str.tonumber(_val)
export get_s(string[] ID, string key)=>
[hashString,_,__] = ___HASH(ID, key, false)
hash = int(str.tonumber(hashString))
//check for key in hash table
val = array.get(ID,hash)
props = array.new_string(0)
//init extraction variables
f_collision_split = array.new_string(0)
_prop = array.new_string(0)
vt = array.new_string(0)
shell = ""
v = ""
type = ""
_val = ""
_key = ""
if val == na
runtime.error(str.format("key: '{0}' is invalid! Check spelling and try again.", key))
//check for collision at hash index
else if str.startswith(val, f_collision)
f_collision_split := str.split(val, f_collision)
shell := array.get(f_collision_split,1)
props := str.split(shell,clsn)
else
array.push(props, val)
for property in props
_prop := str.split(property, keyVal)
_key := array.get(_prop, 0)
if key != _key
continue
v := array.get(_prop, 1)
vt := str.split(v, ".")
type := array.get(vt, 0)
_val := array.get(vt, 1)
break
//return original-typed value
switch
type == "B" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "s"))
type == "F" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "s"))
type == "I" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "s"))
res = _val
export get_b(string[] ID, string key)=>
[hashString,_,__] = ___HASH(ID, key, false)
hash = int(str.tonumber(hashString))
//check for key in hash table
val = array.get(ID,hash)
props = array.new_string(0)
//init extraction variables
f_collision_split = array.new_string(0)
_prop = array.new_string(0)
vt = array.new_string(0)
shell = ""
v = ""
type = ""
_val = ""
_key = ""
if val == na
runtime.error(str.format("key: '{0}' is invalid! Check spelling and try again.", key))
//check for collision at hash index
else if str.startswith(val, f_collision)
f_collision_split := str.split(val, f_collision)
shell := array.get(f_collision_split,1)
props := str.split(shell,clsn)
else
array.push(props, val)
for property in props
_prop := str.split(property, keyVal)
_key := array.get(_prop, 0)
if key != _key
continue
v := array.get(_prop, 1)
vt := str.split(v, ".")
type := array.get(vt, 0)
_val := array.get(vt, 1)
break
//return original-typed value
switch
type == "S" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "b"))
type == "F" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "b"))
type == "I" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "b"))
res = _val == "true" ? true : false
export get_i(string[] ID, string key)=>
[hashString,_,__] = ___HASH(ID, key, false)
hash = int(str.tonumber(hashString))
//check for key in hash table
val = array.get(ID,hash)
props = array.new_string(0)
//init extraction variables
f_collision_split = array.new_string(0)
_prop = array.new_string(0)
vt = array.new_string(0)
shell = ""
v = ""
type = ""
_val = ""
_key = ""
if val == na
runtime.error(str.format("key: '{0}' is invalid! Check spelling and try again.", key))
//check for collision at hash index
else if str.startswith(val, f_collision)
f_collision_split := str.split(val, f_collision)
shell := array.get(f_collision_split,1)
props := str.split(shell,clsn)
else
array.push(props, val)
for property in props
_prop := str.split(property, keyVal)
_key := array.get(_prop, 0)
if key != _key
continue
v := array.get(_prop, 1)
vt := str.split(v, ".")
type := array.get(vt, 0)
_val := array.get(vt, 1)
break
//return original-typed value
switch
type == "S" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "i"))
type == "F" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "i"))
type == "B" => runtime.error(str.format("Wrong get method! expecting get_{0}, called get_{1}",str.lower(type), "i"))
res = int(str.tonumber(_val))
// [COMING SOON...] remove()=>
// [COMING SOON...] size()=>
// [COMING SOON...] keys()=>
// [COMING SOON...] values()=>
// [COMING SOON...] fromArray()=>
// [COMING SOON...] fromString()=>
// [COMING SOON...] toString()=>
// [COMING SOON...] toJSON()=>
//EXAMPLE
obj = new()
set(obj, prop_string("hello", "world"))
greeting = str.format("hello {0}!",get_s(obj, "hello"))
greet=label.new(barstate.islast?bar_index:na,high,yloc=yloc.abovebar,text=greeting,size=size.huge)
label.set_color(greet,color.yellow)
plot(high,display=display.none)
|
HarmonicSwitches | https://www.tradingview.com/script/fV92LLeb-HarmonicSwitches/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// © RozaniGhani-RG
//@version=5
// @description TODO: library for HarmonicSwitches
library('HarmonicSwitches')
// 0. TupleSwitchHL
// 1. TupleSwitchStyleColor
// 2. TupleSwitchString
// 3. TupleSwitchValid
// 4. TupleSwitchTime
// 5. SwitchColor
// 6. SwitchExtend
// ————————————————————————————————————————————————————————————————————————————— 0. TupleSwitchHL {
// @function : Tuple Switch for High Low
// @param : _bool, low_X, high_X, low_A, high_A, low_B, high_B, low_C, high_C
// @returns : price_X, price_A, price_B, price_C
export TupleSwitchHL(bool _bool, float low_X, float high_X, float low_A, float high_A, float low_B, float high_B, float low_C, float high_C) =>
[price_X, price_A, price_B, price_C] = switch _bool
// Output : price_X, price_A, price_B, price_C
true => [ low_X, high_A, low_B, high_C]
=> [high_X, low_A, high_B, low_C]
[price_X, price_A, price_B, price_C]
// }
// ————————————————————————————————————————————————————————————————————————————— 1. TupleSwitchStyleColor {
// @function : Tuple switch for style and color
// @param : _bool
// @returns : style0, style1, col_dir
export TupleSwitchStyleColor(bool _bool) =>
[style0, style1, col_dir] = switch _bool
// Output : style0, style1, col_dir
true => [ label.style_label_up, label.style_label_down, color.lime]
=> [label.style_label_down, label.style_label_up, color.red]
[style0, style1, col_dir]
// }
// ————————————————————————————————————————————————————————————————————————————— 2. TupleSwitchString {
// @function : Tuple switch for string
// @param : _bool
// @returns : str_dir, str_X, str_A
export TupleSwitchString(bool _bool) =>
[str_dir, str_X, str_A] = switch _bool
// Output : str_dir, str_X, str_A
true => ['BULLISH', 'LOW', 'HIGH']
=> ['BEARISH', 'HIGH', 'LOW']
[str_dir, str_X, str_A]
// }
// ————————————————————————————————————————————————————————————————————————————— 3. TupleSwitchValid {
// @function : Tuple switch for valid
// @param : _str
// @returns : str_invalid, str_valid
export TupleSwitchValid(string _str) =>
[str_invalid, str_valid] = switch _str
// Output : str_invalid, str_valid
'Text' => ['INVALID', 'VALID']
'Emoji' => [ '❌','✅']
[str_invalid, str_valid]
// }
// ————————————————————————————————————————————————————————————————————————————— 4. TupleSwitchTime {
// @function : Tuple switch for time
// @param : _str, time_1, time_2, time_3
// @returns : E1, E2
export TupleSwitchTime(string _str, int time_1, int time_2, int time_3) =>
[E1, E2] = switch _str
'Price C' => [time_1, time_2]
'Price D' => [time_2, time_2 + time_3]
[E1, E2]
// }
// ————————————————————————————————————————————————————————————————————————————— 5. SwitchColor {
// @function : Switch color
// @param : _str
// @returns : col_valid
export SwitchColor(string _str) =>
col_valid = switch _str
'INVALID' => color.red
'❌' => color.red
'VALID' => color.blue
'✅' => color.blue
col_valid
// }
// ————————————————————————————————————————————————————————————————————————————— 6. SwitchExtend {
// @function : Extend line
// @param : _str
// @returns : _extend
export SwitchExtend(string _str) =>
_extend = switch _str
'Right' => extend.right
'None' => extend.none
// }
|
Price Displacement - Candlestick (OHLC) Calculations | https://www.tradingview.com/script/8O6HnTVL-Price-Displacement-Candlestick-OHLC-Calculations/ | kurtsmock | https://www.tradingview.com/u/kurtsmock/ | 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/
// © kurtsmock
//@version=5
// @description Price Displacement
library("PD", overlay = false)
// -- Expression Helper List {
// All Components
// (open-high ="oh") (high-open ="ho") (low-open ="lo") (close-open="co") (Upper Wick="uw")
// (open-low ="ol") (high-low ="hl") (low-high ="lh") (close-high="ch") (Body ="bd")
// (open-close="oc") (high-close="hc") (low-close="lc") (close-low ="cl") (Lower Wick="lw")
// Pct Only (Range ="rg")
// (Scalar Close Position="scp") (Vector Close Position="vcp")
// (Scalar Open Position ="sop") (Vector Open Position ="vop")
//}
// -- pt() {
// @function Absolute Point Displacement. Point quantity of given size parameters according to _exp.
// @param _exp (string) Price Parameter
// @returns Point size of given expression as an absolute value. Expressions - (open-high="oh") (open-low="ol") (open-close="oc") (high-open="ho") (high-low="hl") (high-close="hc") (low-open="lo") (low-high="lh") (low-close="lc") (close-open="co") (close-high="ch") (close-low="cl") (Upper Wick="uw") (Body="bd") (Lower Wick="lw") (Range="rg")
export pt(simple string _exp) =>
output = switch _exp
"oh" => math.abs(open - high )
"ol" => math.abs(open - low )
"oc" => math.abs(open - close)
"ho" => math.abs(high - open )
"hl" => math.abs(high - low )
"hc" => math.abs(high - close)
"lo" => math.abs(low - open )
"lh" => math.abs(low - high )
"lc" => math.abs(low - close)
"co" => math.abs(close - open )
"ch" => math.abs(close - high )
"cl" => math.abs(close - low )
"uw" => math.abs(high - math.max(close,open))
"bd" => math.abs(close - open)
"lw" => math.abs(math.min(close,open) - low)
"rg" => math.abs(high - low)
output
//}
// -- vpt() {
// @function Vector Point Displacement. Point quantity of given size parameters according to _exp.
// @param _exp (string) Price Parameter
// @returns Point size of given expression as a vector. Expressions - (open-high="oh") (open-low="ol") (open-close="oc") (high-open="ho") (high-low="hl") (high-close="hc") (low-open="lo") (low-high="lh") (low-close="lc") (close-open="co") (close-high="ch") (close-low="cl") (Upper Wick="uw") (Body="bd") (Lower Wick="lw") (Range="rg")
export vpt(simple string _exp) =>
output = switch _exp
"oh" => open - high
"ol" => open - low
"oc" => open - close
"ho" => high - open
"hl" => high - low
"hc" => high - close
"lo" => low - open
"lh" => low - high
"lc" => low - close
"co" => close - open
"ch" => close - high
"cl" => close - low
"uw" => high - math.max(close,open)
"bd" => close - open
"lw" => math.min(close,open) - low
"rg" => high - low
output
//}
// -- tick() {
// @function Absolute Tick Displacement. Tick quantity of given size parameters according to _exp.
// @param _exp (string) Price Parameter
// @returns Tick size of given expression as an absolute value. Expressions - (open-high="oh") (open-low="ol") (open-close="oc") (high-open="ho") (high-low="hl") (high-close="hc") (low-open="lo") (low-high="lh") (low-close="lc") (close-open="co") (close-high="ch") (close-low="cl") (Upper Wick="uw") (Body="bd") (Lower Wick="lw") (Range="rg")
export tick(simple string _exp) =>
output = switch _exp
"oh" => math.abs((open - high )) / syminfo.mintick
"ol" => math.abs((open - low )) / syminfo.mintick
"oc" => math.abs((open - close)) / syminfo.mintick
"ho" => math.abs((high - open )) / syminfo.mintick
"hl" => math.abs((high - low )) / syminfo.mintick
"hc" => math.abs((high - close)) / syminfo.mintick
"lo" => math.abs((low - open )) / syminfo.mintick
"lh" => math.abs((low - high )) / syminfo.mintick
"lc" => math.abs((low - close)) / syminfo.mintick
"co" => math.abs((close - open )) / syminfo.mintick
"ch" => math.abs((close - high )) / syminfo.mintick
"cl" => math.abs((close - low )) / syminfo.mintick
"uw" => (high - math.max(close,open)) / syminfo.mintick
"bd" => math.abs(close - open) / syminfo.mintick
"lw" => (math.min(close,open) - low) / syminfo.mintick
"rg" => (high - low) / syminfo.mintick
output
//}
// -- vtick() {
// @function Vector Tick Displacement. Tick quantity of given size parameters according to _exp.
// @param _exp (string) Price Parameter
// @returns Tick size of given expression as a vector. Expressions -(open-high="oh") (open-low="ol") (open-close="oc") (high-open="ho") (high-low="hl") (high-close="hc") (low-open="lo") (low-high="lh") (low-close="lc") (close-open="co") (close-high="ch") (close-low="cl") (Upper Wick="uw") (Body="bd") (Lower Wick="lw") (Range="rg")
export vtick(simple string _exp) =>
output = switch _exp
"oh" => (open - high ) / syminfo.mintick
"ol" => (open - low ) / syminfo.mintick
"oc" => (open - close) / syminfo.mintick
"ho" => (high - open ) / syminfo.mintick
"hl" => (high - low ) / syminfo.mintick
"hc" => (high - close) / syminfo.mintick
"lo" => (low - open ) / syminfo.mintick
"lh" => (low - high ) / syminfo.mintick
"lc" => (low - close) / syminfo.mintick
"co" => (close - open ) / syminfo.mintick
"ch" => (close - high ) / syminfo.mintick
"cl" => (close - low ) / syminfo.mintick
"uw" => (high - math.max(close,open)) / syminfo.mintick
"bd" => (close - open ) / syminfo.mintick
"lw" => (math.min(close,open) - low) / syminfo.mintick
"rg" => (high - low ) / syminfo.mintick
output
//}
// -- pct() {
// @function Absolute Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp. (See Library Notes for additional definitions).
// @param _exp (string)
// @param _prec (int) Overload - Place value precision definition
// @returns Percent size of given expression as decimal. Expressions - (open-high="oh") (open-low="ol") (open-close="oc") (high-open="ho") (high-low="hl") (high-close="hc") (low-open="lo") (low-high="lh") (low-close="lc") (close-open="co") (close-high="ch") (close-low="cl") (Upper Wick="uw") (Body="bd") (Lower Wick="lw") (Scalar Close Loc="scp") (Vector Close Loc="vcp") (Scalar Open Loc ="sop") (Vector Open Loc="vop")
export pct(simple string _exp, int _prec) =>
output = switch _exp
"oh" => math.abs (math.round(tick("oh") / tick("rg"), _prec))
"ol" => math.abs (math.round(tick("ol") / tick("rg"), _prec))
"oc" => math.abs (math.round(tick("oc") / tick("rg"), _prec))
"ho" => math.abs (math.round(tick("ho") / tick("rg"), _prec))
"hl" => math.abs (math.round(tick("hl") / tick("rg"), _prec))
"hc" => math.abs (math.round(tick("hc") / tick("rg"), _prec))
"lo" => math.abs (math.round(tick("lo") / tick("rg"), _prec))
"lh" => math.abs (math.round(tick("lh") / tick("rg"), _prec))
"lc" => math.abs (math.round(tick("lc") / tick("rg"), _prec))
"co" => math.abs (math.round(tick("co") / tick("rg"), _prec))
"ch" => math.abs (math.round(tick("ch") / tick("rg"), _prec))
"cl" => math.abs (math.round(tick("cl") / tick("rg"), _prec))
"uw" => math.abs (math.round(tick("uw") / tick("rg"), _prec))
"bd" => math.abs (math.round(tick("bd") / tick("rg"), _prec))
"lw" => math.abs (math.round(tick("lw") / tick("rg"), _prec))
"scp" => math.abs (math.round(tick("cl") / tick("rg"), _prec))
"sop" => math.abs (math.round(tick("ol") / tick("rg"), _prec))
"vcp" => math.abs (math.round((tick("cl") - tick("hc")) / tick("rg"), _prec))
"vop" => math.abs (math.round((tick("ol") - tick("ho")) / tick("rg"), _prec))
output
//}
// -- vpct() {
// @function Vector Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.(See Library Notes for additional definitions).
// @param _exp (string) Price Parameter
// @returns Percent size of given expression as decimal. Expressions - (open-high="oh") (open-low="ol") (open-close="oc") (high-open="ho") (high-low="hl") (high-close="hc") (low-open="lo") (low-high="lh") (low-close="lc") (close-open="co") (close-high="ch") (close-low="cl") (Upper Wick="uw") (Body="bd") (Lower Wick="lw") (Scalar Close Loc="scp") (Vector Close Loc="vcp") (Scalar Open Loc ="sop") (Vector Open Loc="vop")
export vpct(simple string _exp, int _prec) =>
output = switch _exp
"oh" => math.round(vtick("oh") / vtick("rg"), _prec)
"ol" => math.round(vtick("ol") / vtick("rg"), _prec)
"oc" => math.round(vtick("oc") / vtick("rg"), _prec)
"ho" => math.round(vtick("ho") / vtick("rg"), _prec)
"hl" => math.round(vtick("hl") / vtick("rg"), _prec)
"hc" => math.round(vtick("hc") / vtick("rg"), _prec)
"lo" => math.round(vtick("lo") / vtick("rg"), _prec)
"lh" => math.round(vtick("lh") / vtick("rg"), _prec)
"lc" => math.round(vtick("lc") / vtick("rg"), _prec)
"co" => math.round(vtick("co") / vtick("rg"), _prec)
"ch" => math.round(vtick("ch") / vtick("rg"), _prec)
"cl" => math.round(vtick("cl") / vtick("rg"), _prec)
"uw" => math.round(vtick("uw") / vtick("rg"), _prec)
"bd" => math.round(vtick("bd") / vtick("rg"), _prec)
"lw" => math.round(vtick("lw") / vtick("rg"), _prec)
"scp" => math.round(vtick("cl") / vtick("rg"), _prec)
"sop" => math.round(vtick("ol") / vtick("rg"), _prec)
"vcp" => math.round((vtick("cl") - vtick("hc")) / vtick("rg"), _prec)
"vop" => math.round((vtick("ol") - vtick("ho")) / vtick("rg"), _prec)
output
//}
// --pct()/vpct() Overload {
export pct(simple string _exp) =>
output = switch _exp
"oh" => math.abs(tick("oh") / tick("rg"))
"ol" => math.abs(tick("ol") / tick("rg"))
"oc" => math.abs(tick("oc") / tick("rg"))
"ho" => math.abs(tick("ho") / tick("rg"))
"hl" => math.abs(tick("hl") / tick("rg"))
"hc" => math.abs(tick("hc") / tick("rg"))
"lo" => math.abs(tick("lo") / tick("rg"))
"lh" => math.abs(tick("lh") / tick("rg"))
"lc" => math.abs(tick("lc") / tick("rg"))
"co" => math.abs(tick("co") / tick("rg"))
"ch" => math.abs(tick("ch") / tick("rg"))
"cl" => math.abs(tick("cl") / tick("rg"))
"uw" => math.abs(tick("uw") / tick("rg"))
"bd" => math.abs(tick("bd") / tick("rg"))
"lw" => math.abs(tick("lw") / tick("rg"))
"scp" => math.abs(tick("cl") / tick("rg"))
"sop" => math.abs(tick("ol") / tick("rg"))
"vcp" => math.abs((tick("cl") - tick("hc")) / tick("rg"))
"vop" => math.abs((tick("ol") - tick("ho")) / tick("rg"))
output
export vpct(simple string _exp) =>
output = switch _exp
"oh" => vtick("oh") / vtick("rg")
"ol" => vtick("ol") / vtick("rg")
"oc" => vtick("oc") / vtick("rg")
"ho" => vtick("ho") / vtick("rg")
"hl" => vtick("hl") / vtick("rg")
"hc" => vtick("hc") / vtick("rg")
"lo" => vtick("lo") / vtick("rg")
"lh" => vtick("lh") / vtick("rg")
"lc" => vtick("lc") / vtick("rg")
"co" => vtick("co") / vtick("rg")
"ch" => vtick("ch") / vtick("rg")
"cl" => vtick("cl") / vtick("rg")
"uw" => vtick("uw") / vtick("rg")
"bd" => vtick("bd") / vtick("rg")
"lw" => vtick("lw") / vtick("rg")
"scp" => vtick("cl") / vtick("rg")
"sop" => vtick("ol") / vtick("rg")
"vcp" => (vtick("cl") - vtick("hc")) / vtick("rg")
"vop" => (vtick("ol") - vtick("ho")) / vtick("rg")
output
//}
// Point Displacement
plot(pt("uw"), color = color.aqua)
plot(pt("bd"), color = color.aqua)
plot(pt("lw"), color = color.aqua)
plot(pt("rg"), color = color.aqua)
// Tick Displacement
plot(tick("uw"), color = color.navy)
plot(tick("bd"), color = color.navy)
plot(tick("lw"), color = color.navy)
plot(tick("rg"), color = color.navy)
// Percent Displacement Rounded
plot(pct("uw", 2), color = color.orange)
plot(pct("bd", 2), color = color.orange)
plot(pct("lw", 2), color = color.orange)
plot(pct("scp", 2), color = color.fuchsia)
plot(pct("sop", 2), color = color.fuchsia)
// Percent Displacement Not Rounded
plot(pct("vcp"), color = color.purple)
plot(pct("vop"), color = color.purple)
// Notes:
// Scalar - Non-directional. Absolute Value
// Scalar Position: The position of the price attribute relative to the scale of the bar range (high - low)
// Example: high = 100. low = 0. close = 25.
// (A) Measure price distance C-L. How high above the low did the candle close (e.g. close - low = 25)
// (B) Divide by bar range (high - low). 25 / (100 - 0) = .25
// Explaination: The candle closed at the 25th percentile of the bar range given the bar range low = 0 and bar range high = 100.
// (close - low) / (high - low)
// Vector = Directional. [-100% : 100%]
// Vector Position: The position of the price attribute relative to the scale of the bar midpoint (Vector Position at hl2 = 0)
// Example: high = 100. low = 0. close = 25.
// (A) Measure Price distance C-L: How high above the low did the candle close (e.g. close - low = 25)
// (B) Measure Price distance H-C: How far below the high did the candle close (e.g. high - close = 75)
// (C) Take Difference: A - B = C = -50
// (D) Divide by bar range (high - low). -50 / (100 - 0) = -0.50
// Explaination: Candle close at the midpoint between hl2 and the low.
// For vop, substitute open for close.
// Formula: { [(close - low) - (high - close)] / (high - low) }
// -- Bar Patterns ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////// {
// @function Overlap
// @param _off (int) Offset
// @returns Overlap of current bar with prior bar (0.xx)
export overlap(int _off=0) =>
nakedHigh = math.abs(high[_off] - high[_off+1])
nakedLow = math.abs(low[_off] - low[_off+1])
nonOverlap = nakedHigh + nakedLow
twoBarRg = math.max(high[_off], high[_off+1]) - math.min(low[_off], low[_off+1])
overlap = twoBarRg - nonOverlap
pctOverlap = overlap / twoBarRg
pctOverlap
// @function Inside Bar Overlap
// @param _off (int) Offset
// @returns Percent of Bar that is outside prior bar (0.xx)
export ibOverlap(int _off=0) =>
nakedHigh = high[_off] > high[_off+1] ? math.abs(high[_off] - high[_off+1]) : 0
nakedLow = low[_off] < low[_off+1] ? math.abs(low[_off] - low[_off+1]) : 0
nonOverlap = nakedHigh + nakedLow
twoBarRg = math.max(high[_off], high[_off+1]) - math.min(low[_off], low[_off+1])
overlap = twoBarRg - nonOverlap
pctOverlap = overlap / twoBarRg
pctOverlap
// @function a >= b[off]
// @param _a (float) Queried Attribute
// @param _b (float) Reference Attribute
// @param _off (int) Offset
// @param _e (bool) (True = >=) | (False = >)
// @returns (bool) true if a > b[off]. Defaults: _off = 1. _e = false
export gt(float _a, float _b, int _off=1, bool _e=false) => _e ? _a>=_b[_off] : _a>_b[_off]
// @function a <= b[off]
// @param _a (float) Queried Attribute
// @param _b (float) Reference Attribute
// @param _off (int) Offset
// @param _e (bool) (True = <=) | (False = <)
// @returns (bool) true if a < b[off]. Defaults: _off = 1. _e = false
export lt(float _a, float _b, int _off=1, bool _e=false) => _e ? _a<=_b[_off] : _a<_b[_off]
// @function Price At Scalar Position of Bar
// @param _sp (float) Format: 0.XX Scalar Position of Price
// @returns the price of the corresponding Scalar Price Posiiton on current candle from argument rounded to mintick
export priceFromSp(float _sp) => math.round_to_mintick((_sp*(high-low))+low)
//}
// -- Inside Bar/Outside Bars ////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////// {
// @function Inside Bar
// @param _off (int) Offset
// @returns (bool) true if bar is Inside Bar
export ib(int _off=0) => high[_off]<=high[_off+1] and low[_off]>=low[_off+1]
// @function Inside Bar High
// @param _off (int) Offset
// @returns (bool) true if bar is Inside Bar w/outside high
export ibH(int _off=0) => (high[_off]> high[_off+1] and low[_off]>=low[_off+1]) and (close[_off]<=math.max(high[_off+1],low[_off+1]) and close[_off]>=math.min(high[_off+1],low[_off+1]))
// @function Inside Bar Low
// @param _off (int) Offset
// @returns (bool) true if bar is Inside Bar w/outside low
export ibL(int _off=0) => high[_off]<=high[_off+1] and low[_off]<low[_off+1] and close[_off]<=math.max(high[_off+1],low[_off+1]) and close[_off]>=math.min(high[_off+1],low[_off+1])
// @function Outside Bar
// @param _off (int) Offset
// @returns (bool) true if bar is Outside Bar
export ob(int _off=0) => high[_off]>high[_off+1] and low[_off]<low[_off+1]
// @function Outside Bar - Close in Range
// @param _off (int) Offset
// @returns (bool) true if bar is Outside Bar but closes in prior bar range
export obR(int _off=0) => high[_off]>high[_off+1] and low[_off]<low[_off+1] and close[_off]<=math.max(high[_off+1],low[_off+1]) and close[_off]>=math.min(high[_off+1],low[_off+1])
//}
// -- Bull/Bear Bars /////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////// {
// @function Bull Bar
// @returns (bool) true if close > open
export bullbar(int _off=0) => close[_off]>open[_off]
// @function Bear Bar
// @returns (bool) true if close < open
export bearbar(int _off=0) => close[_off]<open[_off]
//}
// -- Candle Attribute Comparisons ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////// {
// @function open > open[off]
// @param _off (int) Offset
// @returns (bool) true if open > open[off]
export oGTo(int _off=1) => open>open[_off]
// @function open > high[off]
// @param _off (int) Offset
// @returns (bool) true if open > high[off]
export oGTh(int _off=1) => open>high[_off]
// @function open > low[off]
// @param _off (int) Offset
// @returns (bool) true if open > low[off]
export oGTl(int _off=1) => open>low[_off]
// @function open > close[off]
// @param _off (int) Offset
// @returns (bool) true if open > close[off]
export oGTc(int _off=1) => open>close[_off]
// @function open < open[off]
// @param _off (int) Offset
// @returns (bool) true if open < open[off]
export oLTo(int _off=1) => open<open[_off]
// @function open < high[off]
// @param _off (int) Offset
// @returns (bool) true if open < high[off]
export oLTh(int _off=1) => open<high[_off]
// @function open < low[off]
// @param _off (int) Offset
// @returns (bool) true if open < low[off]
export oLTl(int _off=1) => open<low[_off]
// @function open < close[off]
// @param _off (int) Offset
// @returns (bool) true if open < close[off]
export oLTc(int _off=1) => open<close[_off]
// @function high > open[off]
// @param _off (int) Offset
// @returns (bool) true if high > open[off]
export hGTo(int _off=1) => high>open[_off]
// @function high > high[off]
// @param _off (int) Offset
// @returns (bool) true if high > high[off]
export hGTh(int _off=1) => high>high[_off]
// @function high > low[off]
// @param _off (int) Offset
// @returns (bool) true if high > low[off]
export hGTl(int _off=1) => high>low[_off]
// @function high > close[off]
// @param _off (int) Offset
// @returns (bool) true if high > close[off]
export hGTc(int _off=1) => high>close[_off]
// @function high < open[off]
// @param _off (int) Offset
// @returns (bool) true if high < open[off]
export hLTo(int _off=1) => high<open[_off]
// @function high < high[off]
// @param _off (int) Offset
// @returns (bool) true if high < high[off]
export hLTh(int _off=1) => high<high[_off]
// @function high < low[off]
// @param _off (int) Offset
// @returns (bool) true if high < low[off]
export hLTl(int _off=1) => high<low[_off]
// @function high < close[off]
// @param _off (int) Offset
// @returns (bool) true if high < close[off]
export hLTc(int _off=1) => high<close[_off]
// @function low > open[off]
// @param _off (int) Offset
// @returns (bool) true if low > open[off]
export lGTo(int _off=1) => low>open[_off]
// @function low > high[off]
// @param _off (int) Offset
// @returns (bool) true if low > high[off]
export lGTh(int _off=1) => low>high[_off]
// @function low > low[off]
// @param _off (int) Offset
// @returns (bool) true if low > low[off]
export lGTl(int _off=1) => low>low[_off]
// @function low > close[off]
// @param _off (int) Offset
// @returns (bool) true if low > close[off]
export lGTc(int _off=1) => low>close[_off]
// @function low < open[off]
// @param _off (int) Offset
// @returns (bool) true if low < open[off]
export lLTo(int _off=1) => low<open[_off]
// @function low < high[off]
// @param _off (int) Offset
// @returns (bool) true if low < high[off]
export lLTh(int _off=1) => low<high[_off]
// @function low < low[off]
// @param _off (int) Offset
// @returns (bool) true if low < low[off]
export lLTl(int _off=1) => low<low[_off]
// @function low < close[off]
// @param _off (int) Offset
// @returns (bool) true if low < close[off]
export lLTc(int _off=1) => low<close[_off]
// @function close > open[off]
// @param _off (int) Offset
// @returns (bool) true if close > open[off]
export cGTo(int _off=1) => close>open[_off]
// @function close > high[off]
// @param _off (int) Offset
// @returns (bool) true if close > high[off]
export cGTh(int _off=1) => close>high[_off]
// @function close > low[off]
// @param _off (int) Offset
// @returns (bool) true if close > low[off]
export cGTl(int _off=1) => close>low[_off]
// @function close > close[off]
// @param _off (int) Offset
// @returns (bool) true if close > close[off]
export cGTc(int _off=1) => close>close[_off]
// @function close < open[off]
// @param _off (int) Offset
// @returns (bool) true if close < open[off]
export cLTo(int _off=1) => close<open[_off]
// @function close < high[off]
// @param _off (int) Offset
// @returns (bool) true if close < high[off]
export cLTh(int _off=1) => close<high[_off]
// @function close < low[off]
// @param _off (int) Offset
// @returns (bool) true if close < low[off]
export cLTl(int _off=1) => close<low[_off]
// @function close < close[off]
// @param _off (int) Offset
// @returns (bool) true if close < close[off]
export cLTc(int _off=1) => close<close[_off]
//}
|
curve | https://www.tradingview.com/script/U0ErLfVJ-curve/ | 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/
// © kaigouthro
import wlhm/UnicodeReplacementFunction/1 as uni
//@version=5
// @description Regression array Creator and Visualizer
library("curve",true)
// @function Curve Regression Values Tool
// @param _size (float) Number of Steps rquired (float works, future consideration)
// @param _power (float) Strength of value decrease
// @returns (float[]) Array of multipliers from 1 downwards
export curve(float _size = 10, float _power = 0)=>
_array = array.new<float>()
_step = (_power == 0 ? 0.1 :math.max(1/math.abs(_size/_power),_power))
_val = 1.
_out = 1.
while array.size(_array) <= _size
_val *= 1 + _step/100
_out := 1 / _val
array.push(_array, math.max(0, _out * _size * _step))
_rng = array.range (_array)
_min = array.max (_array) - _rng
for [index,_value] in _array
array.set(_array,index, math.max(0, (_value - _min) / _rng))
_array
// @function Visible bottom Helper
// @returns lowest since time viewable
getsize()=>
varip _dn = float(na)
varip _up = float(na)
_dn := time > chart.left_visible_bar_time ? math.min(nz(_dn,close),close) : na
_up := time > chart.left_visible_bar_time ? math.max(nz(_up,close),close) : na
[_dn,_up]
// @function Helper
// @param _in Value of array to get time dist for
// @param index array index value
// @returns time of bar for instance
timeMult(_in, index)=> tdis = timeframe.in_seconds(timeframe.period)*1000 , int(time[0] - tdis * _in )
// @function display show curve
// @param _array Values to draw
// @param _timedist Show Seconds
// @param _expandLength Grow over time ( 1/value)
// @param _onbar Show on bar (overlay)
// @param _src Value for overlay
// @returns void
export display(float[] _array, bool _timedist = true, bool _expandLength = false, bool _onbar = true, float _src = high) =>
[_flr,_roof] = getsize()
_hgt = (_roof-_flr)
if barstate.islast
_size = array.size (_array )
_colors = ca.makeGradient (_size + 1 )
var label [] _labels = array.new<label> (_size+1 )
var linefill[] _linefills = array.new<linefill> (_size)
var line [] _lines = array.new<line> (_size)
var line [] _fill_lines = array.new<line> (_size)
var string _isbar = _timedist ? 'sec' : 'bars'
_yvals = array.new<float> ( )
for i = 0 to math.min(bar_index,500)
array.push(_yvals,_src[i])
_alllines = line.all
for itm in _alllines
line.delete(itm)
_alllabels = label.all
for itm in _alllabels
label.delete(itm)
_alllinefills = linefill.all
for itm in _alllinefills
linefill.delete(itm)
for [index , _value] in _array
_baris = math.min(500,_expandLength ? int((index-1) + 1/(math.max(1/100,_value))) : index)
lval = _onbar ? array.get(_yvals,_baris) : _hgt*_value + _flr
_timeis = switch
_timedist => _expandLength ? timeMult((index-1) + 1/_value , index) : timeMult(index , index)
=> bar_index[_baris]
_ltimeis = _timedist ? (last_bar_time[0] - _timeis)/1000 : last_bar_index - _timeis
_locis = _timedist?xloc.bar_time: xloc.bar_index
_lastis = _timedist?last_bar_time+(time[0]-time[1]) : last_bar_index +1
_color = color.new(array.get(_colors , _size -index) , 100 - (_value * (_onbar?20:70) ))
_lbl = label.new(_timeis , lval , uni.replaceFont(str.format('﹟{0} \n {1,number,#} ⇠ '+_isbar+'\n {2,number,percent}' ,
index, _ltimeis, _value),'Regional Indicator'), _locis , yloc.price , color.new(_color,93) ,
label.style_label_down, color.new(_color , 10) , size.small)
array.unshift ( _fill_lines , line.new (_timeis , _onbar ? lval : _flr , _lastis , _onbar ? lval : _hgt*_value + _flr, _locis , extend.none , color.new(#000000 , 100)))
array.unshift ( _lines , line.new (_timeis , lval , _lastis , lval , _locis , extend.none , _color))
array.unshift ( _linefills , linefill.new(array.get(_fill_lines, 0) , array.get(_lines,1) , color.new(_color , int(100 - _value * (_onbar ? 5:25)))))
array.unshift ( _labels , _lbl)
// linefill.delete (array.pop(_linefills ))
// label.delete (array.pop(_labels ))
// line.delete (array.pop(_fill_lines ))
// line.delete (array.pop(_lines ))
// Demo
import kaigouthro/ColorArray/1 as ca
_array = array.new<float>(0)
_power = input.float(1,'power of curve',0,100,0.1)
_size = input.float(10,'size of curve ',2,50,1)
_array := curve(_size , _power)
display ( _array ,
input.bool(true, 'Time based?',group='Options', inline = '_'),
input.bool(true, 'Grow ?',group='Options', inline = '_'),
input.bool(true, 'Overlay ?',group='Options', inline = '_'))
// Bonus Feature
cma(int _len, float _pwr = 2, int _dep = 3)=>
varip init = true
varip ctx = matrix.new<float> ( _dep , _len + _dep + 2 )
if init
vals = array.new<float> ((_len+2)*(2+_len) ,0)
value = float(na)
for i = 0 to _dep -1 by 1
vals := curve(_len + i, (i+1)*_pwr)
for k = 0 to _len -1 by 1
value := array.get(vals,i+k)*(1-i/_dep)
matrix.set(ctx,i, k,value)
init:= false
ctx
_demoMTXma(float src, int _len, int _dep = 3, float _pwr = 2)=>
switch
_pwr <= 0 => runtime.error('Power must be above 0')
_len <= 1 => runtime.error('Length must be above 0')
_dep <= 1 => runtime.error('Depth must be above 0')
var mtx = matrix.new<float> ( _dep , _len + _dep + 2 )
var mtx2 = matrix.new<float> ( _dep , _len + _dep + 2 )
var ctx = cma (_len , _pwr , _dep)
rg = ta.sma(math.abs(ta.mom(src, _dep))*ta.range(src,_dep),_dep)
ra = rg/ta.sma(rg,_len)
for i = 0 to _dep -1
for k = 0 to _len - 1
w = k+i
a = ra[i] * (math.sum(ta.atr(2),i+1)/src)/(1+k+i) * matrix.get(ctx , i, k) * 1/(1+w)
r = src[w]* a
matrix.set(mtx , i , k , r)
matrix.set(mtx2, i , k , a)
matrix.avg(mtx)/matrix.avg(mtx2)
_dep = input.int (5 ,'Depth ' , 2,100 ,group = 'MA Demo')
_len = input.int (5 ,'Length' , 2,100 ,group = 'MA Demo')
_pwr = input.float (1 ,'Power ' , step=0.1 ,group = 'MA Demo')
_showma =input(false)
_val = _showma ? _demoMTXma(close, _len, _dep, _pwr) : float(na)
plot(_showma?_val:na,'out', ta.change(_val)>0 ? color.aqua:color.orange)
bgcolor(#101010)
|
fontilab | https://www.tradingview.com/script/jsr2Yo7O-fontilab/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 33 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Author : @Fontiramisu
// Pivot Calculation is from ©ZenAndTheArtOfTrading
// Trend interpretation is from @Fontiramisu
//@version=5
// @description Provides function's indicators for pivot - trend - resistance.
library("fontilab") // Public fontilab library
// --------- Util Functions ------------- [
// @function to get last high/low (handle multiple rsiOver in a row)
export getHighLowFromNbCandles(bool isLong, int nbCandles) =>
highLow = isLong ? low : high
for counter = 1 to nbCandles + 10
if isLong
highLow := low[counter] < highLow ? low[counter] : highLow
else
highLow := high[counter] > highLow ? high[counter] : highLow
highLow
// ] -------------- FUNCTIONS : Utility Functions ---------------- [
// --- Manipulation Reusable Functions ---
// @function Get the last element of an int array.
export getElIntArrayFromEnd(int[] arrayWanted, int nbLast) =>
result = 99
if array.size(arrayWanted) >= nbLast + 1
result := array.get(arrayWanted, array.size(arrayWanted) - nbLast - 1)
result
// @function Get the last element of an float array.
export getElFloatArrayFromEnd(float[] arrayWanted, int nbLast) =>
result = 99.99
if array.size(arrayWanted) >= nbLast + 1
result := array.get(arrayWanted, array.size(arrayWanted) - nbLast - 1)
result
// @function Get the last element of a bool array.
export getElBoolArrayFromEnd(bool[] arrayWanted, int nbLast) =>
var bool result = na
if array.size(arrayWanted) >= nbLast + 1
result := array.get(arrayWanted, array.size(arrayWanted) - nbLast - 1)
result
// ] -------------- FUNCTIONS : Moving Avg ------------------ [
// @function Double Exponential Average.
export dema(float src, simple int length) =>
ema1= ta.ema(src, length)
ema2 = ta.ema(ema1,length)
dema = (2 * ema1) - ema2
dema
// @function Tripple exponential moving average.
export tema(float src, simple int len)=>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
tema = 3 * (ema1 - ema2) + ema3
tema
// @function calculate Zero Lag SMA.
export zlSma(float src, simple int len) =>
lsma = ta.linreg(src, len, 0)
lsma2 = ta.linreg(lsma, len, 0)
eq = lsma - lsma2
zlsma = lsma + eq
zlsma
// @function Zero-lag Dema.
export zlDema(float src, simple int len) =>
zdema1 = ta.ema(src, len)
zdema2 = ta.ema(zdema1, len)
dema1 = 2 * zdema1 - zdema2
zdema12 = ta.ema(dema1, len)
zdema22 = ta.ema(zdema12, len)
zldema = 2 * zdema12 - zdema22
zldema
// @function Zero-lag Tema.
export zlTema(float src, simple int len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
tema1 = 3 * (ema1 - ema2) + ema3
ema1a = ta.ema(tema1, len)
ema2a = ta.ema(ema1a, len)
ema3a = ta.ema(ema2a, len)
zltema = 3 * (ema1a - ema2a) + ema3a
zltema
// @function McGinley Dynamic
export mcginley(float src, simple int len)=>
mg = 0.0
t = ta.ema(src, len)
mg := na(mg[1]) ? t : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
mg
// ] -------------- FUNCTIONS : Assembly Functions ---------------- [
// @function Select between multiple ma type.
export multiMa(float source, simple int length, string type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
"DEMA" => dema(source, length)
"TEMA" => tema(source, length)
"ZLSMA" => zlSma(source, length)
"ZLDEMA" => zlDema(source, length)
"ZLTEMA" => zlTema(source, length)
"McGinley-D" => mcginley(source, length)
"HMA" => ta.hma(source, length )
// ] -------------- FUNCTIONS : Math Functions ---------------- [
// @function Get source slope.
export getSlope(float source) =>
// STANDARDISE SLOPE
// Multiplicator to have interprationnable results
multiplicator = 100000
// Calculating the PERCENTAGE SLOPE (not the strate slope)
// It's the slope of the percentage change from maToSlope to maToSlope[periodFast]
// So the slope is based on %
dyPer = (source - source[1]) / source
// Slope calculate (equal dy%/dx%)
slopeMa = dyPer / 1 * multiplicator
slopeMa
// @funtion to get MZL.
export getMZL(float src, simple int lengthFast, simple int lengthSlow) =>
// Fast line.
demaFast = dema(src, lengthFast)
// Slow line.
demaSlow = dema(src, lengthSlow)
demaFast - demaSlow
// @function get RSI.
export getRSI(float source, simple int rsiLength, string maType, simple int maLength) =>
up = ta.rma(math.max(ta.change(source), 0), rsiLength)
down = ta.rma(-math.min(ta.change(source), 0), rsiLength)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA = multiMa(rsi, maLength, maType)
[rsi, rsiMA]
// @function get MACD.
export getMACD(float source, simple int fastLength, simple int slowLength, simple int signalLength, string maType) =>
fast_ma = multiMa(source, fastLength, maType)
slow_ma = multiMa(source, slowLength, maType)
macd = fast_ma - slow_ma
signal = multiMa(macd, signalLength, maType)
hist = macd - signal
[macd, signal, hist]
// ] -------------- FUNCTIONS : Indicator ---------------- [
// @function to get Dema supertrend.
export demaSupertrend(simple int lenAtr, simple int lenMas, float mult, float highP, float lowP, float closeP) =>
atr = ta.atr(lenAtr)
bandOffset = mult * atr
upperBand = dema(highP + bandOffset, lenMas)
lowerBand = dema(lowP - bandOffset, lenMas)
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or closeP[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or closeP[1] > prevUpperBand ? upperBand : prevUpperBand
midBand = (lowerBand + upperBand)/2
[lowerBand, upperBand, midBand]
// @function get trend bands.
export getTrendBands(float src, float delta)=>
float upperb = 0.0
float lowerb = 0.0
upperb := nz(upperb[1])
lowerb := nz(lowerb[1])
if src > nz(upperb[1])
upperb := math.max(nz(upperb[1]), math.max(src, nz(src[1])))
lowerb := upperb - delta
if lowerb < nz(lowerb[1]) or lowerb > nz(lowerb[1]) and upperb == nz(upperb[1])
lowerb := nz(lowerb[1])
else if src < nz(lowerb[1])
lowerb := math.min(nz(lowerb[1]), math.min(src, nz(src[1])))
upperb := lowerb + delta
if upperb > nz(upperb[1]) or upperb < nz(upperb[1]) and lowerb == nz(lowerb[1])
upperb := nz(upperb[1])
midb = (lowerb + upperb) / 2
[midb, upperb, lowerb]
// @function get trend brand from pivot/highs lows interpretation.
export getInterTrend(float src, float upB, float lowB, float pLast, bool tDirUp, int pDirStrike, bool isPFound, bool isHighP, int nStrike, float rPerOffset, int depth) =>
upBNew = upB
lowBNew = lowB
pDirStrikeNew = pDirStrike
tDirUpNew = tDirUp
bFactorUp = (100 + rPerOffset)/100
bFactorLow = (100 - rPerOffset)/100
tHesitate = pDirStrike == 1
isUpMove = isPFound and not tHesitate ? (isHighP ? pLast > upB[depth] : pLast > lowB[depth]) : (src > upB ? true : src < lowB ? false : tDirUp)
pDirStrikeNew := isPFound and not tHesitate ? (tDirUp and isUpMove or not tDirUp and not isUpMove ? pDirStrike + 1 : 1) : ( src > upB or src < lowB ? nStrike : pDirStrikeNew)
tDirUpNew := isUpMove
upBNew := isPFound ? ((pDirStrikeNew >= nStrike and isHighP and not (pLast > upB[depth])) ? pLast * bFactorUp : upBNew) : (src > upB ? src * bFactorUp : upBNew)
lowBNew := isPFound ? ((pDirStrikeNew >= nStrike and not isHighP and not (pLast < lowB[depth])) ? pLast * bFactorLow : lowBNew) : (src < lowB ? src * bFactorLow : lowBNew)
midBNew = (upBNew + lowBNew) / 2
[midBNew, upBNew, lowBNew, pDirStrikeNew, tDirUpNew]
// ] ------- Calculate Pivots ----------- [
// @function Detecting pivot points (and returning price + bar index.
// @param src The chart we analyse.
// @param lenght Used for the calcul.
// @param isHigh lookging for high if true, low otherwise.
// @returns The bar index and the price of the pivot.
export pivots(float src, float length, bool isHigh) =>
l2 = length * 2
c = nz(src[length])
ok = true
for i = 0 to l2
if isHigh and src[i] > c // If isHigh, validate pivot high
ok := false
if not isHigh and src[i] < c // If not isHigh, validate pivot low
ok := false
if ok // If pivot is valid, return bar index + high price value
[bar_index[length], c]
else // If pivot is invalid, return na
[int(na), float(na)]
// @function Calculate deviation threshold for identifying major swings.
// @param tresholdMultiplier Usefull to equilibrate the calculate.
// @param closePrice Close price of the chart wanted.
// @returns The deviation threshold.
export calcDevThreshold(float tresholdMultiplier, float closePrice) => ta.atr(10) / closePrice * 100 * tresholdMultiplier
// @function Custom function for calculating price deviation for validating large moves.
// @param basePrice The reference price.
// @param price The price tested.
// @returns The deviation.
export calcDev(float basePrice, float price) => 100 * (price - basePrice) / price
// @function Detecting pivots that meet our deviation criteria.
// @param dev The deviation wanted.
// @param isHigh The type of pivot tested (high or low).
// @param index The Index of the pivot tested.
// @param price The chart price wanted.
// @param dev_threshold The deviation treshold.
// @param isHighLast The type of last pivot.
// @param pLast The pivot price last.
// @param iLast Index of the last pivot.
// @param lineLast The lst line.
// @returns The Line and bool is pivot High.
export pivotFoundWithLines(float dev, bool isHigh, int index, float price, float dev_threshold, bool isHighLast, float pLast, int iLast, line lineLast) =>
if isHighLast == isHigh // Check bull/bear direction of new pivot
// New pivot in same direction as last (a pivot high), so update line upwards (ie. trend-continuation)
if isHighLast ? price > pLast : price < pLast // If new pivot is above last pivot, update line
if not na(lineLast)
line.set_xy2(lineLast, index, price)
[lineLast, isHighLast, true]
else
[line(na), bool(na), false] // New pivot is not above last pivot, so don't update the line
else // Reverse the trend/pivot direction (or create the very first line if lineLast is na)
if math.abs(dev) > dev_threshold
// Price move is significant - create a new line between the pivot points
id = line.new(iLast, pLast, index, price, color=color.gray, width=1, style=line.style_dashed)
[id, isHigh, true]
else
[line(na), bool(na), false]
// @function Get pivot that meet our deviation criteria.
// @param thresholdMultiplier The treshold multiplier.
// @param depth The depth to calculate pivot.
// @param lineLast The last line.
// @param isHighLast The type of last pivot
// @param iLast Index of the last pivot.
// @param pLast The pivot price last.
// @param deleteLines If the line are draw or not.
// @param closePrice The chart close price.
// @param highPrice The chart high price.
// @param lowPrice The chart low price.
// @returns All pivot the informations.
export getDeviationPivots(
float thresholdMultiplier,
float depth,
line lineLast,
bool isHighLast,
int iLast,
float pLast,
bool deleteLines,
float closePrice,
float highPrice,
float lowPrice
) =>
// Vars to return
line newLineLast = na
bool newIsHighLast = na
int newILast = na
float newPLast = na
int newIPrev = na
float newPLastHigh = na
float newPLastLow = na
// Calculate deviation threshold for identifying major swings
devThreshold = calcDevThreshold(thresholdMultiplier, closePrice)
// Get bar index & price high/low for current pivots
[iH, pH] = pivots(highPrice, depth / 2, true)
[iL, pL] = pivots(lowPrice, depth / 2, false)
// If bar index for current pivot high is not NA (ie. we have a new pivot):
if not na(iH)
dev = calcDev(pLast, pH) // Calculate the deviation from last pivot
[id, isHigh, isNewPivot] = pivotFoundWithLines(dev, true, iH, pH, devThreshold, isHighLast, pLast, iLast, lineLast) // Pass the current pivot high into pivotFound() for validation & line update
if isNewPivot // If the line has been updated, update price & index values and delete previous line
if deleteLines and not na(id)
line.delete(id)
newLineLast := id
newIsHighLast := isHigh
newIPrev := iLast
newILast := iH
newPLast := pH
newPLastHigh := pH
else
if not na(iL) // If bar index for current pivot low is not NA (ie. we have a new pivot):
dev = calcDev(pLast, pL) // Calculate the deviation from last pivot
[id, isHigh, isNewPivot] = pivotFoundWithLines(dev, false, iL, pL, devThreshold, isHighLast, pLast, iLast, lineLast) // Pass the current pivot low into pivotFound() for validation & line update
if isNewPivot // If the line has been updated, update price values and delete previous line
if deleteLines and not na(id)
line.delete(id)
newLineLast := id
newIsHighLast := isHigh
newIPrev := iLast
newILast := iL
newPLast := pL
newPLastLow := pL
// return
[newLineLast, newIsHighLast, newIPrev, newILast, newPLast, newPLastHigh, newPLastLow]
// ]-------- Trend From Pivots----------- [
// @function Check if last price is between bounds array.
// @param isTrendUp Is actual trend up.
// @param arrayBounds The trend array.
// @param lastPrice The pivot Price that just be found.
// @param precision The percent we add to actual bounds to validate a move.
// @returns na if price is between bounds, true if continuation, false if not.
export isTrendContinuation(bool isTrendUp, float[] arrayBounds, float lastPrice, float precision) =>
bool isContinuation = na // if true price is following the trend, if not trend is reversed, if na price is between bounds
if not na(arrayBounds)
// Helping vars
lastElementArrayBounds = array.get(arrayBounds, array.size(arrayBounds) - 1)
scdLastElementArrayBounds = array.get(arrayBounds, array.size(arrayBounds) - 2)
if isTrendUp and lastPrice > lastElementArrayBounds * (1 + precision) // continuation trend
or not isTrendUp and lastPrice < lastElementArrayBounds - lastElementArrayBounds * precision
isContinuation := true
else if isTrendUp and lastPrice < scdLastElementArrayBounds - lastElementArrayBounds * precision// reverse the trend
or not isTrendUp and lastPrice > scdLastElementArrayBounds * (1 + precision)
isContinuation := false
// RETURN
isContinuation
// --- Helping variables and functions ---
// - Helping "situationnal" Functions -
isThreeArraysEmpty(array1, array2, array3) =>
if array.size(array1) == 0 and array.size(array2) == 0 and array.size(array3) == 0
true
else
false
// Custom function tu push easely in arrays
pushThreeArrays(array1, array2, array3, el1, el2, el3) =>
array.push(array1, el1)
array.push(array2, el2)
array.push(array3, el3)
// Add and remove
replaceLastElThreeArrays(array1, array2, array3, el1, el2, el3) =>
array.pop(array1) // removes the last element
array.push(array1, el1) // add new
array.pop(array2) // removes the last element
array.push(array2, el2) // add new
array.pop(array3) // removes the last element
array.push(array3, el3) // add new
clearThreeArrays(array1, array2, array3) =>
array.clear(array1)
array.clear(array2)
array.clear(array3)
// Keep only nb last element from an array
keepLastNbElArray(array1, nbToKeep) =>
for counter = 1 to array.size(array1) - nbToKeep
array.shift(array1)
// Keep only nb last el for 3 array
keepLastNbElThreeArray(array1, array2, array3, nbToKeep) =>
for counter = 1 to array.size(array1) - nbToKeep
array.shift(array1)
array.shift(array2)
array.shift(array3)
// @function Function to update array and trend related to pivot trend interpretation.
// @param trendBarIndexes The array trend bar index.
// @param trendPrices The array trend price.
// @param trendPricesIsHigh The array trend is high.
// @param interBarIndexes The array inter bar index.
// @param interPrices The array inter price.
// @param interPricesIsHigh The array inter ishigh.
// @param isTrendHesitate The actual status of is trend hesitate.
// @param isTrendUp The actual status of is trend up.
// @param trendPrecision The var precision to add in "iscontinuation" function.
// @param pLast The last pivot price.
// @param iLast The last pivot bar index.
// @param isHighLast The last pivot "isHigh".
// @returns trend & inter arrays, is trend hesitate, is trend up.
export getTrendPivots(
int[] trendBarIndexes,
float[] trendPrices,
bool[] trendPricesIsHigh,
int[] interBarIndexes,
float[] interPrices,
bool[] interPricesIsHigh,
bool isTrendHesitate,
bool isTrendUp,
float trendPrecision,
float pLast,
int iLast,
bool isHighLast
) =>
// Vars to be returned
trendBarIndexesNew = trendBarIndexes
trendPricesNew = trendPrices
trendPricesNewIsHigh = trendPricesIsHigh
interBarIndexesNew = interBarIndexes
interPricesNew = interPrices
interPricesNewIsHigh = interPricesIsHigh
isTrendHesitateNew = isTrendHesitate
isTrendUpNew = isTrendUp
// Helping "situationnal" vars
isEmptyTrendArrays = isThreeArraysEmpty(trendBarIndexesNew, trendPricesNew, trendPricesNewIsHigh)
// Last trend arrays elements
lastTrendBarIndex = getElIntArrayFromEnd(trendBarIndexesNew, 0)
lastTrendPriceIsHigh = getElBoolArrayFromEnd(trendPricesNewIsHigh, 0)
lastTrendPrice = getElFloatArrayFromEnd(trendPricesNew, 0)
// --- Start Algo --- [
// Init/handle the first trend
if pLast != 0 and lastTrendPrice != pLast
if array.size(trendPricesNew) < 3 // Init array trendPricesNew
if not isEmptyTrendArrays and lastTrendPriceIsHigh == isHighLast // If new pivot is low/high again then we must update array
replaceLastElThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
else
pushThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
else if array.size(trendPricesNew) >= 3// All cases
// ### CONDITION ### : /!\/!\/!\ last Pivot added is not validated until next pivot validate the tendancy /!\/!\/!\
isContinuation = isTrendContinuation(isTrendUpNew, trendPricesNew, pLast, trendPrecision)
if na(isContinuation) // if new price is between bounds
// if pivot is potential bound then we have to push it in inter - arrayTrend is only validated pivots
if array.size(interPricesNew) == 0 // Not hesitate trend but potential bound
if getElBoolArrayFromEnd(trendPricesNewIsHigh, 0) != isHighLast // exclude case where price make new "hesitation" bound
pushThreeArrays(interBarIndexesNew, interPricesNew, interPricesNewIsHigh, iLast, pLast, isHighLast)
else if getElBoolArrayFromEnd(interPricesNewIsHigh, 0) == isHighLast // inter pivot that did same "isHigh" must be replaced
replaceLastElThreeArrays(interBarIndexesNew, interPricesNew, interPricesNewIsHigh, iLast, pLast, isHighLast)
else
pushThreeArrays(interBarIndexesNew, interPricesNew, interPricesNewIsHigh, iLast, pLast, isHighLast)
// Update trend hesitate
if array.size(interPricesNew) <= 1 // We push the first pivot after new high/low but it is not hesitate trend
isTrendHesitateNew := false
else
isTrendHesitateNew := true
else if array.size(interPricesNew) == 0 and isHighLast == getElBoolArrayFromEnd(trendPricesNewIsHigh, 0) // case where bound extend without doing interArray
replaceLastElThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
else if not isContinuation // 1. Test the trend : Trend reverse
isTrendHesitateNew := false
// isTrendUpNew := isHighLast
// Trend is reversed so trendArrays must be updated
if array.size(interPricesNew) > 0 // 2. Test if inter pivot
if isHighLast != getElBoolArrayFromEnd(interPricesNewIsHigh, 0) // 3. Test "same high" case : When continuation interArray size is minimum 1 (if everything work)
// Add the last trendArray element + last 2 interArray element + the last price
keepLastNbElThreeArray(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, 1)
pushThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, getElIntArrayFromEnd(interBarIndexesNew, 1), getElFloatArrayFromEnd(interPricesNew, 1), getElBoolArrayFromEnd(interPricesNewIsHigh, 1))
pushThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, getElIntArrayFromEnd(interBarIndexesNew, 0), getElFloatArrayFromEnd(interPricesNew, 0), getElBoolArrayFromEnd(interPricesNewIsHigh, 0))
pushThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
else // case where last pivot was interArray and also the "same ishigh"
// Add the last 2 trendArray element + Add the last price
keepLastNbElThreeArray(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, 2)
pushThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
// clear inter array
clearThreeArrays(interBarIndexesNew,interPricesNew, interPricesNewIsHigh)
else // 2. case where pivot
pushThreeArrays(trendBarIndexesNew,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
else // 1. Test the trend : It is a continuation
isTrendHesitateNew := false
// isTrendUpNew := isHighLast
// We must update trendArrays
if array.size(interPricesNew) > 0 // 2. Test if inter pivot
if isHighLast != getElBoolArrayFromEnd(interPricesNewIsHigh, 0) // 3. Test "same high" case : When continuation, interArray size is minimum 1 (if everything work)
// Add all existing trendArray + last interArray element + last element
pushThreeArrays(trendBarIndexes,trendPricesNew, trendPricesNewIsHigh, getElIntArrayFromEnd(interBarIndexesNew, 0), getElFloatArrayFromEnd(interPricesNew, 0), getElBoolArrayFromEnd(interPricesNewIsHigh, 0))
pushThreeArrays(trendBarIndexes,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
else
// Case treated at the root : see "if na(isContinuation)""
// Case where price make new bound in same direction but is less than "precision%"" out of last bound
// This pivot is put in inter array, we have to treat this case
// if array.size(interPricesNew) == 1
// keepLastNbElThreeArray(trendBarIndexes,trendPricesNew, trendPricesNewIsHigh, 2)
// pushThreeArrays(trendBarIndexes,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
// Not totaly true, see above : When continuation, interArray size is mini 1, if highLast and interHighLast is the same it means that interArraySize is mini 2
// ex : upTrend - up/ up\ up/ inter\ inter/ continuation/ ==> 2 inter/\ minimum to be same "high"
// Add all trendArray + Add the last 2nd last element from inter + Last Price
pushThreeArrays(trendBarIndexes,trendPricesNew, trendPricesNewIsHigh, getElIntArrayFromEnd(interBarIndexesNew, 1), getElFloatArrayFromEnd(interPricesNew, 1), getElBoolArrayFromEnd(interPricesNewIsHigh, 1))
pushThreeArrays(trendBarIndexes,trendPricesNew, trendPricesNewIsHigh, iLast, pLast, isHighLast)
// clear inter array
clearThreeArrays(interBarIndexesNew,interPricesNew, interPricesNewIsHigh)
// else : there is always an inter array price before continuation (cf case "if na(continuation)", this case is not possible
// Case new extend bound in continuation is treated (cf case "else if array.size(interPricesNew) == 0 and isHighLast == getElArrayFromEnd(interPricesIsHigh, 0)")
// Update trend
isTrendUpNew := getElBoolArrayFromEnd(trendPricesIsHigh, 0)
//] RETURN
[trendBarIndexesNew, trendPricesNew, trendPricesNewIsHigh, interBarIndexesNew, interPricesNew, interPricesNewIsHigh, isTrendHesitateNew, isTrendUpNew]
// ] ------- Do Some Drawings------------ [
// @function Draw bounds and breaking line of the trend.
// @param startIndex Index of the first bound line.
// @param startPrice Price of first bound line.
// @param endIndex Index of second bound line.
// @param endPrice price of second bound line.
// @param breakingPivotIndex The breaking line index.
// @param breakingPivotPrice The breaking line price.
// @param isTrendUp The actual status of the trend.
// @returns The lines bounds and breaking line.
export drawBoundLines(
int startIndex,
float startPrice,
int endIndex,
float endPrice,
int breakingPivotIndex,
float breakingPivotPrice,
bool isTrendUp,
color breakingLineColor
) =>
// Var
firstBoundColor = isTrendUp ? color.red : color.green
scdBoundColor = isTrendUp ? color.green : color.red
firstLineDup = line.new(startIndex, startPrice, endIndex, startPrice, extend=extend.right, color=firstBoundColor)
scdLineDup = line.new(endIndex, endPrice, endIndex + 1, endPrice, extend=extend.right, color=scdBoundColor)
breakingLineDup = line.new(breakingPivotIndex, breakingPivotPrice, endIndex, breakingPivotPrice, extend=extend.right, color=breakingLineColor)
// Remove old
line.delete(firstLineDup[1])
line.delete(scdLineDup[1])
line.delete(breakingLineDup[1])
// Return
[firstLineDup, scdLineDup, breakingLineDup]
// ] ------- Pivot Resistance Algo ------ [
// @function Function to update array and related to resistance interpretation.
// @param resPrices Array that save resis prices.
// @param resBarIndexes Array that save resis bar index.
// @param resWeights Array that save resis weight (how much time a pivot got into a resis).
// @param resNbLows Array that save nb low pivot in resis.
// @param resNbHighs Array that save nb high pivot in resis.
// @param maxResis Max number of resis in resis arrays.
// @param rangePercentResis Percentage vertical range to be taken when finding res.
// @param pLast The last pivot price.
// @param iLast The last pivot bar index.
// @param isHighLast The last pivot "isHigh".
// @returns trend & inter arrays, is trend hesitate, is trend up.
export getResistances(
float[] resPrices,
int[] resBarIndexes,
int[] resWeights,
int[] resNbLows,
int[] resNbHighs,
int maxResis,
float rangePercentResis,
float pLast,
int iLast,
bool isHighLast
) =>
float[] newResPrices = resPrices
int[] newResBarIndexes = resBarIndexes
int[] newResWeights = resWeights
int[] newResNbLows = resNbLows
int[] newResNbHighs = resNbHighs
// Init calculate vars
isStackedResFound = false
float newResPrice = pLast
int newResWeight = 0
int newResBarIndex = na
int newResNbHigh = 0
int newResNbLow = 0
int[] indexesToRemove = array.new<int>(0,0)
// Helping vars
sizeNewResPrices = array.size(newResPrices)
if sizeNewResPrices > 0
// Testing if pLast constitute an older resistance
for i = 0 to sizeNewResPrices - 1
// Update Bar Index to avoid max_bar_back errors :
array.set(newResBarIndexes, i, iLast)
// Find new res :
// Helping vars
resPrice = array.get(newResPrices, i)
resisRangeValid = resPrice * rangePercentResis/2
if resPrice + resisRangeValid > pLast and pLast > resPrice - resisRangeValid
// Helping vars
resNbhigh = array.get(newResNbHighs, i)
resNbLow = array.get(newResNbLows, i)
resWeight = array.get(newResWeights, i)
// Careful : cases where pivot res found is not the first time.
newResPrice := newResPrice > 500 ? math.round((newResPrice + resPrice) / 2) : ((newResPrice + resPrice) / 2)
newResWeight := not isStackedResFound ? newResWeight + resWeight + 1 : newResWeight + resWeight // newResWeight is added -> case pLast is near multiple pivot point.
newResBarIndex := iLast //array.get(newResBarIndexes, i) // More weighted res = further bar index on chart.
newResNbHigh := isHighLast and not isStackedResFound ? newResNbHigh + 1 + resNbhigh : newResNbHigh + resNbhigh
newResNbLow := not isHighLast and not isStackedResFound ? newResNbLow + 1 + resNbLow : newResNbLow + resNbLow
// push index to index to remove arrays
array.push(indexesToRemove, i)
// mini one res found
isStackedResFound := true
// Update new res arrays with updated values
if isStackedResFound
// first remove old arrays.
sizeIndexesToRemove = array.size(indexesToRemove)
if sizeIndexesToRemove > 0
// Sort array to dsc to remove easier.
array.sort(indexesToRemove, order.descending)
for i = 0 to sizeIndexesToRemove - 1
indexToRemove = array.get(indexesToRemove, i)
// Remove old ref of this res
array.remove(newResPrices, indexToRemove)
array.remove(newResWeights, indexToRemove)
array.remove(newResBarIndexes, indexToRemove)
array.remove(newResNbHighs, indexToRemove)
array.remove(newResNbLows, indexToRemove)
// Then push new one.
array.push(newResPrices, newResPrice) // New res price is the average of both
array.push(newResWeights, newResWeight)
array.push(newResBarIndexes, newResBarIndex)
array.push(newResNbHighs, newResNbHigh)
array.push(newResNbLows, newResNbLow)
// Case pLast do not constitute resistance from res before, then it's a new one
if not isStackedResFound
array.push(newResPrices, pLast)
array.push(newResWeights, 1)
array.push(newResBarIndexes, iLast)
array.push(newResNbLows, isHighLast ? 1 : 0)
array.push(newResNbHighs, isHighLast ? 0 : 1)
// Case where maximum resis is obtained : we shift arrays
if sizeNewResPrices > maxResis
array.shift(newResPrices)
array.shift(newResWeights)
array.shift(newResBarIndexes)
array.shift(newResNbLows)
array.shift(newResNbHighs)
[newResPrices, newResWeights, newResBarIndexes, newResNbLows, newResNbHighs]
// @function Get top weighted resistance from multiple res found.
// @param nbShowRes Nb res we want to return .
// @param minTopWeight Minimum res weight we want to return.
// @param resWeights Res weight array.
// @param resPrices Res prices array.
// @param resBarIndexes Res bar index array.
// @return The top arrays.
export getTopRes(int nbShowRes, int minTopWeight, int[] resWeights, float[] resPrices, int[] resBarIndexes) =>
float[] topResPrices = array.new_float(1, 0)
int[] topBarIndexes = array.new_int(1, 0)
int[] topResWeights = array.new_int(1, 0)
sizeRes = array.size(resWeights)
// int j = 0
for j = 0 to sizeRes - 1
// Push every el above the first el
curWeightRes = array.get(resWeights, j)
curPriceRes = array.get(resPrices, j)
curBarIndexRes = array.get(resBarIndexes, j)
sizeTopRes = array.size(topResWeights)
if sizeTopRes < nbShowRes and curWeightRes > minTopWeight // Condition nbShowRes Condition and MinWeight wanted.
array.push(topResPrices, curPriceRes)
array.push(topResWeights, curWeightRes)
array.push(topBarIndexes, curBarIndexRes)
else
// int k = 0
for k = 0 to sizeTopRes - 1
curTopResPrice = array.get(topResPrices, k)
curTopResWeight = array.get(topResWeights, k)
if curWeightRes > curTopResWeight
array.remove(topResPrices, k)
array.remove(topBarIndexes, k)
array.remove(topResWeights, k)
array.push(topResPrices, curPriceRes)
array.push(topResWeights, curWeightRes)
array.push(topBarIndexes, curBarIndexRes)
break
[topResPrices, topResWeights, topBarIndexes]
// @function Draw resistance lines for resistance indicator.
// @param resPrices Array of res prices.
// @param resIndexes Array of res bar indexes.
export drawResLines(float[] resPrices, int[] resBarIndexes) =>
int lineNo = 0
while lineNo < array.size(line.all)
line.delete(array.get(line.all, lineNo))
// Then draw them all.
for i = 0 to array.size(resPrices) - 1
startIndex = array.get(resBarIndexes, i)
startPrice = array.get(resPrices, i)
endIndex = array.get(resBarIndexes, i) + 1
lineResi = line.new(startIndex, startPrice, endIndex, startPrice, extend=extend.both, color=color.purple)
// ] ------- DIVERGENCE ----------------- [
_inRange(cond, barOffset, rangeLower, rangeUpper) =>
bars = ta.barssince(cond)
rangeLower <= bars + barOffset and bars + barOffset <= rangeUpper
// @function Plot divergences.
//
export plotDivergences(
float osc,
int lbR,
bool plFound,
bool phFound,
bool plFoundPot,
bool phFoundPot,
int rangeLower,
int rangeUpper
) =>
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1], 0, rangeLower, rangeUpper)
oscHLPot = osc[1] > ta.valuewhen(plFound, osc[lbR], 0) and _inRange(plFound[0], 4, rangeLower, rangeUpper)
// Price: Lower Low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
priceLLPot = low[1] < ta.valuewhen(plFound, low[lbR], 0)
bullCond = priceLL and oscHL and plFound
bullCondPot = priceLLPot and oscHLPot and plFoundPot
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1], 0, rangeLower, rangeUpper)
oscLLPot = osc[1] < ta.valuewhen(plFound, osc[lbR], 0) and _inRange(plFound[0], 4, rangeLower, rangeUpper)
// Price: Higher Low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
priceHLPot = low[1] > ta.valuewhen(plFound, low[lbR], 0)
hiddenBullCond = priceHL and oscLL and plFound
hiddenBullCondPot = priceHLPot and oscLLPot and plFoundPot
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1], 0, rangeLower, rangeUpper)
oscLHPot = osc[1] < ta.valuewhen(phFound, osc[lbR], 0) and _inRange(phFound[0], 4, rangeLower, rangeUpper)
// Price: Higher High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
priceHHPot = high[1] > ta.valuewhen(phFound, high[lbR], 0)
bearCond = priceHH and oscLH and phFound
bearCondPot = priceHHPot and oscLHPot and phFoundPot
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1], 0, rangeLower, rangeUpper)
oscHHPot = osc[1] > ta.valuewhen(phFound, osc[lbR], 0) and _inRange(phFound[0], 4, rangeLower, rangeUpper)
// Price: Lower High
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
priceLHPot = high[1] < ta.valuewhen(phFound, high[lbR], 0)
hiddenBearCond = priceLH and oscHH and phFound
hiddenBearCondPot = priceLHPot and oscHHPot and phFoundPot
[bullCond, bullCondPot, hiddenBullCond, hiddenBullCondPot, bearCond, bearCondPot, hiddenBearCond, hiddenBearCondPot]
// @function Used to get pivots and potential pivots.
export getOscPivots(float osc, int lbL, int lbR) =>
// Confirmed Pivot.
plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
// Non Confirmed Pivot.
plFoundPot = na(ta.pivotlow(osc, 1, 1)) ? false : true
phFoundPot = na(ta.pivothigh(osc, 1, 1)) ? false : true
[plFound, phFound, plFoundPot, phFoundPot]
// ] |
WpProbabilisticLib | https://www.tradingview.com/script/zbPyIFwl/ | Wpkenpachi | https://www.tradingview.com/u/Wpkenpachi/ | 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/
// © Wpkenpachi
//@version=5
// @description Library that contains functions to calculate probabilistic based on historical candle analysis
library("WpProbabilisticLib")
int g = 1
int r = -1
int d = 0
// Doji meaning table
opts() => ["NO", "AS_RED", "AS_GREEN"]
[opt_no, opt_as_red, opt_as_green] = opts()
// @function This function check what type of candle is, based on its close and open prices
// @param open series float (open price)
// @param close series float (close price)
// @returns This function return the candle type (1 for Bullish, -1 Bearish, 0 as Doji candle)
export CandleType(float open, float close) =>
if (close > open)
g
else if (close < open)
r
else
d
// @function This function calculates the percentage difference between Bullish and Bearish in a candlestick range back in time and which is the type with the least occurrences
// @param open series float (open price series)
// @param close series float (close price series)
// @param qtd_candles_before simple int (Number of candles before to calculate)
// @param consider_dojis simple string (How to consider dojis (no consider "NO", as bearish "AS_RED", as bullish "AS_GREEN"))
// @returns tuple(float, int) (Returns the percentage difference between Bullish and Bearish candles and which type of candle has the least occurrences)
export CandleTypePercentDiff(series float open, series float close, simple int qtd_candles_before, simple string consider_dojis = "NO") =>
int qtd_red = int(0)
int qtd_green = int(0)
float red_p = float(0)
float green_p = float(0)
float diff_p = float(0)
int lower_p = int(0)
for int i = 1 to qtd_candles_before
if CandleType(open[i], close[i]) == r
qtd_red += 1
else if CandleType(open[i], close[i]) == g
qtd_green += 1
else
if consider_dojis == opt_as_red
qtd_red += 1
else if consider_dojis == opt_as_green
qtd_green += 1
red_p := (qtd_red * 100) / qtd_candles_before
green_p := (qtd_green * 100) / qtd_candles_before
diff_p := math.abs(red_p - green_p)
lower_p := (math.min(red_p, green_p) == red_p) and (red_p != green_p) ? r : g
[math.round(diff_p, 2), lower_p]
[diff, lower] = CandleTypePercentDiff(open, close, 89, "NO")
default_max = 16
default_min = -16
float default_exit_up = float(9.0)
float default_exit_down = float(-9.0)
max_diff_bullish = plot(default_max, "Max Bullish Diff", color=color.red)
current_diff = plot( diff * (lower * -1) , "Current Diff")
max_diff_bearish = plot(default_min, "Max Bearish Diff", color=color.green)
hline(default_exit_up, title="Exit", color=color.yellow)
hline(default_exit_down, title="Exit", color=color.yellow)
|
SizeAndPlace | https://www.tradingview.com/script/jFvpGj5i-SizeAndPlace/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// © kaigouthro
//@version=5
// @description size and location shortcuts
library("SizeAndPlace")
// for copy/paste
_size = input.string('Tiny', 'Size', options = ['Tiny','Small','Normal','Large','Huge','Auto' ])
_locattion = input.string('above', 'Location', options = ['above','belowr','bottom','absolute' ])
//@function table posittion from integer
//@param _inp 1-9
export table_posittion ( int _inp ) =>
switch _inp
1 => position.top_left
2 => position.top_center
3 => position.top_right
4 => position.middle_left
5 => position.middle_center
6 => position.middle_right
7 => position.bottom_left
8 => position.bottom_center
9 => position.bottom_right
//@function Size by number 1-5 (else auto)
//@param size 1-5
export size ( int size ) =>
txtSize = switch size
1 => size.tiny
2 => size.small
3 => size.normal
4 => size.large
5 => size.huge
=> size.auto
//@function Size by Short String for input to string
//@param
export size ( string txtSize ) =>
switch txtSize
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
'Auto' => size.auto
=> size.auto
//@function location from number
//@param _inp 1-4
export location ( int _inp ) =>
switch _inp
1 => location.abovebar
2 => location.belowbar
3 => location.bottom
4 => location.absolute
//@function location from number
//@param _inp Sttring name
export location ( string _inp ) =>
switch _inp
'above' => location.abovebar
'belowr' => location.belowbar
'bottom' => location.bottom
'absolute' => location.absolute
|
CarlLib | https://www.tradingview.com/script/mZMr2zK6-CarlLib/ | carlpwilliams2 | https://www.tradingview.com/u/carlpwilliams2/ | 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/
// © carlpwilliams2
//@version=5
// @description
library("CarlLib", overlay=true)
// @function returns values to plot/use volatility oscillator
// @param open the source of the close value to use
// @param open the source of the open value to use
// @param The oscillator length to use as a standard deviation
// @returns [x, y, spike, volOscBullish]
export VolatilityOscillator(float source, float open, int colOscLength) =>
spike = source - open
x = ta.stdev(spike,colOscLength)
y = ta.stdev(spike,colOscLength) * -1
volOscBullish = spike>x
[x, y, spike, volOscBullish]
// @function returns values representing the high of the most recent green and the low of the most recent red
// @param open open series
// @param close close series
// @param high high series
// @param close close series
// @param reqChangePerc the minimum require change percentage for the values to switch to new ones.
// @returns [highOfLastGreen, lowOfLastRed,changeOfLowPerc, distanceToHigh, distanceToLow, distanceToLongExitPercentage,distanceToShortExitPercentage]
export LastLowRedHighGreen(float open, float high, float low, float close, float reqChangePerc) =>
var lowOfLastRed =low
var highOfLastGreen = high
var tpLongPrice = close
candleIsRed = open>close
candleIsGreen = not candleIsRed
changeOfLowPerc = lowOfLastRed>low? ((lowOfLastRed - low)/low)*100 : ((low - lowOfLastRed)/lowOfLastRed) *100
changeOfHighPerc = highOfLastGreen>high? ((highOfLastGreen - high)/high) *100 : ((high - highOfLastGreen)/highOfLastGreen) *100
if(candleIsRed and barstate.isconfirmed and (changeOfLowPerc>reqChangePerc or changeOfLowPerc<0))
lowOfLastRed := low
if(candleIsGreen and barstate.isconfirmed and (changeOfHighPerc>reqChangePerc or changeOfHighPerc>0))
highOfLastGreen := high
distanceToHigh = (highOfLastGreen - close)
distanceToLow = (close - lowOfLastRed)
distanceToLongExitPercentage = (distanceToLow/close)*100
distanceToShortExitPercentage = (distanceToHigh/highOfLastGreen) * 100
// haveReasonableLongExit = distanceToLongExitPercentage > stopLossTarget
// haveReasonableShortExit = distanceToShortExitPercentage > stopLossTarget
[highOfLastGreen, lowOfLastRed,changeOfLowPerc, distanceToHigh, distanceToLow, distanceToLongExitPercentage,distanceToShortExitPercentage]
export pstdev (float Series, int Period) =>
mean = math.sum(Series, Period) / Period
summation = 0.0
for i=0 to Period-1
sampleMinusMean = nz(Series[i]) - mean
summation := summation + sampleMinusMean * sampleMinusMean
math.sqrt(summation / Period)
export candleDetails (float open, float high, float low, float close) =>
bodySize = math.abs(close - open)
upperShadow = math.max(high - math.max(close, open), 0)
// Calculate the size of the lower shadow
lowerShadow = math.max(math.min(close, open) - low, 0)
// Calculate the total size of the shadow
wickSize = upperShadow + lowerShadow
wickPercentage = (wickSize / (wickSize + bodySize)) * 100
lowerShadowPercentage = (lowerShadow /(lowerShadow + bodySize))*100
upperShadowPercentage = (upperShadow /(upperShadow+ bodySize))*100
shadowRatio = lowerShadow /(lowerShadow + upperShadow) * 100
[bodySize, wickSize, upperShadow,lowerShadow, lowerShadowPercentage,upperShadowPercentage,shadowRatio,wickPercentage]
export volumeHeatmap(int volumeMALength, int volumeStdLength) =>
length = volumeMALength
slength = volumeStdLength
thresholdExtraHigh =3// input.float(3, title="Extra High Volume Threshold")
thresholdHigh =1.5// input.float(1.5, title="High Volume Threshold")
thresholdMedium =0.2// input.float(0.2, title="Medium Volume Threshold")
thresholdNormal =-0.5// input.float(-0.5, title="Normal Volume Threshold")
//------------------------------------------------------------------------------
// Calcs
length := length > bar_index + 1 ? bar_index + 1 : length
slength := slength > bar_index + 1 ? bar_index + 1 : slength
mean = ta.sma(volume, length)
std = pstdev(volume, slength)
stdbar = (volume - mean) / std
//------------------------------------------------------------------------------
// Alerts
conditionExtraHigh = stdbar > thresholdExtraHigh
conditionHigh = stdbar <= thresholdExtraHigh and stdbar > thresholdHigh
conditionMedium = stdbar <= thresholdHigh and stdbar > thresholdMedium
conditionNormal = stdbar <= thresholdMedium and stdbar > thresholdNormal
conditionLow = stdbar <= thresholdNormal
[stdbar, conditionLow,conditionMedium, conditionHigh, conditionExtraHigh]
export maAndVolumeConfirmedSupretrend(float Close, int volumeMALength, int volumeStdLength) =>
[stdbar, conditionLow,conditionMedium, conditionHigh, conditionExtraHigh] = volumeHeatmap(volumeMALength, volumeStdLength)
ma1 = ta.ema(Close,50)
ma2 = ta.ema(Close, 200)
maLong = Close > ma1 and Close > ma2 and ma1>ma2
maShort = Close <ma1 and Close < ma2 and ma1 <ma2
// pp supertrend
prd = 2//input.int(defval = 2, title="Pivot Point Period", minval = 1, maxval = 50)
Factor=3//input.float(defval = 3, title = "ATR Factor", minval = 1, step = 0.1)
Pd= 10//input.int(defval = 10, title = "ATR Period", minval=1)
// get Pivot High/Low
float ph = ta.pivothigh(prd, prd)
float pl = ta.pivotlow(prd, prd)
// calculate the Center line using pivot points
var float center = na
float lastpp = ph ? ph : pl ? pl : na
if lastpp
if na(center)
center := lastpp
else
//weighted calculation
center := (center * 2 + lastpp) / 3
// upper/lower bands calculation
Up = center - (Factor * ta.atr(Pd))
Dn = center + (Factor * ta.atr(Pd))
// get the trend
float TUp = na
float TDown = na
Trend = 0
TUp := close[1] > TUp[1] ? math.max(Up, TUp[1]) : Up
TDown := close[1] < TDown[1] ? math.min(Dn, TDown[1]) : Dn
Trend := close > TDown[1] ? 1: close < TUp[1]? -1: nz(Trend[1], 1)
Trailingsl = Trend == 1 ? TUp : TDown
// check and plot the signals
bSignal = Trend == 1 and Trend[1] == -1
cBsignal = bSignal and maLong and (conditionHigh or conditionMedium)
ssignal = Trend == -1 and Trend[1] == 1
cSsignal = ssignal and maShort and (conditionHigh or conditionMedium)
[bSignal, cBsignal, ssignal, cSsignal]
export tripleSupertrend() =>
// 1
[supertrend1, direction1] = ta.supertrend(3, 12)
// 2
[supertrend2, direction2] = ta.supertrend(2, 1)
// 3
[supertrend3, direction3] = ta.supertrend(1, 10)
allBuy = (direction1 < 0) and (direction2 < 0) and (direction3 < 0)
allSell = (direction1 > 0) and (direction2 > 0) and (direction3 > 0)
[allBuy, allSell]
//--
export tdi(float src, int lengthrsi, int lengthband, int lengthrsipl)=>
r=ta.rsi(src, lengthrsi)
ma=ta.sma(r,lengthband)
offs=(1.6185 * ta.stdev(r, lengthband))
up=ma+offs
dn=ma-offs
mid=(up+dn)/2
mab=ta.sma(r, lengthrsipl)
// mbb=ta.sma(r, lengthtradesl)
mabCross = ta.crossover(mab,mid)
sharkFin = ta.crossover(mab,up)
[mid,mab,mabCross,sharkFin]
showVolOsc = input.bool(false,title="Show Volatility Oscillator")
showLastGreen = input.bool(false,title="Show Last green low/last red high")
stopLossTarget = input.float(0.5,title="Stop loss target %", group="Last Green Low/red high")
reqChangePerc = input.float(0.1,title="Change % required for new high/low", group="Last Green Low/red high")
[highOfLastGreen, lowOfLastRed,changeOfLowPerc, distanceToHigh, distanceToLow, distanceToLongExitPercentage,distanceToShortExitPercentage]
= LastLowRedHighGreen(open,high,low,close,reqChangePerc)
plot(showLastGreen and not ta.change(lowOfLastRed) ? lowOfLastRed : na, title = "Low of last red", style = plot.style_stepline_diamond, color = distanceToLongExitPercentage > stopLossTarget ? color.red:color.new(color.red,60), linewidth=2)
plot(showLastGreen and not ta.change(highOfLastGreen) ? highOfLastGreen : na, title="High of last green", style=plot.style_stepline_diamond, color = distanceToShortExitPercentage > stopLossTarget ? color.green:color.new(color.green,60), linewidth=2)
/// plot volOsc
[x, y, spike, volOscBullish] = VolatilityOscillator(close, open, 100)
plot(showVolOsc?spike:na, color = color.black, linewidth = 2, title = "Spike Linel")
p1 = plot(showVolOsc?x:na, "Upper Line")
[bodySize, wickSize, upperShadow,lowerShadow, lowerShadowPercentage,upperShadowPercentage,shadowRatio, wickPercentage]= candleDetails(open,high,low,close)
|
HighTimeframeSampling | https://www.tradingview.com/script/tRv6GGg7-HighTimeframeSampling/ | SimpleCryptoLife | https://www.tradingview.com/u/SimpleCryptoLife/ | 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/
// © SimpleCryptoLife
//@version=5
// @description Library for sampling high timeframe (HTF) data. Returns a matrix of historical values, an array of historical values, an arbitrary historical value, or the highest/lowest value in a range, spending a single security() call.
// An optional pass-through for the chart timeframe is included. Other than that case, the data is fixed and does not alter over the course of the HTF bar. It behaves consistently on historical and elapsed realtime bars.
// For now, it returns floating-point numbers only, and bools for the first two functions.
library("HighTimeframeSampling", overlay = true)
// 🙏 Credits: This library is (yet another) attempt at a solution of the problems in using HTF data that were laid out by Pinecoders - to whom, especially to Luc F, many thanks are due - in "security() revisited" - https://www.tradingview.com/script/00jFIl5w-security-revisited-PineCoders/, which I recommend you consult first. Go ahead, I'll wait.
// All code is my own.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// WHAT'S THE PROBLEM? OR, WHY NOT JUST USE SECURITY()
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// There are many difficulties with using HTF data, and many potential solutions. It's not really possible to convey it only in words: you need to see it on a chart.
// Before using this library, please refer to my other HTF library, HighTimeframeTiming: https://www.tradingview.com/script/F9vFt8aX-HighTimeframeTiming/, which explains it extensively, compares many different solutions, and demonstrates (what I think are) the advantages of using this very library, namely, that it's stable, accurate, versatile and inexpensive. Then if you agree, come back here and choose your function.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// MOAR EXPLANATION
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 🧹 Housekeeping: To see which plot is which, turn line labels on: Settings > Scales > Indicator Name Label. Vertical lines at the top of the chart show the open of a HTF bar: grey for historical and white for real-time bars.
// ‼ LIMITATIONS: To avoid strange behaviour, use this library on liquid assets and at chart timeframes high enough to reliably produce updates at least once per bar period.
// A more conventional and universal limitation is that the library does not offer an unlimited view of historical bars. You need to define upfront how many HTF bars you want to store. Very large numbers might conceivably run into data or performance issues.
// This should be obvious, but to be clear, you need to call the function on every bar update to avoid missing data.
// Another thing that should probably go without saying: you must supply the same timeframe to the functions here as you used in your security() call for the raw data.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// BRING ON THE FUNCTIONS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// @function f_HTF_Float(string _HTF, float _source, int _arrayHistory, int _HTF_Offset, bool _useLiveDataOnChartTF=false)
// Returns a floating-point number from a higher timeframe, with a historical operator within an abitrary (but limited) number of bars.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
// @param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
// @param int _arrayHistory is the number of HTF bars you want to store and must be greater than zero. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
// @param int _HTF_Offset is the historical operator for the value you want to return. E.g., if you want the most recent fixed close, _source=close and _HTF_Offset = 0. If you want the one before that, _HTF_Offset=1, etc.
// The number of HTF bars to look back must be zero or more, and must be one less than the number of bars stored.
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches the raw source values from security()[0].
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @returns a floating-point value that you requested from the higher timeframe.
// @function f_HTF_ArrayFloat(string _HTF, float _source, int _arrayHistory, bool _useLiveDataOnChartTF=false, int _startIn, int _endIn)
// Returns an array of historical values *of a single variable* from a higher timeframe, starting with the current bar. Optionally, returns a slice of the array. The array is in reverse chronological order, i.e., index 0 contains the most recent value.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
// @param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
// @param int _arrayHistory is the number of HTF bars you want to keep in the array.
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches raw source values from security().
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @param int _startIn is the array index to begin taking a slice. Must be at least one less than the length of the array; if out of bounds it is corrected to 0.
// @param int _endIn is the array index BEFORE WHICH to end the slice. If the ending index of the array slice would take the slice past the end of the array, it is corrected to the end of the array. The ending index of the array slice must be greater than or equal to the starting index. If the end is less than the start, the whole array is returned. If the starting index is the same as the ending index, an empty array is returned. If either the starting or ending index is negative, the entire array is returned (which is the default behaviour; this is effectively a switch to bypass the slicing without taking up an extra parameter).
// @returns an array of HTF values.
// @function f_HTF_HighestFloat(string _HTF="", float _source, int _arrayHistory, bool _useLiveDataOnChartTF=true, int _rangeIn)
// Returns the highest value within a range consisting of a given number of bars back from the most recent bar.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
// @param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
// @param int _arrayHistory is the number of HTF bars you want to store and must be greater than zero. You can't have a range greater than this number.
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches raw source values from security().
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @param _rangeIn is the number of bars to include in the range of bars from which we want to find the highest value. It is NOT the historical operator of the last bar in the range. The range always starts at the current bar. A value of 1 doesn't make much sense but the function will generously return the only value it can anyway. A value less than 1 doesn't make sense and will return an error. A value that is higher than the number of stored values will be corrected to equal the number of stored values.
// @returns a floating-point number representing the highest value in the range.
// @function f_HTF_LowestFloat(string _HTF="", float _source, int _arrayHistory, bool _useLiveDataOnChartTF=true, int _rangeIn)
// Returns the lowest value within a range consisting of a given number of bars back from the most recent bar.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
// @param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
// @param int _arrayHistory is the number of HTF bars you want to store and must be greater than zero. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches raw source values from security().
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @param _rangeIn is the number of bars to include in the range of bars from which we want to find the highest value. It is NOT the historical operator of the last bar in the range. The range always starts at the current bar. A value of 1 doesn't make much sense but the function will generously return the only value it can anyway. A value less than 1 doesn't make sense and will return an error. A value that is higher than the number of stored values will be corrected to equal the number of stored values.
// @returns a floating-point number representing the lowest value in the range.
// @function f_HTF_MatrixFloat(string _HTF="", float[] _sourceArray, int _matrixHistory, bool _useLiveDataOnChartTF=true)
// Returns a matrix of historical values *of an array* from a higher timeframe, starting with the current bar. Unlike f_HTF_ArrayFloat, there is no option to return a slice of the matrix. The matrix is in reverse chronological order, i.e., row 0 contains the most recent values.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
// @param float[] _sourceArray is the source array that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
// @param int _matrixHistory is the number of HTF bars for which you want to keep arrays in the matrix.
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches raw source values from security().
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @returns a matrix of historical HTF array values.
// @function f_HTF_Bool(string _HTF, bool _source, int _arrayHistory, int _HTF_Offset, bool _useLiveDataOnChartTF=false)
// Returns a boolean value from a higher timeframe, with a historical operator within an abitrary (but limited) number of bars.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
// @param bool _source is the source value that you want to sample.
// @param int _arrayHistory is the number of HTF bars you want to store and must be greater than zero. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
// @param int _HTF_Offset is the historical operator for the value you want to return. E.g., if you want the most recent fixed close, _source=close and _HTF_Offset = 0. If you want the one before that, _HTF_Offset=1, etc.
// The number of HTF bars to look back must be zero or more, and must be one less than the number of bars stored.
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches the raw source values from security()[0].
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @returns a boolean value that you requested from the higher timeframe.
// @function f_HTF_ArrayBool(string _HTF, bool _source, int _arrayHistory, bool _useLiveDataOnChartTF=false, int _startIn, int _endIn)
// Returns an array of historical values *of a single variable* from a higher timeframe, starting with the current bar. Optionally, returns a slice of the array. The array is in reverse chronological order, i.e., index 0 contains the most recent value.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
// @param bool _source is the source value that you want to sample.
// @param int _arrayHistory is the number of HTF bars you want to keep in the array.
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches raw source values from security().
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @param int _startIn is the array index to begin taking a slice. Must be at least one less than the length of the array; if out of bounds it is corrected to 0.
// @param int _endIn is the array index BEFORE WHICH to end the slice. If the ending index of the array slice would take the slice past the end of the array, it is corrected to the end of the array. The ending index of the array slice must be greater than or equal to the starting index. If the end is less than the start, the whole array is returned. If the starting index is the same as the ending index, an empty array is returned. If either the starting or ending index is negative, the entire array is returned (which is the default behaviour; this is effectively a switch to bypass the slicing without taking up an extra parameter).
// @returns an array of HTF values.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// INPUTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// Inputs needed for the library
bool in_show_HTF_Close = input.bool(defval=true, title="Show raw security()[0] data", group="Display (floats)", tooltip="The source float data that is requested using request.security().")
bool in_show_f_HTF_Float = input.bool(defval=true, title="Show function 1, f_HTF_Float()", tooltip="A single value [H] bars back.")
bool in_show_f_HTF_ArrayFloatLabel = input.bool(defval=true, title="Show function 2, f_HTF_ArrayFloat()", tooltip="The entire array of HTF values")
bool in_show_f_HTF_HighestFloat = input.bool(defval=true, title="Show function 3, f_HTF_HighestFloat()", tooltip="The highest HTF value in a range.")
bool in_show_f_HTF_LowestFloat = input.bool(defval=true, title="Show function 4, f_HTF_LowestFloat()", tooltip="The lowest HTF value in a range.")
bool in_show_f_HTF_MatrixFloat = input.bool(defval=true, title="Show function 5, f_HTF_MatrixFloat()", tooltip="A matrix of historical values of an array.")
bool in_show_HTF_BoolRaw = input.bool(defval=true, title="Show raw security()[0] data", group="Display (bools)", tooltip="The source bool data that is requested using request.security().")
bool in_show_f_HTF_Bool = input.bool(defval=true, title="Show function 1, f_HTF_Bool()", tooltip="A single boolean value [H] bars back.")
bool in_show_f_HTF_ArrayBoolLabel = input.bool(defval=true, title="Show function 2, f_HTF_ArrayBool()", tooltip="The entire array of HTF boolean values")
string in_HTF = input.timeframe(defval="", title="Higher Timeframe", group="General settings")
int in_historyLength = input.int(minval=1, maxval=100, defval=10, title="Number of HTF source values to store", tooltip="Must be one greater than the number of values to look back.")
bool in_useLiveDataOnChartTF = input.bool(defval=true, title="Use live data on chart timeframe (HTF data is always fixed)")
int in_HTF_Offset = input.int(defval=0, minval=0, maxval=4, title="No. of HTF bars to look back [H]", group="Single values")
int in_start = input.int(minval=-1, maxval=999, defval=0, title="Starting index of array subset", group="Arrays", tooltip="The array index to begin taking a slice. This number comes out the same whether you think of it as the array index or as the historical operator [ ]. A value of 0 starts at the current HTF bar. Wrong values are fixed silently; if irreparable, we return the entire array. If you don't supply any start and end values, the entire array is returned.")
int in_end = input.int(minval=-1, maxval=999, defval=-1, title="Ending index of array subset", tooltip="The array index BEFORE WHICH to end the slice. If you supply an end value of 2, the value at index 2 is NOT returned. This is the behaviour of the built-in array slice function and I kept it for consistency. This number comes out the same whether you think of it as the array index or as the historical operator [ ]. A value of 1 ends at the current HTF bar. Wrong values are fixed silently; if irrepairable, we return the entire array. If you don't supply any start and end values, the entire array is returned.")
int in_range = input.int(defval=5, minval=0, maxval=999, group="Highest/Lowest Float in a Range", title="Range", tooltip="Range (number of total bars starting from the current bar) within which to look for the highest/lowest value")
// === Import libraries
import SimpleCryptoLife/Labels/2 as SCL_Label
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// RAW HTF DATA |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// These raw HTF values are requested directly from the security() call on the current bar.
// The close is used as the source for all the float library functions (except f_HTF_MatrixFloat, which uses OHLC), and can also be plotted.
// The boolean value _isUpCandle is used as the source for boolean functions.
f_OHLC() =>
_open=open, _high=high, _low=low, _close=close
bool _isUpCandle=_close > _open ? true : false
[_open, _high, _low, _close, _isUpCandle]
[HTF_Open, HTF_High, HTF_Low, HTF_Close, HTF_IsUpCandle] = request.security(syminfo.tickerid, in_HTF, f_OHLC(), barmerge.gaps_off, barmerge.lookahead_off)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// FLOAT FUNCTION 1: GET A VALUE |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_Float(string _HTF="", float _source, int _arrayHistory, int _HTF_offset=0, bool _useLiveDataOnChartTF=true) =>
var string _errorTextFunctionName = "f_HTF_Float", var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeSampling" // Error-checking.
if timeframe.in_seconds(_HTF) < timeframe.in_seconds(timeframe.period)
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 001:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _arrayHistory < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 002:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _HTF_offset < 0
runtime.error("The number of HTF bars to look back must be zero or more." + " [Error 003:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _HTF_offset + 1 > _arrayHistory
runtime.error("The number of stored values configured is " + str.tostring(_arrayHistory) + ", and must be at least " + str.tostring(_HTF_offset+1) + " in order to look " + str.tostring(_HTF_offset) + " HTF bars back." + " [Error 004:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var float[] _arraySource = array.new_float(_arrayHistory,na) // Create the array to hold the floats.
bool _isChartTimeframe = _HTF=="" or _HTF == timeframe.period // Check if we are using a "higher" timeframe that's actually the chart timeframe.
var int _offset = _isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1 // Use live data on chart TF if that option is selected; otherwise use fixed (the previous bar's) data.
// By using timeframe.change(), we store the source value only when the HTF bar *opens*. We do updates throughout every bar on the chart timeframe; otherwise all throughout the chart bar that corresponds to the first HTF bar.
// It might be more efficient to update only at the beginning of the chart bar, but a) it didn't seem to work, and b) even if I could get it working, I suspect it might be less robust.
if _isChartTimeframe or timeframe.change(_HTF)
array.unshift(_arraySource,_source[_offset]) // Add the source value to index 0 and shift other indexes along. It's important to keep the order so that it's simple to look up values.
if array.size(_arraySource) > _arrayHistory
array.pop(_arraySource) // Remove the oldest value, keeping the array the same length.
float _myFloat = array.get(_arraySource,_HTF_offset) // Return the one value requested.
_myFloat
float HTF_FloatValue = f_HTF_Float(in_HTF, HTF_Close, in_historyLength, in_HTF_Offset, in_useLiveDataOnChartTF) // Call the function and use the offset to get a certain value
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// FLOAT FUNCTION 2: GET AN ARRAY OF VALUES |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_ArrayFloat(string _HTF="", float _source, int _arrayHistory, bool _useLiveDataOnChartTF=true, int _startIn=0, int _endIn=-1) =>
var string _errorTextFunctionName = "f_HTF_ArrayFloat", var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeSampling"
// For timeframe problems we throw an error because we can't fix them from here.
if timeframe.in_seconds(_HTF) < timeframe.in_seconds(timeframe.period)
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 005:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
// For a negative or zero array length we throw errors because we can't guess what the user wants this particular value to be.
if _arrayHistory < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 006:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var float[] _arraySource = array.new_float(_arrayHistory,na)
bool _isChartTimeframe = _HTF=="" or _HTF == timeframe.period
var int _offset = _isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1
if _isChartTimeframe or timeframe.change(_HTF)
array.unshift(_arraySource,_source[_offset])
if _arrayHistory > array.size(_arraySource)
array.pop(_arraySource)
// Fix all slice start and end problems silently, erring towards returning more of the array.
int _start = (_startIn < 0) or (_endIn < 0) ? 0 : _startIn >= _arrayHistory ? 0 : _endIn < _startIn ? 0 : _startIn
int _end = (_startIn < 0) or (_endIn < 0) ? _arrayHistory : _endIn < _startIn ? _arrayHistory : _endIn < _startIn ? _arrayHistory : _endIn > _arrayHistory ? _arrayHistory : _endIn
float[] _arraySubset = array.slice(_arraySource,_start,_end)
_arraySubset
float[] HTF_ArrayFloat = f_HTF_ArrayFloat(in_HTF, HTF_Close, in_historyLength, in_useLiveDataOnChartTF, in_start, in_end)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// FLOAT FUNCTION 3: RETURN THE HIGHEST VALUE IN A RANGE |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_HighestFloat(string _HTF="", float _source, int _arrayHistory, bool _useLiveDataOnChartTF=true, int _rangeIn) =>
var string _errorTextFunctionName = "f_HTF_HighestFloat", var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeSampling"
if timeframe.in_seconds(_HTF) < timeframe.in_seconds(timeframe.period)
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 007:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _arrayHistory < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 008:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var float[] _arraySource = array.new_float(_arrayHistory,na)
bool _isChartTimeframe = _HTF=="" or _HTF == timeframe.period
var int _offset = _isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1
if _isChartTimeframe or timeframe.change(_HTF)
array.unshift(_arraySource,_source[_offset])
if _arrayHistory > array.size(_arraySource)
array.pop(_arraySource)
// Error-check the range. A value of 1 doesn't make much sense but the function will generously return the only value it can anyway. A value less than 1 doesn't make any sense and will return an error.
if _rangeIn < 1
runtime.error("The range within which to look for the highest value must be greater than zero." + " [Error 009:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
int _range = _rangeIn > _arrayHistory ? _arrayHistory : _rangeIn // A range that is higher than the number of stored values will be corrected to equal the number of stored values.
float[] _arraySubset = array.slice(_arraySource,0,_range)
float _highest = array.max(_arraySubset) // Get the largest value (array.max(_arraySubset,0) breaks it for some reason)
_highest
float HTF_Highest = f_HTF_HighestFloat(in_HTF, HTF_Close, in_historyLength, in_useLiveDataOnChartTF, in_range)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// FLOAT FUNCTION 4: RETURN THE LOWEST VALUE IN A RANGE |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_LowestFloat(string _HTF="", float _source, int _arrayHistory, bool _useLiveDataOnChartTF=true, int _rangeIn) =>
var string _errorTextFunctionName = "f_HTF_LowestFloat", var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeSampling"
if timeframe.in_seconds(_HTF) < timeframe.in_seconds(timeframe.period)
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 010:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _arrayHistory < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 011:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var float[] _arraySource = array.new_float(_arrayHistory,na)
bool _isChartTimeframe = _HTF=="" or _HTF == timeframe.period
var int _offset = _isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1
if _isChartTimeframe or timeframe.change(_HTF)
array.unshift(_arraySource,_source[_offset])
if _arrayHistory > array.size(_arraySource)
array.pop(_arraySource)
if _rangeIn < 1
runtime.error("The range within which to look for the lowest value must be greater than zero." + " [Error 012:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
int _range = _rangeIn > _arrayHistory ? _arrayHistory : _rangeIn
float[] _arraySubset = array.slice(_arraySource,0,_range)
float _lowest = array.min(_arraySubset)
_lowest
float HTF_Lowest = f_HTF_LowestFloat(in_HTF, HTF_Close, in_historyLength, in_useLiveDataOnChartTF, in_range)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// FLOAT FUNCTION 5: GET A MATRIX OF VALUES |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_MatrixFloat(string _HTF="", float[] _sourceArray, int _matrixHistory, bool _useLiveDataOnChartTF=true) =>
var string _errorTextFunctionName = "f_HTF_MatrixFloat", var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeSampling"
// For timeframe problems we throw an error because we can't fix them from here.
if timeframe.in_seconds(_HTF) < timeframe.in_seconds(timeframe.period)
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 013:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
// For a negative or zero array length we throw errors because we can't guess what the user wants this particular value to be.
if _matrixHistory < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 014:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
int _sourceArrayLength = array.size(_sourceArray) // Get the length of the input array
// Throw an error if the input array has changed size
if _sourceArrayLength > _sourceArrayLength[1] or _sourceArrayLength < _sourceArrayLength[1]
runtime.error("Length of input array _sourceArray must stay the same [Error 015:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var _matrixSource = matrix.new<float>(_matrixHistory, _sourceArrayLength)
bool _isChartTimeframe = _HTF=="" or _HTF == timeframe.period
var int _offset = _isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1
int _matrixRows = matrix.rows(_matrixSource)
if _isChartTimeframe or timeframe.change(_HTF)
matrix.add_row(_matrixSource, 0, _sourceArray[_offset]) // Insert the source array at the beginning of the matrix. I don't know if you can just add [offset] to an array but let's try.
if _matrixRows > _matrixHistory
matrix.remove_row(_matrixSource,(_matrixRows)) // Remove the last row of the matrix if it has more rows than the input height
_matrixSource
var float[] sourceArray = array.new_float(4,na) // Create the input array for the function to sample
array.set(sourceArray,0,HTF_Open), array.set(sourceArray,1,HTF_High), array.set(sourceArray,2,HTF_Low), array.set(sourceArray,3,HTF_Close) // Populate it with HTF OHLC values
HTF_Matrix = f_HTF_MatrixFloat(_HTF=in_HTF, _sourceArray=sourceArray, _matrixHistory=in_historyLength, _useLiveDataOnChartTF=in_useLiveDataOnChartTF)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// BOOL FUNCTION 1: GET A VALUE |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_Bool(string _HTF="", bool _source, int _arrayHistory, int _HTF_offset=0, bool _useLiveDataOnChartTF=true) =>
var string _errorTextFunctionName = "f_HTF_Bool", var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeSampling" // Error-checking.
if timeframe.in_seconds(_HTF) < timeframe.in_seconds(timeframe.period)
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 016:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _arrayHistory < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 017:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _HTF_offset < 0
runtime.error("The number of HTF bars to look back must be zero or more." + " [Error 018:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _HTF_offset + 1 > _arrayHistory
runtime.error("The number of stored values configured is " + str.tostring(_arrayHistory) + ", and must be at least " + str.tostring(_HTF_offset+1) + " in order to look " + str.tostring(_HTF_offset) + " HTF bars back." + " [Error 019:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var bool[] _arraySource = array.new_bool(_arrayHistory,na) // Create the array to hold the bools.
bool _isChartTimeframe = _HTF=="" or _HTF == timeframe.period // Check if we are using a "higher" timeframe that's actually the chart timeframe.
var int _offset = _isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1 // Use live data on chart TF if that option is selected; otherwise use fixed (the previous bar's) data.
// By using timeframe.change(), we store the source value only when the HTF bar *opens*. We do updates throughout every bar on the chart timeframe; otherwise all throughout the chart bar that corresponds to the first HTF bar.
// It might be more efficient to update only at the beginning of the chart bar, but a) it didn't seem to work, and b) even if I could get it working, I suspect it might be less robust.
if _isChartTimeframe or timeframe.change(_HTF)
array.unshift(_arraySource,_source[_offset]) // Add the source value to index 0 and shift other indexes along. It's important to keep the order so that it's simple to look up values.
if array.size(_arraySource) > _arrayHistory
array.pop(_arraySource) // Remove the oldest value, keeping the array the same length.
bool _myBool = array.get(_arraySource,_HTF_offset) // Return the one value requested.
_myBool
bool HTF_BoolValue = f_HTF_Bool(in_HTF, HTF_IsUpCandle, in_historyLength, in_HTF_Offset, in_useLiveDataOnChartTF) // Call the function and use the offset to get a certain value
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// BOOL FUNCTION 2: GET AN ARRAY OF VALUES |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_ArrayBool(string _HTF="", bool _source, int _arrayHistory, bool _useLiveDataOnChartTF=true, int _startIn=0, int _endIn=-1) =>
var string _errorTextFunctionName = "f_HTF_ArrayBool", var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeSampling"
// For timeframe problems we throw an error because we can't fix them from here.
if timeframe.in_seconds(_HTF) < timeframe.in_seconds(timeframe.period)
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 020:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
// For a negative or zero array length we throw errors because we can't guess what the user wants this particular value to be.
if _arrayHistory < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 021:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var bool[] _arraySource = array.new_bool(_arrayHistory,na)
bool _isChartTimeframe = _HTF=="" or _HTF == timeframe.period
var int _offset = _isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1
if _isChartTimeframe or timeframe.change(_HTF)
array.unshift(_arraySource,_source[_offset])
if _arrayHistory > array.size(_arraySource)
array.pop(_arraySource)
// Fix all slice start and end problems silently, erring towards returning more of the array.
int _start = (_startIn < 0) or (_endIn < 0) ? 0 : _startIn >= _arrayHistory ? 0 : _endIn < _startIn ? 0 : _startIn
int _end = (_startIn < 0) or (_endIn < 0) ? _arrayHistory : _endIn < _startIn ? _arrayHistory : _endIn < _startIn ? _arrayHistory : _endIn > _arrayHistory ? _arrayHistory : _endIn
bool[] _arraySubset = array.slice(_arraySource,_start,_end)
_arraySubset
bool[] HTF_ArrayBool = f_HTF_ArrayBool(in_HTF, HTF_IsUpCandle, in_historyLength, in_useLiveDataOnChartTF, in_start, in_end)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// PLOTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
plot(in_show_HTF_Close ? HTF_Close : na, color=color.new(color.yellow,40), linewidth=14, title=" Raw request.security()[0] float data")
plotchar(in_show_HTF_BoolRaw, char="B", color=(HTF_IsUpCandle ? color.green : not HTF_IsUpCandle ? color.red : color.yellow), location=location.top, size=size.small, title=" Raw request.security()[0] bool data")
plot(in_show_f_HTF_Float ? HTF_FloatValue : na, style=plot.style_circles, title=" 😍 f_HTF_Float()", color=color.new(color.orange,30), linewidth=12)
plotchar(timeframe.change(in_HTF), "timeframe.change(in_HTF)", "|", location.top, color=barstate.ishistory ? color.gray : color.white, size = size.normal) // Show when a new HTF bar opens
// Show the bool value plus array in a label
string labelTextBool = in_show_f_HTF_Bool ? "Bool value [" + str.tostring(in_HTF_Offset) + "]: ": na
labelTextBool += in_show_f_HTF_Bool and HTF_BoolValue ? "True" : in_show_f_HTF_Bool and HTF_BoolValue == false ? "False" : in_show_f_HTF_Bool ? "na" : na
labelTextBool += in_show_f_HTF_ArrayBoolLabel ? "\nBool array: " + str.tostring(HTF_ArrayBool) : na
SCL_Label.labelLast(_condition=in_show_f_HTF_Bool or in_show_f_HTF_ArrayBoolLabel, _style=label.style_label_down, _text=labelTextBool, _offset=0, _y=high, _textAlign=text.align_left)
// Show the float array, plus highest/lowest values, in a label
string labelTextHighestLowestFloat = in_show_f_HTF_ArrayFloatLabel ? "Float Array: " + str.tostring(HTF_ArrayFloat) : na
string labelTextHighest = in_show_f_HTF_HighestFloat ? "\nHighest Value in last " + str.tostring(in_range) + " bars: " + str.tostring(HTF_Highest) : na
labelTextHighestLowestFloat += labelTextHighest
string labelTextLowest = in_show_f_HTF_LowestFloat ? "\nLowest Value in last " + str.tostring(in_range) + " bars: " + str.tostring(HTF_Lowest) : na
labelTextHighestLowestFloat += labelTextLowest
SCL_Label.labelLast(_condition=in_show_f_HTF_HighestFloat or in_show_f_HTF_LowestFloat or in_show_f_HTF_ArrayFloatLabel, _style=label.style_label_up, _text=labelTextHighestLowestFloat, _offset=0, _y=low, _textAlign=text.align_left)
// Show the matrix contents in a table
if in_show_f_HTF_MatrixFloat
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "f_HTF_MatrixFloat\nOHLC:")
table.cell(t, 0, 1, str.tostring(HTF_Matrix))
// ======================================================= //
// //
// (╯°□°)╯︵ ǝlʇoʇsᴉɹ∀ - sɹɐǝʎ ʇou `spǝǝp uᴉ ǝʌᴉl ǝM //
// //
// ======================================================= // |
drawcandles | https://www.tradingview.com/script/Mu97K0Xr-drawcandles/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 274 | library | 5 | MPL-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 simple utility to draw different candles using box and lines. Quite useful for drawing candles such as zigzag candles or MTF candles
library("drawcandles", overlay=true)
import HeWhoMustNotBeNamed/arrayutils/18 as pa
// @function draws candles based on ohlc values
// @param o Open Price
// @param h High Price
// @param l Low Price
// @param c Close Price
// @param oBar Open Time
// @param cBar Close Time
// @returns void
export draw(float o, float h, float l, float c, int oBar, int cBar) =>
var candles = array.new<box>()
var upperWicks = array.new<line>()
var lowerWicks = array.new<line>()
bottom = math.min(o,c)
top = math.max(o,c)
if(array.size(candles)>0)
lastCandle = array.get(candles, 0)
lastStart = box.get_left(lastCandle)
lastUpperWick = array.get(upperWicks, 0)
lastLowerWick = array.get(lowerWicks, 0)
if(lastStart == oBar)
pa.shift(candles)
pa.shift(upperWicks)
pa.shift(lowerWicks)
else
box.set_border_style(lastCandle, line.style_solid)
box.set_border_width(lastCandle, 2)
line.set_width(lastUpperWick, 2)
line.set_width(lastLowerWick, 2)
candleColor = o>c? color.red: color.green
newCandle = box.new(oBar, top, cBar, bottom, border_color=candleColor, border_width=1,
border_style=line.style_dotted, extend=extend.none, xloc=xloc.bar_time, bgcolor=color.new(candleColor, 80))
midTime = (oBar + cBar)/2
newUpperWick = line.new(midTime, top, midTime, h, xloc=xloc.bar_time, extend=extend.none, color=candleColor, style=line.style_solid, width=1)
newLowerWick = line.new(midTime, bottom, midTime, l, xloc=xloc.bar_time, extend=extend.none, color=candleColor, style=line.style_solid, width=1)
pa.unshift(candles, newCandle, 500)
pa.unshift(upperWicks, newUpperWick, 500)
pa.unshift(lowerWicks, newLowerWick, 500)
//MTF Example
tf = input.timeframe("M")
[o,h,l,c,v,oBar,cBar] = request.security(syminfo.tickerid, tf, [open, high, low, close, volume, time, time_close])
if(timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(tf))
draw(o,h,l,c,oBar,cBar) |
PlurexSignalIntegration | https://www.tradingview.com/script/T1aznIds-PlurexSignalIntegration/ | FlintMonk | https://www.tradingview.com/u/FlintMonk/ | 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/
// © Plurex
//@version=5
library("PlurexSignalIntegration")
LONG = "LONG"
SHORT = "SHORT"
CLOSE_LONGS = "CLOSE_LONGS"
CLOSE_SHORTS = "CLOSE_SHORTS"
CLOSE_ALL = "CLOSE_ALL"
// @function Build a Plurex market 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 simple 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 simple Plurex Signal Messages
// @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].
// @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 Executes strategy actions with Plurex Signal messages
// @param secret The secret for your Signal on plurex
// @param openLong Strategy should open long if true, aggregated with other boolean values
// @param openShort Strategy should open short if true, aggregated with other boolean values
// @param closeLongs Strategy should close longs if true, aggregated with other boolean values
// @param closeShorts Strategy should close shorts if true, aggregated with other boolean values
// @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
export executeStrategy(string secret, bool openLong, bool openShort, bool closeLongs, bool closeShorts, string marketOverride = "") =>
actuallyOpenLong = openLong and not closeLongs and not openShort
actuallyOpenShort = openShort and not closeShorts and not openLong
if actuallyOpenLong
strategy.entry("long", strategy.long, alert_message=simpleMessage(secret=secret, action=LONG, marketOverride=marketOverride))
if actuallyOpenShort
strategy.entry("short", strategy.short, alert_message=simpleMessage(secret=secret, action=SHORT, marketOverride=marketOverride))
if closeLongs and closeShorts
strategy.close_all(alert_message=simpleMessage(secret=secret, action=CLOSE_ALL, marketOverride=marketOverride))
else if closeLongs
strategy.close("long", alert_message=simpleMessage(secret=secret, action=CLOSE_LONGS, marketOverride=marketOverride))
else if closeShorts
strategy.close("short", alert_message=simpleMessage(secret=secret, action=CLOSE_SHORTS, marketOverride=marketOverride))
|
StapleIndicators | https://www.tradingview.com/script/tUArxEvY-StapleIndicators/ | gliderfund | https://www.tradingview.com/u/gliderfund/ | 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/
// © gliderfund
//@version=5
// import gliderfund/StapleIndicators/1 as ind
// @description This Library provides some common indicators commonly referenced from other studies in Pine Script
library(title = "StapleIndicators", overlay = true)
// #############################################
// #############################################
// SQUEEZE
// #############################################
// #############################################
// @function Volatility Squeeze
// @param bbSrc (Optional) Bollinger Bands Source. By default close
// @param bbPeriod (Optional) Bollinger Bands Period. By default 20
// @param bbDev (Optional) Bollinger Bands Standard Deviation. By default 2.0
// @param kcSrc (Optional) Keltner Channel Source. By default close
// @param kcPeriod (Optional) Keltner Channel Period. By default 20
// @param kcATR (Optional) Keltner Channel ATR Multiplier. By default 1.5
// @param signalPeriod (Optional) Keltner Channel ATR Multiplier. By default 1.5
// @returns [sqzOn, sqzOsc, sqzSignal]
export squeeze(series float bbSrc = close, simple int bbPeriod = 20, simple float bbDev = 2.0, series float kcSrc = close, simple int kcPeriod = 20, simple float kcATR = 1.5, simple int signalPeriod = 13) =>
// Bollinger Bands
[bbBasis, bbHigh, bbLow] = ta.bb(bbSrc, bbPeriod, bbDev)
// Keltner Channel (simplified version from Linda Raschke)
kcBasis = ta.ema(kcSrc, kcPeriod)
kcDev = kcATR * ta.atr(kcPeriod)
kcHigh = kcBasis + kcDev
kcLow = kcBasis - kcDev
// Squeeze
sqzOn = (bbLow > kcLow) and (bbHigh < kcHigh)
sqzOsc = bbHigh - kcHigh
// Signal Line
sqzSignal = ta.ema(sqzOsc, signalPeriod)
aboveSignal = sqzOsc > sqzSignal
belowSignal = sqzOsc <= sqzSignal
// Result
[sqzOn, sqzOsc, sqzSignal, aboveSignal, belowSignal]
// End of Function
// #############################################
// #############################################
// ADX: AVERAGE DIRECTIONAL INDEX
// #############################################
// #############################################
// @function ADX: Average Directional Index
// @param diPeriod (Optional) Directional Indicator Period. By default 14
// @param adxPeriod (Optional) ADX Smoothing. By default 14
// @param signalPeriod (Optional) Signal Period. By default 13
// @param adxTier1 (Optional) ADX Tier #1 Level. By default 20
// @param adxTier2 (Optional) ADX Tier #2 Level. By default 15
// @param adxTier3 (Optional) ADX Tier #3 Level. By default 10
// @returns [oscillator, signal, adxOff, adx1, adx2, adx3]
export adx(simple int diPeriod = 14, simple int adxPeriod = 14, simple int signalPeriod = 13, simple int adxTier1 = 20, simple int adxTier2 = 15, simple int adxTier3 = 10) =>
// ADX is a lagging indicator that helps us to read if we are in trending or ranging market
// Below 20 signals range
// Above 20 signals trend
[_, _, oscillator] = ta.dmi(diPeriod, adxPeriod)
// Signal
signal = ta.ema(oscillator, signalPeriod)
// Conditions
adxOff = oscillator > adxTier1
adx1 = (oscillator <= adxTier1) and (oscillator > adxTier2)
adx2 = (oscillator <= adxTier2) and (oscillator > adxTier3)
adx3 = (oscillator <= adxTier3)
// Result
[oscillator, signal, adxOff, adx1, adx2, adx3]
// End of Function
// #############################################
// #############################################
// SMAs: SIMPLE MOVING AVERAGES
// #############################################
// #############################################
// @function Delivers a set of frequently used Simple Moving Averages
// @param srcMa (Optional) MA Source. By default 'close'
// @returns [sma3, sma5, sma6, sma7, sma8, sma10, sma20, sma25, sma30, sma50, sma100, sma200, smaAllTime]
export smaPreset(series float srcMa = close) =>
// SMAs
sma3 = ta.sma(srcMa, 3)
sma5 = ta.sma(srcMa, 5)
sma6 = ta.sma(srcMa, 6)
sma7 = ta.sma(srcMa, 7)
sma8 = ta.sma(srcMa, 8)
sma10 = ta.sma(srcMa, 10)
sma20 = ta.sma(srcMa, 20)
sma25 = ta.sma(srcMa, 25)
sma30 = ta.sma(srcMa, 30)
sma50 = ta.sma(srcMa, 50)
sma100 = ta.sma(srcMa, 100)
sma200 = ta.sma(srcMa, 200)
smaAllTime = ta.cum(srcMa) / (ta.barssince(barstate.isfirst) + 1)
// Result
[sma3, sma5, sma6, sma7, sma8, sma10, sma20, sma25, sma30, sma50, sma100, sma200, smaAllTime]
// End of Function
// #############################################
// #############################################
// EMAs: EXPONENTIAL MOVING AVERAGES
// #############################################
// #############################################
// @function Delivers a set of frequently used Exponential Moving Averages
// @param srcMa (Optional) MA Source. By default 'close'
// @returns [ema3, ema5, ema8, ema9, ema13, ema18, ema21, ema34, ema50, ema55, ema89, ema100, ema144, ema200, ema377]
export emaPreset(series float srcMa = close) =>
// EMAs
ema3 = ta.ema(srcMa, 3)
ema5 = ta.ema(srcMa, 5)
ema8 = ta.ema(srcMa, 8)
ema9 = ta.ema(srcMa, 9)
ema13 = ta.ema(srcMa, 13)
ema18 = ta.ema(srcMa, 18)
ema21 = ta.ema(srcMa, 21)
ema34 = ta.ema(srcMa, 34)
ema50 = ta.ema(srcMa, 50)
ema55 = ta.ema(srcMa, 55)
ema89 = ta.ema(srcMa, 89)
ema100 = ta.ema(srcMa, 100)
ema144 = ta.ema(srcMa, 144)
ema200 = ta.ema(srcMa, 200)
ema377 = ta.ema(srcMa, 377)
// Result
[ema3, ema5, ema8, ema9, ema13, ema18, ema21, ema34, ema50, ema55, ema89, ema100, ema144, ema200, ema377]
// End of Function
// #############################################
// #############################################
// MA SELECTION TOOL
// #############################################
// #############################################
// @function Filters and outputs the selected MA
// @param ma (Optional) MA text. By default 'Ema-21'
// @param srcMa (Optional) MA Source. By default 'close'
// @returns maSelected
export maSelect(simple string ma = "Ema-21", series float srcMa = close) =>
float maSelected = switch ma
"Sma-3" => ta.sma(srcMa, 3)
"Ema-3" => ta.ema(srcMa, 3)
"Sma-5" => ta.sma(srcMa, 5)
"Ema-5" => ta.ema(srcMa, 5)
"Sma-6" => ta.sma(srcMa, 6)
"Sma-7" => ta.sma(srcMa, 7)
"Sma-8" => ta.sma(srcMa, 8)
"Ema-8" => ta.ema(srcMa, 8)
"Ema-9" => ta.ema(srcMa, 9)
"Sma-10" => ta.sma(srcMa, 10)
"Ema-13" => ta.ema(srcMa, 13)
"Ema-18" => ta.ema(srcMa, 18)
"Sma-20" => ta.sma(srcMa, 20)
"Ema-21" => ta.ema(srcMa, 21)
"Sma-25" => ta.sma(srcMa, 25)
"Sma-30" => ta.sma(srcMa, 30)
"Ema-34" => ta.ema(srcMa, 34)
"Sma-50" => ta.sma(srcMa, 50)
"Ema-50" => ta.ema(srcMa, 50)
"Ema-55" => ta.ema(srcMa, 55)
"Ema-89" => ta.ema(srcMa, 89)
"Sma-100" => ta.sma(srcMa, 100)
"Ema-100" => ta.ema(srcMa, 100)
"Ema-144" => ta.ema(srcMa, 144)
"Sma-200" => ta.sma(srcMa, 200)
"Ema-200" => ta.ema(srcMa, 200)
"Ema-377" => ta.ema(srcMa, 377)
"Sma All-Time" => ta.cum(srcMa) / (ta.barssince(barstate.isfirst) + 1)
=> na
// Result
maSelected
// End of Function
// #############################################
// #############################################
// ADAPTATIVE PERIOD
// #############################################
// #############################################
// @function Adaptative Period
// @param modeAdaptative (Optional) Adaptative Mode. By default 'Average'
// @param src (Optional) Source. By default 'close'
// @param maxLen (Optional) Max Period. By default '60'
// @param minLen (Optional) Min Period. By default '4'
// @returns periodAdaptative
export periodAdapt(simple string modeAdaptative = "Average", series float src = close, simple int maxLen = 60, simple int minLen = 4) =>
// Credit to EmpiricalFX for his implementation of Cosine, In-Phase & Quadrature IFM [Ehlers] (https://www.tradingview.com/script/1LF6cPby-Cosine-In-Phase-Quadrature-IFM-Ehlers/)
// General Vars
lengthIQ = 0.0
lengthCos = 0.0
P = src - src[7]
// Conditions
modeIQ = modeAdaptative == "In-Phase & Quadrature"
modeCos = modeAdaptative == "Cosine"
modeAvg = modeAdaptative == "Average" // Averages Cosine and I-Q
// I-Q IFM
iMult = 0.635, qMult = 0.338
inPhase = 0.0, quadrature = 0.0
deltaIQ = 0.0, instIQ = 0.0
re = 0.0, im = 0.0, V = 0.0
if(modeIQ or modeAvg)
inPhase := 1.25 * (P[4] - iMult * P[2]) + iMult * nz(inPhase[3])
quadrature := P[2] - qMult * P + qMult * nz(quadrature[2])
re := 0.2 * (inPhase * inPhase[1] + quadrature * quadrature[1]) + 0.8 * nz(re[1])
im := 0.2 * (inPhase * quadrature[1] - inPhase[1] * quadrature) + 0.8 * nz(im[1])
deltaIQ := re != 0.0 ? math.atan(im / re) : deltaIQ
for i = 0 to maxLen
V := V + deltaIQ[i]
instIQ := (V > 2 * math.pi) and (instIQ == 0.0) ? i : instIQ
instIQ := instIQ == 0.0 ? nz(instIQ[1]) : instIQ
lengthIQ := 0.25 * instIQ + 0.75 * nz(lengthIQ[1], 1)
// COSINE IFM
s2 = 0.0, s3 = 0.0
v2 = 0.0, v4 = 0.0
deltaCos = 0.0, instCos = 0.0
if(modeCos or modeAvg)
s2 := 0.2 * (P[1] + P) * (P[1] + P) + 0.8 * nz(s2[1])
s3 := 0.2 * (P[1] - P) * (P[1] - P) + 0.8 * nz(s3[1])
v2 := s2 != 0 ? math.sqrt(s3 / s2) : v2
deltaCos := s3 != 0 ? 2 * math.atan(v2) : deltaCos
for i = 0 to maxLen
v4 := v4 + deltaCos[i]
instCos := (v4 > 2 * math.pi) and (instCos == 0.0) ? i - 1 : instCos
instCos := instCos == 0.0 ? instCos[1] : instCos
lengthCos := 0.25 * instCos + 0.75 * nz(lengthCos[1], 1)
// Adaptative result
int periodAdaptative = switch
modeIQ => math.round(lengthIQ)
modeCos => math.round(lengthCos)
modeAvg => math.round((lengthCos + lengthIQ) / 2.0)
periodAdaptative := math.max(periodAdaptative, minLen)
// Result
periodAdaptative
// End of Function
// #############################################
// #############################################
// AZLEMA: ADAPTATIVE ZERO-LAG EMA
// #############################################
// #############################################
// @function Azlema: Adaptative Zero-Lag Ema
// @param modeAdaptative (Optional) Adaptative Mode. By default 'Average'
// @param srcMa (Optional) MA Source. By default 'close'
// @returns azlema
export azlema(simple string modeAdaptative = "Average", series float srcMa = close) =>
// Vars
maxLen = 60, minLen = 4
azlema = 0.0
// Call the adaptative function
periodAdaptative = periodAdapt(modeAdaptative, srcMa, maxLen, minLen)
// Azlema
alphaZlema = 2 / (periodAdaptative + 1)
azlema := (alphaZlema * srcMa) + ((1 - alphaZlema) * nz(azlema[1]))
// Result
azlema
// End of Function
// #############################################
// #############################################
// SSMA: Smooth Simple MA
// #############################################
// #############################################
// @function SSMA: Smooth Simple MA
// @param lsmaVar Linear Regression Curve.
// @param srcMa (Optional) MA Source. By default 'close'
// @param periodMa (Optional) MA Period. By default '13'
// @returns ssma
export ssma(series float lsmaVar, series float srcMa = close, simple int periodMa = 13) =>
// Factors
a1 = math.exp(-1.414 * 3.14159 / periodMa)
b1 = 2 * a1 * math.cos(1.414 * 3.14159 / periodMa)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
// Ssma
ssma = (c1 * (srcMa + nz(srcMa[1])) / 2) + (c2 * nz(lsmaVar[1])) + (c3 * nz(lsmaVar[2]))
// Result
ssma
// End of Function
// #############################################
// #############################################
// JURIK VOLATILITY FACTOR
// #############################################
// #############################################
// @function Jurik Volatility Factor
// @param srcMa (Optional) MA Source. By default 'close'
// @param periodMa (Optional) MA Period. By default '7'
// @returns [del1, del2, kv, len, pow2]
export jvf(series float srcMa = close, simple int periodMa = 7) =>
// Credit to gorx1 for his implementation of the volatility factor (https://www.tradingview.com/script/gwzRz6tI-Jurik-Moving-Average/)
// Vars
upBand = srcMa, lowBand = srcMa // Upper and Lower Bands
sumVolat = 0.0 // Incremental Volatility Sum
avgLen = 65 // Period of Average Volatility
avgVolat = 0.0 // Average Volatility
// Distance between price and bands
del1 = math.abs(srcMa - nz(upBand[1]))
del2 = math.abs(srcMa - nz(lowBand[1]))
// Price volatility
priceVolat = del1 == del2 ? 0 : math.max(del1, del2)
// Incremental Volatility Sum
sumVolat := nz(sumVolat[1]) + (priceVolat - priceVolat[10]) / 10
// Average Volatility
tempVolat = ta.sma(sumVolat, avgLen) // To avoid pine compiler warning of inconsistency
avgVolat := bar_index <= avgLen ? nz(avgVolat[1]) + 2.0 * (sumVolat - nz(avgVolat[1])) / (avgLen + 1) : tempVolat
// Periodic factor
len = 0.5 * (periodMa - 1)
len1 = math.max(math.log(math.sqrt(len)) / math.log(2.0) + 2, 0)
// Power of Relative Volatility
pow1 = math.max(len1 - 2, 0.5)
// Relative Price Volatility
relVolat = avgVolat > 0 ? priceVolat / avgVolat : 0
relVolat :=
relVolat > math.pow(len1, 1 / pow1) ? math.pow(len1, 1 / pow1) :
relVolat < 1 ? 1 : relVolat
// Volatility Factor
pow2 = math.pow(relVolat, pow1)
len2 = math.sqrt(len) * len1
bet = len2 / (len2 + 1)
kv = math.pow(bet, math.sqrt(pow2))
// Result
[del1, del2, kv, len, pow2]
// End of Function
// #############################################
// #############################################
// JURIK BANDS
// #############################################
// #############################################
// @function Jurik Bands
// @param srcMa (Optional) MA Source. By default 'close'
// @param periodMa (Optional) MA Period. By default '7'
// @returns [upBand, lowBand]
export jBands(series float srcMa = close, simple int periodMa = 7) =>
// Credit to gorx1 for his integrated implementation of the bands along with the volatility factor (https://www.tradingview.com/script/gwzRz6tI-Jurik-Moving-Average/)
// Retrieve the factors
[del1, del2, kv, _, _] = jvf(srcMa, periodMa)
// Jurik Bands
upBand = (bar_index + 1) == 1 or (del1 < 0) ? srcMa : srcMa + kv * del1
lowBand = (bar_index + 1) == 1 or (del2 < 0) ? srcMa : srcMa - kv * del2
// Result
[upBand, lowBand]
// End of Function
// #############################################
// #############################################
// JMA: JURIK MOVING AVERAGE
// #############################################
// #############################################
// @function Jurik MA (JMA)
// @param srcMa (Optional) MA Source. By default 'close'
// @param periodMa (Optional) MA Period. By default '7'
// @param phase (Optional) Phase. By default '50'
// @returns jma
export jma(series float srcMa = close, simple int periodMa = 7, simple float phase = 50) =>
// Credit to gorx1 for his integrated implementation of the JMA along with the volatility factor (https://www.tradingview.com/script/gwzRz6tI-Jurik-Moving-Average/)
// Retrieve the factors
[_, _, _, len, pow2] = jvf(srcMa, periodMa)
// Vars
stage1 = 0.0, stage2 = 0.0, stage3 = 0.0 // JMA stages
factor2 = 0.0, factor3 = 0.0 // Factors in Smoothing stages
// Phase Ratio
phaseRatio =
phase < -100 ? 0.5 :
phase > 100 ? 2.5 : phase / 100 + 1.5
// Periodic Factor
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
// Dynamic Factor
alpha = math.pow(beta, pow2)
// Stage #1: Preliminary smoothing by an Adaptative Ema
stage1 := (1 - alpha) * srcMa + alpha * nz(stage1[1])
// Stage #2: One more smoothing using Kalman Filter
factor2 := (srcMa - stage1) * (1 - beta) + beta * nz(factor2[1])
stage2 := stage1 + phaseRatio * factor2
// Stage #3: Final smoothing by Jurik Adaptative Filter
factor3 := (stage2 - nz(stage3[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(factor3[1])
stage3 := nz(stage3[1]) + factor3
jma = stage3
// Result
jma
// End of Function
// #############################################
// #############################################
// MA CUSTOM
// #############################################
// #############################################
// @function Creates a custom Moving Average
// @param ma (Optional) MA text. By default 'Ema'
// @param srcMa (Optional) MA Source. By default 'close'
// @param periodMa (Optional) MA Period. By default '13'
// @param lrOffset (Optional) Linear Regression Offset. By default '0'
// @param almaOffset (Optional) Alma Offset. By default '0.85'
// @param almaSigma (Optional) Alma Sigma. By default '6'
// @param jmaPhase (Optional) JMA Phase. By default '50'
// @param azlemaMode (Optional) Azlema Adaptative Mode. By default 'Average'
// @returns maTF
export maCustom(simple string ma = "Ema", series float srcMa = close, simple int periodMa = 13, simple int lrOffset = 0, simple float almaOffset = 0.85, simple int almaSigma = 6, simple float jmaPhase = 50, simple string azlemaMode = "Average") =>
smaVar = ta.sma(srcMa, periodMa)
smmaVar = 0.0
smmaVar :=
ma != "Smma" ? float(na) :
(na(smmaVar[1]) ? smaVar :
(smmaVar[1] * (periodMa - 1) + srcMa) / periodMa)
mavVar = 0.0
mavVar := ma == "Mav" ? nz(mavVar[1]) + (srcMa - nz(mavVar[1])) / periodMa : float(na)
float maSelected = switch ma
"Sma" => smaVar // Simple MA
"Ema" => ta.ema(srcMa, periodMa) // Exponential MA
"Dema" => 2 * ta.ema(srcMa, periodMa) - ta.ema(ta.ema(srcMa, periodMa), periodMa) // Double Exponential MA (by Patrick G. Mulloy)
"Tema" => 3 * (ta.ema(srcMa, periodMa) - ta.ema(ta.ema(srcMa, periodMa), periodMa)) + ta.ema(ta.ema(ta.ema(srcMa, periodMa), periodMa), periodMa) // Triple Exponential MA (by Patrick G. Mulloy)
"Wma" => ta.wma(srcMa, periodMa) // Weighted MA
"Vwma" => ta.vwma(srcMa, periodMa) // Volume Weighted MA (by Buff P. Dormeier)
"Hma" => ta.hma(srcMa, periodMa) // Hull MA (by Alan Hull). Previously: wma(2 * wma(src, periodMa / 2) - wmaVar
"Lsma" => ta.linreg(srcMa, periodMa, lrOffset) // Least Squares MA (Moving Linear Regression)
"Rma" => ta.rma(srcMa, periodMa) // Relative MA (by J. Welles Wilder)
"Alma" => ta.alma(srcMa, periodMa, almaOffset, almaSigma) // Arnaud Legoux MA (by Arnaud Legoux and Dimitris Kouzis-Loukas)
"Tma" => ta.sma(smaVar, periodMa) // Triangular MA (generalized by John F. Ehlers)
"Dwma" => ta.wma(ta.wma(srcMa, periodMa), periodMa) // Double Weighted (Linear) MA
"Smma" => smmaVar // Smoothed MA
"Mav" => mavVar // Modified MA (used by Dinapoli in the Preferred Stochastic)
"Zlema" => ta.ema(srcMa + (srcMa - srcMa[(periodMa - 1) / 2]), periodMa) // Zero Lag Exponential MA (by John F. Ehlers and Ric Way).
"Azlema" => azlema(azlemaMode, srcMa) // Adaptative Zero Lag Ema
"Jma" => jma(srcMa, periodMa, jmaPhase) // Jurik MA (by Mark Jurik)
"Ssma" => ssma(ta.linreg(srcMa, periodMa, lrOffset), srcMa, periodMa) // Smooth Simple MA
"Swma" => ta.swma(srcMa) // Symmetrically weighted MA with fixed length: 4. Weights: [1/6, 2/6, 2/6, 1/6]
"All-Time" => ta.cum(srcMa) / (ta.barssince(barstate.isfirst) + 1) // All-time MA comprising the whole history of that market
=>
runtime.error("MA not yet supported")
float(na)
// Result
maSelected
// End of Function
|
FunctionIntrabarCrossValue | https://www.tradingview.com/script/mzWx1JPM-FunctionIntrabarCrossValue/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 74 | library | 5 | MPL-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
library(title='FunctionIntrabarCrossValue')
import RicardoSantos/FunctionForecastLinear/1 as lin
// @function Find the minimum difference of a intrabar cross and return its median value.
// @param a float, series a.
// @param b float, series b.
// @param step float, step to iterate x axis, default=0.01
// @returns float
export intrabar_cross_value(float a, float b, float step=0.01) => //{
if ta.cross(a, b)
array<float> _x = array.from(0.0, 1.0)
array<float> _a = array.from(a, a[1])
array<float> _b = array.from(b, b[1])
float _previous_min = na
float _mina = na
float _minb = na
for _i = step to 1.0 by step
float _ai = lin.forecast(_x, _a, _i)
float _bi = lin.forecast(_x, _b, _i)
float _diff = _ai > _bi ? _ai - _bi : _bi - _ai
switch
na(_previous_min) => _previous_min := _diff , continue
_diff <= _previous_min =>
_previous_min := _diff
_mina := _ai
_minb := _bi
(_mina + _minb) / 2
//}
float sma1 = ta.sma(close, 10)
float sma2 = ta.sma(close, 20)
float x = intrabar_cross_value(sma1, sma2)
plot(series=sma1, title='', color=color.orange)
plot(series=sma2, title='', color=color.red)
plot(series=x, title='', color=color.blue, style=plot.style_cross, linewidth=2)
plot(series=fixnan(x), title='', color=color.teal)
|
CandleStore | https://www.tradingview.com/script/EZBnQDow-CandleStore/ | livingdraculaog | https://www.tradingview.com/u/livingdraculaog/ | 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/
// © livingdraculaog
//@version=5
// @description This library provides to provide simple, semantic, reusable utility functions for analyzing candlesticks, wicks, patterns, trends, volume, and more...
library("CandleStore", true)
////////////////////////////////////////////////////////////////////
// Candle Utilities
////////////////////////////////////////////////////////////////////{
// @returns a series of floats, representing the difference between the high and low
export _candleRange() => high-low
// @param barsback, an int representing how far back you want to get a range
export _PreviousCandleRange(simple int barsback) => high[barsback]-low[barsback]
// @returns a true if close < open
export redCandle() => close < open
// @returns a true if close > open
export greenCandle()=> close > open
// @returns a true if open < close
export _WhiteBody() => open < close
// @returns a true if open > close
export _BlackBody() => open > close
// @returns a series of floats representing the high - open
export HighOpenDiff() => high - open
// @returns a series of floats representing the open - low
export OpenLowDiff() => open - low
// @returns a SERIES of BOOL, after checking if CLOSE was greater or equal to previous OPEN
export _isCloseAbovePreviousOpen(simple int length) => close >= open[length]
// @returns a SERIES of BOOL.
export _isCloseBelowPrevious() => close <= close[1]
// @returns a SERIES of BOOL, after checking if CLOSE was Greater or equal to previous OPEN
export _isOpenGreaterThanPrevious() => open >= close[1]
// @returns a SERIES of BOOL, after checking if OPEN was LESS than or equal to previous CLOSE.
export _isOpenLessThanPrevious() => open <= close[1] // previous _WhiteBody?
export BodyHigh() => math.max(close, open)
export BodyLow() => math.min(close, open)
// @returns a SERIES of FLOATS, each of which are the difference between the top and bottom per candle.
export _candleBody() => BodyHigh() - BodyLow()
// @function _BodyAvg(int) function.
// @param candle_length, Required (recommended is 6).
export _BodyAvg(simple int length) => ta.ema(_candleBody(), length)
// @returns a SERIES of BOOL, after checking if the candle BODY was less then Body Average.
// @param candle_length. length of the slow EMA
export _SmallBody(simple int length) => _candleBody() < _BodyAvg(length)
// @returns a SERIES of BOOL, after checking if the candle BODY was GREATER then Body Average.
export _LongBody(simple int length) => _candleBody() > _BodyAvg(length)
_IsInsideBar = BodyHigh()[1] > BodyHigh() and BodyLow()[1] < BodyLow()
_candleBodyMiddle = _candleBody() / 2 + BodyLow()
////# Shadow
_ShadowPercent = 5.0 // size of shadows
_ShadowEqualsPercent = 100.0
_ShadowDominatLength = 2.0 // shows the number of times the shadow dominates the candlestick body
_UpShadow = high - BodyHigh()
_DownShadow = BodyLow() - low
_HasUpShadow = _UpShadow > _ShadowPercent / 100 * _candleBody()
_HasDownShadow = _DownShadow > _ShadowPercent / 100 * _candleBody()
_ShadowEquals = _UpShadow == _DownShadow or (math.abs(_UpShadow - _DownShadow) / _DownShadow * 100) < _ShadowEqualsPercent and (math.abs(_DownShadow - _UpShadow) / _UpShadow * 100) < _ShadowEqualsPercent
////
////////////////////////////////////////////////////////////////////
////# Wick Utilities
////////////////////////////////////////////////////////////////////{
// This Indicator measures the wick parts of candles and sum it up.
// Wick part of candle is a sign of strength that's why it measures the 60 bars of candles wick. then sum it up and converted it in percentage.
// The output is indicated in the last 10 candles. that's how simple this indicator is but very useful to analyze the strength of every candles.
// The upper numbers is the bear power.
// The lower numbers is the bull power.
// @function bearWick() function.
// @returns a SERIES of FLOATS, checks if it's a blackBody(open > close), if it is, than check the difference between the high and open, else checks the difference between high and close.
export bearWick() => high - (_BlackBody() ? open : close)
// @returns a SERIES of FLOATS, checks if it's a whiteBody(open < close), if it is, than check the difference of OPEN & LOW (open - close), else checks the difference of OPEN & low (open - low).
export bullWick() => (_WhiteBody() ? open : close) - low
// @returns a SERIES of FLOATS, checks if the candle is green, than check the difference of CLOSE & OPEN (close - open), else checks the difference of OPEN & CLOSE (open - close).
export barlength() => greenCandle() ? close - open : open - close
export sumbarlength() => math.sum(barlength(), 60)
export sumbull() => math.sum(bearWick(), 60) / sumbarlength() * 100
export sumbear() => math.sum(bullWick(), 60) / sumbarlength() * 100
bullPower_converted = str.tostring(math.floor(sumbull()))
bearPower_converted = str.tostring(math.floor(sumbear()))
////////////////////////////////////////////////////////////////////}
////////////////////////////////////////////////////////////////////}
// Volume Utilities
////////////////////////////////////////////////////////////////////{
////# Constants for volume fight
export bull_vol() => _WhiteBody() ? volume : volume * (HighOpenDiff() ) / ( _candleRange() )
export bear_vol() => _BlackBody() ? volume : volume * (OpenLowDiff() ) / ( _candleRange() )
// @returns simple int, which is dynamically smoothed based on the timeframe. On higher TF such as the hourly or daily we only look 11 bars back, on smaller tf, we use 50 bars.
export volumeFightMA() => timeframe.isdaily ? 11 : 50
// Smoothing to reduce false signals and highlight the flat zone.
export volumeFightDelta() => 15
// @returns a series of floats, based off volume-weighted moving averages (vwma) with bull_vol() as a source and volumeFightMA() as the length
export weightedAVG_BullVolume() => ta.vwma(bull_vol() , volumeFightMA() )
// @returns a series of floats, based off volume-weighted moving averages (vwma) with bear_vol() as a source and volumeFightMA() as the length
export weightedAVG_BearVolume() => ta.vwma(bear_vol() , volumeFightMA() )
// @returns a series of floats to normalize and smooth the values
export VolumeFightDiff() => ta.sma(weightedAVG_BullVolume() / volume - 1 - (weightedAVG_BearVolume() / volume - 1), volumeFightMA() )
// @returns a series of floats to determine average value for calculation flat-filter
export VolumeFightFlatFilter() => math.abs(weightedAVG_BullVolume() + weightedAVG_BearVolume() ) / 2
////#═════════════════════════════════
////# User Defined Fight Strategy
// @function avg_bull_vol(int) function.
// @param candle_length, Required (recommended is 11).
export avg_bull_vol(simple int userMA) => ta.vwma(bull_vol(), userMA) //determine vwma
// @function avg_bear_vol(int) function.
// @param candle_length, Required (recommended is 11).
export avg_bear_vol(simple int userMA) => ta.vwma(bear_vol(), userMA)
// @function diff_vol(int) function.
// @param candle_length, Required (recommended is 11).
export diff_vol(simple int userMA) => ta.sma(avg_bull_vol(userMA) / volume - 1 - (avg_bear_vol(userMA) / volume - 1), userMA) //normalize and smooth the values
// @function vol_flat(int) function.
// @param candle_length, Required (recommended is 11).
export vol_flat(simple int userMA) => math.abs(avg_bull_vol(userMA) + avg_bear_vol(userMA) ) / 2 //determine average value for calculation flat-filter
//@returns bool - determine up volume zones
export bullVolumeZone(simple int userMA,simple int userDelta) => avg_bull_vol(userMA) > avg_bear_vol(userMA) and vol_flat(userMA) / avg_bull_vol(userMA) < 1 - userDelta / 100
//@returns bool - determine down volume zones
export bearVolumeZone(simple int userMA,simple int userDelta) => avg_bull_vol(userMA) < avg_bear_vol(userMA) and vol_flat(userMA) / avg_bear_vol(userMA) < 1 - userDelta / 100
////# ═════════════════════════════════
// @returns series of bool, if there is a bullish volume profile
export BullishVolumeProfile() => weightedAVG_BullVolume() > weightedAVG_BearVolume() and VolumeFightFlatFilter() / weightedAVG_BullVolume() < (1 - volumeFightDelta() / 100 )
// @returns series of bool, if there is a bearish volume profile
export BearishVolumeProfile() => weightedAVG_BullVolume() < weightedAVG_BearVolume() and VolumeFightFlatFilter() / weightedAVG_BearVolume() < (1 - volumeFightDelta() / 100 )
////////////////////////////////////////////////////////////////////}
// Pivots
////////////////////////////////////////////////////////////////////{
// @function Calculates the pivot point and returns its value.
// @param _type Specifies the type of pivot point.
// @param _open The open price
// @param _high The high price
// @param _low The low price
// @param _clsoe The close price
// @returns Returns the value of the calculated pivot point as a tuple.
export pivots (simple string _type, float _open, float _high, float _low, float _close) =>
PP = 0.0
R1 = 0.0, R2 = 0.0, R3 = 0.0, R4 = 0.0, R5 = 0.0
S1 = 0.0, S2 = 0.0, S3 = 0.0, S4 = 0.0, S5 = 0.0
if _type == 'Traditional'
PP := (_high + _low + _close) / 3
R1 := PP + PP - _low
S1 := PP - (_high - PP)
R2 := PP + _high - _low
S2 := PP - (_high - _low)
R3 := _high + 2 * (PP - _low)
S3 := _low - 2 * (_high - PP)
true
else if _type == 'Fibonacci'
PP := (_high + _low + _close) / 3
R1 := PP + (_high - _low) * 0.382
S1 := PP - (_high - _low) * 0.382
R2 := PP + (_high - _low) * 0.618
S2 := PP - (_high - _low) * 0.618
R3 := PP + (_high - _low) * 1.000
S3 := PP - (_high - _low) * 1.000
R4 := PP + (_high - _low) * 1.272
S4 := PP - (_high - _low) * 1.272
R5 := PP + (_high - _low) * 1.618
S5 := PP - (_high - _low) * 1.618
true
else if _type == 'Woodie'
PP := (_high + _low + 2 * _open) / 4
R1 := PP + PP - _low
S1 := PP - (_high - PP)
R2 := PP + _high - _low
S2 := PP - (_high - _low)
R3 := _high + 2 * (PP - _low)
S3 := _low - 2 * (_high - PP)
R4 := R3 + _high - _low
S4 := S3 - (_high - _low)
true
else if _type == 'Classic'
PP := (_high + _low + _close) / 3
pivot_range = _high - _low
R1 := PP * 2 - _low
S1 := PP * 2 - _high
R2 := PP + 1 * pivot_range
S2 := PP - 1 * pivot_range
R3 := PP + 2 * pivot_range
S3 := PP - 2 * pivot_range
R4 := PP + 3 * pivot_range
S4 := PP - 3 * pivot_range
true
else if _type == 'DM'
pivotX_Demark_X = _high + _low * 2 + _close
if _close == _open
pivotX_Demark_X := _high + _low + _close * 2
if _close > _open
pivotX_Demark_X := _high * 2 + _low + _close
PP := pivotX_Demark_X / 4
R1 := pivotX_Demark_X / 2 - _low
S1 := pivotX_Demark_X / 2 - _high
else if _type == 'Camarilla'
PP := (_high + _low + _close) / 3
pivot_range = _high - _low
R1 := _close + pivot_range * 1.1 / 12.0
S1 := _close - pivot_range * 1.1 / 12.0
R2 := _close + pivot_range * 1.1 / 6.0
S2 := _close - pivot_range * 1.1 / 6.0
R3 := _close + pivot_range * 1.1 / 4.0
S3 := _close - pivot_range * 1.1 / 4.0
R4 := _close + pivot_range * 1.1 / 2.0
S4 := _close - pivot_range * 1.1 / 2.0
true
else if _type == 'Expected Pivot Points'
PP := (_high + _low + _close) / 3
R1 := PP * 2 - _low
S1 := PP * 2 - _high
R2 := PP + (R1 - S1)
S2 := PP - (R1 - S1)
true
[PP, R1, S1, R2, S2, R3, S3, R4, S4, R5, S5]
// @function Calculate the Central Pivot Range
// @param _high The high price
// @param _low The low price
// @param _clsoe The close price
// @returns Returns the values as a tuple.
export cpr (float _high, float _low, float _close) =>
PP = (_high + _low + _close) / 3
BC = (_high + _low) / 2
TC = PP - BC + PP
CPR = math.abs(TC - BC)
[BC, TC, CPR]
// @function Calculate the HTF values
// @param _htf Resolution
// @returns Returns the values as a tuple.
export htf_ohlc (simple string _htf) =>
var htf_o = 0., var htf_h = 0., var htf_l = 0., htf_c = close
var htf_ox = 0., var htf_hx = 0., var htf_lx = 0., var htf_cx = 0.
if ta.change(time(_htf))
htf_ox := htf_o, htf_o := open
htf_hx := htf_h, htf_h := high
htf_lx := htf_l, htf_l := low
htf_cx := htf_c[1]
else
htf_h := math.max(high, htf_h)
htf_l := math.min(low , htf_l)
[htf_ox, htf_hx, htf_lx, htf_cx, htf_o, htf_h, htf_l, htf_c]
c_none = color.new(color.black, 100)
option_pivot1 = 'All'
option_pivot2 = 'New only'
option_pivot3 = 'None'
option_pivot_label1 = 'Levels'
option_pivot_label2 = 'Levels & Price'
option_pivot_label3 = 'Price'
// @function Renders a label
// @returns Returns a label
export render_pivots_label (bool _show, int _x, float _y, string _text, color _color, string _style, string _xloc, bool _show_history, string _pivotsLabel) =>
var label my_label = na
if _show
v_price = str.format('{0,number,#.###}', _y)
v_text = ''
if _pivotsLabel == option_pivot_label1
v_text := _text
else if _pivotsLabel == option_pivot_label2
v_text := _text + ' (' + v_price + ')'
else if _pivotsLabel == option_pivot_label3
v_text := v_price
my_label := label.new(_x, _y, v_text, textcolor=_color, color=c_none, style=_style, size=size.normal, xloc=_xloc)
if not _show_history
label.delete(my_label[1])
// @function Renders a box
// @returns Returns a box
export render_pivots_box (bool _show,int _x1,float _y1, int _x2,float _y2,color _color, string _xloc, bool _show_history, bool _should_delete, int _transp) =>
var box my_box = na
if _show
my_box := box.new(_x1, _y1, _x2, _y2, bgcolor=color.new(_color, _transp), border_color=c_none, xloc=_xloc)
if (not _show_history) or _should_delete
box.delete(my_box[1])
// @function Renders a line for pivot points
// @returns Returns line
export render_pivots_line (bool _show,int _x1, float _y, int _x2, int _width, color _color, string _style, string _xloc, bool _show_history, bool _should_delete, int _transp) =>
var line my_line = na
if _show and _y > 0
my_line := line.new(_x1, _y, _x2, _y, width=_width, color=color.new(_color, _transp), style=_style, xloc=_xloc)
if (not _show_history) or _should_delete
line.delete(my_line[1])
my_line
////////////////////////////////////////////////////////////////////}
// Trend Utilities
////////////////////////////////////////////////////////////////////{
// @function isDownTrend() function.
// @param MAlength, Required (recommended is 50 or 200).
// @returns series of BOOL, if close < priceAVG
export isDownTrend(simple int MAlength) => close < (ta.sma(close, MAlength))
// @function isUpTrend() function.
// @param MAlength, Required (recommended is 50 or 200).
// @returns series of BOOL, if close < priceAVG
export isUpTrend(simple int MAlength) => close > ta.sma(close, MAlength)
export fastEMA() => ta.ema(close, 6)
export slowEMA() => ta.ema(close, 25)
////# BULL
export _isUp(simple int fast) => close > ta.ema(close, fast)
// @function _isStrongUp(int) function.
// @param int Required. length of the slow EMA (recommended is 6)
// @returns a series of bool, if the close > ema(close,x) (slowMA). The purpose of this is to help identify the "Ceiling".
export _isStrongUp(int x) => close > ta.ema(close, x)
////# BEAR
// @function _isStrongDown(int) function.
// @param int Required. length of the slow EMA (recommended is 25)
// @returns a series of bool, if the close < ema(close,x) (slowMA). The purpose of this is to help identify the "Floor".
export _isDown(int x) => close < ta.ema(close, x )
// @function _isStrongDown(int) function.
// @param int Required. length of the slow EMA (recommended is 25)
// @returns a series of bool, if the close < ema(close,x) (slowMA). The purpose of this is to help identify the "Floor".
export _isStrongDown(int x) => close < ta.ema(close, x)
////# NA
// @function _isFastOverSlow, checks if the cross has occured and returns a series of bool.
// @param fast. length of the slow EMA (recommended is 6)
// @param slow. length of the slow EMA (recommended is 25)
export _isFastOverSlow(int fast, int slow) => ta.ema(close, fast) > ta.ema(close, slow)
//ta.crossunder(fast, slow)
// @function _isCrossUnderSlow, checks if close has crossed UNDER the slowEMA
// @param slow. length of the slow EMA (recommended is 25)
export _isCrossUnderSlow(int length) => ta.crossunder(close, ta.ema(close, length) )
// @function _isCrossOverSlow, checks if close has crossed OVER the slowEMA
// @param slow. length of the slow EMA (recommended is 25)
export _isCrossOverSlow(int length) => ta.crossover(close, ta.ema(close, length) )
// NA
isFastOverSlow = fastEMA() > slowEMA()
isCrossUnderSlow = ta.crossunder(close, slowEMA() ) // NA UP?
isCrossOverSlow = ta.crossover(close, slowEMA() ) // NA Down?
// @returns a true if the slowEMA > fastEMA
// export isFastOverSlow()=> fe > se ? true : false
// BEARish Leg
isStrongUp() => close > slowEMA() // yellow
isDown() => close < fastEMA() // black
// BULLish Legs
isStrongDown() => close < slowEMA() // dark green
isUp() => close > fastEMA() // green
// @returns a true if the close < slowEMA.
// export isStrongDown()=> ( close < se ) ? true : false
// @returns a true if the close > fastEMA. The purpose of this is to help identify the "FLOOR of a trend"
// export isUp()=> (close > fe) ? true : false
//// TREND COLORS
_emaDOWN = #660000
_StrongDown = #004d40
// neutral
_naCandle = #ffffff
// strong trends
_emaUP = #009688
_StrongUP = #ffeb3b
export _emaDOWNColor() => #660000
export _StrongDownColor() => #004d40
// neutral
export _naCandleColor() => #ffffff
// strong trends
export _emaUPColor() => #009688
export _StrongUPColor() => #ffeb3b
////# Volume
useVolume = true
volumeDown1 = 100
volumeDown2 = 50
volumeDown3 = 100
///
volumeUp1 = 1
volumeUp2 = 50
volumeUp3 = 1
////
volumeLength = 21
avrg = ta.sma(volume, volumeLength)
////
volDown1 = volume > avrg * 1.5 and redCandle()
volDown2 = volume >= avrg * 0.5 and volume <= avrg * 1.5 and redCandle()
volDown3 = volume < avrg * 0.5 and redCandle()
////
volUp1 = volume > avrg * 1.5 and greenCandle()
volUp2 = volume >= avrg * 0.5 and volume <= avrg * 1.5 and greenCandle()
volUp3 = volume < avrg * 0.5 and greenCandle()
//// Set the opacity based on the volume
// volume down?
cold1 = volumeDown1
cold2 = volumeDown2
cold3 = volumeDown3
// vol up?
hot1 = volumeUp1
hot2 = volumeUp2
hot3 = volumeUp3
////# Convert EMA colors to volume-based colors
// @function createVolumeCandles() function. USAGE : useVolume ? createVolumeCandles(_emaDOWN) : _emaDOWN
// @param color Color to display
export createVolumeCandles(color _color) => ////{
color = volDown1 ? color.new(_color, cold1) : volDown2 ? color.new(_color, cold2) : volDown3 ? color.new(_color, cold3) : volUp1 ? color.new(_color, hot1) : volUp2 ? color.new(_color, hot2) : volUp3 ? color.new(_color, hot3) : na
color
////}
//// Pass in user selected color, than adjust opacity based on volume and return a new color
//// The returned color will than be passed into BC
___emaDOWN = useVolume ? createVolumeCandles(_emaDOWN) : _emaDOWN
___StrongDown = useVolume ? createVolumeCandles(_StrongDown) : _StrongDown
// neutral
___naCandle = useVolume ? createVolumeCandles(_naCandle) : _naCandle
// strong trends
___emaUP = useVolume ? createVolumeCandles(_emaUP) : _emaUP
___StrongUP = useVolume ? createVolumeCandles(_StrongUP) : _StrongUP
////# DIP
export StrongDownBuy(bool _volume) => isStrongDown() and isUp() and _volume
//
//// Coloring Algorithm ////
trendColors = isFastOverSlow ? isCrossUnderSlow ? ___naCandle : isUp() ? ___emaUP : isStrongUp() ? ___StrongUP : _naCandle : isCrossOverSlow ? ___naCandle : isDown() ? ___emaDOWN : isStrongDown() ? ___StrongDown : isUp() ? isStrongUp() ? ___StrongUP : na : na
// export trendCandles() => plotcandle(open, high, low, close, title='Drac Candles', color= trendColors)
plotcandle(open, high, low, close, title='Drac Candles', color= trendColors)
////////////////////////////////////////////////////////////////////}
////////////////////////////////////////////////////////////////////
// Patterns Utilities
////////////////////////////////////////////////////////////////////{
//@returns a series of bool, if there is a EngulfingBullish
export _isEngulfingBullish() => (open[1]-close[1])>0 and (close-open)>0 and high>high[1] and low<low[1] and (close-open)>(open[1]-close[1]) and (close-open)>(high-close) and (close-open)>(open-low)
//@returns a series of bool, if there is a EngulfingBearish
export _isEngulfingBearish() => (close[1]-open[1])>0 and (open-close)>0 and high>high[1] and low<low[1] and (open-close)>(close[1]-open[1]) and (open-close)>(high-open) and (open-close)>(close-low)
//@returns a series of bool, if there is a dojiup
export dojiup() => (open-close)>0 ? (high-open)>(open-close) and (close-low)>(open-close) and (close-low)>(high-open) and (open-close)<((high-open)/8) : (open-low)>(close-open) and (high-close)>(close-open) and (open-low)>(high-close) and (close-open)<((high-close)/8)
//@returns a series of bool, if there is a dojidown
export dojidown() => (open-close)>0 ? (high-open)>(open-close) and (close-low)>(open-close) and (high-open)>(close-low) and (open-close)<((close-low)/8) : (open-low)>(close-open) and (high-close)>(close-open) and (high-close)>(open-low) and (close-open)<((high-close)/8)
//@returns a series of bool, if there is a EveningStar
export EveningStar() => (close[2] > open[2] and math.min(open[1], close[1]) > close[2] and open < math.min(open[1], close[1]) and close < open )
//@returns a series of bool, if there is a MorningStar
export MorningStar() => (close[2] < open[2] and math.max(open[1], close[1]) < close[2] and open > math.max(open[1], close[1]) and close > open )
//@returns a series of bool, if there is a ShootingStar
export ShootingStar() => (open[1] < close[1] and open > close[1] and high - math.max(open, close) >= math.abs(open - close) * 3 and math.min(close, open) - low <= math.abs(open - close))
//@returns a series of bool, if there is a hammer
export Hammer() => (((high - low)>3*(open -close)) and ((close - low)/(.001 + high - low) > 0.6) and ((open - low)/(.001 + high - low) > 0.6))
//@returns a series of bool, if there is a InvertedHammer
export InvertedHammer() => (( (high - low)>3*(open -close) ) and ((high - close)/(.001 + high - low) > 0.6) and ((high - open)/(.001 + high - low) > 0.6))
//@returns a series of bool, if there is a BearishHarami
export BearishHarami() => (close[1] > open[1] and open > close and open <= close[1] and open[1] <= close and open - close < close[1] - open[1] )
//@returns a series of bool, if there is a BullishHarami
export BullishHarami() => (open[1] > close[1] and close > open and close <= open[1] and close[1] <= open and close - open < open[1] - close[1] )
//@returns a series of bool, if there is a BullishBelt
export BullishBelt() => (low == open and open < ( ta.lowest(10)[1] ) and open < close and close > ((high[1] - low[1]) / 2) + low[1])
//@returns a series of bool, if there is a BullishKicker
export BullishKicker() => (open[1]>close[1] and open>=open[1] and close>open)
//@returns a series of bool, if there is a BearishKicker
export BearishKicker() => (open[1]<close[1] and open<=open[1] and close<=open)
//@returns a series of bool, if there is a HangingMan
export HangingMan() => (((high-low>4*(open-close))and((close-low)/(.001+high-low)>=0.75)and((open-low)/(.001+high-low)>=0.75)) and high[1] < open and high[2] < open)
//@returns a series of bool, if there is a DarkCloudCover
export DarkCloudCover() => ((close[1]>open[1])and(((close[1]+open[1])/2)>close)and(open>close)and(open>close[1])and(close>open[1])and((open-close)/(.001+(high-low))>0.6))
////////////////////////////////////////////////////////////////////}
// Price Action Utilities
////////////////////////////////////////////////////////////////////{
//PBar Percentages
//@params UserWickPercentage- "Percentage Input For PBars, What % The Wick Of Candle Has To Be". Recommended: 66
export usePercentagesCP(simple int UserWickPercentage) => UserWickPercentage * .01
export percentageCPO(simple int UserWickPercentage) => 1 - (UserWickPercentage * .01)
//Shaved Bars Percentages
//@params UserPercentageRange - Percentage Input For Shaved Bars, Percent of Range it Has To Close On The Lows or Highs
export percentageShaved(simple int UserPercentageRange) => UserPercentageRange * .01
////# PercentageBars / PinBars
//@function
//@params UserPercentageTimePeriod- "
//@params UserWickPercentage- "Percentage Input For PBars, What % The Wick Of Candle Has To Be". Recommended: 66
// pBarUp() => spb and open > high - (range * pctCPO) and close > high - (range * pctCPO) and low <= lowest(pblb) ? 1 : 0
export PercentageBarUp(simple int UserPercentageTimePeriod, simple int UserWickPercentage) => open > high - (_candleRange() * percentageCPO(UserWickPercentage) ) and close > high - (_candleRange() * percentageCPO(UserWickPercentage) ) and low <= ta.lowest(UserPercentageTimePeriod) ? 1 : 0
export PercentageBarDn(simple int UserPercentageTimePeriod, simple int usePercentagesCP) => open < high - (_candleRange() * usePercentagesCP) and close < high - (_candleRange() * usePercentagesCP) and high >= ta.highest(UserPercentageTimePeriod) ? 1 : 0
//Shaved Bars
export ShavedBarUp(simple int UserWickPercentage) => (close >= (high - (_candleRange() * usePercentagesCP(UserWickPercentage) )))
export ShavedBarDown(simple int UserWickPercentage) => close <= (low + (_candleRange() * usePercentagesCP(UserWickPercentage) ))
//Inside Bars
export insideBar() => (high <= high[1] and low >= low[1]) ? 1 : 0
export outsideBar() =>(high > high[1] and low < low[1]) ? 1 : 0
////////////////////////////////////////////////////////////////////}
////////////////////////////////////////////////////////////////////
// Moving Averages Utilities
////////////////////////////////////////////////////////////////////{
// @function maUI(int) function.
// @description ma1Type = input("EMA", title="", options = ["DEMA", "EMA", "HMA", "LSMA", "MA", "RMA", "SMA", "SWMA", "TEMA", "TMA", "VWMA", "WMA"])
// @returns a SERIES of FLOATs for the desired Average
export maUI(simple string type, simple float src, simple int len) =>
if type == 'DEMA'
2 * ta.ema(src, len) - ta.ema(ta.ema(src, len), len)
else if type == 'EMA'
ta.ema(src, len)
else if type == 'HMA'
ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
else if type == 'LSMA'
3 * ta.wma(src, len) - 2 * ta.sma(src, len)
else if type == 'RMA'
ta.rma(src, len)
else if type == 'SMA'
ta.sma(src, len)
else if type == 'SWMA'
ta.swma(src)
else if type == 'TEMA'
3 * ta.ema(src, len) - 3 * ta.ema(ta.ema(src, len), len) + ta.ema(ta.ema(ta.ema(src, len), len), len)
else if type == 'TMA'
ta.swma(ta.wma(src, len))
else if type == 'VWMA'
ta.vwma(src, len)
else if type == 'WMA'
ta.wma(src, len)
// @function maUI(int) function. Used to create predictive moving averages
// @returns a SERIES of FLOATS, each of which are the difference between the top and bottom per candle.
// @example ma1Type = input("EMA", title="", options = ["DEMA", "EMA", "HMA", "LSMA", "MA", "RMA", "SMA", "SWMA", "TEMA", "TMA", "VWMA", "WMA"])
ma_prediction(_type, _src, _period, _offset) => (maUI(_type, _src, _period - _offset) * (_period - _offset) + _src * _offset) / _period
////////////////////////////////////////////////////////////////////}
// Bollinger Bands Utilities
////////////////////////////////////////////////////////////////////{
////////////////////////////////////////////////////////////////////}
// Ichimoku Utilities
////////////////////////////////////////////////////////////////////{
// Ichimoku Constants
export tenkanPeriods() => 9
export kijunPeriods() => 26
export SSBPeriods() => 52
export displacementPeriods(simple int userDisplacement) => userDisplacement - 1
// @return Converts current "timeframe.multiplier" plus the TF into minutes of type float.
export _resolutionInMinutes() => timeframe.multiplier * (timeframe.isseconds ? 1. / 60. : timeframe.isminutes ? 1. : timeframe.isdaily ? 1440. : timeframe.isweekly ? 10080. : timeframe.ismonthly ? 43800. : na)
// @returns resolution of _resolution period in minutes.
_timeFrameResolutionInMinutes(_res) => request.security(syminfo.tickerid, _res, _resolutionInMinutes() )
// _res: resolution of any TF (in "timeframe.period" string format).
// @returns the average number of current chart bars in the given target HTF resolution (this reflects the dataset's history).
_avgDilationOf(_res) =>
// _res: resolution of any TF (in "timeframe.period" string format).
b = ta.barssince(ta.change(time(_res)))
cumTotal = ta.cum(b == 0 ? b[1] + 1 : 0)
cumCount = ta.cum(b == 0 ? 1 : 0)
math.round(cumTotal / cumCount)
// Returns the displacement of the resolution
_getDisplacement(_res) => _avgDilationOf(_res) * displacementPeriods(26)
// @returns average value between lowest and highest
export _avgLH(simple int _len) => math.avg(ta.lowest(_len), ta.highest(_len))
// Returns _donchian data
_donchian(_timeframe, _src) => request.security(syminfo.tickerid, _timeframe, _src, barmerge.gaps_off, barmerge.lookahead_on)
// Returns ichimoku data
f_ichimokuData(_isActive, _tf) =>
_isShow = _isActive and _timeFrameResolutionInMinutes(_tf) >= _resolutionInMinutes()
_displacement = _isShow ? _getDisplacement(_tf) : na
_tenkan = _isShow ? _donchian(_tf, _avgLH(tenkanPeriods() )) : na
_kijun = _isShow ? _donchian(_tf, _avgLH(kijunPeriods() )) : na
_chikou = _isShow ? _donchian(_tf, close) : na
_SSA = _isShow ? math.avg(_tenkan, _kijun) : na
_SSB = _isShow ? _donchian(_tf, _avgLH(SSBPeriods() )) : na
_middleKumo = _isShow ? _SSA[0] > _SSB[0] ? _SSA[0] - math.abs(_SSA[0] - _SSB[0]) / 2 : _SSA[0] + math.abs(_SSA[0] - _SSB[0]) / 2 : na
[_displacement, _tenkan, _kijun, _chikou, _SSA, _SSB, _middleKumo]
////////////////////////////////////////////////////////////////////
// Other Utilities
////////////////////////////////////////////////////////////////////{
// @function _useRound
// @param _input, should be the user input with a price
// @param _input2, should be a user checkbox which allows the user to toggle rounding on and off
export _useRound(float _input, bool _input2) => math.round(_input,_input2)
// ————— Converts color choise
export _stringInColor(string _color) =>
_color == 'Aqua' ? #0080FFef : _color == 'Black' ? #000000ef : _color == 'Blue' ? #013BCAef : _color == 'Coral' ? #FF8080ef : _color == 'Gold' ? #CCCC00ef : _color == 'Gray' ? #808080ef : _color == 'Green' ? #008000ef : _color == 'Lime' ? #00FF00ef : _color == 'Maroon' ? #800000ef : _color == 'Orange' ? #FF8000ef : _color == 'Pink' ? #FF0080ef : _color == 'Red' ? #FF0000ef : _color == 'Violet' ? #AA00FFef : _color == 'Yellow' ? #FFFF00ef : #FFFFFFff
// _color: color label (string format).
// ————— Converts current resolution
export _resolutionInString(string _res) =>
_res == '1' ? '1m' : _res == '3' ? '3m' : _res == '5' ? '5m' : _res == '15' ? '15m' : _res == '30' ? '30m' : _res == '45' ? '45m' : _res == '60' ? '1h' : _res == '120' ? '2h' : _res == '180' ? '3h' : _res == '240' ? '4h' : _res == '1D' ? 'D' : _res == '1W' ? 'W' : _res == '1M' ? 'M' : _res
// _res: resolution of any TF (in "timeframe.period" string format).
////////////////////////////////////////////////////////////////////}
// Study Utilities
////////////////////////////////////////////////////////////////////{
// @function useStudy
// @param type, should be the function you want to study. Options include: NA, redCandle, greenCandle, EngulfingBullish, EngulfingBearish, dojiup, dojidown, isStrongUp, isDown, isStrongDown, isUp, insideBar, outsideBar, isDownTrend, isUpTrend,
// @returns series of bool, if the conditon is true.
export useStudy(simple string type) =>
if type == 'NA'
na
else if type == "redCandle"
redCandle()
else if type == "greenCandle"
greenCandle()
////#Patterns
else if type == "EngulfingBullish"
_isEngulfingBullish()
else if type == "EngulfingBearish"
_isEngulfingBearish()
else if type == "dojiup"
dojiup()
else if type == "dojidown"
dojidown()
else if type == "EveningStar"
EveningStar()
else if type == "MorningStar"
MorningStar()
else if type == "ShootingStar"
ShootingStar()
else if type == "Hammer"
Hammer()
else if type == "InvertedHammer"
InvertedHammer()
else if type == "BearishHarami"
BearishHarami()
else if type == "BullishHarami"
BullishHarami()
else if type == "BullishBelt"
BullishBelt()
else if type == "BullishKicker"
BullishKicker()
else if type == "BearishKicker"
BearishKicker()
else if type == "HangingMan"
HangingMan()
else if type == "DarkCloudCover"
DarkCloudCover()
////# Trend
else if type == "isStrongUp"
isStrongUp()
else if type == "isDown"
isDown()
else if type == "isStrongDown"
isStrongDown()
else if type == "isUp"
isUp()
////# Other
else if type == "insideBar"
insideBar()
else if type == "outsideBar"
outsideBar()
// @function useStudyPrevious, is used to help study previous candles and check if the close >= open[length], close <= close[length], open >= close[length], open <= close[length]
// @param type, should be the function you want to study. Options include: CloseAbovePreviousOpen, isCloseBelowPreviousClose, OpenGreaterThanPreviousClose, OpenLessThanPreviousClose, OpenLessThanPreviousOpen, OpenMoreThanPreviousOpen
// @param length, how many candles back do you want to study?
// @returns series of bool, if the conditon is true.
export useStudyPrevious(simple string type, simple int length) =>
// if type == 'isDownTrend'
// isDownTrend(length)
// else if type == 'isUpTrend'
// isUpTrend(length)
if type == 'CloseAbovePreviousOpen'
close >= open[length]
else if type == 'isCloseBelowPreviousClose'
close <= close[length]
else if type == 'OpenGreaterThanPreviousClose'
open >= close[length]
else if type == 'OpenLessThanPreviousClose'
open <= close[length]
else if type == 'OpenLessThanPreviousOpen'
open <= open[length]
else if type == 'OpenMoreThanPreviousOpen'
open >= open[length]
//} ══════════════════════════════════════════════════════════════════════════════════════════════════
////////////////////////////////////////////////////////////////////}
// Demo
////////////////////////////////////////////////////////////////////{
test = false
////# floor
barcolor( test and (volUp1) ? color.new(color.green, 1) : na )
barcolor( test and (volUp2) ? color.new(color.green, 50) : na )
barcolor( test and (volUp3) ? color.new(color.green, 90) : na )
////# ceiling
barcolor( test and (volDown1) ? color.new(color.red, 1) : na )
barcolor( test and (volDown2) ? color.new(color.red, 50) : na )
barcolor( test and (volDown3) ? color.new(color.red, 90) : na )
|
MonthlyReturnsVsMarket | https://www.tradingview.com/script/gSlPZC7s-MonthlyReturnsVsMarket/ | levieux | https://www.tradingview.com/u/levieux/ | 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/
// © levieux
//@version=5
// @description Display a table showing monthly returns vs market
// Only one function is exported : displayMonthlyPnL(int precision)
// When precision is 0 value will be rounded as int, precision=1
// value will be rounded to 1 number after decimal point, etc.
//
library("MonthlyReturnsVsMarket")
getCellColor(pnl, bh) =>
if pnl > 0
if bh < 0 or pnl > bh
color.new(color.green, transp = 20)
else
color.new(color.green, transp = 70)
else
if bh > 0 or pnl < -0.2 or pnl < bh
color.new(color.red, transp = 20)
else
color.new(color.red, transp = 70)
export displayMonthlyPnL(simple int precision, simple bool showMonthlyMarketPerformance= true, simple bool showYearlyMarketPerformance= true) =>
cur_month_pnl = 0.0
eq = strategy.equity
bar_pnl = eq / eq[1] - 1
bar_bh = (close-close[1])/close[1]
new_month = month(time) != month(time[1])
new_year = year(time) != year(time[1])
cur_year_pnl = 0.0
cur_month_bh = 0.0
cur_year_bh = 0.0
// Current Monthly P&L
cur_month_pnl := new_month ? 0.0 :
(1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1
cur_month_bh := new_month ? 0.0 :
(1 + cur_month_bh[1]) * (1 + bar_bh) - 1
// Current Yearly P&L
cur_year_pnl := new_year ? 0.0 :
(1 + cur_year_pnl[1]) * (1 + bar_pnl) - 1
cur_year_bh := new_year ? 0.0 :
(1 + cur_year_bh[1]) * (1 + bar_bh) - 1
// Arrays to store Yearly and Monthly P&Ls
var month_pnl = array.new_float(0)
var month_time = array.new_int(0)
var month_bh = array.new_float(0)
var year_pnl = array.new_float(0)
var year_time = array.new_int(0)
var year_bh = array.new_float(0)
end_time = false
end_time:= time_close + (time_close - time_close[1]) > timenow or barstate.islastconfirmedhistory
if (not na(cur_month_pnl[1]) and (new_month or end_time))
if (end_time[1])
array.pop(month_pnl)
array.pop(month_time)
array.push(month_pnl , cur_month_pnl[1])
array.push(month_time, time[1])
array.push(month_bh , cur_month_bh[1])
if (not na(cur_year_pnl[1]) and (new_year or end_time))
if (end_time[1])
array.pop(year_pnl)
array.pop(year_time)
array.push(year_pnl , cur_year_pnl[1])
array.push(year_time, time[1])
array.push(year_bh , cur_year_bh[1])
// Monthly P&L Table
var monthly_table = table(na)
if end_time
monthly_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_pnl) + 1, border_width = 1, bgcolor=color.white)
table.cell(monthly_table, 0, 0, "", bgcolor = #cccccc)
table.cell(monthly_table, 1, 0, "Jan", bgcolor = #cccccc)
table.cell(monthly_table, 2, 0, "Feb", bgcolor = #cccccc)
table.cell(monthly_table, 3, 0, "Mar", bgcolor = #cccccc)
table.cell(monthly_table, 4, 0, "Apr", bgcolor = #cccccc)
table.cell(monthly_table, 5, 0, "May", bgcolor = #cccccc)
table.cell(monthly_table, 6, 0, "Jun", bgcolor = #cccccc)
table.cell(monthly_table, 7, 0, "Jul", bgcolor = #cccccc)
table.cell(monthly_table, 8, 0, "Aug", bgcolor = #cccccc)
table.cell(monthly_table, 9, 0, "Sep", bgcolor = #cccccc)
table.cell(monthly_table, 10, 0, "Oct", bgcolor = #cccccc)
table.cell(monthly_table, 11, 0, "Nov", bgcolor = #cccccc)
table.cell(monthly_table, 12, 0, "Dec", bgcolor = #cccccc)
table.cell(monthly_table, 13, 0, "Year", bgcolor = #999999)
for yi = 0 to array.size(year_pnl) - 1
table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), bgcolor = #cccccc)
y_color = getCellColor(array.get(year_pnl, yi), array.get(year_bh, yi))
cellText= str.tostring(math.round(array.get(year_pnl, yi) * 100,precision))
if showYearlyMarketPerformance
cellText:= cellText + " (" + str.tostring(math.round(array.get(year_bh, yi) * 100,precision)) + ")"
table.cell(monthly_table, 13, yi + 1, cellText , bgcolor = y_color)
for mi = 0 to array.size(month_time) - 1
m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1
m_col = month(array.get(month_time, mi))
m_color = getCellColor(array.get(month_pnl, mi), array.get(month_bh, mi))
cellText= str.tostring(math.round(array.get(month_pnl, mi) * 100,precision))
if showMonthlyMarketPerformance
cellText:= cellText + " (" + str.tostring(math.round(array.get(month_bh, mi) * 100,precision)) +")"
table.cell(monthly_table, m_col, m_row, cellText, bgcolor = m_color)
|
matrixautotable | https://www.tradingview.com/script/fyt5iGYQ-matrixautotable/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// © kaigouthro
//@version=5
import kaigouthro/hsvColor/15 as h
import kaigouthro/font/4
import kaigouthro/into/2
// @description Automatic Table from Matrixes with pseudo correction for na values and default color override for missing
library("matrixautotable")
// Grower (soon to be a lib)
maxcol(a,b,c,d,e) => math.max( matrix.columns(a), matrix.columns(b), matrix.columns(c), matrix.columns(d), matrix.columns(e) )
maxrow(a,b,c,d,e) => math.max( matrix.rows (a), matrix.rows (b), matrix.rows (c), matrix.rows (d), matrix.rows (e) )
growcol(sz,m)=>
_c = matrix.columns(m)
if _c < sz
while _c < sz
matrix.add_col(m,_c)
_c:=matrix.columns(m)
growrow(sz,m)=>
_r = matrix.rows(m)
if _r < sz
while _r < sz
matrix.add_row(m,_r)
_r:=matrix.rows(m)
// quick replacers
mst (_y,_x) => matrix.new<string>(_y,_x)
mfl (_y,_x) => matrix.new<float>(_y,_x)
mcl (_y,_x) => matrix.new<color>(_y,_x)
grow(a,b,c,d,e) =>
var _r = maxrow (a,b,c,d,e)
var _c = maxcol (a,b,c,d,e)
_c := maxcol (a,b,c,d,e)
_r := maxrow (a,b,c,d,e)
growcol(_c,a)
growcol(_c,b)
growcol(_c,c)
growcol(_c,d)
growcol(_c,e)
growrow(_r,a)
growrow(_r,b)
growrow(_r,c)
growrow(_r,d)
growrow(_r,e)
invertcol(color COL)=>
h.tripswitch(COL,0.8,#ffffff,#333333)
sizech(_mtx) => _cl = matrix.columns (_mtx) , _rw = matrix.rows(_mtx), [_rw,_cl]
export type cellsize
float w
float h
// @function autogenerate table from string matrix
mtable( _datamatrix, matrix<string> _stringmatrix, matrix<color> _bgcolormatrix, matrix<color> _textcolormatrix, matrix<string> _tooltipmatrix, int _textSizeinp = 1, string tableYpos = 'bottom', string tableXpos = 'left', bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #86868680,_cellsize)=> //{
[_rwf,_clf] = sizech(_datamatrix) , [_rws,_cls] = sizech(_stringmatrix) , [_rwt,_clt] = sizech(_tooltipmatrix) , [_rwb,_clb] = sizech(_bgcolormatrix) , [_rwtt,_cltt] = sizech(_textcolormatrix)
var table _table = na
varip _rsz = 0
varip _csz = 0
_rsz := math.max(_rwf,_rws,_rwt,_rwb,_rwtt)
_csz := math.max(_clf,_cls,_clt,_clb,_cltt)
if bar_index +3 >= last_bar_index
_table := table.new (tableYpos + '_' + tableXpos, _csz, _rsz, na, na, 1, na, 1)
_wid = _fit ? 100/_csz:_shrink/_csz*_cellsize.w
_hgt = _fit ? 100/_rsz:_shrink/_rsz*_cellsize.h
var _xsize = int(na), var _ysize = int(na)
var _textSize = switch _textSizeinp
1 => size.tiny
2 => size.small
3 => size.normal
4 => size.large
5 => size.huge
=> size.auto
if bar_index > last_bar_index - 3
_xsize := _csz
_ysize := _rsz
var color _nocol = color.new(color.black,100)
for _currClm = 0 to _xsize -1 by 1
for _currRow = 0 to _ysize -1 by 1
_value = matrix.get(_datamatrix,_currRow,_currClm)
_string = matrix.get(_stringmatrix,_currRow,_currClm)
_valstr = str.replace(na(_value) ? '' : (na(_string) ? ' ' : '\n') + into.s(_value), 'NaN','')
_cellcolor = matrix.get(_bgcolormatrix , _currRow , _currClm)
_cellcolor := na(_cellcolor) ? _defaultbg : _cellcolor
_textcolor = matrix.get(_textcolormatrix , _currRow , _currClm)
_textcolor := (_defaultxt == _textcolor) or na(_textcolor) ? invertcol(_cellcolor) : _textcolor
_string := (na(_string) ? ' ' : _string ) + _valstr
_tooltip = matrix.get(_tooltipmatrix , _currRow , _currClm)
_tooltip := na(_tooltip ) ? ' ' : _tooltip
table.cell(_table, _currClm, _currRow , _string, _wid,_hgt , _textcolor , text.align_center , text.align_center , _textSize , _cellcolor , _tooltip )
_table
// @function matrixtable
// @param _floatmatrix <matrix> float vals
// @param _stringmatrix <matrix> string
// @param _bgcolormatrix <matrix> color
// @param _textcolormatrix <matrix>color
// @param _tooltipmatrix <matrix> string
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<float> _floatmatrix, matrix<string> _stringmatrix, matrix<color> _bgcolormatrix,
matrix<color> _textcolormatrix, matrix<string> _tooltipmatrix,
int _textSize = 2, string tableYpos = 'bofloat _w=1,float _h=1, ttom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1,
color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
grow (_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
// @function matrixtable
// @param _floatmatrix <matrix> float vals
// @param _stringmatrix <matrix> string
// @param _bgcolormatrix <matrix> color
// @param _textcolormatrix <matrix>color
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<float> _floatmatrix, matrix<string> _stringmatrix, matrix<color> _bgcolormatrix, matrix<color> _textcolormatrix,
int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
var _sizey = int(na), _sizey := matrix.rows(_floatmatrix), var _sizex = int(na), _sizex := matrix.columns(_floatmatrix)
var matrix<string> _tooltipmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
grow (_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
// @function matrixtable
// @param _floatmatrix <matrix> float vals
// @param _stringmatrix <matrix> string
// @param _bgcolormatrix <matrix> color
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<float> _floatmatrix, matrix<string> _stringmatrix, matrix<color> _bgcolormatrix,
int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
var _sizey = int(na), _sizey := matrix.rows(_floatmatrix), var _sizex = int(na), _sizex := matrix.columns(_floatmatrix)
var matrix<color> _textcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultxt )
var matrix<string> _tooltipmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
grow (_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
// @function matrixtable
// @param _floatmatrix <matrix> float vals
// @param _stringmatrix <matrix> string
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<float> _floatmatrix, matrix<string> _stringmatrix,
int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
var _sizey = int(na), _sizey := matrix.rows(_floatmatrix), var _sizex = int(na), _sizex := matrix.columns(_floatmatrix)
var matrix<color> _bgcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultbg )
var matrix<color> _textcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultxt )
var matrix<string> _tooltipmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
grow (_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
// @function matrixtable
// @param _floatmatrix <matrix> float vals
// @param _stringmatrix <matrix> string
// @param _bgcolormatrix <matrix> color
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<string> _floatmatrix, matrix<string> _stringmatrix, matrix<color> _bgcolormatrix,
int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
var _sizey = int(na), _sizey := matrix.rows(_floatmatrix), var _sizex = int(na), _sizex := matrix.columns(_floatmatrix)
matrix<color> _textcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultxt )
matrix<string> _tooltipmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
grow (_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
// @function matrixtable
// @param _floatmatrix <matrix> float vals
// @param _stringmatrix <matrix> string
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<string> _floatmatrix, matrix<string> _stringmatrix,
int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
var _sizey = int(na), _sizey := matrix.rows(_floatmatrix), var _sizex = int(na), _sizex := matrix.columns(_floatmatrix)
matrix<color> _bgcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultbg )
matrix<color> _textcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultxt )
matrix<string> _tooltipmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
grow (_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
// @function matrixtable
// @param _floatmatrix <matrix> float vals
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<float> _floatmatrix,
int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
var _sizey = int(na), _sizey := matrix.rows(_floatmatrix), var _sizex = int(na), _sizex := matrix.columns(_floatmatrix)
matrix<string> _stringmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
matrix<color> _bgcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultbg )
matrix<color> _textcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultxt )
matrix<string> _tooltipmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
grow (_floatmatrix, _stringmatrix , _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix , _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
// @function matrixtable
// @param _stringmatrix <matrix> float vals
// @param _textSize int
// @param tableYpos string
// @param tableXpos string
export matrixtable(matrix<string> _stringmatrix,
int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' ,
bool _fit = false, int _shrink = 0, float _w=1,float _h=1, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => //{
var _sizey = int(na), _sizey := matrix.rows(_stringmatrix), var _sizex = int(na), _sizex:= matrix.columns(_stringmatrix)
matrix<float> _floatmatrix = matrix.new<float> (_sizey, _sizex, float(na) )
matrix<color> _bgcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultbg )
matrix<color> _textcolormatrix = matrix.new<color> (_sizey, _sizex, _defaultxt )
matrix<string> _tooltipmatrix = matrix.new<string> (_sizey, _sizex, string(na) )
grow (_floatmatrix, _stringmatrix , _bgcolormatrix, _textcolormatrix, _tooltipmatrix)
mtable(_floatmatrix, _stringmatrix , _bgcolormatrix, _textcolormatrix, _tooltipmatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt,cellsize.new(_w,_h))
export anytwo( matrix<float> _titleMTX, matrix<float> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<float> _titleMTX, matrix<int> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<float> _titleMTX, matrix<string> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<float> _titleMTX, matrix<bool> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<float> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<int> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<string> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<bool> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<float> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<int> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<string> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<bool> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<float> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<int> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<string> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<bool> _dataMTX , matrix<color> _bgcolormatrix, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _bgcolormatrix, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<float> _titleMTX, matrix<float> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<float> _titleMTX, matrix<int> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<float> _titleMTX, matrix<string> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<float> _titleMTX, matrix<bool> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<float> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<int> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<string> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<int> _titleMTX, matrix<bool> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<float> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<int> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<string> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<string> _titleMTX, matrix<bool> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<float> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<int> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<string> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anytwo( matrix<bool> _titleMTX, matrix<bool> _dataMTX , int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = into.s(_dataMTX), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anyone( matrix<float> _titleMTX, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = matrix.new<string>(matrix.rows(_titleMTX),matrix.columns(_titleMTX),string(na)), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anyone( matrix<int> _titleMTX, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = matrix.new<string>(matrix.rows(_titleMTX),matrix.columns(_titleMTX),string(na)), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anyone( matrix<string> _titleMTX, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = matrix.new<string>(matrix.rows(_titleMTX),matrix.columns(_titleMTX),string(na)), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anyone( matrix<bool> _titleMTX, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = into.s(_titleMTX),_d = matrix.new<string>(matrix.rows(_titleMTX),matrix.columns(_titleMTX),string(na)), matrixtable(_d,_t, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
export anyone( matrix<color> _colormtx, int _textSize = 2, string tableYpos = 'bottom', string tableXpos = 'left' , bool _fit = false, int _shrink = 0, float _w = 1, float _h = 2, color _defaultbg = #101010ff, color _defaultxt = #fdfdfd41) => _t = matrix.new<string>(matrix.rows(_colormtx),matrix.columns(_colormtx),string(na)), matrixtable(_t,_t,_colormtx, _textSize ,tableYpos ,tableXpos, _fit, _shrink,_w,_h, _defaultbg, _defaultxt)
// wrapped shortcuts for table post-adjusstments
// @function Set background or Table
// @param bgcolor New Background Color
// @returns void
export bgcolor (table _table, color bgcolor ) =>
table.set_bgcolor (_table, bgcolor )
// @function TODO: add function description here
// @param border_color New border color
// @param border_width New border width
// @returns void
export border (table _table, color border_color ,int border_width ) =>
table.set_border_color(_table, border_color )
table.set_border_width(_table, border_width )
export border (table _table, int border_width ) =>
table.set_border_width(_table, border_width )
export border (table _table, color border_color ) =>
table.set_border_color(_table, border_color )
// @function Alter frame
// @param New border color
// @param New border width
// @returns void
export frame (table _table, color frame_color ,int frame_width ) =>
table.set_frame_color (_table, frame_color )
table.set_frame_width (_table, frame_width )
export frame (table _table, int frame_width ) =>
table.set_frame_width (_table, frame_width )
export frame (table _table, color frame_color) =>
table.set_frame_color (_table, frame_color )
// // demo
var string group_table = ' Table'
int _tblssizedemo = input.int ( 10 )
string tableYpos = input.string ( 'middle' , '↕' , inline = 'place' , group = group_table, options=['top', 'middle', 'bottom'])
string tableXpos = input.string ( 'center' , '↔' , inline = 'place' , group = group_table, options=['left', 'center', 'right'], tooltip='Position on the chart.')
int _textSize = input.int ( 1 , 'Table Text Size' , inline = 'place' , group = group_table)
// fulltable
matrix<float> _floatmatrix = matrix.new<float> (_tblssizedemo, _tblssizedemo, 0 )
matrix<string> _stringmatrix = matrix.new<string> (_tblssizedemo, _tblssizedemo, ' ' )
matrix<color> _bgcolormatrix = matrix.new<color> (_tblssizedemo, _tblssizedemo, color(na) )
matrix<color> _textcolormatrix = matrix.new<color> (_tblssizedemo, _tblssizedemo, na )
matrix<string> _tooltipmatrix = matrix.new<string> (_tblssizedemo, _tblssizedemo, 'tooltip' )
//// for demo purpose, random colors, random nums, random na vals
_ysize = matrix.rows (_floatmatrix)
_xsize = matrix.columns (_floatmatrix)
if bar_index + 10 >= last_bar_index
for _currClm = 0 to _xsize -1 by 1
for _currRow = 0 to _ysize -1 by 1
_randomh = math.random(0,360)
_randoms = math.random(.6,1.)
_randomv = math.random(.25,1)
_randoma = math.random(.8,1)
bgcolor = h.hsv(_randomh,_randoms,_randomv,_randoma)
txtcolor = h.hsvInvert(bgcolor)
matrix.set(_bgcolormatrix ,_currRow,_currClm, bgcolor )
matrix.set(_textcolormatrix ,_currRow,_currClm, txtcolor)
matrix.set(_floatmatrix ,_currRow,_currClm, math.round(_randomh,2))
// random na
_ymiss = math.floor(math.random(0, _currRow))
_xmiss = math.floor(math.random(0, _currClm))
matrix.set( _floatmatrix ,_ymiss, _currClm, na)
matrix.set( _stringmatrix ,_ymiss, _currClm, na)
matrix.set( _bgcolormatrix ,_ymiss, _currClm, na)
matrix.set( _textcolormatrix ,_ymiss, _currClm, na)
matrix.set( _tooltipmatrix ,_ymiss, _currClm, na)
_defaultbg = input.color(color.gray)
_defaultxt = input.color(color.black)
_fit = input(true)
_cellsize = input(2)
if barstate.islast
_table = switch input(4,'table')
1 => matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
2 => matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix, _tooltipmatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
3 => matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix, _textcolormatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
4 => matrixtable(_floatmatrix, _stringmatrix, _bgcolormatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
5 => matrixtable(_floatmatrix, _stringmatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
6 => matrixtable(_floatmatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
7 => matrixtable(_stringmatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
8 => anyone (_bgcolormatrix , _textSize ,tableYpos ,tableXpos , _fit, _cellsize )
border ( _table,1)
border ( _table ,h.hsv((timenow/200)%360,1,1,.05))
|
my_choppyness | https://www.tradingview.com/script/Y49s1M2F-my-choppyness/ | danielsaadia0907 | https://www.tradingview.com/u/danielsaadia0907/ | 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/
// © danielsaadia0907
//@version=5
library("my_choppyness")
// firstPriority = input.float(1, "First priority", minval=1)
length = input.int(56, "length", minval=1)
Hline = input.float(55, "HLine", minval=1)
Lline = input.float(45, "LLine", minval=1)
priority = input.float(1, "priority", minval=1)
export choppyness(int length, float prio) =>
totalAmp = 0.0
positiveAmp = 0.0
negativeAmp = 0.0
for i = 0 to length
if (close[i] and open[i])
amp = math.abs(close[i] - open[i]) * math.pow(prio, length - i)
totalAmp := totalAmp + amp
if (close[i] > open[i])
positiveAmp := positiveAmp + amp
else
negativeAmp := negativeAmp + amp
positiveAmp / totalAmp
chopp = choppyness(length, priority)
plot(chopp * 100, "Choppyness", color=color.blue)
h0 = hline(Hline, "Upper Band", color=#787B86)
h1 = hline(Lline, "Lower Band", color=#787B86)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background") |
honest personal library | https://www.tradingview.com/script/Qqb6zsYd-honest-personal-library/ | Honestcowboy | https://www.tradingview.com/u/Honestcowboy/ | 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/
// © Honestcowboy
//@version=5
// @description <library_description>
library("honestpersonallibrary", true)
// @function this will return the number 1,2 or 3 using the logic from Rob Smiths #thestrat which uses these type of bars for setups
// @returns The current candle's #theStrat number based on Rob Smith theStrat type of candles
export thestratnumber() =>
stratnumber = 0
if high<high[1] and low>low[1]
stratnumber := 1
if (high<high[1] and low<low[1]) or (high>high[1] and low>low[1])
stratnumber := 2
if (high>high[1] and low<low[1])
stratnumber := 3
[stratnumber]
// ---- Bar size calculations based on ZenLibrary scripts => all credits for this part goes the ZenAndTheArtOfTrading
// @function Gets the current candle's body size (in POINTS, divide by 10 to get pips)
// @returns The current candle's body size in POINTS
export getBodySize() => math.abs(close - open)>0?math.abs(close - open):0.000000000000000000000000000000000000001
// @function Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
// @returns The current candle's top wick size in POINTS
export getTopWickSize() => math.abs(high - (close > open ? close : open))
// @function Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
// @returns The current candle's bottom wick size in POINTS
export getBottomWickSize() => math.abs((close < open ? close : open) - low)
// @function Gets the current candle's body size as a percentage of its entire size including its wicks
// @returns The current candle's body size percentage
export getBodyPercent() => math.abs(open - close) / math.abs(high - low)
// @function This it to find pinbars with a very long wick compared to the body that are bearish
// @param float minTopMulitplier (default=4) The minimum number of times that the top wick has to be bigger than the candle body size
// @param float minBottomMultiplier (default=2) The minimum number of times that the bottom wick can fit in the top wick
// @returns a bool function true if current candle is withing the parameters
export strictBearPinBar(float minTopMulitplier = 4, float minBottomMultiplier = 2) =>
topCheck = getTopWickSize()>getBodySize()*minTopMulitplier
bottomCheck = getBottomWickSize()<getTopWickSize()/minBottomMultiplier
bearPinbarCheck = topCheck and bottomCheck
// @function This it to find pinbars with a very long wick compared to the body that are bearish
// @param float minBottomMulitplier (default=4) The minimum number of times that the top wick has to be bigger than the candle body size
// @param float minTopMultiplier (default=2) The minimum number of times that the top wick can fit in the bottom wick
// @returns a bool function true if current candle is withing the parameters
export strictBullPinBar(float minBottomMulitplier = 4, float minTopMultiplier = 2) =>
bottomCheck = getBottomWickSize()>getBodySize()*minBottomMulitplier
topCheck = getTopWickSize()<getBottomWickSize()/minTopMultiplier
bearPinbarCheck = topCheck and bottomCheck
// ================================== //
// ------> Pivot Boss Candles <------ //
// ================================== //
O = open
C = close
H = high
L = low
//
// @function This it to find doji within the pivot boss doji reversal system parameters
// @param float maxbodysize (default=0.1) The percentage body size candle can have
// @returns a bool function true if current candle is a doji candle
export PBDoji(float maxbodysize = 0.1) =>
smallbody = getBodyPercent() <= maxbodysize
// @function his it to find pinbars within the pivot boss wick reversal system parameters
// @param float wick_multiplier (default=2.5) The minimum number of times that the bottom wick has to be bigger than the candle body size
// @param float body_percentage (default=0.25) The percentage range from top of the candle the close has to close in.
// @returns a bool function true if current candle is within the wick reversal parameters
export PBWickRevBull(float wick_multiplier = 2.5, float body_percentage = 0.25) =>
PBWickRevBull = (C > O) and (O - L) >= ((C - O) * wick_multiplier) and (H - C) <= ((H - L) * body_percentage) or
(C < O) and (C - L) >= ((O - C) * wick_multiplier) and (H - C) <= ((H - L) * body_percentage) or
(C == O and C != H) and (H - L) >= ((H - C) * wick_multiplier) and (H - C) <= ((H - L) * body_percentage) or
(O == H and C == H) and (H - L) >= ta.sma((H - L), 50)
// @function This it to find pinbars within the pivot boss wick reversal system parameters
// @param float wick_multiplier (default=2.5) The minimum number of times that the top wick has to be bigger than the candle body size
// @param float body_percentage (default=0.25) The percentage range from bottom of the candle the close has to close in.
// @returns a bool function true if current candle is within the wick reversal paramaters
export PBWickRevBear(float wick_multiplier = 2.5, float body_percentage = 0.25) =>
PBWickRevBear = (C < O) and (H - O) >= ((O - C) * wick_multiplier) and (C - L) <= ((H - L) * body_percentage) or
(C > O) and (H - C) >= ((C - O) * wick_multiplier) and (C - L) <= ((H -L) * body_percentage) or
(C == O and not C == L) and (H - L) >= ((C - L) * wick_multiplier) and (C - L) <= ((H - L) * body_percentage) or
(O == L and C == L) and (H - L) >= ta.sma((H - L), 50)
// @function This it to find pivot boss extreme bullish reversals within the system parameters.
// @param float minbodysize (default=0.5) This is the minimum percentage change the body has to be of the total candle.
// @param float maxbodysize (default=0.85) This is the maximum percentage change the body can be of the total candle
// @param float barsback (default=50) The amount of candles the script will look back to find average candle size.
// @param float bodymultiplier (default=2) The multiplier amount the extreme candle has to be bigger than an average candle.
// @returns a bool function true if current candle is within the pivot boss extreme bullish reversal parameters.
export PBExtremeRevBull(float minbodysize = 0.5, float maxbodysize = 0.85, int barsback = 50, float bodymultiplier = 2) =>
mybodysize = math.abs(C - O)
AverageBody = ta.sma(mybodysize, barsback)
mycandlesize = (H - L)
AverageCandle = ta.sma(mycandlesize, barsback)
Elongsignal = ((O[1] - C[1]) >= (minbodysize * (H[1] - L[1]))) and ((O[1] - C[1]) <= (maxbodysize * (H[1] - L[1]))) and ((H[1] - L[1]) > (AverageCandle * bodymultiplier)) and ((O[1] - C[1]) > AverageBody) and (C > O) and (C[1] < O[1])
// @function This it to find pivot boss extreme bearish reversals within the system parameters.
// @param float minbodysize (default=0.5) This is the minimum percentage change the body has to be of the total candle.
// @param float maxbodysize (default=0.85) This is the maximum percentage change the body can be of the total candle
// @param float barsback (default=50) The amount of candles the script will look back to find average candle size.
// @param float bodymultiplier (default=2) The multiplier amount the extreme candle has to be bigger than an average candle.
// @returns a bool function true if current candle is within the pivotboss extreme bearish reversal parameters
export PBExtremeRevBear(float minbodysize = 0.5, float maxbodysize = 0.85, int barsback = 50, float bodymultiplier = 2) =>
mybodysize = math.abs(C - O)
AverageBody = ta.sma(mybodysize, barsback)
mycandlesize = (H - L)
AverageCandle = ta.sma(mycandlesize, barsback)
Eshortsignal = ((C[1] - O[1]) >= (minbodysize * (H[1] - L[1]))) and ((C[1] - O[1]) <= (maxbodysize * (H[1] - L[1]))) and ((H[1] - L[1]) > (AverageCandle * bodymultiplier)) and ((C[1] - O[1]) > AverageBody) and (O > C) and (C[1] > O[1])
// @function This it to find pivot boss outside bullish reversals within the system parameters.
// @param float barsback (default=50) The amount of candles the script will look back to find average candle size.
// @param float barmultiplier (default=2) The multiplier amount the extreme candle has to be bigger than an average candle.
// @returns a bool function true if current candle is within the pivot boss outside bullish reversal parameters.
export PBOutsideRevBull(int barsback = 50, float barmultiplier = 2) =>
mycandlesize = (H - L)
AverageCandle1 = ta.sma(mycandlesize, barsback)
Olongsignal = L < L[1] and C > H[1] and (H - L) >= AverageCandle1 * barmultiplier
// @function This it to find pivot boss outside bearish reversals within the system parameters.
// @param float barsback (default=50) The amount of candles the script will look back to find average candle size.
// @param float barmultiplier (default=2) The multiplier amount the extreme candle has to be bigger than an average candle.
// @returns a bool function true if current candle is within the pivot boss outside bearish reversal parameters.
export PBOutsideRevBear(int barsback = 50, float barmultiplier = 2) =>
mycandlesize = (H - L)
AverageCandle1 = ta.sma(mycandlesize, barsback)
Oshortsignal = H > H[1] and C < L[1] and (H - L) >= AverageCandle1 * barmultiplier
// @function This it to find pivot boss bullish doji reversal.
// @param float percentage (default=0.1) The maximum percentage body size the doji can have.
// @returns a bool function true if current candle is within the pivot boss bullish doji reversal parameters.
export PBDojiRevBull(float percentage = 0.1) =>
candleSize = H[1] - L[1]
candleBodySize = math.abs(C[1] - O[1])
sma10 = ta.sma(close, 10)
Dlongsignal = (candleBodySize <= candleSize * percentage and C > H[1] and H[1] < sma10 and C > O) or (C > H[2] and C[1] <= H[2] and candleBodySize[1] <= candleSize[1] * percentage and C > O and H[2] < sma10)
// @function This it to find pivot boss bullish doji reversal
// @param float percentage (default=0.1) The maximum percentage body size the doji can have.
// @returns a bool function true if current candle is within the pivot boss bearish doji reversal parameters.
export PBDojiRevBear(float percentage = 0.1) =>
candleSize = H[1] - L[1]
candleBodySize = math.abs(C[1] - O[1])
sma10 = ta.sma(close, 10)
Dshortsignal = (candleBodySize <= candleSize * percentage and C < L[1] and L[1] > sma10 and C < O) or (C < L[2] and C[1] >= L[2] and candleBodySize[1] <= candleSize[1] * percentage and C < O and L[2] > sma10)
|
FunctionMatrixSolve | https://www.tradingview.com/script/srzgu6h6-FunctionMatrixSolve/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 34 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Matrix Equation solution for Ax = B, finds the value of x.
library(title='FunctionMatrixSolve')
//reference:
// https://introcs.cs.princeton.edu/java/95linear/Matrix.java.html
// @function helper to create and return a random M-by-N matrix with values between 0 and 1
random (int M, int N) => //{
matrix<float> _A = matrix.new<float>(M, N)
for _i = 0 to M-1
for _j = 0 to N-1
matrix.set(_A, _i, _j, math.random())
_A
//}
// @function Helper to swap rows i and j
swap_rows (matrix<float> M, int i, int j) => //{
int _cols = matrix.columns(M)
for _k = 0 to _cols - 1
_t = matrix.get(M, i, _k)
matrix.set(M, i, _k, matrix.get(M, j, _k))
matrix.set(M, j, _k, _t)
//}
// @function Solves Matrix Equation for Ax = B, finds value for x.
// @param A matrix<float>, Square matrix with data values.
// @param B matrix<float>, One column matrix with data values.
// @returns matrix<float> with X, x = A^-1 b, assuming A is square and has full rank
// https://introcs.cs.princeton.edu/java/95linear/Matrix.java.html
export solve (matrix<float> A, matrix<float> B) => //{
int _Arows = matrix.rows(A)
int _Acols = matrix.columns(A)
int _Brows = matrix.rows(B)
int _Bcols = matrix.columns(B)
//
if (_Arows != _Acols or _Brows != _Acols or _Bcols != 1)
runtime.error("Illegal matrix dimensions.")
//
// create copies of the data
matrix<float> _A = matrix.copy(A)
matrix<float> _B = matrix.copy(B)
// Gaussian elimination with partial pivoting
for _i = 0 to _Acols-1
// find pivot row and swap
int _max = _i
int _j = _i + 1
while _j < _Acols
float _Aji = matrix.get(_A, _j, _i)
float _Ami = matrix.get(_A, _max, _i)
if (math.abs(_Aji) > math.abs(_Ami))
_max := _j
_j += 1
swap_rows(_A, _i, _max)
swap_rows(_B, _i, _max)
// singular
float _Aii = matrix.get(_A, _i, _i)
if (_Aii == 0.0)
runtime.error("Matrix is singular.")
// pivot within b
_j := _i + 1
while _j < _Acols
float _Bj0 = matrix.get(_B, _j, 0) - matrix.get(_B, _i, 0) * matrix.get(_A, _j, _i) / matrix.get(_A, _i, _i)
matrix.set(_B, _j, 0, _Bj0)
_j += 1
// pivot within A
_j := _i + 1
while _j < _Acols
float _m = matrix.get(_A, _j, _i) / matrix.get(_A, _i, _i)
for _k = _i + 1 to _Acols-1
float _Ajk = matrix.get(_A, _j, _k)
matrix.set(_A, _j, _k, _Ajk - matrix.get(_A, _i, _k) * _m)
matrix.set(_A, _j, _i, 0.0)
_j += 1
// back substitution
matrix<float> _X = matrix.new<float>(_Acols, 1)
for _j = _Acols-1 to 0
float _t = 0.0
_k = _j + 1
while _k < _Acols
_t += matrix.get(_A, _j, _k) * matrix.get(_X, _k, 0)
_k += 1
matrix.set(_X, _j, 0, (matrix.get(_B, _j, 0) - _t) / matrix.get(_A, _j, _j))
_X
//}
// A = random(5, 5)
// B = random(5, 1)
A = matrix.new<float>(0, 5)
matrix.add_row(A, 0, array.from( 1.0, 0.0, 0.0, 0.0, 0.0))
matrix.add_row(A, 1, array.from(-1.0, 1.0, 0.0, 0.0, 0.0))
matrix.add_row(A, 2, array.from(-1.0, -1.0, 1.0, 0.0, 0.0))
matrix.add_row(A, 3, array.from(-1.0, -1.0, -1.0, 1.0, 0.0))
matrix.add_row(A, 4, array.from(-1.0, -1.0, -1.0, -1.0, 1.0))
B = matrix.new<float>(5, 0)
matrix.add_col(B, 0, array.from(0.5, 0.0, 0.0, 0.0, 0.5))
// // should be [0.5, 0.5, 1, 2, 4.5] // https://www.mathstools.com/section/main/system_equations_solver#.Yj9zcDzLe2I
// A = matrix.new<float>(0, 5)
// matrix.add_row(A, 0, array.from(1.4350, 0.6996, 1.5083, 1.1921, 1.0485 ))
// matrix.add_row(A, 1, array.from(0.6996, 1.2069, 1.6564, 1.3865, 0.7041 ))
// matrix.add_row(A, 2, array.from(1.5083, 1.6564, 3.2516, 2.5462, 1.9850 ))
// matrix.add_row(A, 3, array.from(1.1921, 1.3865, 2.5462, 2.5376, 1.4350 ))
// matrix.add_row(A, 4, array.from(1.0485, 0.7041, 1.9850, 1.4350, 1.5252 ))
// B = matrix.new<float>(5, 0)
// matrix.add_col(B, 0, array.from(0.9636, 0.2268, 0.2594, 0.3278, 0.1377))
// should be [1.2279, 0.1246, -0.3779, 0.0943, -0.4083 ] //
// https://www.online-java.com/
// with files: https://introcs.cs.princeton.edu/java/stdlib/StdOut.java.html
// https://introcs.cs.princeton.edu/java/95linear/Matrix.java.html
X = solve(A, B)
table T = table.new(position.bottom_right, 5, 2)
table.cell(T, 0, 0, 'A', bgcolor=#ffffff)
table.cell(T, 0, 1, str.tostring(A, '#.0000'), bgcolor=#ffffff)
// table.cell(T, 1, 1, '*', bgcolor=#ffffff)
table.cell(T, 4, 0, 'X', bgcolor=#ffffff)
table.cell(T, 4, 1, str.tostring(X, '#.0000'), bgcolor=#ffffff)
// table.cell(T, 3, 1, '=', bgcolor=#ffffff)
table.cell(T, 2, 0, 'B', bgcolor=#ffffff)
table.cell(T, 2, 1, str.tostring(B, '#.0000'), bgcolor=#ffffff)
|
FunctionPolynomialFit | https://www.tradingview.com/script/hDV6pCFy-FunctionPolynomialFit/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 138 | library | 5 | MPL-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 Performs Polynomial Regression fit to data.
// In statistics, polynomial regression is a form of regression analysis in which
// the relationship between the independent variable x and the dependent variable
// y is modelled as an nth degree polynomial in x.
// reference:
// https://en.wikipedia.org/wiki/Polynomial_regression
// https://www.bragitoff.com/2018/06/polynomial-fitting-c-program/
library(title='FunctionPolynomialFit', overlay=true)
// @function Perform Gauss-Elimination and returns the Upper triangular matrix and solution of equations.
// @param A float matrix, data samples.
// @param m int, defval=na, number of rows.
// @param n int, defval=na, number of columns.
// @returns float array with coefficients.
export gauss_elimination (matrix<float> A, int m=na, int n=na) => //{
int _m = na(m) ? matrix.rows(A) : m , int _pm = _m - 1
int _n = na(n) ? matrix.columns(A) : n , int _pn = _n - 1
float[] _X = array.new_float(_m + 1, 0.0)
//
for _i = 0 to _pm-1
// partial pivoting:
for _k = _i + 1 to _pm
// if diagonal element(absolute value) is smaller than any of the terms below it
if math.abs(matrix.get(A, _i, _i)) < math.abs(matrix.get(A, _k, _i))
for _j = 0 to _pn
float _Aij = matrix.get(A, _i, _j)
matrix.set(A, _i, _j, matrix.get(A, _k, _j))
matrix.set(A, _k, _j, _Aij)
// begin Gauss Elimination:
for _k = _i + 1 to _pm
float _term = matrix.get(A, _k, _i) / matrix.get(A, _i, _i)
for _j = 0 to _pn
matrix.set(A, _k, _j, matrix.get(A, _k, _j) - _term * matrix.get(A, _i, _j))
// begin Back-Substitution:
for _i = _pm to 0
array.set(_X, _i, matrix.get(A, _i, _pn))
for _j = _i + 1 to _pn
array.set(_X, _i, array.get(_X, _i) - matrix.get(A, _i, _j) * array.get(_X, _j))
array.set(_X, _i, array.get(_X, _i) / matrix.get(A, _i, _i))
_X
//}
// @function Fits a polynomial of a degree to (x, y) points.
// @param X float array, data sample x point.
// @param Y float array, data sample y point.
// @param degree int, defval=2, degree of the polynomial.
// @returns float array with coefficients.
// note:
// p(x) = p[0] * x**deg + ... + p[deg]
export polyfit (float[] X, float[] Y, int degree=2) => //{
int _m = array.size(X) , int _pm = _m - 1
//
float[] _X1 = array.new_float(1 + degree * 2, 0.0)
for _i = 0 to degree * 2
for _j = 0 to _pm
array.set(_X1, _i, array.get(_X1, _i) + math.pow(array.get(X, _j), _i))
//the normal augmented matrix
matrix<float> _B = matrix.new<float>(degree + 1, degree + 2)
// rhs
float[] _Y1 = array.new_float(degree + 1, 0.0)
for _i = 0 to degree
for _j = 0 to _pm
array.set(_Y1, _i, array.get(_Y1, _i) + math.pow(array.get(X, _j), _i) * array.get(Y, _j))
for _i = 0 to degree
for _j = 0 to degree
matrix.set(_B, _i, _j, array.get(_X1, _i + _j))
for _i = 0 to degree
matrix.set(_B, _i, degree + 1, array.get(_Y1, _i))
// _str = 'The polynomial fit is given by the equation:\n'
// _str += str.tostring(_B) + '\n'
_A = gauss_elimination(_B)
// _str += str.tostring(_A) + '\n'
// usage:
// if barstate.isfirst
// _x = array.from(1, 2, 3, 4, 5.0)
// _y = array.from(1.0, 7.9, 26.99, 64, 125)
// label.new(bar_index, 0.0, str.tostring(polyfit(_x, _y, 3)))
int length = input.int(10)
int degree = input.int(3)
var x = array.new_float(length, float(bar_index)), array.shift(x), array.push(x, float(bar_index))
var y = array.new_float(length, float(close)), array.shift(y), array.push(y, float(close))
coeffs = polyfit(x, y, degree)
float solve = 0.0
for _i = 0 to array.size(coeffs)-1
solve += array.get(coeffs, _i) * math.pow(bar_index, _i)
plot(series=solve, color=color.teal)
//}
// @function interpolate the y position at the provided x.
// @param coeffs float array, coefficients of the polynomial.
// @param x float, position x to estimate y.
// @returns float.
export interpolate (float[] coeffs, float x) => //{
float _y = 0.0
for _i = 0 to array.size(coeffs) - 1
_y += array.get(coeffs, _i) * math.pow(x, _i)
_y
// usage:
if barstate.islast
_py = interpolate(coeffs, bar_index[length])
for _i = 1 to length
_y = interpolate(coeffs, bar_index[length - _i])
line.new(bar_index[length-_i]-1, _py, bar_index[length-_i], _y, color=color.yellow, width=2)
_py := _y
// forecast
for _i = 1 to 5
_y = interpolate(coeffs, bar_index + _i)
line.new(bar_index + _i - 1, _py, bar_index + _i, _y, color=color.yellow, width=2)
_py := _y
//}
|
ATRStopLossFinder | https://www.tradingview.com/script/V4Hn2MIo-ATRStopLossFinder/ | robbatt | https://www.tradingview.com/u/robbatt/ | 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/
// © robbatt
//@version=5
//@description Average True Range Stop Loss Finder
// credits to https://www.tradingview.com/u/shayankm/ for the initial version
library (title="ATRStopLossFinder", overlay=true)
ma_function(source, length, smoothing) =>
if smoothing == "RMA"
ta.rma(source, length)
else
if smoothing == "SMA"
ta.sma(source, length)
else
if smoothing == "EMA"
ta.ema(source, length)
else
ta.wma(source, length)
// ATR
//@function
//Returns the ATR
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossLong, series float stopLossShort, series float atr
export atr(simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) =>
tr = math.max(refHigh - refLow, math.abs(refHigh - refClose[1]), math.abs(refLow - refClose[1]))
atr = ma_function(tr, length, smoothing) * multiplier
atr // return
// ATR (Ticks)
//@function
//Returns the ATR
//@param tickValue simple float tick value (use getTickValueSymbol)
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossLong, series float stopLossShort, series float atr
export atrTicks(series float tickValue, simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) =>
atrTicks = atr(length, smoothing, multiplier, refHigh, refLow, refClose) / tickValue
atrTicks // return
// Stop Loss Finder
//@function
//Returns the stop losses for an entry on this candle, depending on the ATR
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossLong, series float stopLossShort, series float atr
export stopLossFinder(simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) =>
atr = atr(length, smoothing, multiplier, refHigh, refLow, refClose)
stopLossShort = atr + refHigh
stopLossLong = refLow - atr
[stopLossLong, stopLossShort, atr]
// Stop Loss Finder (Ticks)
//@function
//Returns the stop losses for an entry on this candle in ticks, depending on the ATR
//@param tickValue simple float tick value (use getTickValueSymbol)
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossTicks
export stopLossTicks(series float tickValue, simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) =>
atrTicks = atrTicks(tickValue , length, smoothing, multiplier, refHigh, refLow, refClose)
stopLossTicksShort = (refHigh - refClose) / tickValue + atrTicks // assuming opening positions from last close value, so we need to add the difference to high
stopLossTicksLong = (refClose - refLow) / tickValue + atrTicks // assuming opening positions from last close value, so we need to add the difference to low
[stopLossTicksLong, stopLossTicksShort, atrTicks]
length = input.int(title="Length", defval=14, minval=1)
smoothing = input.string(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
m = input.float(1.5, "Multiplier")
src1 = input.source(high,"Source high")
src2 = input.source(low,"Source low")
src3 = input.source(close,"Source close")
pline = input.bool(true, "Show Price Lines")
col1 = input.color(color.blue, "ATR Text Color")
col2 = input.color(color.teal, "Low Text Color",inline ="1")
col3 = input.color(color.red, "High Text Color",inline ="2")
collong = input.color(color.teal, "Low Line Color",inline ="1")
colshort = input.color(color.red, "High Line Color",inline ="2")
// GetTickValueSymbol() returns the tick value (currency value of
// smallest possible price change) for the specified instrument,
// loaded with 'security' in a non-repainting manner.
getTickValueSymbol(simple string symbol) =>
request.security(symbol, "D", (syminfo.mintick * syminfo.pointvalue)[1],lookahead=barmerge.lookahead_on)
// data
[stopLossLong, stopLossShort, atr] = stopLossFinder(length, smoothing, m, src1, src2, src3)
tickValue = getTickValueSymbol(syminfo.tickerid)
[stopLossTicksLong, stopLossTicksShort, atrTicks] = stopLossTicks(tickValue, length, smoothing, m, src1, src2, src3)
refSymbol = input.symbol("BINANCEUS:BTCUSD", "symbol", group="Reference")
refPeriod = input.timeframe('60', "timeframe", group = "Reference", options=['1','5','15','60','240','1440']) // timeframe.period //15'
[refHigh, refLow, refClose] = request.security(refSymbol, refPeriod, [high, low, close])
[stopLossLongRef, stopLossShortRef, atrRef] = stopLossFinder(length, smoothing, m, refHigh, refLow, refClose)
tickValueRef = getTickValueSymbol(refSymbol)
[stopLossTicksRefLong, stopLossTicksRefShort, atrTicksRef] = stopLossTicks(tickValueRef, length, smoothing, m, refHigh, refLow, refClose)
// plotting
p1 = plot(stopLossShort, title = "ATR Short Stop Loss", color= color.new(colshort, transp = 20), trackprice = pline ? true : false)
p2 = plot(stopLossLong, title = "ATR Long Stop Loss", color= color.new(collong, transp = 20), trackprice = pline ? true : false)
pTicks = plot(atrTicks * tickValue, title = "stop loss ticks", color = color.teal, style = plot.style_cross)
p1Ticks = plot(close - stopLossTicksLong * tickValue, title = "stop loss long ticks", color = color.olive, style = plot.style_cross)
p2Ticks = plot(close + stopLossTicksShort * tickValue, title = "stop loss short ticks", color = color.fuchsia, style = plot.style_cross)
p1Ref = plot(stopLossShortRef, title = "ref ATR Short Stop Loss", color= color.new(colshort, transp = 50), trackprice = pline ? true : false)
p2Ref = plot(stopLossLongRef, title = "ref ATR Long Stop Loss", color= color.new(collong, transp = 50), trackprice = pline ? true : false)
// table of values
var table Table = table.new(position.bottom_center, 7, 2, border_width = 3)
f_fillCell(_table, _column, _row, _value, _timeframe) =>
_cellText = _timeframe+ str.tostring(_value, "#.##")
table.cell(_table, _column, _row, _cellText, text_color = col1)
if barstate.islast
// original
table.cell(Table, 0, 0, "symbol: " + syminfo.tickerid + " - " + timeframe.period + "min")
f_fillCell(Table, 1, 0, atr, "ATR: " )
f_fillCell(Table, 2, 0, stopLossShort, "H: " )
f_fillCell(Table, 3, 0, stopLossTicksShort, "sl short ticks: " )
f_fillCell(Table, 4, 0, stopLossLong, "L: " )
f_fillCell(Table, 5, 0, stopLossTicksLong, "sl long ticks: " )
f_fillCell(Table, 6, 0, tickValue, "tick value: " )
// ref
table.cell(Table, 0, 1, "ref : " + refSymbol + " - " + refPeriod + "min")
f_fillCell(Table, 1, 1, atrRef, "ATR: " )
f_fillCell(Table, 2, 1, stopLossShortRef, "H: " )
f_fillCell(Table, 3, 1, stopLossTicksRefShort, "sl short ticks: " )
f_fillCell(Table, 4, 1, stopLossLongRef, "L: " )
f_fillCell(Table, 5, 1, stopLossTicksRefLong, "sl long ticks: " )
f_fillCell(Table, 6, 1, tickValueRef, "tick value: " )
table.cell_set_text_color(Table, 2, 0, color.new(col3, transp = 0))
table.cell_set_text_color(Table, 3, 0, color.new(col3, transp = 0))
table.cell_set_text_color(Table, 4, 0, color.new(col2, transp = 0))
table.cell_set_text_color(Table, 5, 0, color.new(col2, transp = 0))
table.cell_set_text_color(Table, 2, 1, color.new(col3, transp = 0))
table.cell_set_text_color(Table, 3, 1, color.new(col3, transp = 0))
table.cell_set_text_color(Table, 4, 1, color.new(col2, transp = 0))
table.cell_set_text_color(Table, 5, 1, color.new(col2, transp = 0))
|
CommonFilters | https://www.tradingview.com/script/kI6YjrIH-CommonFilters/ | lastguru | https://www.tradingview.com/u/lastguru/ | 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/
// © lastguru
//@version=5
// @description Collection of some common Filters and Moving Averages. This collection is not encyclopaedic, but to declutter my other scripts. Suggestions are welcome, though. Many filters here are based on the work of John F. Ehlers
library("CommonFilters", true)
// ----------
// Common Moving Averages
// ----------
// @function Simple Moving Average
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export sma(float src, int len) =>
out = 0.0
out := math.sum(src, len)/len
// @function Exponential Moving Average
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export ema(float src, int len) =>
alpha = 2 / (len + 1)
sum = 0.0
sum := alpha * src + (1 - alpha) * nz(sum[1])
// @function Wilder's Smoothing (Running Moving Average)
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export rma(float src, int len) =>
out = 0.0
out := ((len - 1) * nz(out[1]) + src) / len
// @function Hull Moving Average
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export hma(float src, int len) =>
out = 0.0
out := ta.wma(2 * ta.wma(src, len/2) - ta.wma(src, len), math.round(math.sqrt(len)))
// @function Volume Weighted Moving Average
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export vwma(float src, int len) =>
val = math.sum(src*volume, len)
vol = math.sum(volume, len)
val/vol
// ----------
// Fast FIR prefilters
// ----------
// @function Simple denoiser
// @param src Series to use
// @returns Filtered series
export hp2(float src) =>
src - (src - 2 * src[1] + src[2]) / 4
// @function Zero at 2 bar cycle period by John F. Ehlers
// @param src Series to use
// @returns Filtered series
export fir2(float src) =>
(src + src[1]) / 2
// @function Zero at 3 bar cycle period by John F. Ehlers
// @param src Series to use
// @returns Filtered series
export fir3(float src) =>
(src + src[1] + src[2]) / 3
// @function Zero at 2 bar and 3 bar cycle periods by John F. Ehlers
// @param src Series to use
// @returns Filtered series
export fir23(float src) =>
(src + 2 * src[1] + 2 * src[2] + src[3]) / 6
// @function Zero at 2, 3 and 4 bar cycle periods by John F. Ehlers
// @param src Series to use
// @returns Filtered series
export fir234(float src) =>
(src + 2 * src[1] + 3 * src[2] + 3 * src[3] + 2 * src[4] + src[5]) / 12
// ----------
// High Pass Filters
// ----------
// @function High Pass Filter for cyclic components shorter than langth. Part of Roofing Filter by John F. Ehlers
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export hp(float src, int len) =>
alpha = (math.cos(math.sqrt(2) * math.pi / len) + math.sin(math.sqrt(2) * math.pi / len) - 1) / math.cos(math.sqrt(2) * math.pi / len)
highpass = 0.0
highpass := math.pow(1 - alpha / 2, 2) * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * (1 - alpha) * nz(highpass[1]) - math.pow(1 - alpha, 2) * nz(highpass[2])
// @function 2-pole Super Smoother by John F. Ehlers
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export supers2(float src, int len) =>
arg = math.sqrt(2) * math.pi / len
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(arg)
c2 = b1
c3 = -math.pow(a1, 2)
c1 = 1 - c2 - c3
ssf = 0.0
ssf := c1 * (src + nz(src[1])) / 2 + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
// @function Filt11 is a variant of 2-pole Super Smoother with error averaging for zero-lag response by John F. Ehlers
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export filt11(float src, int len) =>
arg = math.sqrt(2) * math.pi / len
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(arg)
c2 = b1
c3 = -math.pow(a1, 2)
c1 = 1 - c2 - c3
ssf = 0.0
ssf := c1 * (src + nz(src[1])) / 2 + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
e1 = 0.0
e1 := c1 * (src - ssf) + c2 * nz(e1[1]) + c3 * nz(e1[2])
ssf + e1
// @function 3-pole Super Smoother by John F. Ehlers
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export supers3(float src, int len) =>
arg = math.pi / len
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(math.sqrt(3) * arg)
c1 = math.pow(a1, 2)
coef2 = b1 + c1
coef3 = -(c1 + b1 * c1)
coef4 = math.pow(c1, 2)
coef1 = 1 - coef2 - coef3 - coef4
ssf = 0.0
ssf := coef1 * (src + nz(src[1])) / 2 + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3])
// ----------
// Windowing FIR Filters
// ----------
// @function Hann Window Filter by John F. Ehlers
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export hannFIR(float src, int len) =>
hann = 0.0
coef = 0.0
for count = 0 to len - 1
m = 1 - math.cos(2 * math.pi * (count+1) / (len+1))
hann := hann + m * nz(src[count])
coef := coef + m
hann := coef != 0 ? hann / coef : 0
// @function Hamming Window Filter (inspired by John F. Ehlers). Simplified implementation as Pedestal input parameter cannot be supplied, so I calculate it from the supplied length
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export hammingFIR(float src, int len) =>
pedestal = len / 2
filt = 0.0
coef = 0.0
for count = 0 to len - 1
sine = math.sin((pedestal + (180 - 2 * pedestal) * count / (len - 1)) * math.pi / 180)
filt := filt + sine * nz(src[count])
coef := coef + sine
filt := coef != 0 ? filt / coef : 0
// @function Triangle Window Filter by John F. Ehlers
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export triangleFIR(float src, int len) =>
filt = 0.0
coef = 0.0
sumcoef = 0.0
for count = 1 to len
if count <= len / 2
coef := count
else
coef := len + 1 - count
filt := filt + coef * nz(src[count - 1])
sumcoef := sumcoef + coef
filt := sumcoef != 0 ? filt / sumcoef : 0
// ----------
// Jurik MA
// ----------
jmapow(src, len) =>
upperBand = src
lowerBand = src
// Volatility
del1 = src - nz(upperBand[1], src)
del2 = src - nz(lowerBand[1], src)
volty = math.abs(del1) == math.abs(del2) ? 0 : math.max(math.abs(del1), math.abs(del2))
// Incremental sum of Volty
vSum = 0.0
vSum := nz(vSum[1]) + 0.1 * (volty - nz(volty[10], volty))
// Jurik used 65
avgLen = 65
avgVolty = ta.sma(vSum, avgLen)
// Relative price volatility
alen = (len - 1) / 2
len1 = math.max(math.log(math.sqrt(alen)) / math.log(2) + 2, 0)
pow1 = math.max(len1 - 2, 0.5)
rVolty = avgVolty != 0 ? volty / avgVolty : 0
if (rVolty > math.pow(len1, 1 / pow1))
rVolty := math.pow(len1, 1 / pow1)
if rVolty < 1
rVolty := 1
// Jurik Bands
pow2 = math.pow(rVolty, pow1)
len2 = math.sqrt(alen) * len1
bet = len2/(len2 + 1)
kv = math.pow(bet, math.sqrt(pow2))
upperBand := del1 > 0 ? src : src - kv * del1
lowerBand := del2 < 0 ? src : src - kv * del2
pow2
// @function Jurik MA
// @param src Series to use
// @param len Filtering length
// @param phase JMA Phase
// @returns Filtered series
// Based on the reverse-engineered JMA documented by somebody called Igor: https://c.mql5.com/forextsd/forum/164/jurik_1.pdf
// Inspired by @everget implementation: https://www.tradingview.com/script/nZuBWW9j-Jurik-Moving-Average/
// Inspired by @gorx1 implementation: https://www.tradingview.com/script/gwzRz6tI-Jurik-Moving-Average/
// As JMA is a proprietary closed-source algorithm, every JMA implementation I've seen is based on the Igor's document
// Many of the implementations, however, are not true to the source
// As far as I know, this is the first correct JMA implementation on TradingView
// As the Igor's document itself is incomplete, however, there is some grey area still...
export jma(float src, int len, int phase = 50) =>
jma = 0.0
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
power = jmapow(src, len)
alpha = math.pow(beta, power)
// 1st stage - preliminary smoothing by adaptive EMA
ma1 = 0.0
ma1 := (1 - alpha) * src + alpha * nz(ma1[1])
// 2nd stage - preliminary smoothing by Kalman filter
det0 = 0.0
det0 := (1 - beta) * (src - ma1) + beta * nz(det0[1])
ma2 = ma1 + phaseRatio * det0
// 3rd stage - final smoothing by Jurik adaptive filter
det1 = 0.0
det1 := math.pow(1 - alpha, 2) * (ma2 - nz(jma[1])) + math.pow(alpha, 2) * nz(det1[1])
jma := nz(jma[1]) + det1
jma
// ----------
// Filter Wrappers
// ----------
// @function Execute a particular Prefilter from the list
// @param type Prefilter type to use
// @param src Series to use
// @returns Filtered series
export doPrefilter(string type, float src) =>
out = 0.0
switch type
"None" =>
out := src
"Simple Denoiser" =>
out := hp2(src)
"2 bar FIR" =>
out := fir2(src)
"3 bar FIR" =>
out := fir3(src)
"2,3 bar FIR" =>
out := fir23(src)
"2,3,4 bar FIR" =>
out := fir234(src)
out
// @function Execute a particular MA from the list
// @param type MA type to use
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
export doMA(string type, float src, int len) =>
out = 0.0
switch type
"None" =>
out := src
"SMA" =>
out := sma(src, len)
"RMA" =>
out := rma(src, len)
"EMA" =>
out := ema(src, len)
"HMA" =>
out := hma(src, len)
"VWMA" =>
out := vwma(src, len)
"2-pole Super Smoother" =>
out := supers2(src, len)
"3-pole Super Smoother" =>
out := supers3(src, len)
"Filt11" =>
out := filt11(src, len)
"Triangle Window" =>
out := triangleFIR(src, len)
"Hamming Window" =>
out := hammingFIR(src, len)
"Hann Window" =>
out := hannFIR(src, len)
"Lowpass" =>
out := src - hp(src, len)
"JMA" =>
out := jma(src, len)
out
|
DateLibrary | https://www.tradingview.com/script/OVwcXIeS-DateLibrary/ | jeanpaulfd | https://www.tradingview.com/u/jeanpaulfd/ | 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/
// © kaka900
//@version=5
// @description TODO: add library description here
library("DateLibrary", overlay=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())
plot(lo())
//DO NOT MODIFY
wickTimesStart = timestamp(2016, 04, 16, 00, 00)
wickTimesEnd = timestamp(2016, 05, 01, 00, 00)
wickTimes() =>
time >= wickTimesStart and time <= wickTimesEnd ? true : false
export window(string TradePeriod) =>
FromYear = 2012
ToYear = 2035
FromMonth = 01
FromDay = 01
ToMonth = 01
ToDay = 01
switch TradePeriod
'2012.04-now' =>
FromMonth := 04
FromDay := 10
'2012.04-2021' =>
FromMonth := 04
FromDay := 10
ToYear := 2021
'2013-now' =>
FromYear := 2013
FromMonth := 01
FromDay := 01
'2014-now' =>
FromYear := 2013
FromMonth := 12
FromDay := 30
'2017-now' =>
FromYear := 2017
'2018-now' =>
FromYear := 2018
'2019-now' =>
FromYear := 2019
'2020-now' =>
FromYear := 2020
'ytd' =>
FromYear := 2022
'2012' =>
FromMonth := 03
FromYear := 2012
ToYear := 2013
'2013' =>
FromYear := 2013
ToYear := 2013
ToMonth := 12
ToDay := 30
'2012-2014' =>
FromYear := 2012
ToYear := 2014
FromMonth := 03
'2012-2017' =>
FromYear := 2012
ToYear := 2017
FromMonth := 03
'2014-2019' =>
FromYear := 2014
ToYear := 2019
'2018-2020' =>
FromYear := 2018
ToYear := 2020
'2019-2020.08' =>
FromYear := 2019
ToYear := 2020
ToMonth := 08
'2014' =>
FromYear := 2014
ToYear := 2015
ToDay := 24
'2015' =>
FromYear := 2015
FromDay := 25
ToYear := 2015
ToMonth := 12
ToDay := 26
'2016' =>
FromYear := 2015
FromMonth := 12
FromDay := 25
ToYear := 2017
'2017' =>
FromYear := 2017
FromDay := 07
ToYear := 2017
ToMonth := 12
ToDay := 31
'2018' =>
FromYear := 2018
ToYear := 2018
ToMonth := 12
ToDay := 24
'2019' =>
FromYear := 2018
FromMonth := 12
FromDay := 24
ToYear := 2019
ToMonth := 12
ToDay := 24
'2020' =>
FromYear := 2019
FromMonth := 12
FromDay := 31
ToYear := 2021
ToMonth := 01
ToDay := 01
'2021' =>
FromYear := 2020
FromMonth := 12
FromDay := 31
ToYear := 2022
ToMonth := 01
ToDay := 01
'tests' =>
FromYear := 2021
FromMonth := 10
FromDay := 27
time >= timestamp(FromYear, FromMonth, FromDay, 00, 00) and time <= timestamp(ToYear, ToMonth, ToDay, 23, 59) ? true : false
//DO NOT MODIFY
CloseBelow3d201201 = timestamp(2012, 03, 27, 23, 59)
GoldenExit201201 = timestamp(2012, 04, 20, 23, 59)
CloseBelow3d201202 = timestamp(2012, 04, 23, 23, 59)
GoldenExit201202 = timestamp(2012, 06, 01, 23, 59)
CloseBelow3d201203 = timestamp(2012, 10, 26, 23, 59)
GoldenExit201203 = timestamp(2012, 10, 29, 23, 59)
CloseBelow3d01 = timestamp(2013, 06, 29, 23, 59)
GoldenExit01 = timestamp(2013, 08, 22, 23, 59)
CloseBelow3d1 = timestamp(2014, 02, 17, 23, 59)
GoldenExit1 = timestamp(2014, 05, 27, 23, 59)
CloseBelow3d2 = timestamp(2014, 08, 13, 23, 59)
GoldenExit2 = timestamp(2015, 06, 17, 23, 59)
CloseBelow3d3 = timestamp(2015, 06, 23, 23, 59)
GoldenExit3 = timestamp(2015, 06, 29, 23, 59)
CloseBelow3d4 = timestamp(2015, 08, 19, 23, 59)
GoldenExit4 = timestamp(2015, 10, 15, 23, 59)
CloseBelow3d5 = timestamp(2016, 08, 27, 23, 59)
GoldenExit5 = timestamp(2016, 09, 05, 23, 59)
CloseBelow3d6 = timestamp(2016, 09, 20, 23, 59)
GoldenExit6 = timestamp(2016, 10, 11, 23, 59)
CloseBelow3d7 = timestamp(2018, 01, 30, 23, 59)
GoldenExit7 = timestamp(2018, 07, 23, 23, 59)
CloseBelow3d8 = timestamp(2018, 08, 01, 23, 59)
GoldenExit8 = timestamp(2019, 03, 16, 23, 59)
CloseBelow3d9 = timestamp(2019, 09, 21, 23, 59)
GoldenExit9 = timestamp(2020, 01, 15, 23, 59)
CloseBelow3d10 = timestamp(2020, 03, 09, 23, 59)
GoldenExit10 = timestamp(2020, 04, 29, 23, 59)
CloseBelow3d11 = timestamp(2020, 09, 23, 23, 59)
GoldenExit11 = timestamp(2020, 09, 26, 23, 59)
CloseBelow3d12 = timestamp(2021, 05, 12, 23, 59)
GoldenExit12 = timestamp(2021, 08, 07, 23, 59)
CloseBelow3d13 = timestamp(2021, 12, 05, 23, 59)
GoldenExit13 = timestamp(2022, 03, 28, 23, 59)
CloseBelow3d14 = timestamp(2022, 04, 09, 23, 59)
GoldenExit14 = timestamp(2023, 01, 01, 23, 59)
export BearishPeriod() =>
time >= CloseBelow3d201201 and time <= GoldenExit201201 or time >= CloseBelow3d201202 and time <= GoldenExit201202 or time >= CloseBelow3d201203 and time <= GoldenExit201203
or time >= CloseBelow3d01 and time <= GoldenExit01 or time >= CloseBelow3d1 and time <= GoldenExit1 or time >= CloseBelow3d2 and time <= GoldenExit2 or time >= CloseBelow3d3 and time <= GoldenExit3
or time >= CloseBelow3d4 and time <= GoldenExit4 or time >= CloseBelow3d5 and time <= GoldenExit5 or time >= CloseBelow3d6 and time <= GoldenExit6 or time >= CloseBelow3d7 and time <= GoldenExit7
or time >= CloseBelow3d8 and time <= GoldenExit8 or time >= CloseBelow3d9 and time <= GoldenExit9 or time >= CloseBelow3d10 and time <= GoldenExit10 or time >= CloseBelow3d11 and time <= GoldenExit11
or time >= CloseBelow3d12 and time <= GoldenExit12
or time >= CloseBelow3d13 and time <= GoldenExit13
or time >= CloseBelow3d14 and time <= GoldenExit14
? true : false
// @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 |
AbdulLibrary | https://www.tradingview.com/script/851iJzAw-AbdulLibrary/ | Abdul_Saif | https://www.tradingview.com/u/Abdul_Saif/ | 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/
// © Abdul_Saif
//@version=5
// @description The library consists of three sections:
// @Technical Analysis Functions - A collection of tools commonly used by day traders
// @Trading Setup Filters Functions - A number of filters that help day traders to screen trading signals
// @Candlestick Pattern Detection Functions - To detect different candelstick patterns that are used in day trading setups
// \nNote that this would have been not possible without the help of @ZenAndTheArtOfTrading as I build-up this library after completing his pine script mastery course so big thanks to him
library("AbdulLibrary")
// --- BEGIN Technical Analysis Functions {
// @function Calculates Daily Pivot Point and Fibonacci Key Levels
// @param preDayClose The previous day candle close
// @param preDayHigh The previous day candle high
// @param preDayLow The previous day candle low
// @returns Returns Daily Pivot Point and Fibonacci Key Levels as a tuple
export fibLevels(float preDayClose, float preDayHigh, float preDayLow) =>
dPP = (preDayHigh + preDayLow + preDayClose) / 3
r1 = (2 * dPP) - preDayLow
r2 = dPP + (preDayHigh - preDayLow)
r3 = dPP + (2 * (preDayHigh - preDayLow))
s1 = (2* dPP) - preDayHigh
s2 = dPP - (preDayHigh - preDayLow)
s3 = dPP - (2 * (preDayHigh - preDayLow))
// returns the dPP, r1, r2, r3, s1, s2 and s3 as a tuple
[dPP, r1, r2, r3, s1, s2, s3]
// @function Calculates Fibonacci Levels in Bullish move
// @param canHigh The high of the move
// @param canLow The low of the move
// @param fibLevel The Fib level as % you want to calculate
// @returns Returns The Fib level for the Bullish move
export bullishFib(float moveHigh, float moveLow, float fibLevel = 0.382) =>
(moveLow - moveHigh) * fibLevel + moveHigh
// @function Calculates Fibonacci Levels in Bearish move
// @param canHigh The high of the move
// @param canLow The low of the move
// @param fibLevel The Fib level as % you want to calculate
// @returns Returns The Fib level for the Bearish move
export bearishFib(float moveHigh, float moveLow, float fibLevel = 0.382) =>
(moveHigh - moveLow) * fibLevel + moveLow
// Originalky this is an indicator created by @DavidBrunet and modified by @FX365_Thailand, but I optimized it into shorter code
// @function Plot Horizontal line at round number
// @param market The markets the user is trading
// @param numRoundNumbers How many round numbers to be plotted above and below current price
// @returns Returns Na - Plot horizontal line at round number
export plotRoundNumber(string market, int numRoundNumbers) =>
// Define the steps based on the market you trade ie Forex, USOIL, Gold Crypto etc...
var step = switch market
"Forex" => syminfo.mintick*500
"Crypto" => syminfo.mintick*500
"XAUUSD" => syminfo.mintick*5000
"XAGUSD" => syminfo.mintick*50000
"USOIL" => syminfo.mintick*5000
"Gold" => syminfo.mintick*500
"Silver" => syminfo.mintick*500
=> syminfo.mintick*500
// Drawing RN lines based on user inputs of market and number of lines required
if barstate.islast
for counter = 0 to numRoundNumbers -1
stepUp = math.ceil(close / step) * step + (counter * step)
line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, style = line.style_dotted, color = color.gray)
stepDown = math.floor(close / step) * step - (counter * step)
line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, style = line.style_dotted, color = color.gray)
// @function Calculates the size of candle (high - low) in points
// @returns Returns candle size in points
export getCandleSize() =>
math.abs(high - low) / syminfo.mintick
// @function Calculates the size of candle (close - open) in points
// @returns Returns candle body size in points
export getCandleBodySize() =>
math.abs(close - open) / syminfo.mintick
// @function Calculates the high wick size of candle in points
// @returns Returns The high wick size of candle in points
export getHighWickSize() =>
math.abs(high - (close > open ? close : open)) / syminfo.mintick
// @function Calculates the low wick size of candle in points
// @returns Returns The low wick size of candle in points
export getLowWickSize() =>
math.abs((close > open ? open : close) - low) / syminfo.mintick
// @function Calculates the candle body size as % of overall candle size
// @returns Returns The candle body size as % of overall candle size
export getBodyPercentage() =>
getCandleBodySize() / getCandleSize()
// } END Technical Analysis Functions
// --- BEGIN Trading Setup Filters Functions {
// @function Checks if the price has created new swing high over a period of time
// @param period The lookback time we want to check for swing high
// @returns Returns True if the current candle or the previous candle is a swing high
export isSwingHigh(int period) =>
swingHigh = high == ta.highest(high, period) or high[1] == ta.highest(high, period)
// @function Checks if the price has created new swing low over a period of time
// @param period The lookback time we want to check for swing low
// @returns Returns True if the current candle or the previous candle is a swing low
export isSwingLow(int period) =>
swingLow = low == ta.lowest(low, period) or low[1] == ta.lowest(low, period)
// @function Checks if a doji is a swing high over a period of time
// @param period The lookback time we want to check for swing high
// @returns Returns True if the doji is a swing high
export isDojiSwingHigh(int period) =>
dojiSwinghigh = high == ta.highest(high, period)
// @function Checks if a doji is a swing low over a period of time
// @param period The lookback time we want to check for swing low
// @returns Returns True if the doji is a swing low
export isDojiSwingLow(int period) =>
dojiSwingLow = low == ta.lowest(low, period)
// @function Checks if a candle has big body compared to ATR
// @param atrFilter Check if user wants to use ATR to filter candle-setup signals
// @param atr The ATR value to be used to compare candle body size
// @param candleBodySize The candle body size
// @param multiplier The multiplier to be used to compare candle body size
// @returns Returns Boolean true if the candle setup is big
export isBigBody(bool atrFilter = false, float atr, float candleBodySize, float multiplier = 1.0) =>
if atrFilter
candleBodySize >= atr * multiplier
else
true
// @function Checks if a candle has small body compared to ATR
// @param atrFilter Check if user wants to use ATR to filter candle-setup signals
// @param atr The ATR value to be used to compare candle body size
// @param candleBodySize The candle body size
// @param multiplier The multiplier to be used to compare candle body size
// @returns Returns Boolean true if the candle setup is small
export isSmallBody(bool atrFilter = false, float atr, float candleBodySize, float multiplier = 0.15) =>
if atrFilter
candleBodySize <= atr * multiplier
else
true
// } END Trading Setup Filters Functions
// --- BEGIN Candlestick Pattern Detection Functions {
// @function Checks if a candle is a hammer based on user input parameters and candle conditions
// @param fibLevel Fib level to base candle body on
// @param colorMatch Checks if user needs for the candel to be green
// @returns Returns Boolean - True if the candle setup is hammer
export isHammer(float fibLevel = 0.236, bool colorFilter = false) =>
// Checks if candle body is above specified fib level
bullFib = bullishFib(high, low, fibLevel)
// Determine which price source closes or opens lowest
lowestBody = close < open ? close : open
// Determine if we have a valid hammer or shooting star candle
hammer = lowestBody >= bullFib and (not colorFilter or close > open)
// @function Checks if a candle is a shooting star based on user input parameters and candle conditions
// @param fibLevel Fib level to base candle body on
// @param colorMatch Checks if user needs for the candel to be red
// @returns Returns Boolean - True if the candle setup is star
export isShootingStar(float fibLevel = 0.236, bool colorFilter = false) =>
// Checks if candle body is above specified fib level
bearFib = bearishFib(high, low, fibLevel)
// Determine which price source closes or opens highest
highestBody = close > open ? close : open
// Determine if we have a valid shooting star candle
shootingStar = highestBody <= bearFib and (not colorFilter or close < open)
// @function Check if a candle is a bullish engulfing candle
// @param allowance How many points the candle open is allowed to be off (To allow for gaps)
// @param period The lookback period for swing low check
// @returns Boolean - True only if the candle is a bullish engulfing candle
export isBullEngCan(float allowance = 1.0) =>
check = getCandleBodySize()[0] > getCandleBodySize()[1] and close[1] < open[1] and open <= (close[1] + allowance) and close >= (open[1] + allowance)
bullEngCan = check
// @function Check if a candle is a bearish engulfing candle
// @param allowance How many points the candle open is allowed to be off (To allow for gaps)
// @param period The lookback period for swing high check
// @returns Boolean - True only if the candle is a bearish engulfing candle
export isBearEngCan(float allowance = 1.0) =>
check = getCandleBodySize()[0] > getCandleBodySize()[1] and close[1] > open[1] and open >= (close[1] - allowance) and close <= (open[1] - allowance)
bearEngCan = check
// @function Check if a candle is a bullish doji candle
// @param maxSize Maximum candle body size as % of total candle size to be considered as doji
// @param wickLimit Maximum wick size of one wick compared to the other wick
// @param colorFilter Checks if the doji is green
// @returns Boolean - True if the candle is a bullish doji
export isBullDoji(float maxSize = 0.2, float wicksLimit = 2, bool colorFilter = false) =>
doji = getHighWickSize() <= getLowWickSize() * wicksLimit and getLowWickSize() <= getHighWickSize() * wicksLimit and getBodyPercentage() <= maxSize and (not colorFilter or close > open)
// @function Check if a candle is a bearish doji candle
// @param maxSize Maximum candle body size as % of total candle size to be considered as doji
// @param wickLimit Maximum wick size of one wick compared to the other wick
// @param colorFilter Checks if the doji is red
// @returns Boolean - True if the candle is a bearish doji
export isBearDoji(float maxSize = 0.2, float wicksLimit = 2,bool colorFilter = false) =>
doji = getHighWickSize() <= getLowWickSize() * wicksLimit and getLowWickSize() <= getHighWickSize() * wicksLimit and getBodyPercentage() <= maxSize and (not colorFilter or close < open)
// @function Check if a candle is a bullish outside bar
// @returns Boolean - True if the candle is a bullish outside bar
export isBullOutBar() =>
check = getCandleSize()[0] > getCandleSize()[1] and close[1] < open[1] and high > high[1] and low < low[1]
bullOutBar = check
// @function Check if a candle is a bearish outside bar
// @returns Boolean - True if the candle is a bearish outside bar
isBearOutBar() =>
// check if current candle size is bigger than previous candle size
check = getCandleSize()[0] > getCandleSize()[1] and close[1] > open[1] and high > high[1] and low < low[1]
bearOutBar = check
// @function Check if a candle is an inside bar
// @returns Returns Boolean - True if a candle is an inside bar
export isInsideBar() =>
high < high[1] and low > low[1]
// } END Candlestick Pattern Detection Functions
|
moving_average | https://www.tradingview.com/script/IjotbRV3/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 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/
// © dandrideng
//@version=5
// @description moving_average: moving average variants
library("moving_average", overlay=true)
// @function variant: moving average variants
// @param string type: type in ["SMA", "EMA", "DEMA", "TEMA", "WMA", "VWMA", "SMMA", "HullMA", "TMA", "SSMA"]
// @param series float src: the source series of moving average
// @param simple int len: the length of moving average
// @returns float: the moving average variant value
export variant(string type, series float src, simple int len) =>
//TODO : add function body and return value here
float v1 = ta.sma(src, len) // Simple
float v2 = ta.ema(src, len) // Exponential2
float v3 = 2 * v2 - ta.ema(v2, len) // Double Exponential
float v4 = 3 * (v2 - ta.ema(v2, len)) + ta.ema(ta.ema(v2, len), len) // Triple Exponential
float v5 = ta.wma(src, len) // Weighted
float v6 = ta.vwma(src, len) // Volume Weighted
float v7 = 0.0
v7 := na(v7[1]) ? v1 : (v7[1] * (len - 1) + src) / len // Smoothed
float v8 = ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) // Hull
float v9 = ta.sma(v1,len) // Triangular (extreme smooth)
// SuperSmoother filter
// © 2013 John F. Ehlers
float a1 = math.exp(-1.414*3.14159 / len)
float b1 = 2*a1*math.cos(1.414*3.14159 / len)
float c2 = b1
float c3 = (-a1)*a1
float c1 = 1 - c2 - c3
float v10 = 0.0
v10 := c1*(src + nz(src[1])) / 2 + c2*nz(v10[1]) + c3*nz(v10[2])
type=="EMA"? v2: type=="DEMA"? v3: type=="TEMA"? v4: type=="WMA"? v5: type=="VWMA"? v6: type=="SMMA"? v7: type=="HullMA"?v8 : type=="TMA"? v9: type=="SSMA"? v10: v1
plot(variant("HullMA", close, 30)) |
divergence | https://www.tradingview.com/script/mPcGqrxb/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 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/
// © dandrideng
//@version=5
// @description divergence: divergence algorithm with top and bottom kline tolerance
library("divergence", overlay=true)
// @function regular_bull: regular bull divergence, lower low src but higher low osc
// @param series float src: the source series
// @param series float osc: the oscillator index
// @param simple int lbL: look back left
// @param simple int lbR: look back right
// @param simple int rangeL: min look back range
// @param simple int rangeU: max look back range
// @param simple int tolerance: the number of tolerant klines
// @returns array: [left_src_value, left_src_bars, left_osc_value, left_osc_bars, right_src_value, right_src_bars, right_osc_value, right_osc_bars, div_cov]
export regular_bull(series float src, series float osc, simple int lbL, simple int lbR, simple int rangeL, simple int rangeU, simple int tolerance) =>
slv = ta.pivotlow(src, lbL, lbR)
olv = ta.pivotlow(osc, lbL, lbR)
slvf = na(slv) ? false : true
olvf = na(olv) ? false : true
slvb = ta.barssince(slvf)
slvr = slvb <= tolerance ? slv[slvb] : na
olvb = ta.barssince(olvf)
olvr = olvb <= tolerance ? olv[olvb] : na
cmb1 = slvb <= tolerance and olvf
cmb2 = olvb <= tolerance and slvf
cmb = cmb1 or cmb2
res = array.new_float(9, na)
if not cmb or na(slvr) or na(slvb) or na(olvr) or na(olvb)
res
for r = math.max(rangeL, lbL, slvb, olvb) to math.max(rangeU, lbL, slvb, olvb)
if cmb[r] and ((slvr[r] > slvr and olv[r] < olv) or (slv[r] > slv and olvr[r] < olvr))
array.set(res, 0, slvr[r])
array.set(res, 1, slvb[r] + r)
array.set(res, 2, olvr[r])
array.set(res, 3, olvb[r] + r)
array.set(res, 4, slvr)
array.set(res, 5, slvb)
array.set(res, 6, olvr)
array.set(res, 7, olvb)
array.set(res, 8, ((slvr/slvr[r] - 1) * 10000 / (slvb[r]+r-slvb)) * ((olvr - olvr[r]) / (olvb[r]+r-olvb)))
break
if src[r] < slvr
break
res
// @function hidden_bull: hidden bull divergence, higher low src but lower low osc
// @param series float src: the source series
// @param series float osc: the oscillator index
// @param simple int lbL: look back left
// @param simple int lbR: look back right
// @param simple int rangeL: min look back range
// @param simple int rangeU: max look back range
// @param simple int tolerance: the number of tolerant klines
// @returns array: [left_src_value, left_src_bars, left_osc_value, left_osc_bars, right_src_value, right_src_bars, right_osc_value, right_osc_bars, div_cov]
export hidden_bull(series float src, series float osc, simple int lbL, simple int lbR, simple int rangeL, simple int rangeU, simple int tolerance) =>
slv = ta.pivotlow(src, lbL, lbR)
olv = ta.pivotlow(osc, lbL, lbR)
slvf = na(slv) ? false : true
olvf = na(olv) ? false : true
slvb = ta.barssince(slvf)
slvr = slvb <= tolerance ? slv[slvb] : na
olvb = ta.barssince(olvf)
olvr = olvb <= tolerance ? olv[olvb] : na
cmb1 = slvb <= tolerance and olvf
cmb2 = olvb <= tolerance and slvf
cmb = cmb1 or cmb2
res = array.new_float(9, na)
if not cmb or na(slvr) or na(slvb) or na(olvr) or na(olvb)
res
for r = math.max(rangeL, lbL, slvb, olvb) to math.max(rangeU, lbL, slvb, olvb)
if cmb[r] and ((slvr[r] < slvr and olv[r] > olv) or (slv[r] < slv and olvr[r] > olvr))
array.set(res, 0, slvr[r])
array.set(res, 1, slvb[r] + r)
array.set(res, 2, olvr[r])
array.set(res, 3, olvb[r] + r)
array.set(res, 4, slvr)
array.set(res, 5, slvb)
array.set(res, 6, olvr)
array.set(res, 7, olvb)
array.set(res, 8, ((slvr/slvr[r] - 1) * 10000 / (slvb[r]+r-slvb)) * ((olvr - olvr[r]) / (olvb[r]+r-olvb)))
break
if osc[r] < olvr
break
res
// @function regular_bear: regular bear divergence, higher high src but lower high osc
// @param series float src: the source series
// @param series float osc: the oscillator index
// @param simple int lbL: look back left
// @param simple int lbR: look back right
// @param simple int rangeL: min look back range
// @param simple int rangeU: max look back range
// @param simple int tolerance: the number of tolerant klines
// @returns array: [left_src_value, left_src_bars, left_osc_value, left_osc_bars, right_src_value, right_src_bars, right_osc_value, right_osc_bars, div_cov]
export regular_bear(series float src, series float osc, simple int lbL, simple int lbR, simple int rangeL, simple int rangeU, simple int tolerance) =>
shv = ta.pivothigh(src, lbL, lbR)
ohv = ta.pivothigh(osc, lbL, lbR)
shvf = na(shv) ? false : true
ohvf = na(ohv) ? false : true
shvb = ta.barssince(shvf)
shvr = shvb <= tolerance ? shv[shvb] : na
ohvb = ta.barssince(ohvf)
ohvr = ohvb <= tolerance ? ohv[ohvb] : na
cmb1 = shvb <= tolerance and ohvf
cmb2 = ohvb <= tolerance and shvf
cmb = cmb1 or cmb2
res = array.new_float(9, na)
if not cmb or na(shvr) or na(shvb) or na(ohvr) or na(ohvb)
res
for r = math.max(rangeL, lbL, shvb, ohvb) to math.max(rangeU, lbL, shvb, ohvb)
if cmb[r] and ((shvr[r] < shvr and ohv[r] > ohv) or (shv[r] < shv and ohvr[r] > ohvr))
array.set(res, 0, shvr[r])
array.set(res, 1, shvb[r] + r)
array.set(res, 2, ohvr[r])
array.set(res, 3, ohvb[r] + r)
array.set(res, 4, shvr)
array.set(res, 5, shvb)
array.set(res, 6, ohvr)
array.set(res, 7, ohvb)
array.set(res, 8, ((shvr/shvr[r] - 1) * 10000 / (shvb[r]+r-shvb)) * ((ohvr - ohvr[r]) / (ohvb[r]+r-ohvb)))
break
if src[r] > shvr
break
res
// @function hidden_bear: hidden bear divergence, lower high src but higher high osc
// @param series float src: the source series
// @param series float osc: the oscillator index
// @param simple int lbL: look back left
// @param simple int lbR: look back right
// @param simple int rangeL: min look back range
// @param simple int rangeU: max look back range
// @param simple int tolerance: the number of tolerant klines
// @returns array: [left_src_value, left_src_bars, left_osc_value, left_osc_bars, right_src_value, right_src_bars, right_osc_value, right_osc_bars, div_cov]
export hidden_bear(series float src, series float osc, simple int lbL, simple int lbR, simple int rangeL, simple int rangeU, simple int tolerance) =>
shv = ta.pivothigh(src, lbL, lbR)
ohv = ta.pivothigh(osc, lbL, lbR)
shvf = na(shv) ? false : true
ohvf = na(ohv) ? false : true
shvb = ta.barssince(shvf)
shvr = shvb <= tolerance ? shv[shvb] : na
ohvb = ta.barssince(ohvf)
ohvr = ohvb <= tolerance ? ohv[ohvb] : na
cmb1 = shvb <= tolerance and ohvf
cmb2 = ohvb <= tolerance and shvf
cmb = cmb1 or cmb2
res = array.new_float(9, na)
if not cmb or na(shvr) or na(shvb) or na(ohvr) or na(ohvb)
res
for r = math.max(rangeL, lbL, shvb, ohvb) to math.max(rangeU, lbL, shvb, ohvb)
if cmb[r] and ((shvr[r] > shvr and ohv[r] < ohv) or (shv[r] > shv and ohvr[r] < ohvr))
array.set(res, 0, shvr[r])
array.set(res, 1, shvb[r] + r)
array.set(res, 2, ohvr[r])
array.set(res, 3, ohvb[r] + r)
array.set(res, 4, shvr)
array.set(res, 5, shvb)
array.set(res, 6, ohvr)
array.set(res, 7, ohvb)
array.set(res, 8, ((shvr/shvr[r] - 1) * 10000 / (shvb[r]+r-shvb)) * ((ohvr - ohvr[r]) / (ohvb[r]+r-ohvb)))
break
if osc[r] > ohvr
break
res
|
OrdinaryLeastSquares | https://www.tradingview.com/script/9AZQdbbL-OrdinaryLeastSquares/ | lejmer | https://www.tradingview.com/u/lejmer/ | 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/
// © lejmer
//@version=5
// @description One of the most common ways to estimate the coefficients for a linear regression is to use the Ordinary Least Squares (OLS) method.
// This library implements OLS in pine. This implementation can be used to fit a linear regression of multiple independent variables onto one dependent variable,
// as long as the assumptions behind OLS hold.
library("OrdinaryLeastSquares")
// @function Solve a linear system of equations using the Ordinary Least Squares method.
// This function returns both the estimated OLS solution and a matrix that essentially measures the model stability (linear dependence between the columns of 'x').
// NOTE: The latter is an intermediate step when estimating the OLS solution but is useful when calculating the covariance matrix and is returned here to save computation time
// so that this step doesn't have to be calculated again when things like standard errors should be calculated.
// @param x The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
// @param y The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
// @returns Returns both the estimated OLS solution and a matrix that essentially measures the model stability (xtx_inv is equal to (X'X)^-1).
export solve_xtx_inv(matrix<float> x, matrix<float> y) =>
//{
if (matrix.columns(y) > 1)
runtime.error("OrdinaryLeastSquares.ols(): Y-matrix must contain only 1 column")
if (matrix.rows(x) != matrix.rows(y))
runtime.error("OrdinaryLeastSquares.ols(): Row count of X and Y does not match")
matrix<float> xt = matrix.transpose(x)
matrix<float> xtx = matrix.mult(xt, x)
matrix<float> xtx_inv = matrix.pinv(xtx)
matrix<float> beta_hat = matrix.mult(matrix.mult(xtx_inv, xt), y)
[beta_hat, xtx_inv]
//}
// @function Solve a linear system of equations using the Ordinary Least Squares method.
// @param x The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
// @param y The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
// @returns Returns the estimated OLS solution.
export solve(matrix<float> x, matrix<float> y) =>
//{
[beta_hat, xtx_inv] = solve_xtx_inv(x, y)
beta_hat
//}
// @function Solve a linear system of equations using the Ordinary Least Squares method.
// @param x The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
// @param y The array containing the dependent variable. The row count of 'x' and the size of 'y' must match.
// @returns Returns the estimated OLS solution.
export solve(matrix<float> x, array<float> y) =>
//{
if (matrix.rows(x) != array.size(y))
runtime.error("OrdinaryLeastSquares.ols(): Row count of X and size of Y does not match")
matrix<float> xt = matrix.transpose(x)
matrix<float> xtx = matrix.mult(xt, x)
matrix<float> xtx_inv = matrix.pinv(xtx)
matrix.mult(matrix.mult(xtx_inv, xt), y)
//}
// @function Calculate the standard errors.
// @param x The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
// @param y The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
// @param beta_hat The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
// @param xtx_inv This is (X'X)^-1, which means we take the transpose of the X matrix, multiply that the X matrix and then take the inverse of the result.
// This essentially measures the linear dependence between the columns of the X matrix.
// @returns The standard errors.
export standard_errors(matrix<float> x, matrix<float> y, matrix<float> beta_hat, matrix<float> xtx_inv) =>
//{
if (matrix.columns(y) > 1)
runtime.error("OrdinaryLeastSquares.standard_errors(): Y-matrix must contain only 1 column")
if (matrix.rows(x) != matrix.rows(y))
runtime.error("OrdinaryLeastSquares.standard_errors(): Row count of X and Y does not match")
matrix<float> residuals = matrix.diff(y, matrix.mult(x, beta_hat))
matrix<float> dev_score_sum_of_squares = matrix.mult(matrix.transpose(residuals), residuals)
float df = math.max(1, matrix.rows(x) - matrix.columns(x))
float sigma2 = matrix.get(matrix.mult(dev_score_sum_of_squares, 1 / df), 0, 0)
matrix<float> covar = matrix.mult(xtx_inv, sigma2)
int size = matrix.rows(covar)
array<float> errors = array.new<float>(size)
for i = 0 to size - 1
array.set(errors, i, math.pow(matrix.get(covar, i, i), 0.5))
errors
//}
// @function Estimate the next step of a linear model.
// @param x The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
// @param beta_hat The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
// @returns Returns the new estimate of Y based on the linear model.
export estimate(matrix<float> x, matrix<float> beta_hat) =>
//{
float y_hat = 0
for column = 0 to matrix.columns(x) - 1
y_hat += matrix.get(beta_hat, column, 0) * matrix.get(x, 0, column)
//}
// ----------------------------------------------------------------------------------------------------------------------------
// Test code for the library. This basically reproduces the result from ta.linreg() with the offset parameter set to 0.
// Essentially it takes and a constant (a series of 1's) as one independent variable and the bar index (counting from 1) as
// another independent variable and takes the close price as the dependent variable and produces of estimate of the close
// price. This is not very useful but works as a demo of how the OLS method can be used to calculate a linear regression
// in a way that can be tested against something that already exists, to verify that the calculations work as expected.
// ----------------------------------------------------------------------------------------------------------------------------
var int n = input.int(50, "Lookback Window [1 to 4999]", minval = 1, maxval = 4999)
var matrix<float> x = matrix.new<float>(n, 2, 0)
var matrix<float> y = matrix.new<float>(n, 1, 0)
if (barstate.isfirst)
//{
for row = 0 to matrix.rows(x) - 1
//{
matrix.set(x, row, 0, 1) // X1: Constant
matrix.set(x, row, 1, row + 1) // X2: Time rank
//}
//}
for row = 0 to matrix.rows(y) - 1
matrix.set(y, row, 0, close[row]) // Y: Close price
[beta_hat, xtx_inv] = solve_xtx_inv(x, y) // Solve using solve_xtx_inv() in order to get access to the xtx_inv matrix
float y_hat = estimate(x, beta_hat)
float[] se = standard_errors(x, y, beta_hat, xtx_inv) // Here the xtx_inv matrix is used
color se_color = color.new(color.blue, transp = 80)
u_se = plot(y_hat + array.get(se, 0), "SE (Upper)", color = se_color)
l_se = plot(y_hat - array.get(se, 0), "SE (Lower)", color = se_color)
fill(u_se, l_se, title = "SE Fill Color", color = se_color)
plot(y_hat, color = color.white, linewidth = 2)
|
NormalizedOscillators | https://www.tradingview.com/script/KEJafm1l-NormalizedOscillators/ | lastguru | https://www.tradingview.com/u/lastguru/ | 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/
// © lastguru
//@version=5
// @description Collection of some common Oscillators. All are zero-mean and normalized to fit in the -1..1 range. Some are modified, so that the internal smoothing function could be configurable (for example, to enable Hann Windowing, that John F. Ehlers uses frequently). Some are modified for other reasons (see comments in the code), but never without a reason. This collection is neither encyclopaedic, nor reference, however I try to find the most correct implementation. Suggestions are welcome.
library("NormalizedOscillators", true)
import lastguru/CommonFilters/1 as cf
import nolantait/HurstExponent/1 as he
// ----------
// Common functions
// ----------
// @function RSI - second step
// @param upper Upwards momentum
// @param lower Downwards momentum
// @returns Oscillator value
// Modified by Ehlers from Wilder's implementation to have a zero mean (oscillator from -1 to +1)
// Originally: 100.0 - (100.0 / (1.0 + upper / lower))
// Ignoring the 100 scale factor, we get: upper / (upper + lower)
// Multiplying by two and subtracting 1, we get: (2 * upper) / (upper + lower) - 1 = (upper - lower) / (upper + lower)
export rsi2(float upper, float lower) =>
rsi = 0.0
if (upper + lower) != 0
rsi := (upper - lower) / (upper + lower)
// ----------
// Internal smoothing algorithm selection
_smooth(type, src, len, default) =>
cf.doMA(type == "Default" or type == "Fast Default" ? default : type, src, type == "Fast Default" ? math.round(len/2) : len)
// @function Root mean square (RMS)
// @param src Source series
// @param len Lookback period
// Based on by John F. Ehlers implementation
export rms(float src, int len) =>
rms = math.sum(math.pow(src, 2), len)
rms := math.sqrt(nz(rms / len))
// ----------
// Oscillator postfilters
// ----------
// @function Inverse Fisher Transform
// @param src Source series
// @returns Normalized series
// Based on by John F. Ehlers implementation
// The input values have been multiplied by 2 (was "2*src", now "4*src") to force expansion - not compression
// The inputs may be further modified, if needed
export ift(float src) =>
(math.exp(4*src)-1) / (math.exp(4*src)+1)
// @function Stochastic
// @param src Source series
// @param len Lookback period
// @returns Oscillator series
export stoch(float src, int len) =>
src1 = src + 1
max = ta.highest(src1, len)
min = ta.lowest(src1, len)
stoch = max != min ? (2 * src1 - max - min) / (max - min) : 0
// @function Super Smooth Stochastic (part of MESA Stochastic) by John F. Ehlers
// @param src Source series
// @param len Lookback period
// @returns Oscillator series
// Introduced in the January 2014 issue of Stocks and Commodities
// This is not an implementation of MESA Stochastic, as it is based on Highpass filter not present in the function (but you can construct it)
// This implementation is scaled by 0.95, so that Super Smoother does not exceed 1/-1
// I do not know, if this the right way to fix this issue, but it works for now
export ssstoch(float src, int len) =>
src1 = src + 1
max = ta.highest(src1, len)
min = ta.lowest(src1, len)
stoch = max != min ? 0.95 * (2 * src1 - max - min) / (max - min) : 0
cf.supers2(stoch, len)
// @function Noise Elimination Technology by John F. Ehlers
// @param src Source series
// @param len Lookback period
// @returns Oscillator series
// Introduced in the December 2020 issue of Stocks and Commodities
// Uses simplified Kendall correlation algorithm
// Implementation by @QuantTherapy: https://www.tradingview.com/script/4wdh1Y1s-NET-MyRSI/
export netKendall(float src, int len) =>
denom = len * (len - 1) / 2
num = 0.0
for i = 1 to len - 1
for k = 0 to i - 1
num := num - math.sign(src[i] - src[k])
num/denom
// @function Momentum
// @param src Source series
// @param len Lookback period
// @returns Oscillator series
// Derivative of the oscillator series with IFT normalization to force the -1..1 range
export momentum(float src, int len) =>
mom = src - src[len]
ift(mom)
// ----------
// Oscillators
// ----------
// @function RSI
// @param src Source series
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
export rsi(float src, int len, string smooth) =>
default = "RMA"
rsiUp = _smooth(smooth, math.max(ta.change(src), 0), len, default)
rsiDown = _smooth(smooth, -math.min(ta.change(src), 0), len, default)
rsi2(rsiUp, rsiDown)
// @function Volume-scaled RSI
// @param src Source series
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
// This is my own version of RSI. It scales price movements by the proportion of RMS of volume
export vrsi(float src, int len, string smooth) =>
default = "RMA"
rsiUp = _smooth(smooth, math.max(ta.change(src), 0) * volume / rms(volume, len), len, default)
rsiDown = _smooth(smooth, -math.min(ta.change(src), 0) * volume / rms(volume, len), len, default)
rsi2(rsiUp, rsiDown)
// @function Momentum RSI
// @param src Source series
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
// Inspired by RocketRSI by John F. Ehlers (Stocks and Commodities, May 2018)
export mrsi(float src, int len, string smooth) =>
default = "RMA"
mom = src - src[len-1]
rsiUp = _smooth(smooth, math.max(ta.change(mom), 0), len, default)
rsiDown = _smooth(smooth, -math.min(ta.change(mom), 0), len, default)
rsi2(rsiUp, rsiDown)
// @function Rocket RSI
// @param src Source series
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
// Inspired by RocketRSI by John F. Ehlers (Stocks and Commodities, May 2018)
// Does not include Fisher Transform of the original implementation, as the output must be normalized
// Does not include momentum smoothing length configuration, so always assumes half the lookback length
export rrsi(float src, int len, string smooth) =>
default = "SMA"
mom = src - src[len-1]
filt = cf.supers2(mom, len/2)
rsiUp = _smooth(smooth, math.max(ta.change(filt), 0), len, default)
rsiDown = _smooth(smooth, -math.min(ta.change(filt), 0), len, default)
rsi2(rsiUp, rsiDown)
// @function Money Flow Index
// @param src Source series
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
export mfi(float src, int len, string smooth) =>
default = "SMA"
mfiUp = _smooth(smooth, (ta.change(src) <= 0 ? 0 : src) * volume, len, default)
mfiDown = _smooth(smooth, (ta.change(src) >= 0 ? 0 : src) * volume, len, default)
rsi2(mfiUp, mfiDown)
// @function Laguerre RSI by John F. Ehlers
// @param src Source series
// @param in_gamma Damping factor (default is -1 to generate from len)
// @param len Lookback period (alternatively, if gamma is not set)
// @returns Oscillator series
// The original implementation is with gamma. As it is impossible to collect gamma in my system, where the only user input is length,
// an alternative calculation is included, where gamma is set by dividing len by 30. Maybe different calculation would be better?
export lrsi (float src, float in_gamma = -1, int len = 0) =>
gamma = in_gamma == -1 ? len / 30 : in_gamma
lrsi = 0.0
L0 = 0.0
L1 = 0.0
L2 = 0.0
L3 = 0.0
L0 := (1 - gamma) * src + gamma * nz(L0[1])
L1 := -gamma * L0 + nz(L0[1]) + gamma * nz(L1[1])
L2 := -gamma * L1 + nz(L1[1]) + gamma * nz(L2[1])
L3 := -gamma * L2 + nz(L2[2]) + gamma * nz(L3[1])
cu = 0.0
cd = 0.0
if (L0 >= L1)
cu := L0 - L1
else
cd := L1 - L0
if (L1 >= L2)
cu := cu + L1 - L2
else
cd := cd + L2 - L1
if (L2 >= L3)
cu := cu + L2 - L3
else
cd := cd + L3 - L2
lrsi := rsi2(cu, cd)
// @function Choppiness Index or Fractal Energy
// @param len Lookback period
// @returns Oscillator series
// The Choppiness Index (CHOP) was created by E. W. Dreiss
// This indicator is sometimes called Fractal Energy
export fe (int len) =>
sumtr = math.sum(ta.tr, len)
fe = math.log(sumtr / (ta.highest(len) - ta.lowest(len))) / math.log(len)
2 * fe - 1
// @function Efficiency ratio
// @param src Source series
// @param len Lookback period
// @returns Oscillator series
// Based on Kaufman Adaptive Moving Average calculation
// This is the correct Efficiency ratio calculation, and most other implementations are wrong:
// the number of bar differences is 1 less than the length, otherwise we are adding the change outside of the measured range!
// For reference, see Stocks and Commodities June 1995
export er(float src, int len) =>
signal = src - src[len]
diff = math.abs(src - src[1])
noise = math.sum(diff, len-1)
er = noise != 0 ? signal / noise : 0
// @function Directional Movement Index
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
// Based on the original Tradingview algorithm
// Modified with inspiration from John F. Ehlers DMH (but not implementing the DMH algorithm!)
// Only ADX is returned
// Rescaled to fit -1 to +1
// Unlike most oscillators, there is no src parameter as DMI works directly with high and low values
export dmi (int len, string smooth) =>
default = "RMA"
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
plus = fixnan(100 * cf.rma(plusDM, len))
minus = fixnan(100 * cf.rma(minusDM, len))
sum = plus + minus
adx = _smooth(smooth, math.abs(plus - minus) / (sum == 0 ? 1 : sum), len, default)
2 * adx - 1
// @function Fast Directional Movement Index
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
// Same as DMI, but without secondary smoothing. Can be smoothed later. Instead, +DM and -DM smoothing can be configured
export fdmi (int len, string smooth) =>
default = "RMA"
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
plus = fixnan(100 * _smooth(smooth, plusDM, len, default))
minus = fixnan(100 * _smooth(smooth, minusDM, len, default))
sum = plus + minus
adx = math.abs(plus - minus) / (sum == 0 ? 1 : sum)
2 * adx - 1
// @function Average Vortex Index (AVX)
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
// Based on the Vortex Indicator. I then apply ADX calculation on the VI+ and VI- lines.
// Only AVX is returned
// Rescaled to fit -1 to +1
// Unlike most oscillators, there is no src parameter as AVX works directly with high and low values
export avx(int len, string smooth) =>
default = "RMA"
plusVM = math.sum(math.abs( high - low[1]), len)
minusVM = math.sum(math.abs( low - high[1]), len)
str = math.sum(ta.tr, len)
plus = plusVM / str
minus = minusVM / str
sum = plus + minus
adx = _smooth(smooth, math.abs(plus - minus) / (sum == 0 ? 1 : sum), len, default)
4 * adx - 1
// @function Hurst Exponent
// @param src Source series
// @param len Lookback period
// @returns Oscillator series
// Until I can write my own, I use the @nolantait library: https://www.tradingview.com/script/LsW08uRb-HurstExponent/
// Which in turn is based on the excellent @balipour implementation: https://www.tradingview.com/script/vTloluai-Hurst-Exponent-Detrended-Fluctuation-Analysis-pig/
// As with all other indicators, this is also rescaled to fit -1 to +1
export hurst(float src, int len) =>
out = he.exponent(src, len)
2 * out - 1
// @function Simple Fractal Dimension
// @param len Reference lookback length
// @returns Oscillator series
// Based on FRAMA by John F. Ehlers
// This function implements just the first part of FRAMA: calculating Fractal Dimension
// It is then transformed to Hurst Exponent (HE = 2 - FD) and normalized to fit -1 to +1
export fd(int len) =>
float result = 0
int hlen = math.floor(len / 2)
h1 = ta.highest(high, hlen)
l1 = ta.lowest(low, hlen)
n1 = (h1 - l1) / hlen
h2 = h1[hlen]
l2 = l1[hlen]
n2 = (h2 - l2) / hlen
h3 = ta.highest(high, 2 * hlen)
l3 = ta.lowest(low, 2 * hlen)
n3 = (h3 - l3) / (2 * hlen)
dimen1 = (math.log(n1 + n2) - math.log(n3)) / math.log(2)
dimen = (n1 > 0 and n2 > 0 and n3 > 0) ? dimen1 : nz(dimen1[1])
ift(2 * (2 - dimen) - 1)
// @function Finite Volume Element (FVE)
// @param len Lookback period
// @returns Oscillator series
// Based on FVE with Volatility adjustment by Markos Katsanos (Stocks and Commodities, September 2003)
export fve(int len) =>
cintra = 0.1
cinter = 0.1
tp = hlc3
intra = math.log(high) - math.log(low)
vintra = ta.stdev(intra, len)
inter = math.log(tp) - math.log(tp[1])
vinter = ta.stdev(inter, len)
cutoff = cintra * vintra + cinter * vinter
mf = close - hl2 + tp - tp[1]
fveFactor = mf > cutoff * close ? 1 : (mf < cutoff * close ? -1 : 0)
volumePM = volume * fveFactor
fveSum = ta.sma(volumePM, len)
fveMA = ta.sma(volume, len)
fve = fveSum / fveMA
// @function Volume Flow Indicator (VFI)
// @param len Lookback period
// @returns Oscillator series
// Based on VFI by Markos Katsanos (Stocks and Commodities, June 2004)
// https://mkatsanos.com/volume-flow-vfi-indicator/
// As with all other indicators, this is also rescaled to fit -1 to +1
export vfi (int len) =>
// Cutoff Coefficient
coef = 0.2
// Volume Volatility Coefficient
vcoef = 2.5
inter = math.log(hlc3) - math.log(hlc3[1])
vinter = ta.stdev(inter, 30)
cutoff = coef * vinter * close
vave = ta.sma(volume[1], len)
vc = math.min(volume, vave * vcoef)
mf = hlc3 - hlc3[1]
vcp = mf > cutoff ? vc : mf < -cutoff ? -vc : 0
vfi = math.sum(vcp, len) / vave
ift(vfi / 20)
// @function Relative Vigor Index by John F. Ehlers
// @param len Lookback period
// @returns Oscillator series
// Introduced in the January 2002 issue of Stocks and Commodities
// Similar to A/D Oscillator
export rvi(int len) =>
co = close - open
hl = high - low
num = cf.fir23(co)
denom = cf.fir23(hl)
snum = cf.sma(num, len)
sdenom = cf.sma(denom, len)
rvi = snum / sdenom
// ----------
// Oscillator wrappers
// ----------
// @function Execute a particular Oscillator from the list
// @param type Oscillator type to use
// @param src Source series
// @param len Lookback period
// @param smooth Internal smoothing algorithm
// @returns Oscillator series
// Chande Momentum Oscillator (CMO) is RSI without smoothing. No idea, why some authors use different calculations
// LRSI with Fractal Energy is a combo oscillator that uses Fractal Energy to tune LRSI gamma, as seen here: https://www.prorealcode.com/prorealtime-indicators/rsi-laguerre-adjusting-gamma-fractals-energy/
export doOsc(string type, float src, int len, string smooth) =>
out = 0.0
switch type
"None" =>
out := src
"Stochastic" =>
out := stoch(src, len)
"Super Smooth Stochastic" =>
out := ssstoch(src, len)
"CMO" =>
out := rsi(src, len, "SMA")
"RSI" =>
out := rsi(src, len, smooth)
"Volume-scaled RSI" =>
out := vrsi(src, len, smooth)
"Momentum RSI" =>
out := mrsi(src, len, smooth)
"Rocket RSI" =>
out := vrsi(src, len, smooth)
"MFI" =>
out := mfi(src, len, smooth)
"LRSI" =>
out := lrsi(src, -1, len)
"LRSI with Fractal Energy" =>
fe = (fe(len) + 1) / 2
out := lrsi(src, fe, 0)
"Fractal Energy" =>
out := fe(len)
"Efficiency Ratio" =>
out := er(src, len)
"DMI" =>
out := dmi(len, smooth)
"Fast DMI" =>
out := fdmi(len, smooth)
"AVX" =>
out := avx(len, smooth)
"Hurst Exponent" =>
out := hurst(src, len)
"Fractal Dimension" =>
out := fd(len)
"FVE" =>
out := fve(len)
"VFI" =>
out := vfi(len)
"RVI" =>
out := rvi(len)
out
// @function Execute a particular Oscillator Postfilter from the list
// @param type Oscillator type to use
// @param src Source series
// @param len Lookback period
// @returns Oscillator series
export doPostfilter(string type, float src, int len) =>
out = 0.0
switch type
"None" =>
out := src
"Stochastic" =>
out := stoch(src, len)
"Super Smooth Stochastic" =>
out := ssstoch(src, len)
"Inverse Fisher Transform" =>
out := ift(src)
"Noise Elimination Technology" =>
out := netKendall(src, len)
"Momentum" =>
out := momentum(src, len)
out
|
LengthAdaptation | https://www.tradingview.com/script/uS94dhvg-LengthAdaptation/ | lastguru | https://www.tradingview.com/u/lastguru/ | 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/
// © lastguru
//@version=5
// @description Collection of dynamic length adaptation algorithms. Mostly from various Adaptive Moving Averages (they are usually just EMA otherwise). Now you can combine Adaptations with any other Moving Averages or Oscillators (see my other libraries), to get something like Deviation Scaled RSI or Fractal Adaptive VWMA. This collection is not encyclopaedic. Suggestions are welcome.
library("LengthAdaptation", true)
import lastguru/CommonFilters/1 as cf
import lastguru/NormalizedOscillators/9 as co
// ----------
// Length Adaptations
// ----------
// @function Chande's Dynamic Length
// @param src Series to use
// @param len Reference lookback length
// @param sdlen Lookback length of Standard deviation
// @param smooth Smoothing length of Standard deviation
// @param power Exponent of the length adaptation (lower is smaller variation)
// @returns Calculated period
// Taken from Chande's Dynamic Momentum Index (CDMI or DYMOI), which is dynamic RSI with this length
// Original default power value is 1, but I use 0.5
// A variant of this algorithm is also included, where volume is used instead of price
export chande(float src, int len, int sdlen = 5, int smooth = 10, float power = 0.5) =>
chandeSd = ta.stdev(src, sdlen)
chandeV = chandeSd / cf.sma(chandeSd, smooth)
chandeT = len / math.pow(chandeV, power)
chandeT
// @function Variable Index Dynamic Average Indicator (VIDYA)
// @param src Series to use
// @param len Reference lookback length
// @param dynLow Lower bound for the dynamic length
// @returns Calculated period
// Standard VIDYA algorithm. The period oscillates from the Lower Bound up (slow)
// I took the adaptation part, as it is just an EMA otherwise
export vidya(float src, int len, int dynLow) =>
rsiUp = cf.sma(math.max(ta.change(src), 0), len)
rsiDown = cf.sma(-math.min(ta.change(src), 0), len)
cmo = co.rsi2(rsiUp, rsiDown)
alpha = (2 / (dynLow + 1)) * math.abs(cmo)
nl = alpha != 0 ? (2 / alpha) - 1 : 0
nl
// @function Relative Strength Dynamic Length - VIDYA RS
// @param src Series to use
// @param len Reference lookback length
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @returns Calculated period
// Based on Vitali Apirine's modification (Stocks and Commodities, January 2022) of VIDYA algorithm. The period oscillates from the Upper Bound down (fast)
// I took the adaptation part, as it is just an EMA otherwise
// There was originally a multiplier for variation variable (RSI). It is replaced by lower bound, which is recalculated into the multiplier
export vidyaRS(float src, int len, int dynLow, int dynHigh) =>
rsiUp = cf.ema(math.max(ta.change(src), 0), len)
rsiDown = cf.ema(-math.min(ta.change(src), 0), len)
rsi = co.rsi2(rsiUp, rsiDown)
mult = ((dynHigh + 1) / (dynLow + 1)) - 1
alpha = (2 / (dynHigh + 1)) * (1 + mult * math.abs(rsi))
nl = alpha != 0 ? (2 / alpha) - 1 : 0
nl
// @function Kaufman Efficiency Scaling
// @param src Series to use
// @param len Reference lookback length
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @returns Calculated period
// Based on Efficiency Ratio calculation orifinally used in Kaufman Adaptive Moving Average developed by Perry J. Kaufman
// I took the adaptation part, as it is just an EMA otherwise
export kaufman(float src, int len, int dynLow, int dynHigh) =>
er = math.abs(co.er(src, len))
fa = 2 / (dynLow + 1)
sa = 2 / (dynHigh + 1)
ka = math.pow((fa - sa) * er + sa, 2)
nl = ka != 0 ? (2 / ka) - 1 : 0
nl
// @function Deviation Scaling
// @param src Series to use
// @param len Reference lookback length
// @returns Calculated period
// Based on Derivation Scaled Super Smoother (DSSS) by John F. Ehlers
// Originally used with Super Smoother
// RMS originally has 50 bar lookback. Changed to 4x length for better flexibility. Could be wrong.
export ds(float src, int len) =>
mom = src - src[len]
hlen = math.round(len/math.sqrt(2))
filt = cf.hannFIR(mom, hlen)
rms = co.rms(filt, len * 4)
scfilt = rms != 0 ? filt/rms : 0
nl = len / math.abs(scfilt)
nl
// @function Median Average Adaptation
// @param src Series to use
// @param len Reference lookback length
// @param threshold Adjustment threshold (lower is smaller length, default: 0.002, min: 0.0001)
// @returns Calculated period
// Based on Median Average Adaptive Filter by John F. Ehlers
// Discovered and implemented by @cheatcountry: https://www.tradingview.com/script/pq6FWb3Y-Ehlers-Median-Average-Adaptive-Filter-CC/
// I took the adaptation part, as it is just an EMA otherwise
export maa(float src, int len, float threshold = 0.002) =>
v3 = 0.2
v2 = 0.0
alpha = 0.0
length = len
while (v3 > threshold and length > 0)
alpha := 2.0 / (length + 1)
v1 = ta.median(src, length)
v2 := (alpha * src) + ((1 - alpha) * nz(v2[1]))
v3 := v1 != 0 ? math.abs(v1 - v2) / v1 : v3
length -= 2
nl = length < 3 ? 3 : length
nl
// @function Fractal Adaptation
// @param len Reference lookback length
// @param fc Fast constant (default: 1)
// @param sc Slow constant (default: 200)
// @returns Calculated period
// Based on FRAMA by John F. Ehlers
// Modified to allow lower and upper bounds by an unknown author
// I took the adaptation part, as it is just an EMA otherwise
export fra(int len, int fc, int sc) =>
float result = 0
int len1 = math.floor(len/2)
w = math.log(2/(sc+1)) / math.log(math.e) // Natural logarithm (ln(2/(SC+1)))
h1 = ta.highest(high,len1)
l1 = ta.lowest(low,len1)
n1 = (h1-l1)/len1
h2 = h1[len1]
l2 = l1[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
nl = (((sc-fc)*(oldN-1))/(sc-1))+fc
nl
// @function MESA Adaptation - MAMA Alpha
// @param src Series to use
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @returns Calculated period
// Based on MESA Adaptive Moving Average by John F. Ehlers
// Introduced in the September 2001 issue of Stocks and Commodities
// Inspired by the @everget implementation: https://www.tradingview.com/script/aaWzn9bK-Ehlers-MESA-Adaptive-Moving-Averages-MAMA-FAMA/
// I took the adaptation part, as it is just an EMA otherwise
export mama(float src, int dynLow, int dynHigh) =>
period = 0.0
C1 = 0.0962
C2 = 0.5769
C3 = 0.075 * nz(period[1]) + 0.54
smooth = (4 * src + 3 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 10
detrend = C3 * (C1 * smooth + C2 * nz(smooth[2]) - C2 * nz(smooth[4]) - C1 * nz(smooth[6]))
// Compute InPhase and Quadrature components
Q1 = C3 * (C1 * detrend + C2 * nz(detrend[2]) - C2 * nz(detrend[4]) - C1 * nz(detrend[6]))
I1 = nz(detrend[3])
// Advance Phase of I1 and Q1 by 90 degrees
jI = C3 * (C1 * I1 + C2 * nz(I1[2]) - C2 * nz(I1[4]) - C1 * nz(I1[6]))
jQ = C3 * (C1 * Q1 + C2 * nz(Q1[2]) - C2 * nz(Q1[4]) - C1 * nz(Q1[6]))
// Phasor addition for 3 bar averaging
I2 = I1 - jQ
Q2 = Q1 + jI
// Smooth I and Q components before applying discriminator
I2 := 0.2*I2 + 0.8*nz(I2[1])
Q2 := 0.2*Q2 + 0.8*nz(Q2[1])
// Extract Homodyne Discriminator
Re = I2*nz(I2[1]) + Q2*nz(Q2[1])
Im = I2*nz(Q2[1]) - Q2*nz(I2[1])
Re := 0.2*Re + 0.8*nz(Re[1])
Im := 0.2*Im + 0.8*nz(Im[1])
period := (Re != 0 and Im != 0) ? 2 * math.pi / math.atan(Im/Re) : 0
period := math.min(period, 1.5 * nz(period[1], period))
period := math.max(period, (2/3) * nz(period[1], period))
period := math.min(math.max(period, dynLow), dynHigh)
period := period*0.2 + nz(period[1])*0.8
phase = I1 != 0 ? (180/math.pi) * math.atan(Q1 / I1) : 0
deltaPhase = phase[1] - phase
deltaPhase := math.max(deltaPhase, 1)
fa = 2 / (dynLow + 1)
sa = 2 / (dynHigh + 1)
alpha = math.max(fa / deltaPhase, sa)
nl = (2 / alpha) - 1
nl
// ----------
// Wrappers
// ----------
// @function Execute a particular Length Adaptation from the list
// @param type Length Adaptation type to use
// @param src Series to use
// @param len Reference lookback length
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @param chandeSDLen Lookback length of Standard deviation for Chande's Dynamic Length
// @param chandeSmooth Smoothing length of Standard deviation for Chande's Dynamic Length
// @param chandePower Exponent of the length adaptation for Chande's Dynamic Length (lower is smaller variation)
// @returns Calculated period (float, not limited)
export doAdapt(string type, float src, int len, int dynLow, int dynHigh, int chandeSDLen = 5, int chandeSmooth = 10, float chandePower = 0.5) =>
out = 0.0
switch type
"None" =>
out := len
"Chande (Price)" =>
out := chande(src, len, chandeSDLen, chandeSmooth, chandePower)
"Chande (Volume)" =>
out := chande(volume, len, chandeSDLen, chandeSmooth, chandePower)
"VIDYA" =>
out := vidya(src, len, dynLow)
"VIDYA-RS" =>
out := vidyaRS(src, len, dynLow, dynHigh)
"Kaufman Efficiency Scaling" =>
out := kaufman(src, len, dynLow, dynHigh)
"Deviation Scaling" =>
out := ds(src, len)
"Median Average" =>
out := maa(src, dynHigh)
"Fractal Adaptation" =>
out := fra(len, dynLow, dynHigh)
"MESA MAMA Alpha" =>
out := mama(src, dynLow, dynHigh)
out
// @function MA wrapper on wrapper: if DSSS is selected, calculate it here
// @param type MA type to use
// @param src Series to use
// @param len Filtering length
// @returns Filtered series
// Demonstration of a combined indicator: Deviation Scaled Super Smoother, Relative Strength Super Smoother
export doMA(string type, float src, int len) =>
out = 0.0
switch type
"DSSS" =>
out := cf.supers2(src, math.round(ds(src, len)))
"RSSS" =>
dynLow = math.round((len + 1) / (10 + 1)) - 1
nl = math.round(vidyaRS(src, len, dynLow, len))
out := cf.supers2(src, nl)
=>
out := cf.doMA(type, src, len)
out
|
simple_squares_regression | https://www.tradingview.com/script/acgD1CJb/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 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/
// © dandrideng
//@version=5
// @description simple_squares_regression: simple squares regression algorithm to find the horizontal price region
library("simple_squares_regression", overlay=true)
// @function basic_ssr: Basic simple squares regression algorithm
// @param series float src: the regression source such as close
// @param series int region_forward: number of candle lines at the right end of the regression region from the current candle line
// @param series int region_len: the length of regression region
// @returns left_loc, right_loc, reg_val, reg_std, reg_max_offset
export basic_ssr(series float src, series int region_forward, series int region_len) =>
p = array.new_float(region_len, 0)
//init array
for i = 0 to region_len - 1
array.set(p, i, src[region_len - 1 + region_forward - i])
//get average and standard devition value
u = array.avg(p)
s = array.stdev(p)
//get regression left location, left value, right location, right value
x1 = region_len - 1 + region_forward
x2 = 0
[x1, x2, u, s]
// @function search_ssr: simple squares regression region search algorithm
// @param series float src: the regression source such as close
// @param series int max_forward: max number of candle lines at the right end of the regression region from the current candle line
// @param series int region_lower: the lower length of regression region
// @param series int region_upper: the upper length of regression region
// @returns left_loc, right_loc, reg_val, reg_level, reg_std_err, reg_max_offset
export search_ssr(series float src, series int max_forward, series int region_lower, series int region_upper) =>
int x1 = 0
int x2 = 0
float u = 0
float s = 1e10
for f = 0 to max_forward
for i = region_lower to region_upper
[_x1, _x2, _u, _s] = basic_ssr(src, f, i)
if s > _s
x1 := _x1
x2 := _x2
u := _u
s := _s
[x1, x2, u, s]
|
on_balance_volume | https://www.tradingview.com/script/AyCkZwOx/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 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/
// © dandrideng
//@version=5
// @description on_balance_volume: custom on balance volume
library("on_balance_volume", overlay=false)
import dandrideng/moving_average/1 as ma
// @function obv_diff: custom on balance volume diff version
// @param string type: the moving average type of on balance volume
// @param simple int len: the moving average length of on balance volume
// @returns obv_diff: custom on balance volume diff value
export obv_diff(string type, simple int len) =>
//TODO : add function body and return value here
float obv = ta.cum(math.sign(ta.change(close)) * volume)
float obv_ma = ma.variant(type, obv, len)
float obv_diff = obv - obv_ma
obv_diff
// @function obv_diff_norm: custom normalized on balance volume diff version
// @param string type: the moving average type of on balance volume
// @param simple int len: the moving average length of on balance volume
// @returns obv_diff: custom normalized on balance volume diff value
export obv_diff_norm(string type, simple int len) =>
//TODO : add function body and return value here
float obv_diff = obv_diff(type, len)
float obv_diff_dev = ta.dev(obv_diff, len)
float obv_diff_norm = obv_diff / obv_diff_dev
obv_diff_norm
// plot(obv_diff("EMA", 30))
plot(obv_diff_norm("EMA", 30)) |
DominantCycle | https://www.tradingview.com/script/cY7DdxyZ-DominantCycle/ | lastguru | https://www.tradingview.com/u/lastguru/ | 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/
// © lastguru
//@version=5
// @description Collection of Dominant Cycle estimators. Length adaptation used in the Adaptive Moving Averages and the Adaptive Oscillators try to follow price movements and accelerate/decelerate accordingly (usually quite rapidly with a huge range). Cycle estimators, on the other hand, try to measure the cycle period of the current market, which does not reflect price movement or the rate of change (the rate of change may also differ depending on the cycle phase, but the cycle period itself usually changes slowly). This collection may become encyclopaedic, so if you have any working cycle estimator, drop me a line in the comments below. Suggestions are welcome. Currently included estimators are based on the work of John F. Ehlers
library("DominantCycle", true)
import lastguru/CommonFilters/1 as cf
import lastguru/NormalizedOscillators/1 as co
import lastguru/LengthAdaptation/3 as la
// ----------
// Dominant Cycle Estimators
// ----------
// @function MESA Adaptation - MAMA Cycle
// @param src Series to use
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @returns Calculated period
// Based on MESA Adaptive Moving Average by John F. Ehlers
// Performs Hilbert Transform Homodyne Discriminator cycle measurement
// Unlike MAMA Alpha function (in LengthAdaptation library), this does not compute phase rate of change
// Introduced in the September 2001 issue of Stocks and Commodities
// Inspired by the @everget implementation: https://www.tradingview.com/script/aaWzn9bK-Ehlers-MESA-Adaptive-Moving-Averages-MAMA-FAMA/
// Inspired by the @anoojpatel implementation: https://www.tradingview.com/script/uUHctAeu-Missile-RSI-RSI-of-momentum-w-Dominant-Cycle-length-Fisher/
export mamaPeriod(float src, int dynLow, int dynHigh) =>
period = 0.0
C1 = 0.0962
C2 = 0.5769
C3 = 0.075 * nz(period[1]) + 0.54
smooth = (4 * src + 3 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 10
detrend = C3 * (C1 * smooth + C2 * nz(smooth[2]) - C2 * nz(smooth[4]) - C1 * nz(smooth[6]))
// Compute InPhase and Quadrature components
Q1 = C3 * (C1 * detrend + C2 * nz(detrend[2]) - C2 * nz(detrend[4]) - C1 * nz(detrend[6]))
I1 = nz(detrend[3])
// Advance Phase of I1 and Q1 by 90 degrees
jI = C3 * (C1 * I1 + C2 * nz(I1[2]) - C2 * nz(I1[4]) - C1 * nz(I1[6]))
jQ = C3 * (C1 * Q1 + C2 * nz(Q1[2]) - C2 * nz(Q1[4]) - C1 * nz(Q1[6]))
// Phasor addition for 3 bar averaging
I2 = I1 - jQ
Q2 = Q1 + jI
// Smooth I and Q components before applying discriminator
I2 := 0.2*I2 + 0.8*nz(I2[1])
Q2 := 0.2*Q2 + 0.8*nz(Q2[1])
// Extract Homodyne Discriminator
Re = I2*nz(I2[1]) + Q2*nz(Q2[1])
Im = I2*nz(Q2[1]) - Q2*nz(I2[1])
Re := 0.2*Re + 0.8*nz(Re[1])
Im := 0.2*Im + 0.8*nz(Im[1])
period := (Re != 0 and Im != 0) ? 2 * math.pi / math.atan(Im/Re) : 0
period := math.min(period, 1.5 * nz(period[1], period))
period := math.max(period, (2/3) * nz(period[1], period))
period := math.min(math.max(period, dynLow), dynHigh)
period := period*0.2 + nz(period[1])*0.8
period
// @function Pearson Autocorrelation
// @param src Series to use
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @param preHP Use High Pass prefilter (default)
// @param preSS Use Super Smoother prefilter (default)
// @param preHP Use Hann Windowing prefilter
// @returns Calculated period
// Based on Pearson Autocorrelation Periodogram by John F. Ehlers
// Introduced in the September 2016 issue of Stocks and Commodities
// Inspired by the @blackcat1402 implementation: https://www.tradingview.com/script/9CbjlKjz-blackcat-L2-Ehlers-Adaptive-CCI-2013/
// Inspired by the @rumpypumpydumpy implementation: https://www.tradingview.com/script/RV0MQvIB-Ehler-s-Autocorrelation-Periodogram-RSI-MFI/
// Corrected many errors, and made small speed optimizations, so this could be the best implementation to date (still slow, though, so may revisit in future)
// High Pass and Super Smoother prefilters are used in the original implementation
export paPeriod (float src, int dynLow, int dynHigh, bool preHP = true, bool preSS = true, bool preHW = false) =>
avglen = 3
var corr = array.new_float(dynHigh+1, initial_value=0)
var R = array.new_float(dynHigh+1, initial_value=0)
var pwr = array.new_float(dynHigh+1, initial_value=0)
hp = preHP ? cf.hp(src, dynHigh) : src
pfilt = preSS ? cf.supers2(hp, dynLow) : hp
filt = preHW ? cf.hannFIR(pfilt, dynLow) : pfilt
//Pearson correlation for each value of lag
for lag = 0 to dynHigh
//Set the averaging length as M
m = avglen == 0 ? lag : avglen
Sx = 0.0
Sy = 0.0
Sxx = 0.0
Sxy = 0.0
Syy = 0.0
//Advance samples of both data streams and sum Pearson components
for count = 0 to m-1
x = filt[count]
y = nz(filt[lag + count])
Sx := Sx + x
Sy := Sy + y
Sxx := Sxx + x * x
Sxy := Sxy + x * y
Syy := Syy + y * y
//Compute correlation for each value of lag
array.set(corr, lag, (m*Sxx - Sx*Sx)*(m*Syy - Sy*Sy) > 0 ? (m*Sxy - Sx*Sy) / math.sqrt((m*Sxx - Sx*Sx) * (m*Syy - Sy*Sy)) : 0)
//Compute the Fourier Transform for each Correlation
for period = dynLow to dynHigh
cosinePart = 0.0
sinePart = 0.0
for n = avglen to dynHigh
cosinePart := cosinePart + array.get(corr, n) * math.cos(2 * math.pi * n / period)
sinePart := sinePart + array.get(corr, n) * math.sin(2 * math.pi * n / period)
sqSum = math.pow(cosinePart, 2) + math.pow(sinePart, 2)
array.set(R, period, 0.2 * math.pow(sqSum, 2) + 0.8 * nz(array.get(R, period), math.pow(sqSum, 2)))
//Find Maximum Power Level for Normalization
maxPwr = 0.0
for period = dynLow to dynHigh
maxPwr := math.max(array.get(R, period), maxPwr)
for period = dynLow to dynHigh
array.set(pwr, period, array.get(R, period) / maxPwr)
//Compute the dominant cycle using the CG of the spectrum
peakPwr = 0.0
for period = dynLow to dynHigh
peakPwr := math.max(array.get(pwr, period), peakPwr)
Spx = 0.0
Sp = 0.0
for period = dynLow to dynHigh
if peakPwr >= 0.25 and array.get(pwr, period) >= 0.25
Spx := Spx + period * array.get(pwr, period)
Sp := Sp + array.get(pwr, period)
domCycle = 0.0
if Sp != 0
domCycle := Spx / Sp
if Sp < 0.25
domCycle := nz(domCycle[1], domCycle)
domCycle
// @function Discrete Fourier Transform
// @param src Series to use
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @param preHP Use High Pass prefilter (default)
// @param preSS Use Super Smoother prefilter (default)
// @param preHP Use Hann Windowing prefilter
// @returns Calculated period
// Based on Spectrum from Discrete Fourier Transform by John F. Ehlers
// Inspired by the @blackcat1402 implementation: https://www.tradingview.com/script/V6wCdSwQ-blackcat-L2-Ehlers-DFT-Adapted-RSI/
// High Pass, Super Smoother and Hann Windowing prefilters are used in the original implementation
export dftPeriod (float src, int dynLow, int dynHigh, bool preHP = true, bool preSS = true, bool preHW = false) =>
var pwr = array.new_float(dynHigh+1, initial_value=0)
hp = preHP ? cf.hp(src, dynHigh) : src
pfilt = preSS ? cf.supers2(hp, dynLow) : hp
filt = preHW ? cf.hannFIR(pfilt, dynLow) : pfilt
//Compute the Fourier Transform
for period = dynLow to dynHigh
cosinePart = 0.0
sinePart = 0.0
for n = 0 to dynHigh - 1
cosinePart := cosinePart + nz(filt[n]) * math.cos(2 * math.pi * n / period)
sinePart := sinePart + nz(filt[n]) * math.sin(2 * math.pi * n / period)
array.set(pwr, period, math.pow(cosinePart, 2) + math.pow(sinePart, 2))
//Find Maximum Power Level for Normalization
maxPwr = array.get(pwr, dynLow)
for period = dynLow to dynHigh
maxPwr := math.max(array.get(pwr, period), maxPwr)
//Normalize Power Levels and Convert to Decibels
for period = dynLow to dynHigh
array.set(pwr, period, array.get(pwr, period) / maxPwr)
//Compute the dominant cycle using the CG of the spectrum
Spx = 0.0
Sp = 0.0
for period = dynLow to dynHigh
if array.get(pwr, period) >= 0.5
Spx := Spx + period * array.get(pwr, period)
Sp := Sp + array.get(pwr, period)
domCycle = 0.0
if Sp != 0
domCycle := Spx / Sp
domCycle
// @function Phase Accumulation
// @param src Series to use
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @param preHP Use High Pass prefilter (default)
// @param preSS Use Super Smoother prefilter (default)
// @param preHP Use Hamm Windowing prefilter
// @returns Calculated period
// Based on Dominant Cycle from Phase Accumulation by John F. Ehlers
// High Pass and Super Smoother prefilters are used in the original implementation
export phasePeriod (float src, int dynLow, int dynHigh, bool preHP = true, bool preSS = true, bool preHW = false) =>
hp = preHP ? cf.hp(src, dynHigh) : src
pfilt = preSS ? cf.supers2(hp, dynLow) : hp
filt = preHW ? cf.hannFIR(pfilt, dynLow) : pfilt
//Correlate with Cosine having a fixed period
Sx = 0.0
Sy = 0.0
Sxx = 0.0
Sxy = 0.0
Syy = 0.0
for count = 0 to dynHigh-1
x = nz(filt[count])
y = math.cos(2 * math.pi * count / dynHigh)
Sx := Sx + x
Sy := Sy + y
Sxx := Sxx + x * x
Sxy := Sxy + x * y
Syy := Syy + y * y
real = (dynHigh * Sxx - Sx*Sx > 0) and (dynHigh * Syy - Sy*Sy > 0) ? (dynHigh * Sxy - Sx*Sy) / math.sqrt((dynHigh * Sxx - Sx*Sx) * (dynHigh * Syy - Sy*Sy)) : 0
//Correlate with negative Sine having a fixed period
Sx := 0.0
Sy := 0.0
Sxx := 0.0
Sxy := 0.0
Syy := 0.0
for count = 0 to dynHigh-1
x = nz(filt[count])
y = -math.sin(2 * math.pi * count / dynHigh)
Sx := Sx + x
Sy := Sy + y
Sxx := Sxx + x * x
Sxy := Sxy + x * y
Syy := Syy + y * y
imag = (dynHigh * Sxx - Sx*Sx > 0) and (dynHigh * Syy - Sy*Sy > 0) ? (dynHigh * Sxy - Sx*Sy) / math.sqrt((dynHigh * Sxx - Sx*Sx) * (dynHigh * Syy - Sy*Sy)) : 0
//Compute the angle as an arctangent function and resolve ambiguity
angle = real != 0 ? 90 - 180 * math.atan(imag/real) / math.pi : 0
if (real < 0)
angle := angle - 180
//Do not allow the angle slope to go negative
if (angle[1] - angle < 270 and angle < angle[1])
angle := angle[1]
//Limit DeltaAngle errors
deltaAngle = angle - angle[1]
if (deltaAngle <= 360/dynHigh)
deltaAngle := deltaAngle[1]
if (deltaAngle >= 360/dynLow)
deltaAngle := deltaAngle[1]
//Compute dominant cycle as summation of delta phases
sumAngle = 0.0
domCycle = 0
for count = 0 to dynHigh
sumAngle := sumAngle + deltaAngle[count]
if sumAngle > 360
domCycle := count
break
domCycle
// ----------
// Wrappers
// ----------
// @function Execute a particular Length Adaptation or Dominant Cycle Estimator from the list
// @param type Length Adaptation or Dominant Cycle Estimator type to use
// @param src Series to use
// @param len Reference lookback length
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @param chandeSDLen Lookback length of Standard deviation for Chande's Dynamic Length
// @param chandeSmooth Smoothing length of Standard deviation for Chande's Dynamic Length
// @param chandePower Exponent of the length adaptation for Chande's Dynamic Length (lower is smaller variation)
// @param preHP Use High Pass prefilter for the Estimators that support it (default)
// @param preSS Use Super Smoother prefilter for the Estimators that support it (default)
// @param preHP Use Hann Windowing prefilter for the Estimators that support it
// @returns Calculated period (float, not limited)
export doAdapt(string type, float src, int len, int dynLow, int dynHigh, int chandeSDLen = 5, int chandeSmooth = 10, float chandePower = 0.5, bool preHP = true, bool preSS = true, bool preHW = false) =>
out = 0.0
switch type
"MESA MAMA Cycle" =>
out := mamaPeriod(src, dynLow, dynHigh)
"Pearson Autocorrelation" =>
out := paPeriod(src, dynLow, dynHigh, preHP, preSS, preHW)
"DFT Cycle" =>
out := dftPeriod(src, dynLow, dynHigh, preHP, preSS, preHW)
"Phase Accumulation" =>
out := phasePeriod(src, dynLow, dynHigh, preHP, preSS, preHW)
=>
out := la.doAdapt(type, src, len, dynLow, dynHigh, chandeSDLen, chandeSmooth, chandePower)
out
// @function Execute a particular Dominant Cycle Estimator from the list
// @param type Dominant Cycle Estimator type to use
// @param src Series to use
// @param dynLow Lower bound for the dynamic length
// @param dynHigh Upper bound for the dynamic length
// @param preHP Use High Pass prefilter for the Estimators that support it (default)
// @param preSS Use Super Smoother prefilter for the Estimators that support it (default)
// @param preHP Use Hann Windowing prefilter for the Estimators that support it
// @returns Calculated period (float, not limited)
export doEstimate(string type, float src, int dynLow, int dynHigh, bool preHP = true, bool preSS = true, bool preHW = false) =>
out = 0.0
switch type
"None" =>
out := dynLow
"MESA MAMA Cycle" =>
out := mamaPeriod(src, dynLow, dynHigh)
"Pearson Autocorrelation" =>
out := paPeriod(src, dynLow, dynHigh, preHP, preSS, preHW)
"DFT Cycle" =>
out := dftPeriod(src, dynLow, dynHigh, preHP, preSS, preHW)
"Phase Accumulation" =>
out := phasePeriod(src, dynLow, dynHigh, preHP, preSS, preHW)
out
|
least_squares_regression | https://www.tradingview.com/script/IBFk6X1d/ | dandrideng | https://www.tradingview.com/u/dandrideng/ | 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/
// © dandrideng
//@version=5
// @description least_squares_regression: Least squares regression algorithm
library("least_squares_regression", overlay=true)
// @function basic_lsr: Basic least squares regression algorithm
// @param series int[] t: time scale value array corresponding to price
// @param series float[] p: price scale value array corresponding to time
// @param series int array_size: the length of regression array
// @returns reg_slop, reg_intercept, reg_level, reg_stdev
export basic_lsr(series int[] t, series float[] p, series int array_size) =>
p_t = array.new_float(array_size, 0)
t_2 = array.new_float(array_size, 0)
//init array
for i = 0 to array_size - 1
array.set(p_t, i, array.get(p, i) * array.get(t, i))
array.set(t_2, i, array.get(t, i) * array.get(t, i))
//get slop and intercept
sum_t = array.sum(t)
sum_p = array.sum(p)
sum_t_2 = array.sum(t_2)
sum_p_t = array.sum(p_t)
a = (array_size * sum_p_t - sum_p * sum_t) / (array_size * sum_t_2 - math.pow(sum_t, 2))
b = (sum_p - a * sum_t) / array_size
//get regression prediction value
_p = array.new_float(array_size, 0)
for i = 0 to array_size - 1
array.set(_p, i, a * array.get(t, i) + b)
//get regression level
float r1 = 0
float r2 = 0
p_avg = array.avg(p)
for i = 0 to array_size - 1
r1 += math.pow(array.get(_p, i) - p_avg, 2)
r2 += math.pow(array.get(p, i) - p_avg, 2)
r = -math.log10(1 - r1 / r2)
//get regression standard devition
_s = array.new_float(array_size, 0)
for i = 0 to array_size - 1
array.set(_s, i, array.get(p, i) - array.get(_p, i))
s = array.stdev(_s)
//return results
[a, b, r, s]
// @function top_trend_line_lsr: Trend line fitting based on least square algorithm
// @param series int[] t: time scale value array corresponding to price
// @param series float[] p: price scale value array corresponding to time
// @param series int array_size: the length of regression array
// @param string reg_type: regression type in 'top' and 'bottom'
// @param series int max_iter: maximum fitting iterations
// @param series int min_points: the threshold of regression point numbers
// @returns reg_slop, reg_intercept, reg_level, reg_stdev, reg_point_num
export trend_line_lsr(series int[] t, series float[] p, series int array_size, string reg_type, series int max_iter, series int min_points) =>
[a, b, r, s] = basic_lsr(t, p, array_size)
x1 = array.get(t, 0)
x2 = array.get(t, array_size - 1)
n = array_size //Function arguments cannot be mutable, what the fuck!
for i = 0 to max_iter - 1
//exit conditions
if n < min_points
break
//init new tick and price array
_t = array.new_int(n, 0)
_p = array.new_float(n, 0)
_n = 0
//fine the ground truth values that bigger than predictions
for j = 0 to n - 1
if reg_type == 'top'
if (a * array.get(t, j) + b) < array.get(p, j)
array.set(_t, _n, array.get(t, j))
array.set(_p, _n, array.get(p, j))
_n += 1
else if reg_type == 'bottom'
if (a * array.get(t, j) + b) > array.get(p, j)
array.set(_t, _n, array.get(t, j))
array.set(_p, _n, array.get(p, j))
_n += 1
else
break
//exit if new array size is less than threshold
if _n < min_points
break
//override result if r of new array is bigger than last array
[_a, _b, _r, _s] = basic_lsr(_t, _p, _n)
if _r > r
x1 := array.get(_t, 0)
x2 := array.get(_t, _n - 1)
a := _a
b := _b
r := _r
s := _s
n := _n
//after for loop
[x1, x2, a, b, r, s, n]
|
OscillatorPivots | https://www.tradingview.com/script/VLil0j5F-OscillatorPivots/ | SimpleCryptoLife | https://www.tradingview.com/u/SimpleCryptoLife/ | 132 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SimpleCryptoLife
// @version=5
// @description Measures pivots in an oscillator and flags if they are above a configurable size. Uses absolute size rather than just highest/lowest in a candle range.
// Can return confirmation of pivots by momentum and by price. Can return divergent peaks and dips. Can filter by oscillator value.
library(title='OscillatorPivots', overlay=false)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// INPUTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
float in_oscPivotSize = input.float(minval=1, defval=10, group="General", title="Oscillator Pivot Size", tooltip="Absolute cumulative change in the oscillator value that will trigger a pivot when it is observed both before and after. There is no maximum value hardcoded, but since most oscillators are fitted 0-100, a sensible maximum might be 50.")
string in_oscMode = input.string(defval="RSI", options=["RSI","Stoch %K","Stoch %D"], tooltip="Choose the example oscillator to be plotted and checked for pivots.")
string in_displayMode = input.string(defval="f_osc_PivotsAndShoulders", title="Function to display", group="Display", options=["f_osc_Pivots","f_osc_PivotsLite","f_osc_PivotsAndShoulders"])
float osc = switch in_oscMode // Derive the oscillator value according to what the user chose.
"RSI" => ta.rsi(close,14)
"Stoch %K" => ta.stoch(close, high, low, 14)
"Stoch %D" => ta.sma(ta.stoch(close, high, low, 14), 3)
float in_oscDipRecovery = input.float(defval=30, title="Dip Recovery Threshold", group="f_osc_PivotsAndShoulders", minval=0, maxval=100, tooltip="The oscillator must be above this value before a dip can be confirmed by momentum. To bypass this setting, use a very low value such as zero.")
float in_oscPeakRecovery = input.float(defval=70, title="Peak Recovery Threshold", minval=0, maxval=100, tooltip="The oscillator must be below this value before a peak can be confirmed by momentum. To bypass this setting, use a very high value such as 100.")
int in_priceBuffer = input.int(defval=10, minval=1, maxval=100, title="ATR % Buffer for Price Confirmation", tooltip="The close must exceed the high/low by this percentage of ATR in order to count.")
in_oscExcludePeakAbove = input.float(defval=80, minval=0, maxval=100, step=5, title="Exclude Peaks Above", tooltip="Exclude peak if the highest oscillator value is above this value. For example, if Stoch is very high maybe you don't want to short.")
in_oscExcludePeakBelow = input.float(defval=20, minval=0, maxval=100, step=5, title="Exclude Peaks Below", tooltip="Exclude peak if the highest oscillator value is below this value. For example, if RSI is oversold maybe you don't want to short.")
in_oscExcludeDipAbove = input.float(defval=80, minval=0, maxval=100, step=5, title="Exclude Dips Above", tooltip="Exclude dip if the lowest oscillator value is above this value. For example, if RSI is overbought maybe you don't want to long.")
in_oscExcludeDipBelow = input.float(defval=20, minval=0, maxval=100, step=5, title="Exclude Dips Below", tooltip="Exclude dip if the lowest oscillator value is below this value. For example, if Stoch is very low maybe you don't want to long.")
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// PIVOTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// @function f_osc_Pivots() Measures pivots in an oscillator value. Uses the total change in the Y axis, instead of a simple Williams pivot over a defined number of bars.
// In other words, it measures the size of the actual pivot, not just whether it happens to be the highest/lowest value in a range.
// Measures the absolute, cumulative change both before and after the pivot, to avoid flagging mere kinks in trends.
// The advantage is that absolute pivot size is, in some cases, precisely what we care about. A disadvantage is that it can take an arbitrary, perhaps long, time to confirm.
// You can configure the threshold size of the pivot so that it finds large or small pivots.
// Always returns a pivot high after a pivot low, then another pivot high and so on, in order. It never returns a high followed by a high, which simple indicators based on the ta.pivot() function can do.
// @param float _oscPivotSize This is the user setting for what counts as a big enough change to be a pivot.
// @param float _osc This is the oscillator float value.
// @param float _osc1In Optional: the oscillator float value from one HTF bar back. Use this parameter if you are running the function on a timeframe higher than the chart timeframe. An example of using my HighTimeframeSampling library to provide the values to do this is given below the function. For normal usage, just leave this out.
// @param float _osc2In Optional: the oscillator float value from two HTF bars back. For normal usage, just leave this out.
// @returns Information about the pivot that is likely to be useful in further calculations:
// confirmPeak, confirmDip - whether the pivot was confirmed this bar
// peakBarsBack, dipBarsBack - how many *chart* bars back the actual peak or dip was
// peakOsc, dipOsc - the value of the oscillator at the peak/dip
// It also returns some internal variables, which are plotted in this library only for an understanding of how the function works.
// debug_peakStartLevel, debug_dipStartLevel - The level of the currently active peak/dip
export f_osc_Pivots(float _oscPivotSize, float _osc, float _osc1In=na, float _osc2In=na) =>
var bool _trailUp = true, var bool _trailDown = true //
var bool _confirmPeak = false, var bool _confirmDip = false
// This form of declaration might look strange but it saves us endless "..or persist" logic.
// We can define these variables here because they are not *modified* outside this function, even if they are output.
var float _peakStartLevel = na, _peakStartLevel := _peakStartLevel[1], var float _dipStartLevel = na, _dipStartLevel := _dipStartLevel[1] // The level of an active candidate pivot
var int _peakStartIndex = na, _peakStartIndex := _peakStartIndex[1], var int _dipStartIndex = na, _dipStartIndex := _dipStartIndex[1] // The bar_index of an active candidate pivot
var int _peakBarsBack = na, _peakBarsBack := _peakBarsBack[1], var int _dipBarsBack = na, _dipBarsBack := _dipBarsBack[1] // How many bars have elapsed from the pivot to its confirmation
var float _peakOsc = na, _peakOsc := _peakOsc[1], var float _dipOsc = na, _dipOsc := _dipOsc[1] // The level of a confirmed pivot
// Assign the HTF versions of the oscillator value if necessary.
// Note: we don't need HTF versions of the peak and dip levels because we're only looking for a change from the previous bar and the previous chart bar works fine for this. Those variables are derived from the oscillator, which itself is fixed for the HTF. So it magically just works.
float _osc1 = na(_osc1In) ? _osc[1] : _osc1In, float _osc2 = na(_osc2In) ? _osc[2] : _osc2In
// PEAKS
bool _justPeaked = (_osc < _osc1) and (_osc1 >= _osc2) ? true : false // Is there a pivot peak of any size, as yet unconfirmed, in the oscillator?
if _justPeaked and _trailDown
_peakStartLevel := na(_peakStartLevel) ? _osc1 : (_osc1 > _peakStartLevel) ? _osc1 : _peakStartLevel // If starting level is na or higher than peak starting level, store current level as starting level for peak.
_trailDown := _trailUp and _trailDown ? true : not _trailUp ? true : false // We can only start trailing down (=looking to confirm a peak) if we are not now trailing up, because we must alternate.
_peakStartIndex := na(_peakStartIndex) ? bar_index : (_peakStartLevel > _peakStartLevel[1]) ? bar_index : _peakStartIndex // Store bar_index when we get a peak. Reset if we get a higher peak, otherwise persist.
if _trailDown and _osc < (_peakStartLevel - _oscPivotSize)
_confirmPeak := true // If we dropped far enough, confirm the peak.
_peakStartLevel := na // Unset starting level for peak.
_trailDown := false, _trailUp := true // Reverse direction.
else
_confirmPeak := false // So this variable is only true for the bar that confirmed.
if _confirmPeak
_peakBarsBack := bar_index + 1 - _peakStartIndex // How far back was the peak? Add 1 because we stored the bar_index one bar after the actual peak.
_peakStartIndex := na // Unset on same-direction confirmation, after the barsBack has been calculated.
_peakOsc := na(_peakStartLevel[1]) ? _osc1 : math.max (_osc1, _peakStartLevel[1]) // What was the oscillator value at the peak? Extra logic for the case where we confirm a peak in one bar.
_peakStartLevel := na // We don't need it after a peak has been confirmed
else
_peakBarsBack := na // Unset just to be tidy
// DIPS
bool _justDipped = (_osc > _osc1) and (_osc1 <= _osc2) ? true : false
if _justDipped and _trailUp
_dipStartLevel := na(_dipStartLevel) ? _osc1 : (_osc1 < _dipStartLevel) ? _osc1 : _dipStartLevel
_trailUp := _trailUp and _trailDown ? true : not _trailDown ? true : false
_dipStartIndex := na(_dipStartIndex) ? bar_index : (_dipStartLevel < _dipStartLevel[1]) ? bar_index : _dipStartIndex
if _trailUp and _osc > (_dipStartLevel + _oscPivotSize)
_confirmDip := true
_dipStartLevel := na
_trailUp := false, _trailDown := true
else
_confirmDip := false
if _confirmDip
_dipBarsBack := bar_index + 1 - _dipStartIndex
_dipStartIndex := na
_dipOsc := na(_dipStartLevel[1]) ? _osc1 : math.min(_osc1, _dipStartLevel[1])
_dipStartLevel := na
else
_dipBarsBack := na
// Output the variables
[_confirmPeak, _confirmDip, _peakBarsBack, _dipBarsBack, _peakOsc, _dipOsc, _peakStartLevel, _dipStartLevel]
// Call the function (to use HTF example, comment this out)
[confirmPeak, confirmDip, peakBarsBack, dipBarsBack, peakOsc, dipOsc, debug_peakStartLevel, debug_dipStartLevel] = f_osc_Pivots(in_oscPivotSize, osc)
// 🧪🧪🧪 =========== HTF EXAMPLE STARTS ===========
// // Example of using values from higher timeframes. Note that because the library fixes the HTF values they are exactly one HTF bar late by design. Consult the explanation in the HighTimeframeSampling library for more information.
// in_HTF = input.timeframe(defval="", title="EXAMPLE High Timeframe")
// float HTF_osc = request.security(syminfo.tickerid, in_HTF, ta.rsi(close,14), barmerge.gaps_off, barmerge.lookahead_off) // Raw HTF oscillator value. Fixed to RSI for this example.
// import SimpleCryptoLife/HighTimeframeSampling/2 as SCL_HTF // Get some.
// float HTF_osc1 = SCL_HTF.f_HTF_Float(in_HTF, HTF_osc, 10, 1, true), float HTF_osc2 = SCL_HTF.f_HTF_Float(in_HTF, HTF_osc, 10, 2, true) // Can we fix it? Yes we can.
// plot(HTF_osc1, style=plot.style_circles, title="HTF_osc1", color=color.new(color.orange,30), linewidth=10), plot(HTF_osc2, style=plot.style_circles, title="HTF_osc2", color=color.new(color.blue,30), linewidth=5) // If you're bored you can follow the logic through the magic of circles.
// [confirmPeak, confirmDip, peakBarsBack, dipBarsBack, peakOsc, dipOsc, debug_peakStartLevel, debug_dipStartLevel] = f_osc_Pivots(in_oscPivotSize, HTF_osc, HTF_osc1, HTF_osc2) // Get the stuff from the thing.
// osc := HTF_osc // So you don't have to comment out the plots later. But do comment out the other call to the function just below here.
// 🧪🧪🧪 =========== HTF EXAMPLE ENDS ===========
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// MINIMALIST PIVOTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// @function f_osc_PivotsLite() This is exactly the same as f_osc_Pivots() except that it returns only the boolean values to tell you if there is a confirmed dip or peak.
// Note that because the optional parameters are the final ones, you do not need to supply the parameter names in the function call as long as you supply them in the correct order.
// @param float _oscPivotSize: the user setting for what counts as a big enough change to be a pivot.
// @param float _osc: the oscillator float value.
// @param float _osc1In Optional: the oscillator float value from one HTF bar back. Use this parameter if you are running the function on a timeframe higher than the chart timeframe. For normal usage, just leave this out.
// @param float _osc2In Optional: the oscillator float value from two HTF bars back. For normal usage, just leave this out.
// @returns confirmPeak, confirmDip - whether the pivot was confirmed this bar
export f_osc_PivotsLite(float _oscPivotSize, float _osc, float _osc1In=na, float _osc2In=na) =>
var bool _trailUp = true, var bool _trailDown = true, var bool _confirmPeak = false, var bool _confirmDip = false
var float _peakStartLevel = na, _peakStartLevel := _peakStartLevel[1], var float _dipStartLevel = na, _dipStartLevel := _dipStartLevel[1]
var int _peakStartIndex = na, _peakStartIndex := _peakStartIndex[1], var int _dipStartIndex = na, _dipStartIndex := _dipStartIndex[1]
var int _peakBarsBack = na, _peakBarsBack := _peakBarsBack[1], var int _dipBarsBack = na, _dipBarsBack := _dipBarsBack[1]
var float _peakOsc = na, _peakOsc := _peakOsc[1], var float _dipOsc = na, _dipOsc := _dipOsc[1]
float _osc1 = na(_osc1In) ? _osc[1] : _osc1In, float _osc2 = na(_osc2In) ? _osc[2] : _osc2In
bool _justPeaked = (_osc < _osc1) and (_osc1 >= _osc2) ? true : false
if _justPeaked and _trailDown
_peakStartLevel := na(_peakStartLevel) ? _osc1 : (_osc1 > _peakStartLevel) ? _osc1 : _peakStartLevel, _trailDown := _trailUp and _trailDown ? true : not _trailUp ? true : false, _peakStartIndex := na(_peakStartIndex) ? bar_index : (_peakStartLevel > _peakStartLevel[1]) ? bar_index : _peakStartIndex
if _trailDown and _osc < (_peakStartLevel - _oscPivotSize)
_confirmPeak := true, _peakStartLevel := na, _trailDown := false, _trailUp := true
else
_confirmPeak := false
if _confirmPeak
_peakBarsBack := bar_index + 1 - _peakStartIndex, _peakStartIndex := na, _peakOsc := na(_peakStartLevel[1]) ? _osc1 : math.max (_osc1, _peakStartLevel[1]), _peakStartLevel := na
else
_peakBarsBack := na
bool _justDipped = (_osc > _osc1) and (_osc1 <= _osc2) ? true : false
if _justDipped and _trailUp
_dipStartLevel := na(_dipStartLevel) ? _osc1 : (_osc1 < _dipStartLevel) ? _osc1 : _dipStartLevel, _trailUp := _trailUp and _trailDown ? true : not _trailDown ? true : false, _dipStartIndex := na(_dipStartIndex) ? bar_index : (_dipStartLevel < _dipStartLevel[1]) ? bar_index : _dipStartIndex
if _trailUp and _osc > (_dipStartLevel + _oscPivotSize)
_confirmDip := true, _dipStartLevel := na, _trailUp := false, _trailDown := true
else
_confirmDip := false
if _confirmDip
_dipBarsBack := bar_index + 1 - _dipStartIndex, _dipStartIndex := na, _dipOsc := na(_dipStartLevel[1]) ? _osc1 : math.min(_osc1, _dipStartLevel[1]), _dipStartLevel := na
else
_dipBarsBack := na
[_confirmPeak, _confirmDip]
[confirmPeakLite, confirmDipLite] = f_osc_PivotsLite(in_oscPivotSize, osc)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// PIVOTS AND SHOULDERS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// @function f_osc_PivotsAndShoulders() Measures pivots in an oscillator value. Uses the total change in the Y axis, instead of a simple Williams pivot over a defined number of bars.
// In other words, it measures the size of the actual pivot, not just whether it happens to be the highest/lowest value in a range.
// Measures the absolute, cumulative change both before and after the pivot, to avoid flagging mere kinks in trends.
// The advantage is that absolute pivot size is, in some cases, precisely what we care about. A disadvantage is that it can take an arbitrary, perhaps long, time to confirm.
// You can configure the threshold size of the pivot so that it finds large or small pivots.
// The function distinguishes between four types of pivot:
// + Pivots. Simple peaks or dips in momentum.
// + Pivot shoulders. These are smaller pivots directly after a major pivot. The lead-in is too small to count as a major pivot but the exit is the same size.
// + Pivots confirmed by price. A momentum pivot that is also confirmed by the close in price.
// + Pivot shoulders confirmed by price. A momentum pivot shoulder that is also confirmed by the close in price.
// Each of the pivot types is either a dip or a peak, giving eight confirmation variables in total.
// Simple pivots confirmed by momentum only are always returned in sequence, i.e., high-low-high-low. The function with default values never returns a high followed by a high, which simple indicators based on the ta.pivot() function can do.
// However, shoulders have no sequencing at all. And price confirmations have no sequencing, because you never know if a pivot in momentum is going to be confirmed by price.
// If you exclude pivots based on the oscillator level, they are removed from the sequence, i.e. you can have a dip followed by a dip, or peak by a peak.
// The function automatically delays confirming pivots if another divergent pivot appears in the meantime. Shoulders can suppress unconfirmed simple pivots.
// @param float _oscPivotSize: The user setting for what counts as a big enough change to be a pivot.
// @param float _high: The High of the current bar. Used for price confirmation.
// @param float _low: The Low of the current bar. Used for price confirmation.
// @param float _open: The Open of the current bar. Used for price confirmation.
// @param float _close: The Close of the current bar. Used for price confirmation.
// @param float _osc: The oscillator float value.
// @param float _osc1In Optional: the oscillator float value from one HTF bar back. Use this parameter if you are running the function on a timeframe higher than the chart timeframe. An example of using my HighTimeframeSampling library to provide the values to do this is given below the function. For normal usage, just leave this out.
// @param float _osc2In Optional: the oscillator float value from two HTF bars back. For normal usage, just leave this out.
// @param float _oscDipRecovery Optional: After a dip, the oscillator has to recover above this threshold (if it ever went below it) in order for the dip to qualify.
// @param float _oscPeakRecovery Optional: After a peak, the oscillator has to recover below this threshold (if it ever went above it) in order for the peak to qualify.
// @param float _priceBuffer Optional: A percentage of ATR which is added (or subtracted) to the price that must be exceeded in order to confirm a pivot with price. If either _priceBuffer or _atr are not supplied, this defaults to zero.
// @param float _atr Optional: The current ATR of the asset.
// @param float _oscExcludePeakAbove Optional: Exclude peak if the highest oscillator value is above this value. For example, if Stoch is very high maybe you don't want to short.
// @param float _oscExcludePeakBelow Optional: Exclude peak if the highest oscillator value is below this value. For example, if RSI is oversold maybe you don't want to short.
// @param float _oscExcludeDipAbove Optional: Exclude dip if the lowest oscillator value is above this value. For example, if RSI is overbought maybe you don't want to long.
// @param float _oscExcludeDipBelow Optional: Exclude dip if the lowest oscillator value is below this value. For example, if Stoch is very low maybe you don't want to long.
// @returns two arrays: float[] _arrayFloats and bool[] _arrayBools, which can be expanded to the following variables (in order):
// 0 float peakBarsBack_M How many bars back the peak was confirmed by momentum. This variable stays accurate and is reset at the next peak confirmation.
// 1 float peakBarsBack_P How many bars back the peak was confirmed by price. This variable has a non-na value only for the confirming bar.
// 2 float peakShoulderBarsBack_M How many bars back the peak shoulder was confirmed by momentum. This variable stays accurate and is reset at the next peak shoulder confirmation.
// 3 float peakShoulderBarsBack_P How many bars back the peak shoulder was confirmed by price. This variable has a non-na value only for the confirming bar.
// 4 float oscPeak The oscillator value at the peak/peak shoulder. This variable has a non-na value only on the bar when a peak/peak shoulder is confirmed by momentum or price. If you want to track the oscillator values for these four kinds of peaks separately, combine this value with the confirmation bools.
// 5 float dipBarsBack_M How many bars back the dip was confirmed by momentum. This variable stays accurate and is reset at the next dip confirmation.
// 6 float dipBarsBack_P How many bars back the dip was confirmed by price. This variable has a non-na value only for the confirming bar.
// 7 float dipShoulderBarsBack_M How many bars back the dip shoulder was confirmed by momentum. This variable stays accurate and is reset at the next dip shoulder confirmation.
// 8 float dipShoulderBarsBack_P How many bars back the dip shoulder was confirmed by price. This variable has a non-na value only for the confirming bar.
// 9 float oscDip The oscillator value at the peak/peak shoulder. This variable has a non-na value only on the bar when a peak/peak shoulder is confirmed by momentum or price. If you want to track the oscillator values for these four kinds of peaks separately, combine this value with the confirmation bools.
// 10 float _closestPivotLevel The closest pivot start level, or the value of the oscillator when we confirm a pivot and until we start tracking again. Provided in case anyone else wants to use it for post-processing.
// 0 bool confirmPeak_M True for the bar when a peak is confirmed by momentum.
// 1 bool confirmPeak_P True for the bar when a peak is confirmed by price.
// 2 bool confirmPeakShoulder_M True for the bar when a peak shoulder is confirmed by momentum.
// 3 bool confirmPeakShoulder_P True for the bar when a peak shoulder is confirmed by price.
// 4 bool confirmDip_M True for the bar when a dip is confirmed by momentum.
// 5 bool confirmDip_P True for the bar when a dip is confirmed by price.
// 6 bool confirmDipShoulder_M True for the bar when a dip shoulder is confirmed by momentum.
// 7 bool confirmDipShoulder_P True for the bar when a dip shoulder is confirmed by price.
export f_osc_PivotsAndShoulders(float _oscPivotSize, float _high, float _low, float _open, float _close, float _osc, float _osc1In=na, float _osc2In=na, float _oscDipRecovery=na, float _oscPeakRecovery=na, float _priceBuffer=0, float _atr=na, float _oscExcludePeakAbove=na, float _oscExcludePeakBelow=na, float _oscExcludeDipAbove=na, float _oscExcludeDipBelow=na) =>
var bool _trailUp = true, var bool _trailDown = true // Looking for peaks or dips
var bool _confirmPeak_M = false, var bool _confirmDip_M = false // Pivots confirmed by momentum only
var float _peakStartLevel = na, _peakStartLevel := _peakStartLevel[1], var float _dipStartLevel = na, _dipStartLevel := _dipStartLevel[1]
var float _peakStartIndex = na, _peakStartIndex := _peakStartIndex[1], var float _dipStartIndex = na, _dipStartIndex := _dipStartIndex[1] // These and other variables that should really be ints are floats here so we can add them to a float array to be returned. We only process them using whole numbers so it's ok.
var float _peakBarsBack_M = na, _peakBarsBack_M := _peakBarsBack_M[1], var float _dipBarsBack_M = na, _dipBarsBack_M := _dipBarsBack_M[1]
float _osc1 = na(_osc1In) ? _osc[1] : _osc1In, float _osc2 = na(_osc2In) ? _osc[2] : _osc2In
var float _peakClose = na, _peakClose := _peakClose[1], var float _dipClose = na, _dipClose := _dipClose[1] // The price close at the time of a pivot
bool _peakDoReset = false, bool _dipDoReset = false // Should we reset the pivot this very bar because price shows regular divergence?
var bool _trailDown_S_0 = na, _trailDown_S_0 := _trailDown_S_0[1], var bool _trailUp_S_0 = na, _trailUp_S_0 := _trailUp_S_0[1] // Prerequisite trailing state for shoulders
var bool _trailDown_S = na, _trailDown_S := _trailDown_S[1], var bool _trailUp_S = na, _trailUp_S := _trailUp_S[1] // Trail state for shoulders only, which have different sequencing.
var float _peakStartLevel_S = na, _peakStartLevel_S := _peakStartLevel_S[1], var float _dipStartLevel_S = na, _dipStartLevel_S := _dipStartLevel_S[1] // Starting oscillator value for shoulders only.
bool _peakDoReset_S = false, bool _dipDoReset_S = false // Reset the shoulder levels on divergence? True for only that bar, hence not var.
var float _peakStartIndex_S = na, _peakStartIndex_S := _peakStartIndex_S[1], var float _dipStartIndex_S = na, _dipStartIndex_S := _dipStartIndex_S[1] // The bar_index of the shoulder pivot.
var float _peakClose_S = na, _peakClose_S := _peakClose_S[1], var float _dipClose_S = na, _dipClose_S := _dipClose_S[1] // The price close at the time of a shoulder pivot.
var bool _confirmPeakShoulder_M = na, _confirmPeakShoulder_M := _confirmPeakShoulder_M[1], var bool _confirmDipShoulder_M = na, _confirmDipShoulder_M := _confirmDipShoulder_M[1] // Shoulder pivots confirmed by momentum only
var float _peakShoulderBarsBack_M = na, _peakShoulderBarsBack_M := _peakShoulderBarsBack_M[1], var float _dipShoulderBarsBack_M = na, _dipShoulderBarsBack_M := _dipShoulderBarsBack_M[1] // How many bars back was the shoulder?
var float _peakClosePersist = na, _peakClosePersist := _peakClosePersist[1], var float _dipClosePersist = na, _dipClosePersist := _dipClosePersist[1] // A copy of the peak close to use for measuring if peak shoulders are divergent.
var float _peak_M_LowCandidate = na, _peak_M_LowCandidate := _peak_M_LowCandidate[1], var float _dip_M_HighCandidate = na, _dip_M_HighCandidate := _dip_M_HighCandidate[1] // The Low of the peak/High of the dip candle, for confirmations, before confirmation with momentum.
var float _peak_M_Low = na, _peak_M_Low := _peak_M_Low[1], var float _dip_M_High = na, _dip_M_High := _dip_M_High[1] // The Low of the peak/High of the dip candle, for confirmations, after confirmation with momentum.
var float _peakShoulder_M_Low = na, _peakShoulder_M_Low := _peakShoulder_M_Low[1], var float _dipShoulder_M_High = na, _dipShoulder_M_High := _dipShoulder_M_High[1] // The Low/High of the peak/dip SHOULDER candle, for confirmations, after confirmation with momentum.
var bool _confirmPeak_P = na, _confirmPeak_P := _confirmPeak_P[1], var bool _confirmDip_P = na, _confirmDip_P := _confirmDip_P[1] // Confirm a pivot with price (and momentum).
var bool _confirmPeakShoulder_P = na, _confirmPeakShoulder_P := _confirmPeakShoulder_P[1], var bool _confirmDipShoulder_P = na, _confirmDipShoulder_P := _confirmDipShoulder_P[1] // Confirm a pivot SHOULDER with price (and momentum).
var float _oscPeak_M = na, _oscPeak_M := _oscPeak_M[1], var float _oscPeak_S = na, _oscPeak_S := _oscPeak_S[1], var float _oscDip_M = na, _oscDip_M := _oscDip_M[1], var float _oscDip_S = na, _oscDip_S := _oscDip_S[1] // Internal helper values. _oscPeak and _oscDip are derived from these and they are returned as the oscillator value at the peak/shoulder, or dip/shoulder. We return only two variables rather than 4 or 8 so as not to get too cluttered, because they can be differentiated, if needed, by the client script after calling this function, by combining them with the confirmation variables. They're only true for the confirming bar.
float _priceConfirmBuffer = nz(_atr) * (_priceBuffer/100) // The buffer which is added (or subtracted) to the price that must be exceeded in order to confirm a pivot with price. If either ATR or the buffer are not supplied, this defaults to zero.
var bool _isOscPeakTooHigh = false, var bool _isOscPeakTooLow = false, var bool _isOscDipTooHigh = false, var bool _isOscDipTooLow = false // One-off variables for out-of-bounds peaks.
var bool _suppressOutOfBoundsPeak = false, var bool _suppressOutOfBoundsDip = false // States that persist and supress the *output* of pivots and pivot shoulders but let the internal pivot values continue (so we don't interfere with the order of dips and peaks or break anything else).
// PEAKS
bool _justPeaked = (_osc < _osc[1]) and (_osc1 >= _osc2) ? true : false // Using osc[1] instead of osc1 makes it true ONLY for the FIRST chart bar of the HTF bar after the peak
if _justPeaked
_isOscPeakTooHigh := na(_oscExcludePeakAbove) ? false : _osc[1] > _oscExcludePeakAbove ? true : false // We can use osc[1] even for HTF because _justPeaked is only true for the first chart bar of the HTF bar.
_isOscPeakTooLow := na(_oscExcludePeakBelow) ? false : _osc[1] < _oscExcludePeakBelow ? true : false // Ignore the TooHigh/TooLow conditions if the input is na.
else
_isOscPeakTooHigh := false, _isOscPeakTooLow := false // Unset just to make sure they're only true for the one bar.
if _justPeaked and _trailDown
_peakStartLevel := na(_peakStartLevel) ? _osc1 : (_osc1 > _peakStartLevel) ? _osc1 : _peakStartLevel
_peakDoReset := math.max(_open,_close) > _peakClose ? true : false // We have a higher close in price so let's reset some stuff in the next loop
_trailDown := _trailUp and _trailDown ? true : not _trailUp ? true : false // We can only start trailing down (=looking to confirm a peak) if we are not now trailing up, because we must alternate.
_peakStartIndex := na(_peakStartIndex) ? bar_index : (_peakStartLevel > _peakStartLevel[1]) ? bar_index : _peakStartIndex // Store bar_index when we get a peak. Reset if we get a higher peak, otherwise persist.
_peakClose := math.max(_open[1],_close[1]) // Update this now after we checked for it in deciding whether _peakDoReset was the case, to make sure we were checking the previous value.
if _peakDoReset
_peakStartLevel := _osc1 // If we have a divergent peak, reset the peak start level
_peakStartIndex := bar_index // ..and the bar index.
bool _oscPeakIsBelowRecovery = na(_oscPeakRecovery) ? true : _osc < _oscPeakRecovery ? true : false // Serves both peaks and peak shoulders
if _trailDown and _osc < (_peakStartLevel - _oscPivotSize) and _oscPeakIsBelowRecovery
_confirmPeak_M := true // If we dropped far enough, confirm the peak.
_oscPeak_M := _peakStartLevel // Capture this before we unset it. Persists.
_peakStartLevel := na // Unset starting level for peak.
_trailDown := false, _trailUp := true // Reverse direction.
else
_confirmPeak_M := false // So this variable is only true for the bar that confirmed.
if _confirmPeak_M
_peakBarsBack_M := bar_index + 1 - _peakStartIndex // How far back was the peak? Add 1 because we stored the bar_index one bar after the actual peak.
_peakStartIndex := na // Unset on same-direction confirmation, after the barsBack has been calculated.
_peakStartLevel := na // We don't need it after a peak has been confirmed.
else
_peakBarsBack_M +=1 // Maintain _peakBarsBack and reset it only on a new peak.
// PEAK SHOULDERS
// Shoulders need a separate logic because they do not alternate peak-dip-peak like pivots do.
_trailDown_S_0 := _confirmPeak_M[1] ? true : _confirmDip_M ? false : _trailDown_S_0 // Prerequisite for _trailDown_S. Start looking for peak shoulders only after peak confirmation. We can do this because shoulders always start after peaks are confirmed. If they start before peak confirmation, the divergent logic moves the peak itself. This is a prerequisite to the other trailing condition.
_trailDown_S := _confirmDip_M ? false : _osc >= _peakStartLevel ? false : _justPeaked and _trailDown_S_0 ? true : _trailDown_S
_peakStartLevel_S := not _trailDown_S ? na : _peakStartLevel_S // Unset when we're no longer looking for peak shoulders
_peakClosePersist := _confirmPeak_M ? math.max(_open,_close,_peakClose) : _confirmPeakShoulder_M ? math.max(_peakClosePersist,_peakClose_S) : _peakClosePersist // Initialise on peak confirmation; Unset on dip confirmation (in the dip section). Reset to the higher of itself and peak shoulder close on confirmation of a peak shoulder.
if _justPeaked and _trailDown_S and not _trailDown
_peakStartLevel_S := na(_peakStartLevel_S) ? _osc1 : (_osc1 > _peakStartLevel_S) ? _osc1 : _peakStartLevel_S
_peakDoReset_S := math.max(_open,_close) > math.max(_peakClose, _peakClose_S) ? true : false // To be higher than both the original peak and the previous shoulder
_peakStartIndex_S := na(_peakStartIndex_S) ? bar_index : (_peakStartLevel_S > _peakStartLevel_S[1]) ? bar_index : _peakStartIndex_S // Store bar_index when we get a peak. Reset if we get a higher peak, otherwise persist.
_peakClose_S := math.max(_open[1],_close[1]) // Update this now after we checked for it in deciding whether _peakDoReset_S was the case, to make sure we were checking the previous value.
_peakClose_S := not _trailDown_S ? na : _peakClose_S // We should probably unset this
if _peakDoReset_S
_peakStartIndex_S := bar_index // If we have a divergent peak, reset the bar index
_peakStartLevel_S := _osc1 // ..and the peak start level.
if _trailDown_S and _osc < (_peakStartLevel_S - _oscPivotSize) and not (_peakClose_S < _peakClosePersist) and _oscPeakIsBelowRecovery
_confirmPeakShoulder_M := true // If we dropped far enough, confirm the peak shoulder.
else
_confirmPeakShoulder_M := false // So this variable is only true for the bar that confirmed.
if _confirmPeakShoulder_M and not _confirmPeak_M
_peakShoulderBarsBack_M := bar_index + 1 - _peakStartIndex_S // How far back was the peak shoulder? Add 1 because we stored the bar_index one bar after the actual peak.
_oscPeak_S := _peakStartLevel_S // Oscillator value at the time of confirming the shoulder. Capture this before we reset it. Persists.
_peakStartLevel_S := _osc1 // If we confirm a peak shoulder, reset the peak start level
else
_peakShoulderBarsBack_M += 1 // Maintain _peakShoulderBarsBack_M and reset it only on a new peak
if _confirmPeakShoulder_M or _confirmPeak_M
_peakStartIndex_S := na // Unset on ANY same-direction confirmation, after the barsBack has been calculated.
if _confirmPeakShoulder_M and _confirmPeak_M
_peakShoulderBarsBack_M := na // We don't need this set if we're not confirming a shoulder on its own
_confirmPeakShoulder_M := false // Cancel the peak shoulder if this is a normal peak
_peakStartLevel_S := _confirmPeakShoulder_M ? na : _peakStartLevel_S
// DIPS
bool _justDipped = (_osc > _osc[1]) and (_osc1 <= _osc2) ? true : false
if _justDipped
_isOscDipTooHigh := na(_oscExcludeDipAbove) ? false : _osc[1] > _oscExcludeDipAbove ? true : false
_isOscDipTooLow := na(_oscExcludeDipBelow) ? false : _osc[1] < _oscExcludeDipBelow ? true : false
else
_isOscDipTooHigh := false, _isOscDipTooLow := false
if _justDipped and _trailUp
_dipStartLevel := na(_dipStartLevel) ? _osc1 : (_osc1 < _dipStartLevel) ? _osc1 : _dipStartLevel
_dipDoReset := math.min(_open,_close) < _dipClose ? true : false
_trailUp := _trailUp and _trailDown ? true : not _trailDown ? true : false
_dipStartIndex := na(_dipStartIndex) ? bar_index : (_dipStartLevel < _dipStartLevel[1]) ? bar_index : _dipStartIndex
_dipClose := math.min(_open[1],_close[1])
if _dipDoReset
_dipStartLevel := _osc1 // If we have a divergent dip, reset the dip start level
_dipStartIndex := bar_index // ..and the bar index
bool _oscDipIsAboveRecovery = na(_oscDipRecovery) ? true : _osc > _oscDipRecovery ? true : false
if _trailUp and _osc > (_dipStartLevel + _oscPivotSize) and _oscDipIsAboveRecovery
_confirmDip_M := true
_oscDip_M := _dipStartLevel
_dipStartLevel := na
_trailUp := false, _trailDown := true
else
_confirmDip_M := false
if _confirmDip_M
_dipBarsBack_M := bar_index + 1 - _dipStartIndex
_dipStartIndex := na
_dipStartLevel := na
else
_dipBarsBack_M += 1
// DIP SHOULDERS
_trailUp_S_0 := _confirmDip_M[1] ? true : _confirmPeak_M ? false : _trailUp_S_0
_trailUp_S := _confirmPeak_M ? false : _osc <= _dipStartLevel ? false : _justDipped and _trailUp_S_0 ? true : _trailUp_S
_dipStartLevel_S := not _trailUp_S ? na : _dipStartLevel_S
_dipClosePersist := _confirmDip_M ? math.min(_open,_close,_dipClose) : _confirmDipShoulder_M ? math.min(_dipClosePersist,_dipClose_S) : _dipClosePersist
if _justDipped and _trailUp_S and not _trailUp
_dipStartLevel_S := na(_dipStartLevel_S) ? _osc1 : (_osc1 < _dipStartLevel_S) ? _osc1 : _dipStartLevel_S
_dipDoReset_S := math.min(_open,_close) < math.min(_dipClose, _dipClose_S) ? true : false
_dipStartIndex_S := na(_dipStartIndex_S) ? bar_index : (_dipStartLevel_S < _dipStartLevel_S[1]) ? bar_index : _dipStartIndex_S
_dipClose_S := math.min(_open[1],_close[1])
_dipClose_S := not _trailUp_S ? na : _dipClose_S
if _dipDoReset_S
_dipStartIndex_S := bar_index
_dipStartLevel_S := _osc1
if _trailUp_S and _osc > (_dipStartLevel_S + _oscPivotSize) and not (_dipClose_S > _dipClosePersist) and _oscDipIsAboveRecovery
_confirmDipShoulder_M := true
else
_confirmDipShoulder_M := false
if _confirmDipShoulder_M and not _confirmDip_M
_dipShoulderBarsBack_M := bar_index + 1 - _dipStartIndex_S
_oscDip_S := _dipStartLevel_S
_dipStartLevel_S := _osc1
else
_dipShoulderBarsBack_M += 1
if _confirmDipShoulder_M or _confirmDip_M
_dipStartIndex_S := na
if _confirmDipShoulder_M and _confirmDip_M
_dipShoulderBarsBack_M := na
_confirmDipShoulder_M := false
_dipStartLevel_S := _confirmDipShoulder_M ? na : _dipStartLevel_S
// PEAK & PEAK SHOULDER CONFIRMATIONS BY PRICE
_peak_M_LowCandidate := _justPeaked ? math.max(_low[1],_low) : _peak_M_LowCandidate
_peak_M_LowCandidate := na(_peak_M_LowCandidate)? na: math.max(_peak_M_LowCandidate,_low) // Trail the Low up only, unless it's unset in which case keep it unset.
if _confirmPeak_M
_peak_M_Low := _peak_M_LowCandidate // Take a copy on peak confirmation
_peak_M_LowCandidate := na // Unset the candidate once we've taken a copy
_peak_M_Low := _confirmDip_M or _confirmDipShoulder_M ? na : _peak_M_Low // Unset on opposing confirmation with momentum.
if _confirmPeakShoulder_M
_peakShoulder_M_Low := _peak_M_LowCandidate // Take a copy on peak SHOULDER confirmation. Need a separate variable so that we can output separate peak/shoulder price confirmations.
_peak_M_LowCandidate := na
_peakShoulder_M_Low := _confirmDip_M or _confirmDipShoulder_M ? na : _peakShoulder_M_Low
// This very bar, confirm with price if the close or close[1] is lower than the _peak_M_Low Separate variables for peaks and peak shoulders. (It doesn't make sense to look back at all the candles for the minimum since if price isn't confirming now or in the next few bars then it shouldn't count).
_confirmPeak_P := ((_close < (_peak_M_Low - _priceConfirmBuffer)) or (_close[1] < (_peak_M_Low - _priceConfirmBuffer))) // True now or not true at all. Since we're checking every chart bar, [1] on the chart TF should be ok.
_confirmPeakShoulder_P := (_close < (_peakShoulder_M_Low - _priceConfirmBuffer)) or (_close[1] < (_peakShoulder_M_Low - _priceConfirmBuffer))
_peak_M_Low := _confirmPeak_P or _confirmPeakShoulder_P ? na : _peak_M_Low // Unset _peak_M_Low on peak or peak shoulder confirmation with price.
_peakShoulder_M_Low := _confirmPeakShoulder_P ? na : _peakShoulder_M_Low // Unset _peakShoulder_M_Low on peak shoulder confirmation with price.
float _peakBarsBack_P = _confirmPeak_P ? _peakBarsBack_M : na // Unlike _peakBarsBack_M, which is running, _peakBarsBack_P has a value only once.
float _peakShoulderBarsBack_P = _confirmPeakShoulder_P ? _peakShoulderBarsBack_M : na // Unlike _peakShoulderBarsBack_M, which is running, _peakShoulderBarsBack_P has a value only once.
// DIP & DIP SHOULDER CONFIRMATIONS BY PRICE
_dip_M_HighCandidate := _justDipped ? math.min(_high[1],_high) : _dip_M_HighCandidate
_dip_M_HighCandidate := na(_dip_M_HighCandidate)? na: math.min(_dip_M_HighCandidate,_high)
if _confirmDip_M
_dip_M_High := _dip_M_HighCandidate
_dip_M_HighCandidate := na
_dip_M_High := _confirmPeak_M or _confirmPeakShoulder_M ? na : _dip_M_High
if _confirmDipShoulder_M
_dipShoulder_M_High := _dip_M_HighCandidate
_dip_M_HighCandidate := na
_dipShoulder_M_High := _confirmPeak_M or _confirmPeakShoulder_M ? na : _dipShoulder_M_High
_confirmDip_P := ((_close > (_dip_M_High + _priceConfirmBuffer)) or (_close[1] > (_dip_M_High + _priceConfirmBuffer)))
_confirmDipShoulder_P := (_close > (_dipShoulder_M_High + _priceConfirmBuffer)) or (_close[1] > (_dipShoulder_M_High + _priceConfirmBuffer))
_dip_M_High := _confirmDip_P or _confirmDipShoulder_P ? na : _dip_M_High
_dipShoulder_M_High := _confirmDipShoulder_P ? na : _dipShoulder_M_High
float _dipBarsBack_P = _confirmDip_P ? _dipBarsBack_M : na
float _dipShoulderBarsBack_P = _confirmDipShoulder_P ? _dipShoulderBarsBack_M : na
// CLEANUP
_peakClosePersist := _confirmDip_M ? na : _peakClosePersist, _dipClosePersist := _confirmPeak_M ? na : _dipClosePersist // Don't remember what this is for but cleaning up is good.
_confirmDip_P := _confirmDip_P and _confirmDipShoulder_P ? false : _confirmDip_P, _confirmPeak_P := _confirmPeak_P and _confirmPeakShoulder_P ? false : _confirmPeak_P // Suppress pivot confirmation with price if we have a pivot shoulder confirmation with price this bar because the pivot had its chance and shoulders are cooler.
float _oscDip = _confirmDip_M or _confirmDip_P ? _oscDip_M : _confirmDipShoulder_M or _confirmDipShoulder_P ? _oscDip_S : na, float _oscPeak = _confirmPeak_M or _confirmPeak_P ? _oscPeak_M : _confirmPeakShoulder_M or _confirmPeakShoulder_P ? _oscPeak_S : na // This needs to come after all confirmations.
var float _closestPivotLevel = na, _closestPivotLevel := not na(_peakStartLevel) ? _peakStartLevel : not na(_dipStartLevel) ? _dipStartLevel : _osc // The closest pivot start level, or _osc when we confirm a pivot.
// SUPPRESSION
_suppressOutOfBoundsPeak := _justDipped ? false : _isOscPeakTooHigh or _isOscPeakTooLow ? true : _suppressOutOfBoundsPeak // Turn on when we get the out-of-bounds peak. Off when we get any dip (because after that we'll get a peak and we need to re-evaluate it). Must be after all peak and dip calculations.
_suppressOutOfBoundsDip := _justPeaked ? false : _isOscDipTooHigh or _isOscDipTooLow ? true : _suppressOutOfBoundsDip
// Define copies of the output variables. This is overkill but I want to be sure there's no unintended effects or edge cases.
var bool _confirmPeak_M_Out = na, var float _peakBarsBack_M_Out = na, var bool _confirmPeak_P_Out = na, var float _peakBarsBack_P_Out = na, var bool _confirmPeakShoulder_M_Out = na, var float _peakShoulderBarsBack_M_Out = na, var bool _confirmPeakShoulder_P_Out = na, var float _peakShoulderBarsBack_P_Out = na, var float _oscPeak_Out = na, var float _peakStartLevelRunning_Out = na
var bool _confirmDip_M_Out = na, var float _dipBarsBack_M_Out = na, var bool _confirmDip_P_Out = na, var float _dipBarsBack_P_Out = na, var bool _confirmDipShoulder_M_Out = na, var float _dipShoulderBarsBack_M_Out = na, var bool _confirmDipShoulder_P_Out = na, var float _dipShoulderBarsBack_P_Out = na, var float _oscDip_Out = na, var float _dipStartLevelRunning_Out = na
if _suppressOutOfBoundsPeak
_confirmPeak_M_Out := false, _peakBarsBack_M_Out := _peakBarsBack_M_Out[1], _confirmPeak_P_Out := false, _peakBarsBack_P_Out := _peakBarsBack_P_Out[1], _confirmPeakShoulder_M_Out := false, _peakShoulderBarsBack_M_Out := _peakShoulderBarsBack_M_Out[1], _confirmPeakShoulder_P_Out := false, _peakShoulderBarsBack_P_Out := _peakShoulderBarsBack_P_Out[1], _oscPeak_Out := _oscPeak_Out[1]
else
_confirmPeak_M_Out := _confirmPeak_M, _peakBarsBack_M_Out := _peakBarsBack_M, _confirmPeak_P_Out := _confirmPeak_P, _peakBarsBack_P_Out := _peakBarsBack_P, _confirmPeakShoulder_M_Out := _confirmPeakShoulder_M, _peakShoulderBarsBack_M_Out := _peakShoulderBarsBack_M, _confirmPeakShoulder_P_Out := _confirmPeakShoulder_P, _peakShoulderBarsBack_P_Out := _peakShoulderBarsBack_P, _oscPeak_Out := _oscPeak
if _suppressOutOfBoundsDip
_confirmDip_M_Out := false, _dipBarsBack_M_Out := _dipBarsBack_M_Out[1], _confirmDip_P_Out := false, _dipBarsBack_P_Out := _dipBarsBack_P_Out[1], _confirmDipShoulder_M_Out := false, _dipShoulderBarsBack_M_Out := _dipShoulderBarsBack_M_Out[1], _confirmDipShoulder_P_Out := false, _dipShoulderBarsBack_P_Out := _dipShoulderBarsBack_P_Out[1], _oscDip_Out := _oscDip_Out[1]
else
_confirmDip_M_Out := _confirmDip_M, _dipBarsBack_M_Out := _dipBarsBack_M, _confirmDip_P_Out := _confirmDip_P, _dipBarsBack_P_Out := _dipBarsBack_P, _confirmDipShoulder_M_Out := _confirmDipShoulder_M, _dipShoulderBarsBack_M_Out := _dipShoulderBarsBack_M, _confirmDipShoulder_P_Out := _confirmDipShoulder_P, _dipShoulderBarsBack_P_Out := _dipShoulderBarsBack_P, _oscDip_Out := _oscDip
// Return everything in two arrays
float[] _arrayFloats = array.from(_peakBarsBack_M_Out, _peakBarsBack_P_Out, _peakShoulderBarsBack_M_Out, _peakShoulderBarsBack_P_Out, _oscPeak_Out, _dipBarsBack_M_Out, _dipBarsBack_P_Out, _dipShoulderBarsBack_M_Out, _dipShoulderBarsBack_P_Out, _oscDip_Out, _closestPivotLevel)
bool[] _arrayBools = array.from(_confirmPeak_M_Out, _confirmPeak_P_Out, _confirmPeakShoulder_M_Out, _confirmPeakShoulder_P_Out, _confirmDip_M_Out, _confirmDip_P_Out, _confirmDipShoulder_M_Out, _confirmDipShoulder_P_Out)
[_arrayFloats, _arrayBools]
// Call the function (to use the HTF example, comment this line out):
[arrayFloats, arrayBools] = f_osc_PivotsAndShoulders(_oscPivotSize=in_oscPivotSize, _high=high, _low=low, _open=open, _close=close, _osc=osc, _oscDipRecovery=in_oscDipRecovery, _oscPeakRecovery=in_oscPeakRecovery, _priceBuffer=in_priceBuffer, _atr=ta.atr(14), _oscExcludePeakAbove=in_oscExcludePeakAbove, _oscExcludePeakBelow=in_oscExcludePeakBelow, _oscExcludeDipAbove=in_oscExcludeDipAbove, _oscExcludeDipBelow=in_oscExcludeDipBelow)
// 🧪🧪🧪 =========== HTF EXAMPLE STARTS ===========
// To use the HTF example, uncomment everything in this section
// // There's no error-checking of the timeframe on this end, but there is in the HTF sampling library.
// in_HTF = input.timeframe(defval="", title="EXAMPLE High Timeframe")
// f_sec_HTF_RawValues() =>
// // This function is only defined so we can call it using security() and get multiple variables at once
// _raw_high = high, _raw_low = low, _raw_open = open, _raw_close = close, _raw_osc = ta.rsi(close,14), _raw_atr = ta.atr(14)
// [_raw_high, _raw_low, _raw_open, _raw_close, _raw_osc, _raw_atr]
// // Get the raw values from the HTF using a single security() call
// [raw_high, raw_low, raw_open, raw_close, raw_osc, raw_atr] = request.security(syminfo.tickerid, in_HTF, f_sec_HTF_RawValues(), barmerge.gaps_off, barmerge.lookahead_off)
// import SimpleCryptoLife/HighTimeframeSampling/2 as SCL_HTF // Let's fix the "current" HTF data, so it doesn't change and we avoid repainting and other issues.
// float[] HTF_Array = array.from(raw_high, raw_low, raw_open, raw_close, raw_osc, raw_atr) // Create input array for the HTF matrix
// HTF_Matrix = SCL_HTF.f_HTF_MatrixFloat(_HTF=in_HTF, _sourceArray=HTF_Array, _matrixHistory=3, _useLiveDataOnChartTF=true) // Fix the array and get historical values. Note that we use the chart TF passthrough.
// // var0 means fixed with no (extra) offset; var1 means fixed and going back [1]; var2 means [2].
// HTF_high0 = matrix.get(HTF_Matrix, 0, 0), HTF_low0 = matrix.get(HTF_Matrix, 0, 1), HTF_open0 = matrix.get(HTF_Matrix, 0, 2), HTF_close0 = matrix.get(HTF_Matrix, 0, 3), HTF_osc0 = matrix.get(HTF_Matrix, 0, 4), HTF_atr0 = matrix.get(HTF_Matrix, 0, 5)
// HTF_osc1 = matrix.get(HTF_Matrix, 1, 4), HTF_osc2 = matrix.get(HTF_Matrix, 2, 4)
// // Call the pivot function with HTF values.
// [arrayFloats, arrayBools] = f_osc_PivotsAndShoulders(_oscPivotSize=in_oscPivotSize, _high=HTF_high0, _low=HTF_low0, _open=HTF_open0, _close=HTF_close0, _osc=HTF_osc0, _osc1In=HTF_osc1, _osc2In=HTF_osc2, _oscDipRecovery=in_oscDipRecovery, _oscPeakRecovery=in_oscPeakRecovery, _priceBuffer=in_priceBuffer, _atr=HTF_atr0, _oscExcludePeakAbove=in_oscExcludePeakAbove, _oscExcludePeakBelow=in_oscExcludePeakBelow, _oscExcludeDipAbove=in_oscExcludeDipAbove, _oscExcludeDipBelow=in_oscExcludeDipBelow)
// 🧪🧪🧪 =========== HTF EXAMPLE ENDS ===========
// Extract all the variables from the arrays. You might only be interested in a subset, in which case you can delete or comment out the relevant lines.
float peakBarsBack_M = array.get(arrayFloats,0) // How many bars back the peak was confirmed by momentum. This variable stays accurate and is reset at the next peak confirmation.
float peakBarsBack_P = array.get(arrayFloats,1) // How many bars back the peak was confirmed by price. This variable has a non-na value only for the confirming bar.
float peakShoulderBarsBack_M = array.get(arrayFloats,2) // How many bars back the peak shoulder was confirmed by momentum. This variable stays accurate and is reset at the next peak shoulder confirmation.
float peakShoulderBarsBack_P = array.get(arrayFloats,3) // How many bars back the peak shoulder was confirmed by price. This variable has a non-na value only for the confirming bar.
float oscPeak = array.get(arrayFloats,4) // The oscillator value at the peak/peak shoulder. This variable has a non-na value only on the bar when a peak/peak shoulder is confirmed by momentum or price. If you want to track the oscillator values for these four kinds of peaks separately, combine this value with the confirmation bools.
float dipBarsBack_M = array.get(arrayFloats,5) // How many bars back the dip was confirmed by momentum. This variable stays accurate and is reset at the next dip confirmation.
float dipBarsBack_P = array.get(arrayFloats,6) // How many bars back the dip was confirmed by price. This variable has a non-na value only for the confirming bar.
float dipShoulderBarsBack_M = array.get(arrayFloats,7) // How many bars back the dip shoulder was confirmed by momentum. This variable stays accurate and is reset at the next dip shoulder confirmation.
float dipShoulderBarsBack_P = array.get(arrayFloats,8) // How many bars back the dip shoulder was confirmed by price. This variable has a non-na value only for the confirming bar.
float oscDip = array.get(arrayFloats,9) // The oscillator value at the peak/peak shoulder. This variable has a non-na value only on the bar when a peak/peak shoulder is confirmed by momentum or price. If you want to track the oscillator values for these four kinds of peaks separately, combine this value with the confirmation bools.
float closestPivotLevel = array.get(arrayFloats,10) // The closest level of a relevant confirmed or unconfirmed pivot.
bool confirmPeak_M = array.get(arrayBools, 0) // True for the bar when a peak is confirmed by momentum.
bool confirmPeak_P = array.get(arrayBools, 1) // True for the bar when a peak is confirmed by price.
bool confirmPeakShoulder_M = array.get(arrayBools, 2) // True for the bar when a peak shoulder is confirmed by momentum.
bool confirmPeakShoulder_P = array.get(arrayBools, 3) // True for the bar when a peak shoulder is confirmed by price.
bool confirmDip_M = array.get(arrayBools, 4) // True for the bar when a dip is confirmed by momentum.
bool confirmDip_P = array.get(arrayBools, 5) // True for the bar when a dip is confirmed by price.
bool confirmDipShoulder_M = array.get(arrayBools, 6) // True for the bar when a dip shoulder is confirmed by momentum.
bool confirmDipShoulder_P = array.get(arrayBools, 7) // True for the bar when a dip shoulder is confirmed by price.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// PLOTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
plot(osc, title="Oscillator", linewidth=2, color=color.white) // Plot the oscillator value.
// Get the right values from the function that's selected for display
bool showLinesFills = in_displayMode == "f_osc_Pivots"
bool showLabels = in_displayMode == "f_osc_Pivots" or in_displayMode == "f_osc_PivotsAndShoulders"
bool confirmPeakPlot = switch in_displayMode
"f_osc_Pivots" => confirmPeak
"f_osc_PivotsLite" => confirmPeakLite
"f_osc_PivotsAndShoulders" => confirmPeak_M
bool confirmDipPlot = switch in_displayMode
"f_osc_Pivots" => confirmDip
"f_osc_PivotsLite" => confirmDipLite
"f_osc_PivotsAndShoulders" => confirmDip_M
// Confirmation of pivots (shown for all functions)
plotchar(confirmPeakPlot ? osc : na, title="Peak Confirmed", char="☑", color=color.red, size=size.small, location=location.absolute) // Appears on the bar where the peak was actually confirmed
plotchar(confirmDipPlot ? osc : na, title="Dip Confirmed", char="☑", color=color.green, size=size.small, location=location.absolute)
// Confirmation of pivot shoulders (shown for f_osc_PivotsAndShoulders)
plotchar(confirmPeakShoulder_M and in_displayMode=="f_osc_PivotsAndShoulders" ? osc : na, title="Peak Shoulder Confirmed", char="☑", color=color.orange, size=size.small, location=location.absolute)
plotchar(confirmDipShoulder_M and in_displayMode=="f_osc_PivotsAndShoulders" ? osc : na, title="Dip Shoulder Confirmed", char="☑", color=color.teal, size=size.small, location=location.absolute)
// Confirmation of pivot shoulders with price (shown for f_osc_PivotsAndShoulders)
plotshape(confirmPeak_P and in_displayMode=="f_osc_PivotsAndShoulders", title="Peak Confirmed by Price", style=shape.triangledown, color=color.new(color.red,30), text="Peak\nconfirmed\nby price", size=size.large, textcolor=color.red, location=location.top)
plotshape(confirmPeakShoulder_P and in_displayMode=="f_osc_PivotsAndShoulders", title="Peak Shoulder Confirmed by Price", style=shape.triangledown, color=color.new(color.orange,30), text="Peak shoulder\nconfirmed\nby price", size=size.normal, textcolor=color.orange, location=location.top)
plotshape(confirmDip_P and in_displayMode=="f_osc_PivotsAndShoulders", title="Dip Confirmed by Price", style=shape.triangleup, color=color.new(color.green,30), text="Dip\nconfirmed\nby price", size=size.large, textcolor=color.green, location=location.bottom)
plotshape(confirmDipShoulder_P and in_displayMode=="f_osc_PivotsAndShoulders", title="Dip Shoulder Confirmed by Price", style=shape.triangleup, color=color.new(color.teal,30), text="Dip shoulder\nconfirmed\nby price", size=size.normal, textcolor=color.teal, location=location.bottom)
// Lines and fills for visualising the necessary levels to confirm pivots (shown only for f_osc_Pivots)
debug_peakStartLevelPlot = plot(showLinesFills ? debug_peakStartLevel : na, title="Peak Start Level", linewidth=3, color=color.new(color.red,30), style=plot.style_linebr)
debug_dipStartLevelPlot = plot(showLinesFills ? debug_dipStartLevel : na, title="Dip Start Level", linewidth=3, color=color.new(color.green,30), style=plot.style_linebr)
debug_peakConfirmLevelPlot = plot(na(debug_peakStartLevel) ? na : showLinesFills ? debug_peakStartLevel - in_oscPivotSize : na, title="Peak Confirmation Level", linewidth=1, color=color.new(color.red,90), style=plot.style_linebr)
debug_dipConfirmLevelPlot = plot(na(debug_dipStartLevel) ? na : showLinesFills ? debug_dipStartLevel + in_oscPivotSize : na, title="Dip Confirmation Level", linewidth=1, color=color.new(color.green,90), style=plot.style_linebr)
fill(debug_peakStartLevelPlot, debug_peakConfirmLevelPlot, color=color.new(color.red,80))
fill(debug_dipStartLevelPlot, debug_dipConfirmLevelPlot, color=color.new(color.green,80))
plot(showLinesFills ? peakOsc : na, title="Last Peak Oscillator Value", color=color.orange, linewidth=2)
plot(showLinesFills ? dipOsc : na, title="Last Dip Oscillator Value", color=color.teal, linewidth=2)
// Get the right values for the labels
float peakBarsBackPlot = switch in_displayMode
"f_osc_Pivots" => peakBarsBack
"f_osc_PivotsAndShoulders" => peakBarsBack_M
float dipBarsBackPlot = switch in_displayMode
"f_osc_Pivots" => dipBarsBack
"f_osc_PivotsAndShoulders" => dipBarsBack_M
float peakOscPlot = switch in_displayMode
"f_osc_Pivots" => peakOsc
"f_osc_PivotsAndShoulders" => osc[peakBarsBack_M]
float dipOscPlot = switch in_displayMode
"f_osc_Pivots" => dipOsc
"f_osc_PivotsAndShoulders" => osc[dipBarsBack_M]
// Show peak/dip labels(for f_osc_Pivots and f_osc_PivotsAndShoulders). Remember that TradingView has a limit to how many labels can be displayed, so if you don't see any labels, scroll right.
import SimpleCryptoLife/Labels/2 as SCL_Label
peakLabelOffset = int(0 - peakBarsBackPlot)
SCL_Label.labelLast(_condition = showLabels and confirmPeakPlot, _text="Peak (" + str.tostring(peakBarsBackPlot) + ")", _offset=peakLabelOffset, _keepLast=false, _y=peakOscPlot+3, _style=label.style_label_down)
peakShoulderLabelOffset = int(0 - peakShoulderBarsBack_M)
SCL_Label.labelLast(_condition = showLabels and in_displayMode=="f_osc_PivotsAndShoulders" and confirmPeakShoulder_M, _text="Peak\nShoulder (" + str.tostring(peakShoulderBarsBack_M) + ")", _color=color.new(color.orange,50), _textColor=color.white, _offset=peakShoulderLabelOffset, _keepLast=false, _y=osc[peakShoulderBarsBack_M]-3, _style=label.style_label_down)
dipLabelOffset = int(0 - dipBarsBackPlot)
SCL_Label.labelLast(_condition = showLabels and confirmDipPlot, _text="Dip (" + str.tostring(dipBarsBackPlot) + ")", _offset=dipLabelOffset, _keepLast=false, _y=dipOscPlot-3, _style=label.style_label_up)
dipShoulderLabelOffset = int(0 - dipShoulderBarsBack_M)
SCL_Label.labelLast(_condition = showLabels and in_displayMode=="f_osc_PivotsAndShoulders" and confirmDipShoulder_M, _text="Dip\nShoulder (" + str.tostring(dipShoulderBarsBack_M) + ")", _color=color.new(color.orange,50), _textColor=color.white, _offset=dipShoulderLabelOffset, _keepLast=false, _y=osc[dipShoulderBarsBack_M]-3, _style=label.style_label_up)
// ======================================================= //
// //
// (╯°□°)╯︵ ǝdʎɥ ǝɥʇ ǝʌǝᴉlǝq ʇ,uoD //
// //
// ======================================================= // |
MathProbabilityDistribution | https://www.tradingview.com/script/yU0hwo2Q-MathProbabilityDistribution/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 104 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
// Special Apreciation for help to: Anton Berlin, LucF.
//@version=5
// @description Probability Distribution Functions.
library(title='MathProbabilityDistribution')
// reference:
// https://r-forge.r-project.org/scm/viewvc.php/pkg/fGarch/src/dist.f?view=markup&revision=5924&root=rmetrics
// https://itl.nist.gov/div898/handbook/eda/section3/eda3661.htm
// https://rdrr.io/cran/fGarch/src/R/dist-sstd.R
// https://rdrr.io/rforge/fGarch/
import RicardoSantos/MathSpecialFunctionsGamma/1 as msf
// .gamma()
import RicardoSantos/Probability/1 as prob
// .erf() .cumulative_distribution_function()
// Common Constant Variables:
var float __2PI__ = 2.0 * math.pi
var float __SQ2PI__ = math.sqrt(__2PI__)
// Shared variables and utility:
int __CYCLE4__ = bar_index % 81
float __CYCLE4F__ = (-40 + __CYCLE4__) * 0.1
plot(math.abs(__CYCLE4F__) == 0 ? 0 : na, title='Cycle 1 Marker', color=color.white, linewidth=2, style=plot.style_cross)
plot(math.abs(__CYCLE4F__) == 1 ? 0 : na, title='Cycle 1 Marker', color=color.maroon, linewidth=2, style=plot.style_cross)
plot(math.abs(__CYCLE4F__) == 2 ? 0 : na, title='Cycle 2 Marker', color=color.red, linewidth=2, style=plot.style_cross)
plot(math.abs(__CYCLE4F__) == 3 ? 0 : na, title='Cycle 3 Marker', color=color.orange, linewidth=3, style=plot.style_cross)
plot(math.abs(__CYCLE4F__) == 4 ? 0 : na, title='Cycle 4 Marker', color=color.yellow, linewidth=3, style=plot.style_cross)
// @function Indexed names helper function.
// @param idx int, position in the range (0, 6).
// @returns string, distribution name.
// usage:
// .name(1)
// Notes:
// (0) => 'StdNormal'
// (1) => 'Normal'
// (2) => 'Skew Normal'
// (3) => 'Student T'
// (4) => 'Skew Student T'
// (5) => 'GED'
// (6) => 'Skew GED'
export name (int idx) => //{
switch idx
(0) => 'StdNormal'
(1) => 'Normal'
(2) => 'Skew Normal'
(3) => 'Student T'
(4) => 'Skew Student T'
(5) => 'GED'
(6) => 'Skew GED'
=> 'StdNormal'
//}
// @function Z-score helper function for x calculation.
// @param position float, position.
// @param mean float, mean.
// @param deviation float, standard deviation.
// @returns float, z-score.
// usage:
// .zscore(1.5, 2.0, 1.0)
export zscore (float position, float mean, float deviation) => //{
(position - mean) / deviation
// test:
// plot(zscore(__CYCLE4F__, 0.0, 1.0)) // OK
//}
// @function Standard Normal Distribution.
// @param position float, position.
// @returns float, probability density.
// usage:
// .std_normal(0.6)
export std_normal (float position) => //{
math.exp(-math.pow(position, 2.0) / 2.0) / __SQ2PI__
// test:
// plot(std_normal(__CYCLE4F__)) // OK
//}
// @function Normal Distribution.
// @param position float, position in the distribution.
// @param mean float, mean of the distribution, default=0.0 for standard distribution.
// @param scale float, scale of the distribution, default=1.0 for standard distribution.
// @returns float, probability density.
// usage:
// .normal(0.6)
export normal (float position, float mean=0.0, float scale=1.0) => //{
math.exp(-math.pow(position - mean, 2.0) / (2.0 * math.pow(scale, 2.0))) / (scale * __SQ2PI__)
// test:
// plot(normal(__CYCLE4F__)) // OK
//}
// @function Skew Normal Distribution.
// @param position float, position in the distribution.
// @param skew float, skewness of the distribution.
// @param mean float, mean of the distribution, default=0.0 for standard distribution.
// @param scale float, scale of the distribution, default=1.0 for standard distribution.
// @returns float, probability density.
// usage:
// .skew_normal(0.8, -2.0)
export skew_normal (float position, float skew, float mean=0.0, float scale=1.0) => //{
2.0 * std_normal(position) * prob.cumulative_distribution_function(mean, scale, skew * position)
// test:
// plot(skew_normal(__CYCLE4F__, 0.5)) // OK
//}
// @function Generalized Error Distribution.
// @param position float, position.
// @param shape float, shape.
// @param mean float, mean, default=0.0 for standard distribution.
// @param scale float, scale, default=1.0 for standard distribution.
// @returns float, probability.
// usage:
// .ged(0.8, -2.0)
export ged (float position, float shape, float mean=0.0, float scale=1.0) => //{
float _1shape = 1.0 / shape
float _g1shape = msf.Gamma(_1shape)
float _g3shape = msf.Gamma(3.0 / shape)
float _z = zscore(position, mean, scale)
float _lambda = math.sqrt(math.pow(2.0, (-2.0 / shape)) * _g1shape / _g3shape)
float _g = shape / (_lambda * (math.pow(2.0, 1.0 + _1shape) * _g1shape))
_g * math.exp(-0.5 * math.pow(math.abs(_z / _lambda), shape)) / scale
// test:
// run: https://rdrr.io/snippets/
// library(fGarch)
// x = seq(-4, 4, by=0.1)
// # x, m, s, n
// plot(x, dged(x, 0, 1, 0.7))
// box()
// lines(x, dged(x, 0, 1, 1))
// lines(x, dged(x, 0, 1, 2))
// lines(x, dged(x, 0, 1, 100))
// lines(x, dged(x, 0, 1, 2))
// lines(x, dged(x, 0, 2, 2))
// lines(x, dged(x, 0, 3, 2))
// lines(x, dged(x, 0, 4, 2))
// plot(ged(__CYCLE4F__, 0.7)) // OK
// plot(ged(__CYCLE4F__, 1)) // OK
// plot(ged(__CYCLE4F__, 2)) // OK
// plot(ged(__CYCLE4F__, 100)) // OK
// plot(ged(__CYCLE4F__, 2, 0, 1)) // OK
// plot(ged(__CYCLE4F__, 2, 0, 2)) // OK
// plot(ged(__CYCLE4F__, 2, 0, 3)) // OK
// plot(ged(__CYCLE4F__, 2, 0, 4)) // OK
//}
// @function Skew Generalized Error Distribution.
// @param position float, position.
// @param shape float, shape.
// @param skew float, skew.
// @param mean float, mean, default=0.0 for standard distribution.
// @param scale float, scale, default=1.0 for standard distribution.
// @returns float, probability.
// usage:
// .skew_ged(0.8, 2.0, 1.0)
export skew_ged (float position, float shape, float skew, float mean=0.0, float scale=1.0) => //{
// common
float _1shape = 1.0 / shape
float _2shape = 2.0 / shape
float _1skew = 1.0 / skew
float _g1shape = msf.Gamma(_1shape)
float _g2shape = msf.Gamma(_2shape)
float _g3shape = msf.Gamma(3.0 / shape)
// standardize:
float _lambda = math.sqrt(math.pow(2.0, -_2shape) * _g1shape / _g3shape)
// float _g = shape / (_lambda * math.pow(2.0, 1.0 + _1shape) * _g1shape) // not used
float _m1 = math.pow(2.0, _1shape) * _lambda * _g2shape / _g1shape
float _mu = _m1 * (skew - _1skew)
float _xi2 = math.pow(skew, 2.0)
float _m12 = math.pow(_m1, 2.0)
float _sigma = math.sqrt((1.0 - _m12) * (_xi2 + 1.0 / _xi2) + 2.0 * _m12 - 1.0)
float _z = zscore(position, mean, scale) * _sigma + _mu
// compute:
float _xxi = math.pow(skew, math.sign(_z))
if (_z == 0.0)
_xxi := math.pow(skew, 0.0)//math.sign(skew)//skew**0.0
float _g = (2.0 / (skew + _1skew))
float _density = _g * ged(_z / _xxi, shape)
(_density * _sigma) / scale
// test:
// run: https://rdrr.io/snippets/
// library(fGarch)
// x = seq(-4, 4, by=0.1)
// # x, m, s, n, xi
// plot(x, dsged(x, 0, 1, 2, 1.5))
// box()
// lines(x, dsged(x, 0, 2, 2, 1.5))
// lines(x, dsged(x, 0, 3, 2, 1.5))
// lines(x, dsged(x, 0, 4, 2, 1.5))
// plot(skew_ged(__CYCLE4F__, 2, 1.5, 0, 1)) // OK
// plot(skew_ged(__CYCLE4F__, 2, 1.5, 0, 2)) // OK
// plot(skew_ged(__CYCLE4F__, 2, 1.5, 0, 3)) // OK
// plot(skew_ged(__CYCLE4F__, 2, 1.5, 0, 4)) // OK
//}
// @function Student-T Distribution.
// @param position float, position.
// @param shape float, shape.
// @param mean float, mean, default=0.0 for standard distribution.
// @param scale float, scale, default=1.0 for standard distribution.
// @returns float, probability.
// usage:
// .student_t(0.8, 2.0, 1.0)
export student_t (float position, float shape, float mean=0.0, float scale=1.0) => //{
float _z = zscore(position, mean, scale)
float _s = math.sqrt(shape / (shape - 2))
float _shape2 = (shape + 1.0) / 2.0
float _gshape2 = msf.Gamma(_shape2)
float _a = _gshape2 / math.sqrt(shape * math.pi)
float _b = msf.Gamma(shape / 2.0) * math.pow((1.0 + math.pow(_z * _s, 2.0) / shape), _shape2)
(_a / _b) * _s / scale
// test:
// run: https://rdrr.io/snippets/
// library(fGarch)
// x = seq(-4, 4, by=0.1)
// # x, m, s, n
// plot(x, dstd(x, 0, 1, 5))
// box()
// lines(x, dstd(x, 0, 2, 5))
// lines(x, dstd(x, 0, 3, 5))
// lines(x, dstd(x, 0, 4, 5))
// plot(student_t(__CYCLE4F__, 5, 0, 1)) // OK
// plot(student_t(__CYCLE4F__, 5, 0, 2)) // OK
// plot(student_t(__CYCLE4F__, 5, 0, 3)) // OK
// plot(student_t(__CYCLE4F__, 5, 0, 4)) // OK
//}
// @function Skew Student-T Distribution.
// @param position float, position.
// @param shape float, shape.
// @param skew float, skew.
// @param mean float, mean, default=0.0 for standard distribution.
// @param scale float, scale, default=1.0 for standard distribution.
// @returns float, probability.
// usage:
// .skew_student_t(0.8, 2.0, 1.0)
export skew_student_t (float position, float shape, float skew, float mean=0.0, float scale=1.0) => //{
float _1skew = 1.0 / skew
float _a = 0.5
float _b = shape / 2.0
float _beta = (msf.Gamma(_a) / msf.Gamma(_a + _b)) * msf.Gamma(_b)
float _m1 = 2.0 * math.sqrt(shape - 2.0) / (shape - 1.0) / _beta
float _mu = _m1 * (skew - _1skew)
float _xi2 = math.pow(skew, 2.0)
float _m12 = math.pow(_m1, 2.0)
float _sigma = math.sqrt((1.0 - _m12) * (_xi2 + 1.0 / _xi2) + 2.0 * _m12 - 1.0)
float _z = position * _sigma + _mu
float _xxi = math.pow(skew, math.sign(_z))
if (_z == 0.0)
_xxi := math.pow(skew, 0.0)//math.sign(skew)//skew**0.0
float _g = 2.0 / (skew + _1skew)
_g * student_t(_z / _xxi, shape, mean, scale) * _sigma
// test:
// run: https://rdrr.io/snippets/
// library(fGarch)
// x = seq(-4, 4, by=0.1)
// # x, m, s, n, xi
// plot(x, dsstd(x, 0, 0.25, 5, 1))
// box()
// lines(x, dsstd(x, 0, 1, 5, 2))
// lines(x, dsstd(x, 0, 1, 5, 3))
// plot(skew_student_t(__CYCLE4F__, 5, 1, 0, 0.25)) // OK
// plot(skew_student_t(__CYCLE4F__, 5, 2, 0, 1)) // OK
// plot(skew_student_t(__CYCLE4F__, 5, 3, 0, 1)) // OK
//}
// @function Conditional Distribution.
// @param distribution string, distribution name.
// @param position float, position.
// @param mean float, mean, default=0.0 for standard distribution.
// @param scale float, scale, default=1.0 for standard distribution.
// @param shape float, shape.
// @param skew float, skew.
// @param log bool, if true apply log() to the result.
// @returns float, probability.
// usage:
// .select('StdNormal', __CYCLE4F__, log=true)
export select (string distribution='StdNormal', float position, float mean=0.0, float scale=1.0, float skew=na, float shape=na, bool log=false) => //{
float _p = switch (distribution)
('StdNormal' ) => std_normal(position / scale) / scale
('Normal' ) => normal(position, mean, scale)
('Skew Normal' ) => skew_normal(position, skew, mean, scale)
('Student T' ) => student_t(position, shape, mean, scale)
('Skew Student T' ) => skew_student_t(position, shape, skew, mean, scale)
('GED' ) => ged(position, shape, mean, scale)
('Skew GED' ) => skew_ged(position, shape, skew, mean, scale)
=> float(na)
log ? math.log(_p) : _p
// test:
plot(select('StdNormal', __CYCLE4F__, log=true)) // OK
//}
|
Colors | https://www.tradingview.com/script/h5iP3EyW-Colors/ | gliderfund | https://www.tradingview.com/u/gliderfund/ | 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/
// © gliderfund
//@version=5
// @description This Library delivers Hex Codes of Colors frequently used in indicators and strategies.
library("Colors", overlay = true)
// @function Collection: Pinescript v3 Colors.
// @param colorName Color Name.
// @returns Hex code of the inquired color.
export v3(simple string colorName) =>
switch colorName
'maroon' => #800000
'red' => #FF0000
'navy' => #000080
'blue' => #0000FF
'aqua' => #00FFFF
'teal' => #008080
'green' => #008000
'lime' => #00FF00
'olive' => #808000
'fuchsia' => #FF00FF
'purple' => #800080
'orange' => #FF7F00
'yellow' => #FFFF00
'black' => #000000
'gray' => #808080
'silver' => #C0C0C0
'white' => #FFFFFF
=>
runtime.error("No matching color found.")
color(na)
// End of Function
// @function Collection: Pinescript v4 Colors.
// @param colorName Color Name.
// @returns Hex code of the inquired color.
export v4(simple string colorName) =>
switch colorName
'maroon' => #880E4F
'red' => #FF5252
'navy' => #311B92
'blue' => #2196F3
'aqua' => #00BCD4
'teal' => #00897B
'green' => #4CAF50
'lime' => #00E676
'olive' => #808000
'fuchsia' => #E040FB
'purple' => #9C27B0
'orange' => #FF9800
'yellow' => #FFEB3B
'black' => #363A45
'gray' => #787B86
'silver' => #B2B5BE
'white' => #FFFFFF
=>
runtime.error("No matching color found.")
color(na)
// End of Function
// Test
plot(series = close, color = v3('red'))
|
eHarmonicpatternsExtended | https://www.tradingview.com/script/tzz1aHhR-eHarmonicpatternsExtended/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 216 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
// @description Library provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations
library("eHarmonicpatternsExtended")
isInRange(ratio, min, max)=> ratio >= min and ratio <= max
getadj(p1, p2, adj)=>math.max(0, p2 - (p2 - p1) * adj)
getrange(float p1, float p2, simple float min, simple float max,
simple float ep, simple float adjs, simple float adje,
bool[] pArray, float[] startRange, float[] endRange, simple int index)=>
returnval = false
if(array.get(pArray, index))
eamin = (100 - (ep+adjs)) / 100
eamax = (100 + ep+adje) / 100
start = getadj(p1, p2, min*eamin)
end = getadj(p1, p2, max*eamax)
array.set(startRange, index, start)
array.set(endRange, index, end)
returnval := true
returnval
getrange(float p1, float p2, simple float min1, simple float max1,
float p3, float p4, simple float min2, simple float max2,
bool[] pArray, float[] startRange, float[] endRange, simple int index)=>
returnval = false
if(array.get(pArray, index))
start1 = getadj(p1, p2, min1)
end1 = getadj(p1, p2, max1)
start2 = getadj(p3, p4, min2)
end2 = getadj(p3, p4, max2)
start = start1 > end1? math.min(start1, start2) : math.max(start1, start2)
end = start1 > end1? math.max(end1, end2) : math.min(end1, end2)
d1 = start1>end1? 1 : -1
d2 = start2>end2? 1 : -1
d = start>end? 1 : -1
if(d1 == d2 and d == d1 and (start > 0 or end > 0))
returnval := true
array.set(startRange, index, start)
array.set(endRange, index, end)
else
array.set(pArray, index, false)
returnval
getrange(float p1, float p2, simple float min1, simple float max1,
float p3, float p4, simple float min2, simple float max2,
simple float ep1, simple float ep2,
simple float adjs, simple float adje,
bool[] pArray, float[] startRange, float[] endRange, simple int index)=>
returnval = false
if(array.get(pArray, index))
eamin1 = (100 - (ep1+adjs)) / 100
eamax1 = (100 + ep1+adje) / 100
eamin2 = (100 - (ep2+adjs)) / 100
eamax2 = (100 + ep2+adje) / 100
start1 = getadj(p1, p2, min1*eamin1)
end1 = getadj(p1, p2, max1*eamax1)
start2 = getadj(p3, p4, min2*eamin2)
end2 = getadj(p3, p4, max2*eamax2)
start = start1 > end1? math.min(start1, start2) : math.max(start1, start2)
end = start1 > end1? math.max(end1, end2) : math.min(end1, end2)
d1 = start1>end1? 1 : -1
d2 = start2>end2? 1 : -1
d = start>end? 1 : -1
if(d1 == d2 and d == d1 and (start > 0 or end > 0))
returnval := true
array.set(startRange, index, start)
array.set(endRange, index, end)
else
array.set(pArray, index, false)
returnval
isCypherProjection(float xabRatio, float axcRatio, simple float err_min=0.92, simple float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
axcMin = 1.13 * err_min
axcMax = 1.414 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(axcRatio, axcMin, axcMax)
isCypherPattern(float xabRatio, float axcRatio, float xcdRatio, simple float err_min=0.92, simple float err_max=1.08, enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
axcMin = 1.13 * err_min
axcMax = 1.414 * err_max
xcdMin = 0.786 * err_min
xcdMax = 0.786 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(axcRatio, axcMin, axcMax) and
isInRange(xcdRatio, xcdMin, xcdMax)
getNumberOfSupportedPatterns()=>25
export getSupportedPatterns()=>
patternLabelArray = array.new_string()
array.push(patternLabelArray, "Gartley")
array.push(patternLabelArray, "Crab")
array.push(patternLabelArray, "DeepCrab")
array.push(patternLabelArray, "Bat")
array.push(patternLabelArray, "Butterfly")
array.push(patternLabelArray, "Shark")
array.push(patternLabelArray, "Cypher")
array.push(patternLabelArray, "NenStar")
array.push(patternLabelArray, "Anti NenStar")
array.push(patternLabelArray, "Anti Shark")
array.push(patternLabelArray, "Anti Cypher")
array.push(patternLabelArray, "Anti Crab")
array.push(patternLabelArray, "Anti Butterfly")
array.push(patternLabelArray, "Anti Bat")
array.push(patternLabelArray, "Anti Gartley")
array.push(patternLabelArray, "Navarro200")
array.push(patternLabelArray, "Five Zero")
array.push(patternLabelArray, "Three Drives")
array.push(patternLabelArray, "White Swan")
array.push(patternLabelArray, "Black Swan")
array.push(patternLabelArray, "Sea Pony")
array.push(patternLabelArray, "Leonardo")
array.push(patternLabelArray, "121")
array.push(patternLabelArray, "Snorm")
array.push(patternLabelArray, "Total")
patternLabelArray
scan_xab(float xabRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_0_382_to_0_618 = isInRange(xabRatio, 0.382*err_min, 0.618*err_max)
is_0_446_to_0_618 = isInRange(xabRatio, 0.446*err_min, 0.618*err_max)
is_0_500_to_0_786 = isInRange(xabRatio, 0.500*err_min, 0.786*err_max)
is_0_618_to_0_786 = isInRange(xabRatio, 0.618*err_min, 0.786*err_max)
is_1_270_to_1_618 = isInRange(xabRatio, 1.270*err_min, 1.618*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and isInRange(xabRatio, 0.618*err_min, 0.618*err_max))
//Crab
array.set(patternArray, 1, array.get(patternArray, 1) and is_0_382_to_0_618)
//DeepCrab
array.set(patternArray, 2, array.get(patternArray, 2) and isInRange(xabRatio, 0.886*err_min, 0.886*err_max))
//Bat
array.set(patternArray, 3, array.get(patternArray, 3) and isInRange(xabRatio, 0.382*err_min, 0.500*err_max))
//Butterfly
array.set(patternArray, 4, array.get(patternArray, 4) and isInRange(xabRatio, 0.786*err_min, 0.786*err_max))
//Shark
array.set(patternArray, 5, array.get(patternArray, 5) and is_0_446_to_0_618)
//Cypher
array.set(patternArray, 6, array.get(patternArray, 6) and is_0_382_to_0_618)
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and is_0_382_to_0_618)
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_0_500_to_0_786)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and is_0_446_to_0_618)
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_0_500_to_0_786)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and isInRange(xabRatio, 0.276*err_min, 0.446*err_max))
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and is_0_382_to_0_618)
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and is_0_382_to_0_618)
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and is_0_618_to_0_786)
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(xabRatio, 0.382*err_min, 0.786*err_max))
//5-0
array.set(patternArray, 16, array.get(patternArray, 16) and is_1_270_to_1_618)
//Three Drives
array.set(patternArray, 17, array.get(patternArray, 17) and isInRange(xabRatio, 0.618*err_min, 0.786*err_max))
//White Swan
array.set(patternArray, 18, array.get(patternArray, 18) and isInRange(xabRatio, 0.382*err_min, 0.786*err_max))
//Black Swan
array.set(patternArray, 19, array.get(patternArray, 19) and isInRange(xabRatio, 1.382*err_min, 2.618*err_max))
//Sea Pony
array.set(patternArray, 20, array.get(patternArray, 20) and isInRange(xabRatio, 0.128*err_min, 3.618*err_max))
//Leonardo
array.set(patternArray, 21, array.get(patternArray, 21) and isInRange(xabRatio, 0.5*err_min, 0.5*err_max))
//121
array.set(patternArray, 22, array.get(patternArray, 22) and isInRange(xabRatio, 0.5*err_min, 0.786*err_max))
//Snorm
array.set(patternArray, 23, array.get(patternArray, 23) and isInRange(xabRatio,0.9*err_min, 1.1*err_max))
//Total
array.set(patternArray, 24, array.get(patternArray, 24) and isInRange(xabRatio, 0.236*err_min, 0.786*err_max))
scan_abc_axc(float abcRatio, float axcRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_0_382_to_0_886 = isInRange(abcRatio, 0.382*err_min, 0.886*err_max)
is_0_467_to_0_707 = isInRange(abcRatio, 0.467*err_min, 0.707*err_max)
is_1_128_to_2_618 = isInRange(abcRatio, 1.128*err_min, 2.618*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and is_0_382_to_0_886)
//Crab
array.set(patternArray, 1, array.get(patternArray, 1) and is_0_382_to_0_886)
//DeepCrab
array.set(patternArray, 2, array.get(patternArray, 2) and is_0_382_to_0_886)
//Bat
array.set(patternArray, 3, array.get(patternArray, 3) and is_0_382_to_0_886)
//Butterfly
array.set(patternArray, 4, array.get(patternArray, 4) and is_0_382_to_0_886)
//Shark
array.set(patternArray, 5, array.get(patternArray, 5) and isInRange(abcRatio, 1.130*err_min, 1.618*err_max))
//Cypher
array.set(patternArray, 6, array.get(patternArray, 6) and isInRange(axcRatio, 1.130*err_min, 1.414*err_max))
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and isInRange(abcRatio, 1.414*err_min, 2.140*err_max))
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_0_467_to_0_707)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and isInRange(abcRatio, 0.618*err_min, 0.886*err_max))
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_0_467_to_0_707)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and is_1_128_to_2_618)
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and is_1_128_to_2_618)
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and is_1_128_to_2_618)
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and is_1_128_to_2_618)
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(abcRatio, 0.886*err_min, 1.127*err_max))
//5-0
array.set(patternArray, 16, array.get(patternArray, 16) and isInRange(abcRatio, 1.168*err_min, 2.240*err_max))
//Three Drives
array.set(patternArray, 17, array.get(patternArray, 17) and isInRange(abcRatio, 1.272*err_min, 1.618*err_max))
//White Swan
array.set(patternArray, 18, array.get(patternArray, 18) and isInRange(abcRatio, 2.0*err_min, 4.237*err_max))
//Black Swan
array.set(patternArray, 19, array.get(patternArray, 19) and isInRange(abcRatio, 0.236*err_min, 0.5*err_max))
//Sea Pony
array.set(patternArray, 20, array.get(patternArray, 20) and isInRange(abcRatio, 0.382*err_min, 0.5*err_max))
//Leonardo
array.set(patternArray, 21, array.get(patternArray, 21) and isInRange(abcRatio, 0.382*err_min, 0.886*err_max))
//121
array.set(patternArray, 22, array.get(patternArray, 22) and isInRange(abcRatio, 1.128*err_min, 3.618*err_max))
//Snorm
array.set(patternArray, 23, array.get(patternArray, 23) and isInRange(abcRatio,0.9*err_min, 1.1*err_max))
//Total
array.set(patternArray, 24, array.get(patternArray, 24) and isInRange(abcRatio, 0.382*err_min, 2.618*err_max))
scan_bcd(float bcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_1_618_to_2_618 = isInRange(bcdRatio, 1.618*err_min, 2.618*err_max)
is_1_272_to_1_618 = isInRange(bcdRatio, 1.272*err_min, 1.618*err_max)
is_1_272_to_2_000 = isInRange(bcdRatio, 1.272*err_min, 2.000*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and is_1_272_to_1_618)
//Crab
array.set(patternArray, 1, array.get(patternArray, 1) and isInRange(bcdRatio, 2.240*err_min, 3.618*err_max))
//DeepCrab
array.set(patternArray, 2, array.get(patternArray, 2) and isInRange(bcdRatio, 2.000*err_min, 3.618*err_max))
//Bat
array.set(patternArray, 3, array.get(patternArray, 3) and is_1_618_to_2_618)
//Butterfly
array.set(patternArray, 4, array.get(patternArray, 4) and is_1_618_to_2_618)
//Shark
array.set(patternArray, 5, array.get(patternArray, 5) and isInRange(bcdRatio, 1.618*err_min, 2.236*err_max))
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and is_1_272_to_2_000)
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_1_618_to_2_618)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and is_1_618_to_2_618)
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_1_618_to_2_618)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and is_1_618_to_2_618)
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and isInRange(bcdRatio, 1.272*err_min, 1.272*err_max))
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and isInRange(bcdRatio, 2.000*err_min, 2.618*err_max))
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and isInRange(bcdRatio, 1.618*err_min, 1.618*err_max))
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(bcdRatio, 0.886*err_min, 3.618*err_max))
//5-0
array.set(patternArray, 16, array.get(patternArray, 16) and isInRange(bcdRatio, 0.5*err_min, 0.5*err_max))
//Three Drives
array.set(patternArray, 17, array.get(patternArray, 17) and isInRange(bcdRatio, 0.618*err_min, 0.786*err_max))
//White Swan
array.set(patternArray, 18, array.get(patternArray, 18) and isInRange(bcdRatio, 0.5*err_min, 0.886*err_max))
//Black Swan
array.set(patternArray, 19, array.get(patternArray, 19) and isInRange(bcdRatio, 1.128*err_min, 2.0*err_max))
//Sea Pony
array.set(patternArray, 20, array.get(patternArray, 20) and isInRange(bcdRatio, 1.618*err_min, 2.618*err_max))
//Leonardo
array.set(patternArray, 21, array.get(patternArray, 21) and isInRange(bcdRatio, 1.128*err_min, 2.618*err_max))
//121
array.set(patternArray, 22, array.get(patternArray, 22) and isInRange(bcdRatio, 0.382*err_min, 0.786*err_max))
//Snorm
array.set(patternArray, 23, array.get(patternArray, 23) and isInRange(bcdRatio,0.9*err_min, 1.1*err_max))
//Total
array.set(patternArray, 24, array.get(patternArray, 24) and isInRange(bcdRatio, 1.272*err_min, 4.236*err_max))
scan_xad_xcd(float xadRatio, float xcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_1_618_to_1_618 = isInRange(xadRatio, 1.618*err_min, 1.618*err_max)
is_0_786_to_0_786 = isInRange(xadRatio, 0.786*err_min, 0.786*err_max)
is_0_886_to_0_886 = isInRange(xadRatio, 0.886*err_min, 0.886*err_max)
is_1_272_to_1_272 = isInRange(xadRatio, 1.272*err_min, 1.272*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and is_0_786_to_0_786)
//Crab
array.set(patternArray, 1, array.get(patternArray, 1) and is_1_618_to_1_618)
//DeepCrab
array.set(patternArray, 2, array.get(patternArray, 2) and is_1_618_to_1_618)
//Bat
array.set(patternArray, 3, array.get(patternArray, 3) and is_0_886_to_0_886)
//Butterfly
array.set(patternArray, 4, array.get(patternArray, 4) and isInRange(xadRatio, 1.272, 1.618))
//Shark
array.set(patternArray, 5, array.get(patternArray, 5) and is_0_886_to_0_886)
//Cypher
array.set(patternArray, 6, array.get(patternArray, 6) and isInRange(xcdRatio, 0.786*err_min, 0.786*err_max))
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and is_1_272_to_1_272)
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_0_786_to_0_786)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and isInRange(xadRatio, 1.13*err_min, 1.13*err_max))
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_1_272_to_1_272)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and isInRange(xadRatio, 0.618*err_min, 0.618*err_max))
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and isInRange(xadRatio, 0.618*err_min, 0.786*err_max))
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and isInRange(xadRatio, 1.128*err_min, 1.128*err_max))
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and isInRange(xadRatio, 1.272*err_min, 1.272*err_max))
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(xadRatio, 0.886, 1.127))
//5-0
array.set(patternArray, 16, array.get(patternArray, 16) and isInRange(xadRatio, 0.886, 1.13))
//Three Drives
array.set(patternArray, 17, array.get(patternArray, 17) and isInRange(xadRatio, 0.13, 0.886))
//White Swan
array.set(patternArray, 18, array.get(patternArray, 18) and isInRange(xadRatio, 0.236, 0.886))
//Black Swan
array.set(patternArray, 19, array.get(patternArray, 19) and isInRange(xadRatio, 1.128, 2.618))
//Sea Pony
array.set(patternArray, 20, array.get(patternArray, 20) and isInRange(xadRatio, 0.618, 3.618))
//Leonardo
array.set(patternArray, 21, array.get(patternArray, 21) and isInRange(xadRatio, 0.786*err_min, 0.786*err_max))
//121
array.set(patternArray, 22, array.get(patternArray, 22) and isInRange(xadRatio, 0.382, 0.786))
//Snorm
array.set(patternArray, 23, array.get(patternArray, 23) and isInRange(xadRatio, 0.618, 1.618))
//Total
array.set(patternArray, 24, array.get(patternArray, 24) and isInRange(xadRatio, 0.618, 1.618))
// @function Provides PRZ range based on BCD and XAD ranges
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param patternArray Pattern flags for which PRZ range needs to be calculated
// @param errorPercent Error threshold
// @param start_adj - Adjustments for entry levels
// @param end_adj - Adjustments for stop levels
// @returns [dStart, dEnd] Start and end of consolidated PRZ range
export get_prz_range(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent = 8, simple float start_adj=0, simple float end_adj=0)=>
startRange = array.new_float(array.size(patternArray), na)
endRange = array.new_float(array.size(patternArray), na)
if(array.includes(patternArray, true))
//Gartley
getrange(x, a, 0.786, 0.786, b, c, 1.272, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0)
//Crab
getrange(x, a, 1.618, 1.618, b, c, 2.240, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1)
//DeepCrab
getrange(x, a, 1.618, 1.618, b, c, 2.000, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2)
//Bat
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3)
//Butterfly
getrange(x, a, 1.272, 1.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4)
//Shark
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5)
//Cypher
getrange(x, c, 0.786, 0.786, x, c, 0.786, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6)
//NenStar
getrange(x, a, 1.272, 1.272, b, c, 1.272, 2.000, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7)
//Anti NenStar
getrange(x, a, 0.786, 0.786, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8)
//Anti Shark
getrange(x, a, 1.130, 1.130, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9)
//Anti Cypher
getrange(x, a, 1.272, 1.272, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10)
//Anti Crab
getrange(x, a, 0.618, 0.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11)
//Anti Butterfly
getrange(x, a, 0.618, 0.786, b, c, 1.272, 1.272, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12)
//Anti Bat
getrange(x, a, 1.128, 1.128, b, c, 2.000, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13)
//Anti Gartley
getrange(x, a, 1.272, 1.272, b, c, 1.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14)
//Navarro200
getrange(x, a, 0.886, 1.127, b, c, 0.886, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15)
//5-0
getrange(x, a, 0.886, 1.13, b, c, 0.5, 0.5, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 16)
//Three Drives
getrange(x, a, 0.13, 1.886, b, c, 0.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 17)
//White Swan
getrange(x, a, 0.236, 0.886, b, c, 0.5, 0.886, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 18)
//Black Swan
getrange(x, a, 1.128, 2.618, b, c, 1.128, 2.0, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 19)
//Sea Pony
getrange(x, a, 0.618, 3.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 20)
//Leonardo
getrange(x, a, 0.786, 0.786, b, c, 1.128, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 21)
//121
getrange(x, a, 0.382, 0.786, b, c, 0.382, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 22)
//Snorm
getrange(x, a, 0.618, 1.618, b, c, 0.9, 1.1, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 23)
//Total
getrange(x, a, 0.618, 1.618, b, c, 1.272, 4.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 24)
dStart = b > c? array.min(startRange) : array.max(startRange)
dEnd = b > c? array.max(endRange) : array.min(endRange)
[dStart, dEnd]
// @function Provides PRZ range based on XAD range only
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param patternArray Pattern flags for which PRZ range needs to be calculated
// @param errorPercent Error threshold
// @param start_adj - Adjustments for entry levels
// @param end_adj - Adjustments for stop levels
// @returns [dStart, dEnd] Start and end of consolidated PRZ range
export get_prz_range_xad(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent = 8, simple float start_adj=0, simple float end_adj=0)=>
startRange = array.new_float(array.size(patternArray), na)
endRange = array.new_float(array.size(patternArray), na)
if(array.includes(patternArray, true))
//Gartley
getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0)
//Crab
getrange(x, a, 1.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1)
//DeepCrab
getrange(x, a, 1.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2)
//Bat
getrange(x, a, 0.886, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3)
//Butterfly
getrange(x, a, 1.272, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4)
//Shark
getrange(x, a, 0.886, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5)
//Cypher
getrange(x, c, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6)
//NenStar
getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7)
//Anti NenStar
getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8)
//Anti Shark
getrange(x, a, 1.130, 1.130, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9)
//Anti Cypher
getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10)
//Anti Crab
getrange(x, a, 0.618, 0.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11)
//Anti Butterfly
getrange(x, a, 0.618, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12)
//Anti Bat
getrange(x, a, 1.128, 1.128, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13)
//Anti Gartley
getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14)
//Navarro200
getrange(x, a, 0.886, 1.127, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15)
//5-0
getrange(x, a, 0.886, 1.130, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 16)
//Three Drives
getrange(x, a, 0.130, 1.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 17)
//White Swan
getrange(x, a, 0.236, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 18)
//Black Swan
getrange(x, a, 1.128, 2.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 19)
//Sea Pony
getrange(x, a, 0.618, 3.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 20)
//Leonardo
getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 21)
//121
getrange(x, a, 0.382, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 22)
//Snorm
getrange(x, a, 0.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 23)
//Total
getrange(x, a, 0.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 24)
dStart = b > c? array.min(startRange) : array.max(startRange)
dEnd = b > c? array.max(endRange) : array.min(endRange)
[dStart, dEnd]
// @function Provides Projection range based on BCD and XAD ranges
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param patternArray Pattern flags for which PRZ range needs to be calculated
// @param errorPercent Error threshold
// @param start_adj - Adjustments for entry levels
// @param end_adj - Adjustments for stop levels
// @returns [startRange, endRange] Array containing start and end ranges
export get_projection_range(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent = 8, simple float start_adj=0, simple float end_adj=0)=>
startRange = array.new_float(array.size(patternArray), na)
endRange = array.new_float(array.size(patternArray), na)
if(array.includes(patternArray, true))
//Gartley
getrange(x, a, 0.786, 0.786, b, c, 1.272, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0)
//Crab
getrange(x, a, 1.618, 1.618, b, c, 2.240, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1)
//DeepCrab
getrange(x, a, 1.618, 1.618, b, c, 2.000, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2)
//Bat
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3)
//Butterfly
getrange(x, a, 1.272, 1.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4)
//Shark
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5)
//Cypher
getrange(x, c, 0.786, 0.786, x, c, 0.786, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6)
//NenStar
getrange(x, a, 1.272, 1.272, b, c, 1.272, 2.000, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7)
//Anti NenStar
getrange(x, a, 0.786, 0.786, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8)
//Anti Shark
getrange(x, a, 1.130, 1.130, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9)
//Anti Cypher
getrange(x, a, 1.272, 1.272, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10)
//Anti Crab
getrange(x, a, 0.618, 0.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11)
//Anti Butterfly
getrange(x, a, 0.618, 0.786, b, c, 1.272, 1.272, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12)
//Anti Bat
getrange(x, a, 1.128, 1.128, b, c, 2.000, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13)
//Anti Gartley
getrange(x, a, 1.272, 1.272, b, c, 1.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14)
//Navarro200
getrange(x, a, 0.886, 1.127, b, c, 0.886, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15)
//5-0
getrange(x, a, 0.886, 1.13, b, c, 0.5, 0.5, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 16)
//Three Drives
getrange(x, a, 0.13, 1.886, b, c, 0.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 17)
//White Swan
getrange(x, a, 0.236, 0.886, b, c, 0.5, 0.886, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 18)
//Black Swan
getrange(x, a, 1.128, 2.618, b, c, 1.128, 2.0, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 19)
//Sea Pony
getrange(x, a, 0.618, 3.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 20)
//Leonardo
getrange(x, a, 0.786, 0.786, b, c, 1.128, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 21)
//121
getrange(x, a, 0.382, 0.786, b, c, 0.382, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 22)
//Snorm
getrange(x, a, 0.618, 1.618, b, c, 0.9, 1.1, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 23)
//Total
getrange(x, a, 0.618, 1.618, b, c, 1.272, 4.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 24)
[startRange, endRange]
// @function Checks for harmonic patterns
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param d D coordinate value
// @param flags flags to check patterns. Send empty array to enable all
// @param errorPercent Error threshold
// @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
export isHarmonicPattern(float x, float a, float b, float c, float d,
simple bool[] flags, simple bool defaultEnabled = true, simple int errorPercent = 8)=>
numberOfPatterns = getNumberOfSupportedPatterns()
err_min = (100 - errorPercent) / 100
err_max = (100 + errorPercent) / 100
xabRatio = (b - a) / (x - a)
abcRatio = (c - b) / (a - b)
axcRatio = (c - x) / (a - x)
bcdRatio = (d - c) / (b - c)
xadRatio = (d - a) / (x - a)
xcdRatio = (d - c) / (x - c)
patternArray = array.new_bool()
for i=0 to numberOfPatterns-1
array.push(patternArray, array.size(flags)>i ? array.get(flags, i) : defaultEnabled)
scan_xab(xabRatio, err_min, err_max, patternArray)
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray)
scan_bcd(bcdRatio, err_min, err_max, patternArray)
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray)
patternArray
// @function Checks for harmonic pattern projection
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param flags flags to check patterns. Send empty array to enable all
// @param errorPercent Error threshold
// @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
export isHarmonicProjection(float x, float a, float b, float c,
simple bool[] flags, simple bool defaultEnabled = true, simple int errorPercent = 8)=>
numberOfPatterns = getNumberOfSupportedPatterns()
err_min = (100 - errorPercent) / 100
err_max = (100 + errorPercent) / 100
xabRatio = (b - a) / (x - a)
abcRatio = (c - b) / (a - b)
axcRatio = (c - x) / (a - x)
patternArray = array.new_bool()
for i=0 to numberOfPatterns-1
array.push(patternArray, array.size(flags)>i ? array.get(flags, i) : defaultEnabled)
scan_xab(xabRatio, err_min, err_max, patternArray)
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray)
patternArray |
Strategy | https://www.tradingview.com/script/mCOgJC67-Strategy/ | TradingView | https://www.tradingview.com/u/TradingView/ | 518 | library | 5 | MPL-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
// @description This library contains strategy helper functions that assist in various positional calculations such as PnL, percent, ticks, price, or currency.
library("Strategy", true)
// ———————————————————— Library functions {
// @function Converts a percentage of the supplied price or the average entry price to ticks.
// @param percent (series int/float) The percentage of supplied price to convert to ticks. 50 is 50% of the entry price.
// @param from (series int/float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
// @returns (float) A value in ticks.
export percentToTicks(series float percent, series float from = strategy.position_avg_price) =>
strategy.position_size != 0 ? percent / 100 * from / syminfo.mintick : float(na)
// @function Converts a percentage of the supplied price or the average entry price to a price.
// @param percent (series int/float) The percentage of the supplied price to convert to price. 50 is 50% of the supplied price.
// @param from (series int/float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
// @returns (float) A value in the symbol's quote currency (USD for BTCUSD).
export percentToPrice(series float percent, series float from = strategy.position_avg_price) =>
strategy.position_size != 0 ? (1 + percent / 100) * from : float(na)
// @function Converts the percentage of a price to money.
// @param price (series int/float) The symbol's price.
// @param percent (series int/float) The percentage of `price` to calculate.
// @returns (float) A value in the symbol's currency.
export percentToCurrency(series float price, series float percent) =>
price * percent / 100 * syminfo.pointvalue
// @function Calculates the profit (as a percentage of the position's `strategy.position_avg_price` entry price) if the trade is closed at `exitPrice`.
// @param exitPrice (series int/float) The potential price to close the position.
// @returns (float) Percentage profit for the current position if closed at the `exitPrice`.
export percentProfit(series float exitPrice) =>
if strategy.position_size != 0
(exitPrice - strategy.position_avg_price) / strategy.position_avg_price * math.sign(strategy.position_size) * 100
else
float(na)
// @function Converts a price to ticks.
// @param price (series int/float) Price to convert to ticks.
// @returns (float) A quantity of ticks.
export priceToTicks(series float price) =>
price / syminfo.mintick
// @function Converts ticks to a price offset from the supplied price or the average entry price.
// @param ticks (series int/float) Ticks to convert to a price.
// @param from (series int/float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
// @returns (float) A price level that has a distance from the entry price equal to the specified number of ticks.
export ticksToPrice(series float ticks, series float from = strategy.position_avg_price) =>
float offset = ticks * syminfo.mintick
strategy.position_size != 0 ? from + offset : float(na)
// @function Converts ticks to money.
// @param ticks (series int/float) Number of ticks.
// @returns (float) Money amount in the symbol's currency.
export ticksToCurrency(series float ticks) =>
ticks * syminfo.mintick * syminfo.pointvalue
// @function Calculates a stop loss level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `stop` parameter of a `strategy.exit()` call. NOTE: The stop level automatically flips based on whether the position is long or short.
// @param ticks (series int/float) The distance in ticks from the entry price to the stop loss level.
// @returns (float) A stop loss level for the current position.
export ticksToStopLevel(series float ticks) =>
ticksToPrice(-ticks * math.sign(strategy.position_size))
// @function Calculates a take profit level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `limit` parameter of a `strategy.exit()` call. NOTE: The take profit level automatically flips based on whether the position is long or short.
// @param ticks (series int/float) The distance in ticks from the entry price to the take profit level.
// @returns (float) A take profit level for the current position.
export ticksToTpLevel(series float ticks) =>
ticksToPrice(ticks * math.sign(strategy.position_size))
// @function Calculates the position size needed to implement a given stop loss (in ticks) corresponding to `riskPercent` of equity.
// @param stopLossTicks (series int) The stop loss (in ticks) that will be used to protect the position.
// @param riskPercent (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
// @returns (int) A quantity of contracts.
export calcPositionSizeByStopLossTicks(series int stopLossTicks, series float riskPercent) =>
float risk = strategy.equity * riskPercent / 100
math.floor(risk / ticksToCurrency(stopLossTicks))
// @function Calculates the position size needed to implement a given stop loss (%) corresponding to `riskPercent` of equity.
// @param stopLossPercent (series int/float) The stop loss in percent that will be used to protect the position.
// @param riskPercent (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
// @param entryPrice (series int/float) The entry price of the position.
// @returns (int) A quantity of contracts.
export calcPositionSizeByStopLossPercent(series float stopLossPercent, series float riskPercent, series float entryPrice = close) =>
float risk = strategy.equity * riskPercent / 100
math.floor(risk / percentToCurrency(entryPrice, stopLossPercent))
// @function A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit as a value in percent. NOTE: this function may work incorrectly with pyramiding turned on due to the use of `strategy.position_avg_price` in its calculations of stop loss and take profit offsets.
// @param id (series string) The order identifier of the `strategy.exit()` call.
// @param lossPercent (series int/float) Stop loss as a percent of the entry price.
// @param profitPercent (series int/float) Take profit as a percent of the entry price.
// @param qty (series int/float) Number of contracts/shares/lots/units to exit a trade with. Optional. The default value is `na`.
// @param qtyPercent (series int/float) The percent of the position's size to exit a trade with. If `qty` is `na`, the default value of `qty_percent` is 100.
// @param comment (series string) Optional. Additional notes on the order.
// @param when (series bool) Condition of the order. The order is placed if it is true.
// @param alertMessage (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @returns (void)
export exitPercent(series string id = "Exit",
series float lossPercent ,
series float profitPercent ,
series float qty = na ,
series float qtyPercent = na ,
series string comment = na ,
series bool when = true ,
series string alertMessage = na ) =>
strategy.exit(id, qty = qty, qty_percent = qtyPercent, loss = math.ceil(percentToTicks(lossPercent)), profit = math.round(percentToTicks(profitPercent)), comment = comment, when = when, alert_message = alertMessage)
// @function A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit as a value in ticks.
// @param id (series string) The order identifier of the `strategy.exit()` call.
// @param lossTicks (series int/float) Loss in ticks.
// @param profitTicks (series int/float) Profit in ticks.
// @param qty (series int/float) Number of contracts/shares/lots/units to exit a trade with. Optional. The default value is `na`.
// @param qtyPercent (series int/float) The percent of the position's size to exit a trade with. If `qty` is `na`, the default value of `qty_percent` is 100.
// @param comment (series string) Optional. Additional notes on the order.
// @param when (series bool) Condition of the order. The order is placed if it is true.
// @param alertMessage (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @returns (void)
export exitTicks(series string id = "Exit",
series float lossTicks ,
series float profitTicks ,
series float qty = na ,
series float qtyPercent = na ,
series string comment = na ,
series bool when = true ,
series string alertMessage = na ) =>
strategy.exit(id, qty = qty, qty_percent = qtyPercent, loss = lossTicks * syminfo.mintick, profit = profitTicks * syminfo.mintick, comment = comment, when = when, alert_message = alertMessage)
// @function A wrapper of the `strategy.close_all()` built-in which closes all positions on the close of the last bar of the trading session.
// @param comment (series string) Optional. Additional notes on the order.
// @param alertMessage (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @returns (void) Closes all positions on the `close` of the last bar of the trading session, instead of the `open` of the next session.
export closeAllAtEndOfSession(series string comment = na, series string alertMessage = na) =>
if session.islastbar and barstate.isconfirmed
strategy.close_all(comment = comment, alert_message = alertMessage, immediately = true)
// @function A wrapper of the `strategy.close()` built-in which closes the position matching the `entryId` on the close of the last bar of the trading session.
// @param entryId (series string) A required parameter. The order identifier. It is possible to close an order by referencing its identifier.
// @param comment (series string) Optional. Additional notes on the order.
// @param alertMessage (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @returns (void) Closes `entryId` on the `close` of the last bar of the trading session, instead of the `open` of the next session.
export closeAtEndOfSession(series string entryId, series string comment = na, series string alertMessage = na) =>
if session.islastbar and barstate.isconfirmed
strategy.close(entryId, comment, alert_message = alertMessage, immediately = true)
days(series int t) =>
int result = math.floor(t / 86400000.0 + 2440587.5)
months(series int t) =>
int result = year(t) * 12 + month(t)
numberOfPeriodsInYear(series bool useMonths) =>
int result = useMonths ? 12 : 365
numberOfPeriods(series int prevT, series int curT, series bool useMonths) =>
int result = useMonths ? (months(curT) - months(prevT)) : (days(curT) - days(prevT))
addPeriodsReturns(series int prevTime, series int xTime, series float profit, series bool useMonths, series float[] periodsReturn) =>
int periods = numberOfPeriods(prevTime, xTime, useMonths)
if periods > 0
for j = 0 to periods - 1
array.push(periodsReturn, 0)
if array.size(periodsReturn) == 0
array.push(periodsReturn, 0)
int lastIdx = array.size(periodsReturn) - 1
float periodProfit = array.get(periodsReturn, lastIdx) + profit
array.set(periodsReturn, lastIdx, periodProfit)
int result = xTime
interestRatePerPeriod(series float interestRateYearlyPercent, series bool useMonths) =>
float result = interestRateYearlyPercent / numberOfPeriodsInYear(useMonths) / 100
periodsReturnsPercent(series bool useMonths) =>
float[] periodsReturn = array.new<float>()
if strategy.closedtrades > 0
int prevTime = strategy.closedtrades.entry_time(0)
for i = 0 to strategy.closedtrades - 1
prevTime := addPeriodsReturns(prevTime, strategy.closedtrades.exit_time(i), strategy.closedtrades.profit(i), useMonths, periodsReturn)
if strategy.opentrades > 0
for i = 0 to strategy.opentrades - 1
int prevTime = strategy.opentrades.entry_time(0)
addPeriodsReturns(prevTime, time, strategy.opentrades.profit(i), useMonths, periodsReturn)
while array.size(periodsReturn) > 0
if array.get(periodsReturn, array.size(periodsReturn) - 1) == 0
array.pop(periodsReturn)
else
break
float[] periodsReturnPercent = array.new<float>()
float cum = strategy.initial_capital
for pR in periodsReturn
float pp = cum == 0 ? 0 : pR / cum
cum += pR
array.push(periodsReturnPercent, pp)
float[] result = periodsReturnPercent
downsideDeviation(float[] returns, series float targetReturn) =>
int count = 0
float sum = 0
for r in returns
float rr = math.min(0, r - targetReturn)
sum += rr * rr
count += 1
sum /= count
float result = 0 < sum ? math.sqrt(sum) : na
sortinoRatioImpl(series bool useMonths, simple float interestRate) =>
float[] periodsReturnPcnt = periodsReturnsPercent(useMonths)
float minRateOfReturn = interestRatePerPeriod(interestRate, useMonths)
float dd = downsideDeviation(periodsReturnPcnt, minRateOfReturn)
if not na(dd)
float avgPP = array.avg(periodsReturnPcnt)
float result = not na(avgPP) ? (avgPP - minRateOfReturn) / dd : na
else
na
sharpeRatioImpl(series bool useMonths, simple float interestRate) =>
float[] periodsReturnPcnt = periodsReturnsPercent(useMonths)
float minRateOfReturn = interestRatePerPeriod(interestRate, useMonths)
float stdev = array.stdev(periodsReturnPcnt)
if not na(stdev)
float avgPP = array.avg(periodsReturnPcnt)
float result = not na(avgPP) ? (avgPP - minRateOfReturn) / stdev : na
else
na
detectPeriod() =>
int start = strategy.closedtrades > 0 ? strategy.closedtrades.entry_time(0) : strategy.opentrades > 0 ? strategy.opentrades.entry_time(0) : int(na)
int end = strategy.opentrades > 0 ? time_close : strategy.closedtrades > 0 ? strategy.closedtrades.exit_time(strategy.closedtrades - 1) : int(na)
if not(na(start) or na(end))
int daysDiff = days(end) - days(start)
int monthsDiff = math.floor(daysDiff/30)
bool result = monthsDiff > 2 ? true : daysDiff > 2 ? false : bool(na)
// @function Calculates the Sortino Ratio for the trading period.
// @param interestRate (simple int/float) The benchmark "risk-free" rate of return to compare strategy risk against in the ratio.
// @param forceCalc (series bool) When `true`, forces a recalculation on each bar. Optional. The default is `false`, whereby calculations are performed only on the last bar, for efficiency.
// @returns (float) The Sortino Ratio. Useful for measuring the risk-adjusted return of a strategy, taking into account only drawdowns.
export sortinoRatio(simple float interestRate = 2.0, series bool forceCalc = false) =>
if barstate.islastconfirmedhistory or barstate.islast or forceCalc
bool useMonths = detectPeriod()
float result = not na(useMonths) ? sortinoRatioImpl(useMonths, interestRate) : na
// @function Calculates the Sharpe Ratio for the trading period.
// @param interestRate (simple int/float) The benchmark "risk-free" rate of return to compare strategy risk against in the ratio.
// @param forceCalc (series bool) When `true`, forces a recalculation on each bar. Optional. The default is `false`, whereby calculations are performed only on the last bar, for efficiency.
// @returns (float) The Sharpe Ratio. Useful for measuring the risk-adjusted return of a strategy, taking into account both run-ups and drawdowns.
export sharpeRatio(simple float interestRate = 2.0, series bool forceCalc = false) =>
if barstate.islastconfirmedhistory or barstate.islast or forceCalc
bool useMonths = detectPeriod()
float result = not na(useMonths) ? sharpeRatioImpl(useMonths, interestRate) : na
// }
// ———————————————————— Example code {
// —————————— Calculations
// Inputs for stop and limit orders in percent.
float percentStop = input.float(1.0, "Percent Stop", minval = 0.0, step = 0.25, group = "Exit Orders")
float percentTP = input.float(2.0, "Percent Limit", minval = 0.0, step = 0.25, group = "Exit Orders")
// Using the input stop/ limit percent, we can convert to ticks and use the ticks to level functions.
// This can be used to calculate the take profit and stop levels.
float sl = ticksToStopLevel (percentToTicks (percentStop))
float tp = ticksToTpLevel (percentToTicks (percentTP))
// Conditions used to reference position and determine trade bias
bool long = strategy.position_size > 0
bool short = strategy.position_size < 0
bool enterLong = long and not long [1]
bool enterShort = short and not short[1]
bool enter = enterLong or enterShort
bool exit = strategy.position_size == 0 and not (strategy.position_size == 0)[1]
// Condition to flip labels based on trade bias.
string stopStyle = short ? label.style_label_up : label.style_label_down
string limitStyle = long ? label.style_label_up : label.style_label_down
// Used to determine the exit price to draw an arrow for stop and limit exits
// and determine a color for the arrow (fuchsia for stop exits, lime for limits).
// We can use the trade bias as a multiplier to invert the condition for short trades.
exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades-1)
bias = math.sign(strategy.position_size)
avg = strategy.position_avg_price
plotCol = exitPrice * bias[1] < avg[1] * bias[1] ? color.fuchsia : color.lime
// —————————— Strategy Calls
// Calculate two moving averages.
float maFast = ta.sma(close, 10)
float maSlow = ta.sma(close, 30)
// Create cross conditions for the averages.
bool longCondition = ta.crossover(maFast, maSlow)
bool shortCondition = ta.crossunder(maFast, maSlow)
// Create entries based on the cross conditions for both trades biases.
if longCondition
strategy.entry("My Long Entry Id", strategy.long)
if shortCondition
strategy.entry("My Short Entry Id", strategy.short)
// Create a hard exit level for a take profit and stop loss.
// Using the `strategy.exit` wrapper function, we can simply specify the percent stop and limit using the input variables.
exitPercent("exit", percentStop, percentTP)
// Another option is to use the "ticksToLevel" functions with the percent to ticks functions to convert percent directly to the stop or limit level:
// strategy.exit("exit", stop = ticksToStopLevel (percentToTicks (percentStop)), limit = ticksToTpLevel (percentToTicks (percentTP)), comment = "exit")
// —————————— Plots
// Plot the entry level.
plot(strategy.position_avg_price, "strategy.position_avg_price", not enter ? color.new(color.orange, 60) : na, 2, plot.style_linebr)
// Plot the exit levels.
plot(sl, "Stop2", not enter ? color.new(color.fuchsia, 60) : na, 6, plot.style_linebr)
plot(tp, "TP2" , not enter ? color.new(color.green, 60) : na, 6, plot.style_linebr)
// Plot an entry tag for both directions
plotshape(enterLong, "longCondition", shape.arrowup, location.belowbar, color.new(color.green, 30), text = "Long")
plotshape(enterShort, "shortCondition", shape.arrowdown, location.abovebar, color.new(color.fuchsia, 30), text = "Short")
// Plot and arrow for stop or limit exits at the trade exit price. We use the price and the color from above.
plotchar(exit ? exitPrice : na, "Exit Arrow", "◄", location.absolute, color.new(plotCol, 20))
// Plot labels using the percentProfit() functions to display the distance from entry to the level for the current trade
label labLimit = label.new(bar_index, sl, str.tostring(percentProfit(sl), format.percent), color = color.new(color.red, 70), style = limitStyle, textcolor = color.white)
label labStop = label.new(bar_index, tp, str.tostring(percentProfit(tp), format.percent), color = color.new(color.green, 70), style = stopStyle, textcolor = color.white)
// We delete the labels drawn one bar ago, or we end up with many labels drawn
label.delete(labLimit[1])
label.delete(labStop [1])
// Show ratios in indicator values and the Data Window.
plotchar(sortinoRatio(2.0), "Sortino", "", location.top, size = size.tiny)
plotchar(sharpeRatio(2.0), "Sharpe", "", location.top, size = size.tiny)
// }
|
Adaptive_Length | https://www.tradingview.com/script/XLRrjMZR-Adaptive-Length/ | MightyZinger | https://www.tradingview.com/u/MightyZinger/ | 49 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MightyZinger
//@version=5
// @description This library contains functions to calculate Adaptive dynamic length which can be used in Moving Averages and other indicators.
library("Adaptive_Length")
// @function Adaptive dynamic length based on boolean parameter
// @param para Boolean parameter; if true then length would decrease and would increase if its false
// @param adapt_Pct Percentage adaption based on parameter
// @param minLength Minimum allowable length
// @param maxLength Maximum allowable length
// @returns Adaptive Dynamic Length based on Boolean Parameter
export dynamic(bool para, float adapt_Pct, simple int minLength, simple int maxLength) =>
var dyna_len = int(na)
var float i_len = math.avg(minLength, maxLength)
i_len := para ? math.max(minLength, i_len * adapt_Pct) : math.min(maxLength, i_len * (2-adapt_Pct))
dyna_len := int(i_len)
dyna_len
// @function Adaptive dynamic length based on two boolean parameters for increasing and decreasing dynamic length seperatally with more precision
// @param up_para Boolean parameter; if true then length would decrease
// @param dn_para Boolean parameter; if true then length would increase
// @param adapt_Pct Percentage adaption based on parameter
// @param minLength Minimum allowable length
// @param maxLength Maximum allowable length
// @returns Adaptive Dynamic Length based on Two Boolean Parameters for increasing and decreasing dynamic length seperatally with more precision
export dynamic_2(bool up_para, bool dn_para, float adapt_Pct, simple int minLength, simple int maxLength) =>
var _dyna_len = int(na)
var float i_len = math.avg(minLength, maxLength)
i_len := up_para and not dn_para ? math.max(minLength, i_len * adapt_Pct) :
dn_para and not up_para ? math.min(maxLength, i_len * (2-adapt_Pct)) : nz(i_len[1])
_dyna_len := int(i_len)
_dyna_len
med(x,y,z) => (x+y+z) - math.min(x,math.min(y,z)) - math.max(x,math.max(y,z))
// @function Adaptive length based automatic alpha calculations from source input
// @param src Price source for alpha calculations
// @param a Input Alpha value
// @returns Adaptive Length calculated from input price Source and Alpha
export auto_alpha(float src, float a)=>
float ip = 0.0
s = (src + 2*src[1] + 2*src[2] + src[3])/6.0
float c = 0.0
var n = bar_index
c := n<7?(src - 2*src[1] + src[2])/4.0:((1 - 0.5*a)*(1 - 0.5*a)*(s - 2*s[1] + s[2]) + 2*(1-a)*c[1] - (1 - a)*(1-a)*c[2])
q1 = (.0962*c + 0.5769*c[2] - 0.5769*c[4] - .0962*c[6])*(0.5+.08*nz(ip[1]))
I1 = c[3]
dp_ = q1 != 0 and q1[1] != 0 ? (I1/q1 - I1[1]/q1[1]) / (1 + I1*I1[1]/(q1*q1[1])) : 0
dp = dp_ < 0.1 ? 0.1 : dp_ > 1.1 ? 1.1 : dp_
md = med(dp,dp[1], med(dp[2], dp[3], dp[4]))
dc = md == 0 ? 15 : 6.28318 / md + 0.5
ip := .33*dc + .67*nz(ip[1])
int p = 0
p := int(.15*ip + .85*nz(p[1]))
p
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
///// Plots //////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
src = input.source(hlc3, 'Source')
string grp1 = 'MA Parameters'
AadaptPerc = input.float(96.85, minval=0, maxval=100, title='MA Dynamic Adapting Percentage:', group=grp1) / 100.0
MA1_min_Length = input.int(20, title='MA 1 Minimum Length:', group=grp1, inline = 'ma1')
MA1_max_Length = input.int(50, title='MA 1 Maximum Length:', group=grp1, inline = 'ma1')
MA2_Length = input.int(50, title='MA 2 Length:', group=grp1)
alpha_val = input(.07, title="Alpha", group=grp1)
MA3_min_Length = input.int(50, title='MA 3 Minimum Length:', group=grp1, inline = 'ma3')
MA3_max_Length = input.int(200, title='MA 3 Maximum Length:', group=grp1, inline = 'ma3')
import MightyZinger/Chikou/2 as filter
[c_col, _trend] = filter.chikou(src, 50, 50, high, low, color.green, color.red, color.yellow)
up_para = _trend == 1
dn_para = _trend == -1
dynamic_Length = dynamic(up_para , AadaptPerc , MA1_min_Length , MA1_max_Length)
auto_Length = auto_alpha(src, alpha_val)
dynamic_2_length = dynamic_2(up_para , dn_para, AadaptPerc , MA3_min_Length , MA3_max_Length)
_ema(src, length)=> // EMA with Series Int Support
var result = float(na)
result := (src - nz(result[1])) * (2.0 / (length + 1)) + nz(result[1])
result
ma1 = _ema(src, dynamic_Length)
ma2 = _ema(src, auto_Length)
ma3 = _ema(src, dynamic_2_length)
// MAs Plot
ma1_plot = plot(ma1, color= c_col , title="MA 1", linewidth=4)
ma2_plot = plot(ma2, color= c_col , title="MA 2", linewidth=2)
ma3_plot = plot(ma3, color= c_col , title="MA 3", linewidth=2)
plotchar(dynamic_Length, 'Dynamic Length', '', location.top, color.new(color.green, 0))
plotchar(auto_Length, 'Auto Alpha Length', '', location.top, color.new(color.lime, 0))
plotchar(dynamic_2_length, 'Dynamic_2 Length', '', location.top, color.new(color.yellow, 0))
/////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////// |
harmonicpatternsarrays | https://www.tradingview.com/script/XtQhV4Rr-harmonicpatternsarrays/ | CryptoArch_ | https://www.tradingview.com/u/CryptoArch_/ | 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/
// © CryptoArch_
//@version=5
// @description Library provides an alternative method to scan harmonic patterns and contains utility functions using arrays.
// These are mostly customized for personal use. Hence, will not add documentation for arrays. All credit to @HeWhoMustNotBeNamed
library("harmonicpatternsarrays")
//import HeWhoMustNotBeNamed/arrayutils/17 as pa
export getLabel(simple bool[] include, simple string[] labels)=>
labelText = ''
for i=0 to array.size(include)-1
labelText := labelText + (array.get(include, i) ? (labelText == '' ? '' : '\n') + array.get(labels, i) : '')
labelText
unshift_to_array(arr, val, maxItems)=>
array.insert(arr, 0, val)
if(array.size(arr) > maxItems)
array.pop(arr)
arr
push_to_array(arr, val, maxItems)=>
array.push(arr, val)
if(array.size(arr) > maxItems)
array.remove(arr, 0)
arr
export delete(simple line[] arr, int index)=>line.delete(array.remove(arr, index))
export delete(simple label[] arr, int index)=>label.delete(array.remove(arr, index))
export delete(simple box[] arr, int index)=>box.delete(array.remove(arr, index))
export delete(simple table[] arr, int index)=>table.delete(array.remove(arr, index))
export delete(simple linefill[] arr, int index)=>linefill.delete(array.remove(arr, index))
export pop(simple line[] arr)=>line.delete(array.pop(arr))
export pop(simple label[] arr)=>label.delete(array.pop(arr))
export pop(simple box[] arr)=>box.delete(array.pop(arr))
export pop(simple table[] arr)=>table.delete(array.pop(arr))
export pop(simple linefill[] arr)=>linefill.delete(array.pop(arr))
unshift_to_object_array(arr, val, maxItems)=>
array.insert(arr, 0, val)
if(array.size(arr) > maxItems)
pop(arr)
arr
export shift(simple line[] arr)=>line.delete(array.shift(arr))
export shift(simple label[] arr)=>label.delete(array.shift(arr))
export shift(simple box[] arr)=>box.delete(array.shift(arr))
export shift(simple table[] arr)=>table.delete(array.shift(arr))
export shift(simple linefill[] arr)=>linefill.delete(array.shift(arr))
push_to_object_array(arr, val, maxItems)=>
array.push(arr, val)
if(array.size(arr) > maxItems)
shift(arr)
arr
export unshift(simple int[] arr, int val, simple int maxItems)=>unshift_to_array(arr, val, maxItems)
export unshift(simple float[] arr, float val, simple int maxItems)=>unshift_to_array(arr, val, maxItems)
export unshift(simple bool[] arr, bool val, simple int maxItems)=>unshift_to_array(arr, val, maxItems)
export unshift(simple string[] arr, string val, simple int maxItems)=>unshift_to_array(arr, val, maxItems)
export unshift(simple color[] arr, color val, simple int maxItems)=>unshift_to_array(arr, val, maxItems)
export unshift(simple line[] arr, line val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems)
export unshift(simple label[] arr, label val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems)
export unshift(simple box[] arr, box val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems)
export unshift(simple table[] arr, table val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems)
export unshift(simple linefill[] arr, linefill val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems)
clear_array_objects(arr)=>
len = array.size(arr)-1
for i=0 to len >=0 ? len:na
pop(arr)
export clear(simple line[] arr)=>clear_array_objects(arr)
export clear(simple label[] arr)=>clear_array_objects(arr)
export clear(simple box[] arr)=>clear_array_objects(arr)
export clear(simple table[] arr)=>clear_array_objects(arr)
export clear(simple linefill[] arr)=>clear_array_objects(arr)
export push(simple int[] arr, int val, simple int maxItems)=>push_to_array(arr, val, maxItems)
export push(simple float[] arr, float val, simple int maxItems)=>push_to_array(arr, val, maxItems)
export push(simple bool[] arr, bool val, simple int maxItems)=>push_to_array(arr, val, maxItems)
export push(simple string[] arr, string val, simple int maxItems)=>push_to_array(arr, val, maxItems)
export push(simple color[] arr, color val, simple int maxItems)=>push_to_array(arr, val, maxItems)
export push(simple line[] arr, line val, simple int maxItems)=>push_to_object_array(arr, val, maxItems)
export push(simple label[] arr, label val, simple int maxItems)=>push_to_object_array(arr, val, maxItems)
export push(simple box[] arr, box val, simple int maxItems)=>push_to_object_array(arr, val, maxItems)
export push(simple table[] arr, table val, simple int maxItems)=>push_to_object_array(arr, val, maxItems)
export push(simple linefill[] arr, linefill val, simple int maxItems)=>push_to_object_array(arr, val, maxItems)
export get_trend_series(float[] pivots, int firstIndex, int lastIndex)=>
startIndex = firstIndex
endIndex = math.min(array.size(pivots), lastIndex)
trendIndexes = array.new_int()
if(startIndex+1 < endIndex)
first = array.get(pivots, startIndex)
sec = array.get(pivots, startIndex+1)
dir = first > sec? 1 : -1
min = array.slice(pivots, startIndex, endIndex)
while(array.size(min) > 1)
peak = (dir == 1? array.min(min) : array.max(min))
peakIndex = array.lastindexof(min, peak)
min := array.slice(pivots, startIndex, startIndex+peakIndex)
reversePeak = (dir == 1? array.max(min) : array.min(min))
if(reversePeak == first)
array.push(trendIndexes, startIndex+peakIndex)
trendIndexes
getadj(p1, p2, adj)=>math.max(0, p2 - (p2 - p1) * adj)
export getrange(float p1, float p2, simple float min1, simple float max1,
float p3, float p4, simple float min2, simple float max2,
simple float ep1, simple float ep2,
simple float adjs, simple float adje,
bool[] pArray, float[] startRange, float[] endRange, simple int index)=>
returnval = false
if(array.get(pArray, index))
eamin1 = (100 - (ep1+adjs)) / 100
eamax1 = (100 + ep1+adje) / 100
eamin2 = (100 - (ep2+adjs)) / 100
eamax2 = (100 + ep2+adje) / 100
start1 = getadj(p1, p2, min1*eamin1)
end1 = getadj(p1, p2, max1*eamax1)
start2 = getadj(p3, p4, min2*eamin2)
end2 = getadj(p3, p4, max2*eamax2)
start = start1 > end1? math.min(start1, start2) : math.max(start1, start2)
end = start1 > end1? math.max(end1, end2) : math.min(end1, end2)
d1 = start1>end1? 1 : -1
d2 = start2>end2? 1 : -1
d = start>end? 1 : -1
if(d1 == d2 and d == d1 and (start > 0 or end > 0))
returnval := true
array.set(startRange, index, start)
array.set(endRange, index, end)
else
array.set(pArray, index, false)
returnval
isInRange(ratio, min, max)=> ratio >= min and ratio <= max
isCypherProjection(float xabRatio, float axcRatio, simple float err_min=0.92, simple float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
axcMin = 1.13 * err_min
axcMax = 1.414 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(axcRatio, axcMin, axcMax)
isCypherPattern(float xabRatio, float axcRatio, float xcdRatio, simple float err_min=0.92, simple float err_max=1.08, enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
axcMin = 1.13 * err_min
axcMax = 1.414 * err_max
xcdMin = 0.786 * err_min
xcdMax = 0.786 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(axcRatio, axcMin, axcMax) and
isInRange(xcdRatio, xcdMin, xcdMax)
getNumberOfSupportedPatterns()=>16
// @function Returns the list of supported patterns in order
// @param patternLabelArray Supported Patterns
export getSupportedPatterns()=>
patternLabelArray = array.new_string()
array.push(patternLabelArray, "Gartley")
array.push(patternLabelArray, "Bat")
array.push(patternLabelArray, "Butterfly")
array.push(patternLabelArray, "Crab")
array.push(patternLabelArray, "DeepCrab")
array.push(patternLabelArray, "Cypher")
array.push(patternLabelArray, "Shark")
array.push(patternLabelArray, "NenStar")
array.push(patternLabelArray, "Anti NenStar")
array.push(patternLabelArray, "Anti Shark")
array.push(patternLabelArray, "Anti Cypher")
array.push(patternLabelArray, "Anti Crab")
array.push(patternLabelArray, "Anti Butterfly")
array.push(patternLabelArray, "Anti Bat")
array.push(patternLabelArray, "Anti Gartley")
array.push(patternLabelArray, "Navarro200")
patternLabelArray
// @function Checks if bcd ratio is in range of any harmonic pattern
// @param bcdRatio AB/XA ratio
// @param err_min minimum error threshold
// @param err_max maximum error threshold
// @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
export scan_xab(float xabRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_0_382_to_0_618 = isInRange(xabRatio, 0.382*err_min, 0.618*err_max)
is_0_446_to_0_618 = isInRange(xabRatio, 0.446*err_min, 0.618*err_max)
is_0_500_to_0_786 = isInRange(xabRatio, 0.500*err_min, 0.786*err_max)
is_0_618_to_0_786 = isInRange(xabRatio, 0.618*err_min, 0.786*err_max)
is_1_270_to_1_618 = isInRange(xabRatio, 1.270*err_min, 1.618*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and isInRange(xabRatio, 0.618*err_min, 0.618*err_max))
//Bat
array.set(patternArray, 1, array.get(patternArray, 1) and isInRange(xabRatio, 0.382*err_min, 0.500*err_max))
//Butterfly
array.set(patternArray, 2, array.get(patternArray, 2) and isInRange(xabRatio, 0.786*err_min, 0.786*err_max))
//Crab
array.set(patternArray, 3, array.get(patternArray, 3) and is_0_382_to_0_618)
//DeepCrab
array.set(patternArray, 4, array.get(patternArray, 4) and isInRange(xabRatio, 0.886*err_min, 0.886*err_max))
//Cypher
array.set(patternArray, 5, array.get(patternArray, 5) and is_0_382_to_0_618)
//Shark
array.set(patternArray, 6, array.get(patternArray, 6) and is_0_446_to_0_618)
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and is_0_382_to_0_618)
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_0_500_to_0_786)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and is_0_446_to_0_618)
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_0_500_to_0_786)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and isInRange(xabRatio, 0.276*err_min, 0.446*err_max))
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and is_0_382_to_0_618)
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and is_0_382_to_0_618)
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and is_0_618_to_0_786)
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(xabRatio, 0.382*err_min, 0.786*err_max))
// @function Checks if abc or axc ratio is in range of any harmonic pattern
// @param abcRatio BC/AB ratio
// @param axcRatio XC/AX ratio
// @param err_min minimum error threshold
// @param err_max maximum error threshold
// @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
export scan_abc_axc(float abcRatio, float axcRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_0_382_to_0_886 = isInRange(abcRatio, 0.382*err_min, 0.886*err_max)
is_0_467_to_0_707 = isInRange(abcRatio, 0.467*err_min, 0.707*err_max)
is_1_128_to_2_618 = isInRange(abcRatio, 1.128*err_min, 2.618*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and is_0_382_to_0_886)
//Bat
array.set(patternArray, 1, array.get(patternArray, 1) and is_0_382_to_0_886)
//Butterfly
array.set(patternArray, 2, array.get(patternArray, 2) and is_0_382_to_0_886)
//Crab
array.set(patternArray, 3, array.get(patternArray, 3) and is_0_382_to_0_886)
//DeepCrab
array.set(patternArray, 4, array.get(patternArray, 4) and is_0_382_to_0_886)
//Cypher
array.set(patternArray, 5, array.get(patternArray, 5) and isInRange(axcRatio, 1.130*err_min, 1.414*err_max))
//Shark
array.set(patternArray, 6, array.get(patternArray, 6) and isInRange(abcRatio, 1.130*err_min, 1.618*err_max))
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and isInRange(abcRatio, 1.414*err_min, 2.140*err_max))
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_0_467_to_0_707)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and isInRange(abcRatio, 0.618*err_min, 0.886*err_max))
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_0_467_to_0_707)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and is_1_128_to_2_618)
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and is_1_128_to_2_618)
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and is_1_128_to_2_618)
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and is_1_128_to_2_618)
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(abcRatio, 0.886*err_min, 1.127*err_max))
// @function Checks if bcd ratio is in range of any harmonic pattern
// @param bcdRatio CD/BC ratio
// @param err_min minimum error threshold
// @param err_max maximum error threshold
// @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
export scan_bcd(float bcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_1_618_to_2_618 = isInRange(bcdRatio, 1.618*err_min, 2.618*err_max)
is_1_272_to_1_618 = isInRange(bcdRatio, 1.272*err_min, 1.618*err_max)
is_1_272_to_2_000 = isInRange(bcdRatio, 1.272*err_min, 2.000*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and is_1_272_to_1_618)
//Bat
array.set(patternArray, 1, array.get(patternArray, 1) and is_1_618_to_2_618)
//Butterfly
array.set(patternArray, 2, array.get(patternArray, 2) and is_1_618_to_2_618)
//Crab
array.set(patternArray, 3, array.get(patternArray, 3) and isInRange(bcdRatio, 2.240*err_min, 3.618*err_max))
//DeepCrab
array.set(patternArray, 4, array.get(patternArray, 4) and isInRange(bcdRatio, 2.000*err_min, 3.618*err_max))
//Shark
array.set(patternArray, 6, array.get(patternArray, 6) and isInRange(bcdRatio, 1.618*err_min, 2.236*err_max))
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and is_1_272_to_2_000)
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_1_618_to_2_618)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and is_1_618_to_2_618)
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_1_618_to_2_618)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and is_1_618_to_2_618)
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and isInRange(bcdRatio, 1.272*err_min, 1.272*err_max))
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and isInRange(bcdRatio, 2.000*err_min, 2.618*err_max))
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and isInRange(bcdRatio, 1.618*err_min, 1.618*err_max))
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(bcdRatio, 0.886*err_min, 3.618*err_max))
// @function Checks if xad or xcd ratio is in range of any harmonic pattern
// @param xadRatio AD/XA ratio
// @param xcdRatio CD/XC ratio
// @param err_min minimum error threshold
// @param err_max maximum error threshold
// @param patternArray Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
export scan_xad_xcd(float xadRatio, float xcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
is_1_618_to_1_618 = isInRange(xadRatio, 1.618*err_min, 1.618*err_max)
is_0_786_to_0_786 = isInRange(xadRatio, 0.786*err_min, 0.786*err_max)
is_0_886_to_0_886 = isInRange(xadRatio, 0.886*err_min, 0.886*err_max)
is_1_272_to_1_272 = isInRange(xadRatio, 1.272*err_min, 1.272*err_max)
//Gartley
array.set(patternArray, 0, array.get(patternArray, 0) and is_0_786_to_0_786)
//Bat
array.set(patternArray, 1, array.get(patternArray, 1) and is_0_886_to_0_886)
//Butterfly
array.set(patternArray, 2, array.get(patternArray, 2) and isInRange(xadRatio, 1.272, 1.618))
//Crab
array.set(patternArray, 3, array.get(patternArray, 3) and is_1_618_to_1_618)
//DeepCrab
array.set(patternArray, 4, array.get(patternArray, 4) and is_1_618_to_1_618)
//Cypher
array.set(patternArray, 5, array.get(patternArray, 5) and isInRange(xcdRatio, 0.786*err_min, 0.786*err_max))
//Shark
array.set(patternArray, 6, array.get(patternArray, 6) and is_0_886_to_0_886)
//NenStar
array.set(patternArray, 7, array.get(patternArray, 7) and is_1_272_to_1_272)
//Anti NenStar
array.set(patternArray, 8, array.get(patternArray, 8) and is_0_786_to_0_786)
//Anti Shark
array.set(patternArray, 9, array.get(patternArray, 9) and isInRange(xadRatio, 1.13*err_min, 1.13*err_max))
//Anti Cypher
array.set(patternArray, 10, array.get(patternArray, 10) and is_1_272_to_1_272)
//Anti Crab
array.set(patternArray, 11, array.get(patternArray, 11) and isInRange(xadRatio, 0.618*err_min, 0.618*err_max))
//Anti Butterfly
array.set(patternArray, 12, array.get(patternArray, 12) and isInRange(xadRatio, 0.618*err_min, 0.786*err_max))
//Anti Bat
array.set(patternArray, 13, array.get(patternArray, 13) and isInRange(xadRatio, 1.128*err_min, 1.128*err_max))
//Anti Gartley
array.set(patternArray, 14, array.get(patternArray, 14) and isInRange(xadRatio, 1.272*err_min, 1.272*err_max))
//Navarro200
array.set(patternArray, 15, array.get(patternArray, 15) and isInRange(xadRatio, 0.886, 1.127))
// @function Provides PRZ range based on BCD and XAD ranges
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param patternArray Pattern flags for which PRZ range needs to be calculated
// @param errorPercent Error threshold
// @param start_adj - Adjustments for entry levels
// @param end_adj - Adjustments for stop levels
// @returns [dStart, dEnd] Start and end of consolidated PRZ range
export get_prz_range(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent = 8, simple float start_adj=0, simple float end_adj=0)=>
startRange = array.new_float(array.size(patternArray), na)
endRange = array.new_float(array.size(patternArray), na)
if(array.includes(patternArray, true))
//Gartley
getrange(x, a, 0.786, 0.786, b, c, 1.272, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0)
//Bat
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1)
//Butterfly
getrange(x, a, 1.272, 1.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2)
//Crab
getrange(x, a, 1.618, 1.618, b, c, 2.240, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3)
//DeepCrab
getrange(x, a, 1.618, 1.618, b, c, 2.000, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4)
//Cypher
getrange(x, c, 0.786, 0.786, x, c, 0.786, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5)
//Shark
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6)
//NenStar
getrange(x, a, 1.272, 1.272, b, c, 1.272, 2.000, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7)
//Anti NenStar
getrange(x, a, 0.786, 0.786, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8)
//Anti Shark
getrange(x, a, 1.130, 1.130, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9)
//Anti Cypher
getrange(x, a, 1.272, 1.272, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10)
//Anti Crab
getrange(x, a, 0.618, 0.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11)
//Anti Butterfly
getrange(x, a, 0.618, 0.786, b, c, 1.272, 1.272, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12)
//Anti Bat
getrange(x, a, 1.128, 1.128, b, c, 2.000, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13)
//Anti Gartley
getrange(x, a, 1.272, 1.272, b, c, 1.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14)
//Navarro200
getrange(x, a, 0.886, 1.127, b, c, 0.886, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15)
dStart = b > c? array.min(startRange) : array.max(startRange)
dEnd = b > c? array.max(endRange) : array.min(endRange)
[dStart, dEnd]
// @function Checks for harmonic patterns
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param d D coordinate value
// @param flags flags to check patterns. Send empty array to enable all
// @param errorPercent Error threshold
// @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
export isHarmonicPattern(float x, float a, float b, float c, float d,
simple bool[] flags, simple bool defaultEnabled = true, simple int errorPercent = 8)=>
numberOfPatterns = getNumberOfSupportedPatterns()
err_min = (100 - errorPercent) / 100
err_max = (100 + errorPercent) / 100
xabRatio = (b - a) / (x - a)
abcRatio = (c - b) / (a - b)
axcRatio = (c - x) / (a - x)
bcdRatio = (d - c) / (b - c)
xadRatio = (d - a) / (x - a)
xcdRatio = (d - c) / (x - c)
patternArray = array.new_bool()
for i=0 to numberOfPatterns-1
if(array.size(flags) > i)
currentFlag = defaultEnabled? array.size(flags)<=i or array.get(flags, i) :
array.size(flags)>i and array.get(flags, i)
array.push(patternArray, currentFlag)
else
array.push(patternArray, false)
scan_xab(xabRatio, err_min, err_max, patternArray)
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray)
scan_bcd(bcdRatio, err_min, err_max, patternArray)
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray)
patternArray
|
HighTimeframeTiming | https://www.tradingview.com/script/F9vFt8aX-HighTimeframeTiming/ | SimpleCryptoLife | https://www.tradingview.com/u/SimpleCryptoLife/ | 40 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SimpleCryptoLife
//@version=5
// @description Functions for sampling high timeframe (HTF) historical data at an arbitrary number of HTF bars back, using a single security() call.
// The data is fixed and does not alter over the course of the HTF bar. It also behaves consistently on historical and elapsed realtime bars.
library("HighTimeframeTiming", overlay = true)
// @function f_offset_synch(float _HTF_X, int _HTF_H, int _openChartBarsIn, bool _updateEarly)
// Returns the number of chart bars that you need to go back in order to get a stable HTF value from a given number of HTF bars ago.
// @param float _HTF_X is the timeframe multiplier, i.e. how much bigger the selected timeframe is than the chart timeframe. The script shows a way to calculate this using another of my libraries without using up a security() call.
// @param int _HTF_H is the historical operator on the HTF, i.e. how many bars back you want to go on the higher timeframe. If omitted, defaults to zero.
// @param int _openChartBarsIn is how many chart bars have been opened within the current HTF bar. An example of calculating this is given below.
// @param bool _updateEarly defines whether you want to update the value at the closing calculation of the last chart bar in the HTF bar or at the open of the first one.
// @returns an integer that you can use as a historical operator to retrieve the value for the appropriate HTF bar.
// ‼ LIMITATIONS: This function depends on there being a consistent number of chart timeframe bars within the HTF bar. This is almost always true in 24/7 markets like crypto.
// This might not be true if the chart doesn't produce an update when expected, for example because the asset is thinly traded and there is no volume or price update from the feed at that time.
// To mitigate this risk, use this function on liquid assets and at chart timeframes high enough to reliably produce updates at least once per bar period.
// The consistent ratio of bars might also break down in markets with irregular sessions and hours. I'm not sure if or how one could mitigate this.
// Another limitation is that because we're accessing a multiplied number of chart bars, you will run out of chart bars faster than you would HTF bars. This is only a problem if you use a large historical operator.
// If you call a function from this library, you should probably reproduce these limitations in your script description.
// However, all of this doesn't mean that this function might not still be the best available solution, depending what your needs are.
// If a single chart bar is skipped, for example, the calculation will be off by 1 until the next HTF bar opens. This is certainly inconsistent, but potentially still usable.
// @function f_HTF_Array(string _HTF=, float _source, int _arrayLength, int _HTF_Offset, bool _useLiveDataOnChartTF=false)
// Returns a floating-point number from a higher timeframe, with a historical operator within an abitrary (but limited) number of bars.
// @param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises.
// @param float _source is the source value that you want to sample, e.g. close will use the chart timeframe close, or you can use any floating-point number.
// @param int _arrayLength is the number of HTF bars you want to store. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
// @param int _HTF_Offset is the historical operator for the value you want to return. E.g., if you want the most recent fixed close, _source=close and _HTF_Offset = 0.
// If you want the one before that, _HTF_Offset=1, etc.
// @param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
// If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
// The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
// This means that on default settings, on the chart timeframe, it matches option B, raw source values from security(), and differs from every other option.
// You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
// @returns a floating-point value that you requested from the higher timeframe.
// ‼ LIMITATIONS: This function does NOT depend on there being a consistent number of chart timeframe bars within the HTF bar. It should be, and seems to be, more robust than f_offset_synch() for this reason.
// You can, however, see some strange discrepancies between f_HTF_Array(), f_offset_synch, method E (the PineCoders' modified function), and raw security() data on thinly traded assets that do not update every chart bar.
// Therefore, use this function on liquid assets and at chart timeframes high enough to reliably produce updates at least once per bar period.
// A more conventional and universal limitation is that the function does not offer an unlimited view of historical bars. You need to define upfront how many HTF bars you want to store. Very large numbers might conceivably run into data or performance issues.
// 🙏Credits: This library is an attempt at a solution of the problems in using HTF data that were laid out by Pinecoders in "security() revisited" - https://www.tradingview.com/script/00jFIl5w-security-revisited-PineCoders/
// Thanks are due to the authors of that work for an understanding of HTF issues. In addition, the current script also includes some of its code.
// Specifically, this script reuses the main function recommended in "security() revisited", for the purposes of comparison. And it extends that function to access historical data, again just for comparison.
// All the rest of the code, and in particular all of the code in the exported function, is my own.
// Special thanks to LucF for pointing out the limitations of my approach.
// ~~~~~~~~~~~~~~~~~
// EXPLANATION
// ~~~~~~~~~~~~~~~~~
// Problems with live HTF data: Many problems with using live HTF data from security() have been clearly explained by Pinecoders in "security() revisited"
// In short, its behaviour is inconsistent between historical and elapsed realtime bars, and it changes in realtime, which can cause calculations and alerts to misbehave.
// Various unsatisfactory solutions are discussed in "security() revisited", and understanding that script is a prerequisite to understanding this library.
// PineCoders give their own solution, which is to fix the data by essentially using the previous HTF bar's data. Importantly, that solution is consistent between historical and realtime bars.
// This library is an attempt to provide an alternative to that solution.
// Problems with historical HTF data: In addition to the problems with live HTF data, there are different issues when trying to access historical HTF data.
// Why use historical HTF data? Maybe you want to do custom calculations that involve previous HTF bars. Or to use HTF data in a function that has mutable variables and so can't be done in a security() call.
// Most obviously, using the historical operator (in this description, represented using { } because the square brackets don't render) on variables already retrieved from a security() call, e.g. HTF_Close{1}, is not very useful:
// it retrieves the value from the previous *chart* bar, not the previous HTF bar.
// Using {1} directly in the security() call instead does get data from the previous HTF bar, but it behaves inconsistently, as we shall see.
// This library addresses these concerns as well.
// Housekeeping: To follow what's going on with the example and comparisons, turn line labels on: Settings > Scales > Indicator Name Label.
// The following explanation assumes "close" as the source, but you can change it if you want.
// To quickly see the difference between historical and realtime bars, set the HTF to something like 3 minutes on a 15s chart.
// The bars at the top of the screen show the status. Historical bars are grey, elapsed realtime bars are red, and the realtime bar is green. A white vertical line shows the open of a HTF bar.
// A1: This library function f_offset_synch(): When supplied with an input offset of 0, it plots a stable value of the close of the *previous* HTF bar. This value is thus safe to use for calculations and alerts.
// For a historical operator of {1}, it gives the close of the *last-but-one* bar. Sounds simple enough. Let's look at the other options to see its advantages.
// B: Live HTF data: Represented on the line label as "security(){0}". Note: this is the source that f_offset_synch() samples.
// The raw HTF data is very different on historical and realtime bars:
// + On historical bars, it uses a flat value from the end of the previous HTF bar. It updates at the close of the HTF bar.
// + On realtime bars, it varies between and within each chart bar.
// There might be occasions where you want to use live data, in full knowledge of its drawbacks described above. For example, to show simple live conditions that are reversible after a chart bar close.
// This library transforms live data to get the fixed data, thus giving you access to both live and fixed data with only one security() call.
// C: Historical data using security(){H}: To see how this behaves, set the {H} value in the settings to 1 and show options A, B, and C.
// + On historical bars, this option matches option A, this library function, exactly. It behaves just like security(){0} but one HTF bar behind, as you would expect.
// + On realtime bars, this option takes the value of security(){0} at the end of a HTF bar, but it takes it from the previous *chart* bar, and then persists that.
// The easiest way to see this inconsistency is on the first realtime bar (marked red at the top of the screen). This option suddenly jumps, even if it's in the middle of a HTF bar.
// Contrast this with option A, which is always constant, until it updates, once per HTF bar.
// D: PineCoders' original function: To see how this behaves, show options A, B, and D. Set the {H} value in the settings to 0, then 1.
// The PineCoders' original function (D) and extended function (E) do not have the same limitations as this library, described in the Limitations section.
// This option has all of the same advantages that this library function, option A, does, with the following differences:
// + It cannot access historical data. The {H} setting makes no difference.
// + It always updates at the open of the first chart bar in a new HTF bar.
// By contrast, this library function, option A, is configured by default to update at the close of the last chart bar in a HTF bar.
// This little frontrunning is only a few seconds but could be significant in trading. E.g. on a 1D HTF with a 4H chart, an alert that involves a HTF change set to trigger ON CLOSE would trigger 4 hours later using this method -
// but use exactly the same value. It depends on the market and timeframe as to whether you could actually trade this. E.g. at the very end of a tradfi day your order won't get executed.
// This behaviour mimics how security() itself updates, as is easy to see on the chart. If you don't want it, just set in_updateEarly to false. Then it matches option D exactly.
// E: PineCoders' function, extended to get history: To see how this behaves, show options A and E. Set the {H} value in the settings to 0, then 1.
// I modified the original function to be able to get historical values. In all other respects it is the same.
// Apart from not having the option to update earlier, the only disadvantage of this method vs this library function is that it requires one security() call for each historical operator.
// For example, if you wanted live data, and fixed data, and fixed data one bar back, you would need 3 security() calls. My library function requires just one.
// This is the essential tradeoff: extra complexity and less robustness in certain circumstances (the PineCoders function is simple and universal by comparison) for more flexibility with fewer security() calls.
// A2: This library's alternative function using an array to store values as we go along rather than calculating an offset like A1 does.
// This function appears to be more stable than A1 in practice, although in theory they should be the same.
// A2 should be the same as E, the PineCoders' function, which we can use as a standard. However, for tradfi markets with sessions, E is one chart bar behind when the new HTF bar/trading session opens,
// at least with historical data. If you have the patience to leave the indicator running for several days you can test elapsed realtime data for such sessions.
// Therefore, this function seems to me to be, overall, tied for accuracy with the PineCoders' function out of all the options presented here (with the caveat, additional to the limitations described above, that I haven't tested it with extended sessions).
// Like A1, it is inexpensive, using only a single security() call for the raw data and returning values from an abritrary number of bars back.
// It is a little simpler than A1. And it has potential to be extended, for example, to retrieve the highest value in a range of HTF bars back.
// A single version of this function is included in this library, in order that a comparison with other methods of fixing HTF data can be made. Multiple variations of this function are published in a separate library https://www.tradingview.com/script/tRv6GGg7-HighTimeframeSampling/, which, because it does not contain any other methods, is easier to refer to and use. In other words, this library, although functional, should be considered more like an extended example or proof of concept to be understood first, while the HighTimeframeSampling library contains the functions that you would probably want to call if you decided to use this method of sampling HTF data in your script.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// INPUTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// Inputs needed for the library
in_HTF = input.timeframe(defval="", title="Higher Timeframe", group="General")
in_source = input.source(defval=close, title="Source")
in_HTF_Offset = input.int(defval=0, minval=0, maxval=4, title="No. of HTF bars to look back [H]", tooltip="This lookback value is used for all options that have [H] in the description.")
bool in_updateEarly = input.bool(defval=false, title="Update on the close of the last chart bar (the earliest possible time to update)", group="Option A1")
in_arrayLength = input.int(minval=1, maxval=100, defval=10, title="Number of HTF source values to store", group="Option A2")
in_useLiveDataOnChartTF = input.bool(defval=false, title="Use live data on chart timeframe (HTF data is always fixed)") //
in_showHTF_Synch = input.bool(defval=true, title="A1: Show this library function f_offset_synch()[H]]", group="Display", tooltip="Looking back X bars, but synchronised to the beginning of the HTF bar. This is my preferred method.")
in_showHTF_Array = input.bool(defval=true, title="A2: Show this library function f_HTF_Array()[H]", tooltip="Looking back X bars, using an array.")
// Inputs for examples and comparisons
in_showHTF_Raw = input.bool(defval=true, title="B: Show HTF Raw [0] source values using security()")
in_showHTF_Sec = input.bool(defval=false, title="C: Show security(source[H])", tooltip="The simplest way of accessing HTF historical values - but not the best.")
in_showHTF_PineCoders = input.bool(defval=false, title="D: Show Pinecoders original function")
in_showHTF_PineCodersHist = input.bool(defval=false, title="E: Show Pinecoders extended function [H]")
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// RAW HTF DATA |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// This raw HTF value is requested directly from the security() call on the current bar. It used as the source for the library functions f_offset_synch() and f_HTF_Array, and can also be plotted.
float HTF_Raw = request.security(syminfo.tickerid, in_HTF, in_source, barmerge.gaps_off, barmerge.lookahead_off)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// CALCULATIONS FOR OFFSET FUNCTION |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// === Get the timeframe multiplier ===
var int chartTFInSeconds = timeframe.in_seconds(timeframe.period)
var int HTF_FixedInSeconds = timeframe.in_seconds(in_HTF) // Need separate for error-checking
var HTF_X = int(HTF_FixedInSeconds / chartTFInSeconds) // How much bigger HTF is than the chart timeframe
// Error-checking
var string errorTextLibraryName = "SimpleCryptoLife/HighTimeframeTiming"
if HTF_FixedInSeconds < chartTFInSeconds
runtime.error("Input timeframe cannot be lower than the chart timeframe [Error 001:" + " from section \"Get the timeframe multiplier\" in library " + errorTextLibraryName + "]")
if HTF_FixedInSeconds % chartTFInSeconds > 0
runtime.error("Input timeframe must be exact multiple of chart timeframe [Error 002:" + " from section \"Get the timeframe multiplier\" in library " + errorTextLibraryName + "]")
export f_offset_synch(float _HTF_X, int _HTF_H = 0, int _openChartBarsIn, bool _updateEarly) =>
// Throw an error if HTF_H is out of bounds
var string _errorTextFunctionName = "f_offset_synch"
if _HTF_H < 0
runtime.error("Historical operator " + str.tostring(_HTF_H) + " is less than zero" + " [Error 003:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _HTF_H % 1 > 0
runtime.error("Historical operator " + str.tostring(_HTF_H) + " is not a whole number" + " [Error 004:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if barstate.isrealtime and ((_HTF_H * _HTF_X) > bar_index)
runtime.error("Historical operator " + str.tostring(_HTF_H) + " is greater than number of HTF bars: " + str.tostring(bar_index) + " [Error 005:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
float _chart_H_Normal = _openChartBarsIn + (_HTF_X * _HTF_H) // The offset for most bars most of the time
bool _isLastChartUpdate = barstate.isconfirmed // This is true only for the closing update of a chart bar. It is true once for each chart bar.
bool _isLastHTFBar = _openChartBarsIn == _HTF_X // Is this the last chart bar in the current HTF bar?
float _chart_H_Last = _isLastChartUpdate and _isLastHTFBar and _updateEarly ? (_HTF_X * _HTF_H) : na // The offset for the last update of the HTF bar
float _chart_H_float = na(_chart_H_Last) ? _chart_H_Normal : _chart_H_Last // Choose which one to use
int _chart_H = int(_chart_H_float) // We had to use floats for ints before because reasons. But it's really an int. OCD satisfied.
// These bits are just required for the function and can be reused without much thought.
var int openChartBars = na, openChartBars := ta.change(time(in_HTF)) ? 1 : openChartBars + 1 // Count the number of opened chart bars in this HTF bar.
// Here's where we actually call the function
chart_H = f_offset_synch(HTF_X, in_HTF_Offset, openChartBars, in_updateEarly) // Get the offset
// Using the offset to get a certain value
float HTF_HistSynch = HTF_Raw[chart_H] // Keeping this outside the function for maximum flexibility
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// CALCULATIONS FOR ARRAY FUNCTION |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
export f_HTF_Array(string _HTF="", float _source, int _arrayLength, int _HTF_Offset=0, bool _useLiveDataOnChartTF=false) =>
var string _errorTextFunctionName = "f_HTF_Array" // Error-checking.
if _HTF_Offset + 1 > _arrayLength
runtime.error("The number of stored values configured is " + str.tostring(_arrayLength) + ", and must be at least " + str.tostring(_HTF_Offset+1) + " in order to look " + str.tostring(_HTF_Offset) + " HTF bars back." + " [Error 006:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _arrayLength < 1
runtime.error("The number of stored values configured must be more than zero." + " [Error 007:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
if _HTF_Offset < 0
runtime.error("The number of HTF bars to look back must be zero or more." + " [Error 008:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]")
var _arraySource = array.new_float(_arrayLength,na) // Create the array to hold the floats.
bool isChartTimeframe = _HTF=="" or _HTF == timeframe.period
var int _offset = isChartTimeframe and _useLiveDataOnChartTF==true ? 0 : 1 // Use live data on chart TF if that option is selected; otherwise use fixed (the previous bar's) data.
// By using ta.change(), we store the source value only when the HTF bar *opens*. We do updates throughout every bar if the timeframe =""; otherwise all throughout the chart bar that corresponds to the first HTF bar.
// It might be more efficient to update only at the beginning of the chart bar, but a) it didn't seem to work, and b) even if I could get it working, it might be less robust.
if _HTF=="" or ta.change(time(_HTF))
array.unshift(_arraySource,_source[_offset]) // Add the source value to index 0 and shift other indexes along. It's important to keep the order so that it's simple to look up values.
if array.size(_arraySource) > _arrayLength
array.pop(_arraySource) // Remove the oldest value, keeping the array the same length.
float _myFloat = array.get(_arraySource,_HTF_Offset) // This function just returns the one value requested. There's more you could do with the array.
_myFloat
HTF_valueFromArray = f_HTF_Array(in_HTF, HTF_Raw, in_arrayLength, in_HTF_Offset, in_useLiveDataOnChartTF) // Call the function and use the offset to get a certain value
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// CALCULATIONS FOR COMPARISONS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// This value is also requested directly from a security() call, but with a variable historical operator. It is not used as input to anything else, just for comparison.
float HTF_HistSec = request.security(syminfo.tickerid, in_HTF, in_source[in_HTF_Offset], barmerge.gaps_off, barmerge.lookahead_off)
// This is the preferred (non-tuple) function presented by PineCoders in "security() revisited" - https://www.tradingview.com/script/00jFIl5w-security-revisited-PineCoders/
// It presents a fixed (as in static) version of live data which is one bar behind.
f_security(_sym, _res, _src, _rep) => request.security(_sym, _res, _src[not _rep and barstate.isrealtime ? 1 : 0])[_rep or barstate.isrealtime ? 0 : 1]
HTF_PineCoders = f_security(syminfo.tickerid, in_HTF, in_source, false) // Hardcoding repainting to false so as not to confuse matters.
// This is the same PineCoders' function but with a historical operator added.
f_securityHistorical(_sym, _res, _src, _rep) => request.security(_sym, _res, _src[not _rep and barstate.isrealtime ? 1 + in_HTF_Offset: 0 + in_HTF_Offset])[_rep or barstate.isrealtime ? 0 : 1]
HTF_PineCodersHist = f_securityHistorical(syminfo.tickerid, in_HTF, in_source, false) // Hardcoding repainting to false so as not to confuse matters.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
// PLOTS |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
plot(in_showHTF_Raw? HTF_Raw : na, color=color.new(color.orange,20), linewidth=14, title=" B: security() [0]")
plot(in_showHTF_Sec ? HTF_HistSec : na, color=color.blue, linewidth=6, title=" C: security() [H]")
plot(in_showHTF_Synch ? HTF_HistSynch : na, style=plot.style_circles, color=color.new(color.green,50), linewidth=18, title=" A: 😎 f_offset_synch()[H]")
plot(in_showHTF_PineCoders ? HTF_PineCoders : na, title=" D: PineCoders Original", color=color.yellow, linewidth=2)
plot(in_showHTF_PineCodersHist ? HTF_PineCodersHist : na, style=plot.style_cross, title=" E: PineCoders Historical", color=color.purple, linewidth=5)
plot(in_showHTF_Array ? HTF_valueFromArray : na, style=plot.style_circles, title=" A2: 😍 f_HTF_Array", color=color.new(color.orange,30), linewidth=12)
// ————— Colored bar at the top of the chart lifted from "security() revisited" by PineCoders
plotchar(na, "══════════ BAR STATES", "", location.top)
plotchar(barstate.ishistory, "ishistory", "█", location.top, color=color.new(color.silver,50), size = size.normal)
plotchar(barstate.isrealtime, "isrealtime", "█", location.top, color=color.new(color.green,50), size = size.normal)
plotchar(barstate.isrealtime and barstate.isconfirmed, "isrealtime and isconfirmed", "█", location.top, color=color.new(color.red,50), size = size.normal)
plotchar(ta.change(time(in_HTF)), "ta.change(time(in_HTF))", "|", location.top, color=color.white, size = size.normal) // Show when a new HTF bar opens
// ======================================================= //
// //
// (╯°□°)╯︵ ǝsn pǝpuǝʇuᴉ ǝɥʇ ʇou sᴉ ʇɐɥʇ ɹᴉS //
// //
// ======================================================= // |
historicalrange | https://www.tradingview.com/script/RSBz7Vx7-historicalrange/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 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/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
// @description Library provices a method to calculate historical percentile range of series.
library("historicalrange")
import HeWhoMustNotBeNamed/enhanced_ta/10 as eta
// @function calculates historical percentrank of the source
// @param source Source for which historical percentrank needs to be calculated. Source should be ranging between 0-100. If using a source which can beyond 0-100, use short term percentrank to baseline them.
// @returns pArray - percentrank array which contains how many instances of source occurred at different levels.
// upperPercentile - percentile based on higher value
// lowerPercentile - percentile based on lower value
// median - median value of the source
// max - max value of the source
export hpercentrank(float source, simple bool invert = false) =>
if(source < 0 or source > 100)
runtime.error('Source need to be between 0 and 100. Use percentrank to limit the source between 0-100')
precisionMultiplier = 10
var pArray = array.new_int(100*precisionMultiplier+2, 0)
index = math.round(source*precisionMultiplier)
array.set(pArray, index, array.get(pArray, index)+1)
upperPortion = array.slice(pArray, index+1, array.size(pArray))
lowerPortion = array.slice(pArray, 0, index)
total = array.sum(pArray)
upper = array.sum(upperPortion)
lower = array.sum(lowerPortion)
same = array.get(pArray, index)
upperPercentile = (total-upper)*100/total
lowerPercentile = (total-lower)*100/total
percentrank = invert ? lowerPercentile : upperPercentile
cumulativeCount = 0
medianIndex = 0
maxIndex = 0
for i=0 to array.size(pArray)-1
cumulativeCount += array.get(pArray, i)
if(cumulativeCount < total/2)
medianIndex := i+1
if(cumulativeCount == total)
maxIndex := i
break
median = medianIndex/precisionMultiplier
max = maxIndex/precisionMultiplier
[source, index, pArray, percentrank, median, max]
// @function returns stats on historical distance from ath in terms of percentage
// @param source for which stats are calculated
// @returns percentile and related historical stats regarding distance from ath
export distancefromath(float source = close, float highSource = high)=>
var ath = highSource
ath := na(ath)? highSource : math.max(ath, highSource)
distanceFromAth = ath - source
percentageFromAth = distanceFromAth*100/ath
hpercentrank(percentageFromAth, true)
// @function returns stats on historical distance from moving average in terms of percentage
// @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
// @param length Moving Average Length
// @param source for which stats are calculated
// @returns percentile and related historical stats regarding distance from ath
export distancefromma(float source, simple string maType, simple int length)=>
ma = eta.ma(source, maType, length)
percentFromMa = (close-ma)/close
var ath = percentFromMa
var atl = percentFromMa
ath := na(ath)? percentFromMa : math.max(ath, percentFromMa)
atl := na(atl)? percentFromMa : math.min(atl, percentFromMa)
relativeDistance = (percentFromMa-atl)*100/(ath-atl)
hpercentrank(relativeDistance)
// @function returns percentrank and stats on historical bpercentb levels
// @param source Moving Average Source
// @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
// @param length Moving Average Length
// @param multiplier Standard Deviation multiplier
// @param sticky - sticky boundaries which will only change when value is outside boundary.
// @returns percentile and related historical stats regarding Bollinger Percent B
export bpercentb(float source=close, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool sticky=false) =>
percentb = math.min(math.max(eta.bpercentb(source, maType, length, multiplier, sticky), 0), 100)
hpercentrank(percentb)
// @function returns percentrank and stats on historical kpercentk levels
// @param source Moving Average Source
// @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
// @param length Moving Average Length
// @param multiplier Standard Deviation multiplier
// @param useTrueRange - if set to false, uses high-low.
// @param sticky - sticky boundaries which will only change when value is outside boundary.
// @returns percentile and related historical stats regarding Keltener Percent K
export kpercentk(float source=close, simple string maType="ema", simple int length=20, float multiplier=2, simple bool useTrueRange=true, simple bool sticky=false) =>
percentk = math.min(math.max(eta.kpercentk(source, maType, length, multiplier, useTrueRange, sticky), 0), 100)
hpercentrank(percentk)
// @function returns percentrank and stats on historical dpercentd levels
// @param useAlternateSource - Custom source is used only if useAlternateSource is set to true
// @param alternateSource - Custom source
// @param length - donchian channel length
// @param sticky - sticky boundaries which will only change when value is outside boundary.
// @returns percentile and related historical stats regarding Donchian Percent D
export dpercentd(simple int length=20, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false) =>
dpercentd = math.min(math.max(eta.dpercentd(length, useAlternateSource, alternateSource, sticky), 0), 100)
hpercentrank(dpercentd)
// @function oscillator - returns Choice of oscillator with custom overbought/oversold range
// @param type - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr
// @param length - Oscillator length - not used for TSI
// @param shortLength - shortLength only used for TSI
// @param longLength - longLength only used for TSI
// @param source - custom source if required
// @param highSource - custom high source for stochastic oscillator
// @param lowSource - custom low source for stochastic oscillator
// @param method - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
// @param highlowLength - length on which highlow of the oscillator is calculated
// @param sticky - overbought, oversold levels won't change unless crossed
// @returns percentile and related historical stats regarding oscillator
export oscillator(simple string type="rsi", simple int length=14, simple int shortLength = 13, simple int longLength = 25,
float source = close, float highSource = high, float lowSource = low,
simple string method="highlow", simple int highlowLength=50, simple bool sticky=false, simple bool useDynamicRange = false)=>
[oscillator, overbought, oversold] = eta.oscillator(type, length, shortLength, longLength, source, highSource, lowSource, method, highlowLength, sticky)
var ath = oscillator
var atl = oscillator
ath := na(ath)? oscillator : math.max(ath, oscillator)
atl := na(atl)? oscillator : math.min(atl, oscillator)
oscHigh = useDynamicRange ? overbought : ath
oscLow = useDynamicRange ? oversold : atl
oscPercent = math.min(math.max((oscillator-oscLow)*100/(oscHigh-oscLow), 0), 100)
hpercentrank(oscPercent)
// ******************************************************* Code Examples **************************************************************
type = input.string("oscillator", options=["distancefromath", "distancefromma", "bpercentb", "kpercentk", "dpercentd", "oscillator"], group="Stats")
displayDetailedStats = input.bool(true, title="Detailed Stats", group="Stats")
masource = input.source(close, title="Source", group="Moving Average/Bands")
matype = input.string("sma", title="Type", group="Moving Average/Bands", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"])
malength = input.int(20, title="Length", group="Moving Average/Bands")
multiplier = input.float(2.0, step=0.5, title="Multiplier", group="Moving Average/Bands")
useTrueRange = input.bool(true, title="Use True Range (KC)", group="Moving Average/Bands")
useAlternateSource = input.bool(false, title="Use Alternate Source (DC)", group="Moving Average/Bands")
sticky = input.bool(true, title="Sticky", group="Moving Average/Bands")
oscType = input.string("rsi", title="Oscillator Type", group="Oscillator", options=["cci", "cmo", "cog", "mfi", "roc", "rsi", "stoch", "tsi", "wpr"])
oLength = input.int(14, title="Length", group="Oscillator")
shortLength = input.int(9, title="Short Length (TSI)", group="Oscillator")
longLength = input.int(9, title="Long Length (TSI)", group="Oscillator")
method = input.string("highlow", title="Dynamic Overvought/Oversold Calculation method", group="Oscillator", options=["highlow", "sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"])
highlowlength = input.int(50, title="Length", group="Oscillator")
useDynamicRange = input.bool(false, title="Dynamic Range", group="Oscillator")
osticky = input.bool(true, title="Sticky", group="Oscillator")
[source, index, pArray, percentile, median, max] = switch(type)
"distancefromath" => distancefromath()
"distancefromma" => distancefromma(masource, matype, malength)
"bpercentb" => bpercentb(masource, matype, malength, multiplier, sticky)
"kpercentk" => kpercentk(masource, matype, malength, multiplier, useTrueRange, sticky)
"dpercentd" => dpercentd(malength, useAlternateSource, masource, sticky)
"oscillator" => oscillator(oscType, oLength, shortLength, longLength, method = method, highlowLength=highlowlength,
sticky=osticky, useDynamicRange=useDynamicRange)
textSize = input.string(size.small, title='Text Size', options=[size.tiny, size.small, size.normal, size.large, size.huge], group='Table', inline='text')
headerColor = input.color(color.maroon, title='Header', group='Table', inline='GC')
neutralColor = input.color(#FFEEBB, title='Cell', group='Table', inline='GC')
presentColor = input.color(color.aqua, title='Present', group='Table', inline='GC')
medianColor = input.color(color.olive, title='Median', group='Table', inline='GC')
total = array.sum(pArray)
color cellColor = color.blue
var dateStart = str.tostring(year) + '/' + str.tostring(month) + '/' + str.tostring(dayofmonth)
dateEnd = str.tostring(year) + '/' + str.tostring(month) + '/' + str.tostring(dayofmonth)
if(displayDetailedStats and total!=0 and barstate.islastconfirmedhistory)
legend = table.new(position=position.middle_right, columns=2, rows=5, border_width=1)
table.cell(table_id=legend, column=0, row=0, text='Legend', bgcolor=color.teal, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=0, row=1, text='Value Range', bgcolor=color.black, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=1, row=1, text=' ', bgcolor=headerColor, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=0, row=2, text='Percentile Range', bgcolor=color.black, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=1, row=2, text=' ', bgcolor=neutralColor, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=0, row=3, text='Present Range', bgcolor=color.black, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=1, row=3, text=' ', bgcolor=presentColor, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=0, row=4, text='Median Range', bgcolor=color.black, text_color=color.white, text_size=textSize)
table.cell(table_id=legend, column=1, row=4, text=' ', bgcolor=medianColor, text_color=color.white, text_size=textSize)
detailedTable = table.new(position=position.middle_center, columns=21, rows=10, border_width=1)
table.cell(table_id=detailedTable, column=0, row=0, text=dateStart + ' to ' + dateEnd, bgcolor=color.teal, text_color=color.white, text_size=textSize)
table.cell(table_id=detailedTable, column=0, row=1, text=syminfo.tickerid, bgcolor=color.teal, text_color=color.white, text_size=textSize)
headerArray = array.new_string()
valueArray = array.new_string()
cellColorArray = array.new_color()
precisionMultiplier = 10
for i=0 to 99
end = math.min((i+1)*precisionMultiplier, array.size(pArray))
slice = array.slice(pArray, 0, end)
count = array.sum(slice)
row = math.floor(i/10)
col = (i%10) * 2 + 1
if (count != 0)
percent = count*100/total
headerText = '0 - ' + str.tostring(end/precisionMultiplier)
cColor = math.floor(index/precisionMultiplier) == i ? presentColor : math.floor(median) == i ? medianColor : neutralColor
array.push(headerArray, headerText)
array.push(valueArray, str.tostring(percent, format.percent))
array.push(cellColorArray, cColor)
if(count == total)
break
rowCol = math.ceil(math.sqrt(array.size(headerArray)))
counter = 0
for i=0 to rowCol-1
for j=0 to rowCol-1
row = i
col = j*2 + 1
if(counter >= array.size(headerArray))
break
table.cell(table_id=detailedTable, column=col, row=row, text=array.get(headerArray, counter), bgcolor=headerColor, text_color=color.white, text_size=textSize)
table.cell(table_id=detailedTable, column=col + 1, row=row, text=array.get(valueArray, counter), bgcolor=array.get(cellColorArray, counter), text_color=color.black, text_size=textSize)
counter += 1
plot(displayDetailedStats? na : percentile, title="Historical Percentile", color=cellColor)
|
adx: Configurable ADX (library) | https://www.tradingview.com/script/EI9z8EVc-adx-Configurable-ADX-library/ | t92a4 | https://www.tradingview.com/u/t92a4/ | 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/
// © t92a4
//@version=5
// @description Calculate ADX (and its constituent parts +DI, -DI, ATR),
// using different moving averages and periods.
library("adx", overlay=false)
ma(simple string type, float src, simple int len) =>
if type == "RMA"
ta.rma(src, len)
else if type == "SMA"
ta.sma(src, len)
else if type == "EMA"
ta.ema(src, len)
else if type == "WMA"
ta.wma(src, len)
else if type == "HMA"
ta.hma(src, len)
else if type == "LSMA"
ta.linreg(src, len, 0)
else
runtime.error(str.format("adx.ma(): unknown type {0}", type))
na
// @description Calculate ADX (and its constituent parts +DI, -DI, ATR),
// using different moving averages and periods.
//
// @returns [ATR, +DI, -DI, ADX]
//
// @param atrMA Moving Average used for calculating the Average True Range.
// Traditionally RMA, but using SMA here and in adxMA gives good results too.
//
// @param diMA Moving Average used for calculating the Directional Index.
// Traditionally, RMA.
//
// @param adxMA Moving Average used for calculating the Average Directional
// Index. Traditionally RMA, but using SMA here and in atrMA gives good results
// too.
//
// @param atrLen Length of the Average True Range.
//
// @param diLen Length of the Directional Index.
//
// @param adxLen Length (smoothing) of the Average Directional Index.
//
// @param h Candle's high.
//
// @param l Candle's low.
//
// @param c Candle's close.
export adx(
simple string atrMA="RMA",
simple string diMA="RMA",
simple string adxMA="RMA",
simple int atrLen=14,
simple int diLen=14,
simple int adxLen=14,
float h=high,
float l=low,
float c=close) =>
float ch = ta.change(h)
float cl = -ta.change(l)
float dmp = na(ch) ? na : (ch > cl and ch > 0 ? ch : 0)
float dmm = na(cl) ? na : (cl > ch and cl > 0 ? cl : 0)
float tr = math.max(h - l, math.abs(h - c[1]), math.abs(l - c[1]))
float atr = ma(atrMA, tr, atrLen)
float dip = fixnan(100 * ma(diMA, dmp, diLen) / atr)
float dim = fixnan(100 * ma(diMA, dmm, diLen) / atr)
float sum = dip + dim
float adx = 100 * ma(adxMA, math.abs(dip - dim) / (sum == 0 ? 1 : sum), adxLen)
[atr, dip, dim, adx]
/// USAGE
string ATR_MA = input.string("RMA", "ATR Moving Average",
options=["RMA", "SMA", "EMA", "WMA", "HMA", "LSMA"],
tooltip="Traditionally RMA, but using SMA here and in ADX gives good results too.")
string DI_MA = input.string("RMA", "DI Moving Average",
options=["RMA", "SMA", "EMA", "WMA", "HMA", "LSMA"],
tooltip="Traditionally RMA.")
string ADX_MA = input.string("RMA", "ADX Moving Average",
options=["RMA", "SMA", "EMA", "WMA", "HMA", "LSMA"],
tooltip="Traditionally RMA, but using SMA here and in ATR gives good results too.")
int ATR_LEN = input.int(14, "ATR Length", tooltip="Normally the same as the DI length")
int DI_LEN = input.int(14, "DI Length", tooltip="Normally the same as the ATR length")
int ADX_LEN = input.int(14, "ADX Length", tooltip="Also known as ADX Smoothing")
float H = input.source(high, "High")
float L = input.source(low, "Low")
float C = input.source(close, "Close")
[atr, dip, dim, adx] = adx(
atrMA=ATR_MA, diMA=DI_MA, adxMA=ADX_MA,
atrLen=ATR_LEN, diLen=DI_LEN, adxLen=ADX_LEN,
h=H, l=L, c=C)
plot(atr, "ATR", color.blue, display=display.none)
plot(adx, "ADX", color.purple, linewidth=2)
plot(dip, "+DI", color.lime)
plot(dim, "-DI", color.red)
hline(25)
|
TAExt | https://www.tradingview.com/script/3i8MeCJw-TAExt/ | TheBacktestGuy | https://www.tradingview.com/u/TheBacktestGuy/ | 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/
// © wallneradam
//@version=5
// @description Indicator functions can be used in other indicators and strategies. This will be extended by time with indicators I use in my strategies and studies. All indicators are highly configurable with good defaults.
library("TAExt", overlay=true)
///////////////
// Constants //
///////////////
PI = 3.1415926535
TORAD = 180 / PI
///////////////
// Functions //
///////////////
// @function Jurik Moving Average
// @param src The source of the moving average
// @param length The length of the moving average calculation
// @param phase The phase of jurik MA calculation (-100..100)
// @param power The power of jurik MA calculation
// @returns The Jurik MA series
export jma(series float src = close, simple int length = 7, simple int phase = 50, simple float power = 2) =>
var phase_ratio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
var beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
var alpha = math.pow(beta, power)
var _index = 0
float jma = na
float e0 = na
float e1 = na
float e2 = na
if not na(src)
e0 := (1 - alpha) * src + alpha * nz(e0[1])
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
e2 := (e0 + phase_ratio * e1 - nz(jma[1], src)) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1], src)
res = jma
_index += 1
if _index < length * 2.5
res := na
res
else
na
// @function Builtin Moving Average by type, used by other functions
// @param src The source of the moving average
// @param length The length of the moving average calculation
// @param type The type of the moving average
// @param offset Used only by ALMA, it is the ALMA offset
// @param sigma Used only by ALMA, it is the ALMA sigma
// @param phase The phase of jurik MA calculation (-100..100)
// @param power The power of jurik MA calculation
// @returns The moving average series
_anyma_builtin(series float src, simple int length, simple string type = "EMA",
simple float offset = 0.85, simple int sigma = 6,
simple int phase = 50, simple float power = 2) =>
switch type
"SMA" => ta.sma(src, length)
"EMA" => ta.ema(src, length)
"WMA" => ta.wma(src, length)
"VWMA" => ta.vwma(src, length)
"RMA" => ta.rma(src, length)
"DEMA" =>
ema1 = ta.ema(src, length)
ema2 = ta.ema(ema1, length)
2 * ema1 - ema2
"TEMA" =>
ema1 = ta.ema(src, length)
ema2 = ta.ema(ema1, length)
ema3 = ta.ema(ema2, length)
3 * (ema1 - ema2) + ema3
"ZLEMA" => ta.ema(src + (src - src[math.round(length / 2)]), length)
"HMA" => ta.hma(src, length)
"ALMA" => ta.alma(src, length, offset, sigma)
"LSMA" => ta.linreg(src, length, 0)
"SWMA" => ta.swma(src)
"SMMA" =>
float smma = 0.0
smma := na(smma[1]) ? src : (smma[1] * (length - 1) + src) / length
"DONCHIAN" => math.avg(ta.lowest(src, length), ta.highest(src, length))
"JMA" => jma(src, length, phase=phase, power=power)
=> na
// @function ATR without outliers
// @param length The length of the TR smoothing
// @param stdev_length The length of the standard deviation, used for detecting outliers
// @param stdev_mult The multiplier of the standard deviation, used for detecting outliers
// @param ma_type The moving average type used for smoothing
// @returns The ATR value
export atrwo(simple int length = 14, simple int stdev_length = 100, simple float stdev_mult = 1.0, simple string ma_type = "RMA") =>
float atrwo = 0.0
float trwo = 0.0
max_tr = (na(atrwo[1]) ? ta.tr : atrwo[1]) + stdev_mult * ta.stdev(ta.tr, stdev_length)
trwo := ta.tr > max_tr ? trwo[1] : ta.tr
atrwo := _anyma_builtin(trwo, length, ma_type)
atrwo
// @function ATR without outlier weighted moving average
// @param src The source of the moving average
// @param length The length of the moving average
// @param type The type of the moving average, possible values: SMA, EMA, RMA
// @param atr_length The length of the ATR
// @param stdev_length The length of the standard deviation, used for detecting outliers
// @param stdev_mult The multiplier of the standard deviation, used for detecting outliers
// @returns The moving average series
export atrwma(series float src = close, simple int length = 50, simple string type = "SMA",
simple int atr_length = 14, simple int stdev_length = 100, simple float stdev_mult = 1.0) =>
atrwo = atrwo(length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult)
switch type
"SMA" => ta.sma(src * atrwo, length) / ta.sma(atrwo, length)
"EMA" => ta.ema(src * atrwo, length) / ta.ema(atrwo, length)
"RMA" => ta.rma(src * atrwo, length) / ta.rma(atrwo, length)
"WMA" => ta.wma(src * atrwo, length) / ta.wma(atrwo, length)
// @function Moving Average by type
// @param src The source of the moving average
// @param length The length of the moving average calculation
// @param type The type of the moving average
// @param offset Used only by ALMA, it is the ALMA offset
// @param sigma Used only by ALMA, it is the ALMA sigma
// @param phase The phase of jurik MA calculation (-100..100)
// @param power The power of jurik MA calculation
// @returns The moving average series
export anyma(series float src, simple int length, simple string type = "EMA",
simple float offset = 0.85, simple int sigma = 6,
simple int atr_length = 14, simple int stdev_length = 100, simple float stdev_mult = 1.0,
simple int phase = 50, simple float power = 2) =>
switch type
"ATRWSMA" => atrwma(src, length, type="SMA", atr_length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult)
"ATRWEMA" => atrwma(src, length, type="EMA", atr_length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult)
"ATRWRMA" => atrwma(src, length, type="RMA", atr_length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult)
"ATRWWMA" => atrwma(src, length, type="WMA", atr_length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult)
"JMA" => jma(src, length, phase=phase, power=power)
=> _anyma_builtin(src=src, length=length, type=type, offset=offset, sigma=sigma, phase=phase, power=power)
// @function Slope per ATR, it is a slope, that can be used across multiple assets
// @param src The Source of slope
// @param lookback How many timestaps to look back
// @param atr_length The length of the TR smoothing
// @param stdev_length The length of the standard deviation, used for detecting outliers
// @param stdev_mult The multiplier of the standard deviation, used for detecting outliers
// @param atr_ma_type The moving average type used for smoothing
// @returns The slope value
export slope_per_atr(series float src, simple int lookback,
simple int atr_length = 14, simple int stdev_length = 100, simple float stdev_mult = 0.5, simple string atr_ma_type = "RMA") =>
atr = atrwo(length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult, ma_type=atr_ma_type)
ta.change(src, lookback) / lookback / atr
// @function Angle of Slope per ATR
// @param src The Source of slope
// @param lookback How many timestaps to look back
// @param atr_length The length of the TR smoothing
// @param stdev_length The length of the standard deviation, used for detecting outliers
// @param stdev_mult The multiplier of the standard deviation, used for detecting outliers
// @param atr_ma_type The moving average type used for smoothing
// @returns The slope value
export angle(series float src, simple int lookback,
simple int atr_length = 14, simple int stdev_length = 100, simple float stdev_mult = 0.5, simple string atr_ma_type = "RMA") =>
slope = slope_per_atr(src=src, lookback=lookback, atr_length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult, atr_ma_type=atr_ma_type)
math.atan(slope) * TORAD
// @function Moving Average Convergence Divergence (MACD)
// @param fast_src The source series used by MACD fast
// @param slow_src The source series used by MACD slow
// @param fast_ma_type The MA type for the MACD
// @param slow_ma_type The MA type for the MACD
// @param fast_length The fast MA length of the MACD
// @param slow_length The slow MA length of the MACD
// @param signal_ma_type The MA type for the MACD signal
// @param signal_length The signal MA length of the MACD
export macd(series float fast_src = close, series float slow_src = close,
simple string fast_ma_type = "EMA", simple string slow_ma_type = "EMA",
simple int fast_length = 12, simple int slow_length = 26,
simple string signal_ma_type = "EMA", simple int signal_length = 9) =>
fast_ma = anyma(fast_src, fast_length, fast_ma_type)
slow_ma = anyma(slow_src, slow_length, slow_ma_type)
macd = fast_ma - slow_ma
signal = anyma(macd, signal_length, signal_ma_type)
hist = macd - signal
[macd, signal, hist]
// @function Waddah Attar Explosion (WAE)
// @param macd_src The source series used by MACD
// @param macd_ma_type The MA type for the MACD
// @param macd_fast_length The fast MA length of the MACD
// @param macd_slow_length The slow MA length of the MACD
// @param macd_sensitivity The MACD diff multiplier
// @param bb_base_src The source used by stdev
// @param bb_upper_src The source used by the upper Bollinger Band
// @param bb_lower_src The source used by the lower Bollinger Band
// @param bb_ma_type The MA type of the Bollinger Bands
// @param bb_length The lenth for Bollinger Bands
// @param bb_mult The multiplier for Bollinger Bands
// @param dead_zone_length The ATR length for dead zone calculation
// @param dead_zone_mult The ATR multiplier for dead zone
// @returns [float up, float down, float explosion, float dead_zone]
export wae(series float macd_src = close, simple string macd_ma_type = "EMA", simple int macd_fast_length = 20, simple int macd_slow_length = 40, simple float macd_sensitivity = 100.0,
series float bb_base_src = close, series float bb_upper_src = high, series float bb_lower_src = low,
simple string bb_ma_type = "SMA", simple int bb_length = 20, simple float bb_mult = 2.0,
simple int dead_zone_length = 100, simple float dead_zone_mult = 3.7) =>
macd_fast_ma = anyma(macd_src, macd_fast_length, macd_ma_type)
macd_slow_ma = anyma(macd_src, macd_slow_length, macd_ma_type)
macd_diff = ((macd_fast_ma - macd_slow_ma) - (macd_fast_ma[1] - macd_slow_ma[1])) * macd_sensitivity
bb_dev = ta.stdev(bb_base_src, bb_length) * bb_mult
bb_upper = anyma(bb_upper_src, bb_length, bb_ma_type) + bb_dev
bb_lower = anyma(bb_lower_src, bb_length, bb_ma_type) - bb_dev
explosion = bb_upper - bb_lower
float up = (macd_diff >= 0) ? macd_diff : na
float down = (macd_diff < 0) ? (-1 * macd_diff) : na
dead_zone = nz(ta.rma(ta.tr(true), dead_zone_length)) * dead_zone_mult
[up, down, explosion, dead_zone]
// @function Semaphore Signal Level channel (SSL)
// @param length The length of the moving average
// @param src Source of compare
// @param high_src Source of the high moving average
// @param low_src Source of the low moving average
// @returns [ssl_up, ssl_down]
export ssl(simple int length = 10, simple string ma_type = "SMA",
series float src = close, series float high_src = high, series float low_src = low) =>
ma_high = anyma(high_src, length, ma_type)
ma_low = anyma(low_src, length, ma_type)
float hlv = na
hlv := src > ma_high ? 1 : src < ma_low ? -1 : hlv[1]
ssl_down = hlv < 0 ? ma_high: ma_low
ssl_up = hlv < 0 ? ma_low : ma_high
[ssl_up, ssl_down]
// @function Average Directional Index + Direction Movement Index (ADX + DMI)
// @param atr_length The length of ATR
// @param di_length DI plus and minus smoothing length
// @param adx_length ADX smoothing length
// @param high_src Source of the high moving average
// @param low_src Source of the low moving average
// @param atr_ma_type MA type of the ATR calculation
// @param di_ma_type MA type of the DI calculation
// @param adx_ma_type MA type of the ADX calculation
// @param atr_stdev_length The length of the standard deviation, used for detecting outliers
// @param atr_stdev_mult The multiplier of the standard deviation, used for detecting outliers
// @returns [plus, minus, adx]
export adx(simple int atr_length = 14, simple int di_length = 14, simple int adx_length = 14,
series float high_src = high, series float low_src = low,
simple string atr_ma_type = "RMA", simple string di_ma_type = "RMA", simple string adx_ma_type="RMA",
simple int atr_stdev_length=100, simple float atr_stdev_mult=1.0) =>
up = ta.change(high_src)
down = -ta.change(low_src)
plus_dm = na(up) ? na : (up > down and up > 0 ? up : 0)
minus_dm = na(down) ? na : (down > up and down > 0 ? down : 0)
atr = atrwo(length=atr_length, stdev_length=atr_stdev_length, stdev_mult=atr_stdev_mult, ma_type=atr_ma_type)
plus = fixnan(100 * anyma(plus_dm, di_length, di_ma_type) / atr)
minus = fixnan(100 * anyma(minus_dm, di_length, di_ma_type) / atr)
sum = plus + minus
adx = 100 * anyma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_length, adx_ma_type)
[plus, minus, adx]
// @function Choppiness Index (CHOP) using ATRWO
// @param length The sum and highest/lowest length
// @param atr_length The length of the ATR
// @param stdolev_length The length of the standard deviation, used for detecting outliers
// @param stdev_mult The multiplier of the standard deviation, used for detecting outliers
// @param ma_type The MA type of ATR
// @returns The choppiness value
export chop(simple int length = 12, simple int atr_length = 3, simple int stdev_length = 100, simple float stdev_mult = 1.0, simple string ma_type = "RMA") =>
atr = atrwo(length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult, ma_type=ma_type)
100 * math.log10(math.sum(atr, length) / (ta.highest(length) - ta.lowest(length))) / math.log10(length)
// @function Choppiness Index (CHOP) using stdev instead of ATR
// @param length The sum and highest/lowest length
// @param src The source of the stdev
// @param stdev_length The length of the stdev calculation
// @returns The choppiness value
export chop_stdev(simple int length = 12, series float src = close, simple int stdev_length = 12) =>
stdev = ta.stdev(src, stdev_length)
100 * math.log10(math.sum(stdev, length) / (ta.highest(length) - ta.lowest(length))) / math.log10(length)
// @function Keltner Channels (KC)
// @param length The length of moving averages
// @param atr_length The ATR length, the ATR is used to shift the upper and lower bands
// @param mult The ATR multiplier
// @param base_src Source of the base line
// @param upper_src Source of the upper line
// @param lower_src Source of the lower line
// @param base_ma_type The MA type of the base line
// @param upper_ma_type The MA type of the upper line
// @param lower_ma_type The MA type of the lower line
// @param stdev_length The length of the standard deviation, used for detecting outliers
// @param stdev_mult The multiplier of the standard deviation, used for detecting outliers
// @retrurns [base, lower, upper]
export kc(simple int length = 20, simple int atr_length = 14, simple float mult=2.0,
series float base_src = close, series float upper_src = close, series float lower_src = close,
simple string base_ma_type = "SMA", simple string upper_ma_type = "SMA", simple string lower_ma_type = "SMA",
simple int stdev_length = 100, simple float stdev_mult = 1.0, simple string atr_ma_type = "RMA") =>
atr = atrwo(length=atr_length, stdev_length=stdev_length, stdev_mult=stdev_mult, ma_type=atr_ma_type) * mult
// KC
base= anyma(base_src, length, base_ma_type)
upper = anyma(upper_src, length, upper_ma_type) + atr
lower = anyma(lower_src, length, lower_ma_type) - atr
[base, lower, upper]
// @function Keltner Channel Trend
// @param base The base value returned by kc function
// @param upper The upper value returned by kc function
// @param lower The lower value returned by kc function
// @param lookback Howmany timestaps to look back to determine the trend
// @returns [uptrend, downtrend, base_uptrend, lower_uptrend, upper_uptrend]
export kc_trend(series float base, series float lower, series float upper, simple int lookback = 1) =>
// Trends
upper_uptrend = upper > upper[lookback]
base_uptrend = base > base[lookback]
lower_uptrend = lower > lower[lookback]
uptrend = upper_uptrend and base_uptrend and lower_uptrend
downtrend = not upper_uptrend and not base_uptrend and not lower_uptrend
[uptrend, downtrend, base_uptrend, lower_uptrend, upper_uptrend]
// @function Supertrend, calculated from above "kc" (Keltner Channel Function)
// @param upper The upper value returned by kc function
// @param lower The lower value returned by kc function
// @param compare_src Source of the base line
// @param returns [supertrend, direction]
export supertrend(series float lower, series float upper, series float compare_src = close) =>
float _upper = na
float _lower = na
prev_upper = _upper[1]
prev_lower = _lower[1]
_lower := lower > prev_lower or compare_src[1] < prev_lower or na(prev_lower) ? lower : prev_lower
_upper := upper < prev_upper or compare_src[1] > prev_upper or na(prev_upper) ? upper : prev_upper
int direction = na
float supertrend = na
prev_supertrend = supertrend[1]
if prev_supertrend == prev_upper
direction := compare_src > _upper ? -1 : 1
else
direction := compare_src < _lower ? 1 : -1
supertrend := direction == -1 ? _lower : _upper
[supertrend, direction]
// @function Heiken Ashi (Smoothed) Candle
// @param smooth_length Smooth length before heiken ashi calculation
// @param smooth_ma_type Type of smoothing MA before heiken ashi calculation
// @param after_smooth_length Smooth length after
// @param after_smooth_ma_type Smooth MA type after
// @param src_open Sourve of open
// @param src_high Source of high
// @param src_low Source of low
// @param src_close Source of close
// @returns [open, high, low, close]
export heiken_ashi(simple int smooth_length = 1, simple string smooth_ma_type = "EMA",
simple int after_smooth_length = 1, simple string after_smooth_ma_type = "EMA",
series float src_open = open, series float src_high = high, series float src_low = low, series float src_close = close) =>
float haopen = na
o = anyma(src_open, smooth_length, smooth_ma_type)
h = anyma(src_high, smooth_length, smooth_ma_type)
l = anyma(src_low, smooth_length, smooth_ma_type)
c = anyma(src_close, smooth_length, smooth_ma_type)
haclose = (o + h + l + c) / 4.0
haopen := na(haopen[1]) ? (o + c) / 2 : (haopen[1] + haclose[1]) / 2
hahigh = math.max(h, math.max(haopen, haclose))
halow = math.min(l, math.min(haopen, haclose))
o := anyma(haopen, after_smooth_length, after_smooth_ma_type)
h := anyma(hahigh, after_smooth_length, after_smooth_ma_type)
l := anyma(halow, after_smooth_length, after_smooth_ma_type)
c := anyma(haclose, after_smooth_length, after_smooth_ma_type)
[o, h, l, c]
// @function Calculate recent swing high and low from Heiken Ashi candle reverse points
// @param use_ha_candle If true, use HA candle open/close to swing high/low instead of normal high/low
export swinghl(simple bool use_ha_candle = false) =>
var float upper = na
var float lower = na
[o, h, l, c] = heiken_ashi()
if c[1] > o[1] and c < o
upper := use_ha_candle ? c[1] : high[1]
else if c[1] < o[1] and c > o
lower := use_ha_candle ? o[1] : low[1]
[upper, lower]
/////////////
// Testing //
/////////////
//
// MA Selector
//
// ma_type = input.string("EMA", "MA Type", options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="MA")
// ma_src = input.source(close, "MA Source", group="MA")
// ma_length = input.int(50, "MA Length", group="MA")
// plot(anyma(ma_src, ma_length, ma_type), "Any MA", color=color.white, linewidth=3)
//
// SSL
//
// ssl_length = input.int(20, "SSL Length", group="SSL")
// ssl_src = input.source(hl2, "Source", group="SSL")
// ssl_high_src = input.source(high, "Source of High", group="SSL")
// ssl_low_src = input.source(low, "Source of Low", group="SSL")
// ssl_ma_type = input.string("SMA", "MA Type", options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="SSL")
// [ssl_up, ssl_down] =
// ssl(length=ssl_length, src=ssl_src, high_src=ssl_high_src, low_src=ssl_low_src, ma_type=ssl_ma_type)
// pup = plot(ssl_up, "SSL Up", linewidth=2, color=color.new(color.lime, 50))
// pdown = plot(ssl_down, "SSL Down", linewidth=2, color=color.new(color.red, 50))
// fill(pup, pdown, ssl_up >= ssl_down ? color.new(color.green, 90) : color.new(color.red, 90))
//
// Keltner Channels
//
// kc_length = input.int(20, "KC Length", minval=1, group="KC")
// kc_atr_length = input.int(20, 'ATR Length', minval=1, group="KC")
// kc_mult = input.float(1.0, 'KC Mult', step=0.1, group="KC")
// kc_base_src = input(close, title='Base Source', group="KC")
// kc_upper_src = input(close, title='Upper Source', group="KC")
// kc_lower_src = input(close, title='Lower Source', group="KC")
// kc_base_ma_type = input.string('SMA', 'Base MA Type', options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="KC")
// kc_upper_ma_type = input.string('SMA', 'Upper MA Type', options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="KC")
// kc_lower_ma_type = input.string('SMA', 'Lower MA Type', options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN"], group="KC")
// kc_stdev_length = input.int(200, 'TR StDev Length', minval=1, group="KC")
// kc_stdev_mult = input.float(1.0, 'TR StDev Multiplier', minval=0.01, step=0.1, group="KC")
// kc_atr_ma_type = input.string('RMA', 'ATR MA Type', options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="KC")
// kc_trend_lookback = input.int(1, "Trend Lookback", minval=1, group="KC")
// [kc_base, kc_lower, kc_upper] = kc(length=kc_length, atr_length=kc_atr_length, mult=kc_mult,
// base_src=kc_base_src, upper_src=kc_upper_src, lower_src=kc_lower_src,
// base_ma_type=kc_base_ma_type, upper_ma_type=kc_upper_ma_type, lower_ma_type=kc_lower_ma_type,
// stdev_length=kc_stdev_length, stdev_mult=kc_stdev_mult, atr_ma_type=kc_atr_ma_type)
// [kc_uptrend, kc_downtrend, kc_base_uptrend, kc_lower_uptrend, kc_upper_uptrend] = kc_trend(base=kc_base, lower=kc_lower, upper=kc_upper, lookback=kc_trend_lookback)
// // Dynamic colors
// kc_color_upper = kc_upper_uptrend ? color.new(color.green, 50) : color.new(color.red, 50)
// kc_color_base = kc_base_uptrend ? color.new(color.green, 50) : color.new(color.red, 50)
// kc_color_lower = kc_lower_uptrend ? color.new(color.green, 50) : color.new(color.red, 50)
// kc_color_bg = kc_uptrend ? color.new(color.green, 90) : kc_downtrend ? color.new(color.red, 90) : color.new(color.gray, 90)
// // Plotting
// kc_up_plot = plot(kc_upper, color=kc_color_upper, title='KC Upper')
// plot(kc_base, color=kc_color_base, title='KC Base')
// kc_low_plot = plot(kc_lower, color=kc_color_lower, title='KC Lower')
// fill(kc_up_plot, kc_low_plot, color=kc_color_bg, title='KC Background')
//
// Smoothed Heiken Ashi
//
// ha_smooth_length = input.int(10, "Before Smooth Length", minval=1, group="Heiken Ashi")
// ha_after_smooth_length = input.int(10, "After Smooth Length", minval=1, group="Heiken Ashi")
// ha_smooth_ma_type = input.string('EMA', 'Before MA Type', options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="Heiken Ashi")
// ha_after_smooth_ma_type = input.string('EMA', 'After MA Type', options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "LSMA", "SWMA", "SMMA", "JMA", "DONCHIAN", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="Heiken Ashi")
// [o, h, l, c] = heiken_ashi(smooth_length=ha_smooth_length, smooth_ma_type=ha_smooth_ma_type, after_smooth_length=ha_after_smooth_length, after_smooth_ma_type=ha_after_smooth_ma_type)
// plotcandle(o, h, l, c, title="Smoothed Heiken Ashi", color=o > c ? color.red : color.lime)
//
// Recent Swing H/L
//
swing_use_ha_candle = input.bool(false, "Use HA Open/High")
[swing_upper, swing_lower] = swinghl(swing_use_ha_candle)
plot(swing_upper, "Swing Upper", color=color.green, style=plot.style_stepline)
plot(swing_lower, "Swing Lower", color=color.red, style=plot.style_stepline)
//
// Supertrend
//
// [supertrend, supertrend_direction] = supertrend(lower=kc_lower, upper=kc_upper)
// plot(supertrend_direction < 0 ? supertrend : na, "Supertrend Up direction", color=color.green, style=plot.style_linebr)
// plot(supertrend_direction < 0 ? na : supertrend, "Supertrend Down direction", color=color.red, style=plot.style_linebr)
//
// WAE + MA selector
//
// wae_macd_src = input.source(close, "WAE MACD Source", group="WAE")
// wae_macd_ma_type = input.string("EMA", "MACD MA Type", options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "JMA", "LSMA", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="WAE")
// wae_macd_fast_length = input.int(20, "FastEMA Length", minval=1, group="WAE")
// wae_macd_slow_length = input.int(40, "SlowEMA Length", minval=1, group="WAE")
// wae_macd_sensitivity = input.int(100, "Sensitivity", minval=1, group="WAE")
// wae_bb_base_src = input.source(close, "WAE BB Base Source", group="WAE")
// wae_bb_upper_src = input.source(high, "WAE BB Base Source", group="WAE")
// wae_bb_lower_src = input.source(low, "WAE BB Base Source", group="WAE")
// wae_bb_ma_type = input.string("SMA", "BB MA Type", options=['SMA', 'EMA', 'WMA', "VWMA", "RMA", "DEMA", "TEMA", "ZLEMA", "HMA", "ALMA", "JMA", "LSMA", "ATRWSMA", "ATRWEMA", "ATRWRMA", "ATRWWMA"], group="WAE")
// wae_bb_length = input.int(20, "BB Channel Length", minval=1, group="WAE")
// wae_bb_mult = input.float(2.0, "BB Stdev Multiplier", step=0.1, minval=0.1, group="WAE")
// [wae_up, wae_down, wae_explosion, wae_dead_zone] = wae(
// macd_src=wae_macd_src, macd_ma_type=wae_macd_ma_type, macd_fast_length=wae_macd_fast_length, macd_slow_length=wae_macd_slow_length, macd_sensitivity=wae_macd_sensitivity,
// bb_base_src=wae_bb_base_src, bb_upper_src=wae_bb_upper_src, bb_lower_src=wae_bb_lower_src, bb_ma_type=wae_bb_ma_type, bb_length=wae_bb_length, bb_mult=wae_bb_mult)
// plot(wae_up, "WAE Up Trend", style=plot.style_columns, linewidth=1, color=(wae_up < wae_up[1]) ? color.green : color.lime, transp=45)
// plot(wae_down, "WAE Down Trend", style=plot.style_columns, linewidth=1, color=(wae_down < wae_down[1]) ? color.maroon : color.red, transp=45)
// plot(wae_explosion, "WAE Explosion Line", style=plot.style_line, linewidth=2, color=color.orange)
// plot(wae_dead_zone, "WAE Dead Zone", color=color.blue, linewidth=1, style=plot.style_cross)
//
// Chop
//
// chop_length = input.int(12, "Chop Length", minval=1, group="Chop")
// chop_atr_length = input.int(3, "ATR Length", minval=1, group="Chop")
// chop_atrwo_stdev_length = input.int(100, "ATRWO STDev Length", minval=1, group="Chop")
// chop_atrwo_stdev_mult = input.float(1.0, "ATRWO STDev Multiplier", minval=0.0, step=0.1, group="Chop")
// chop_stdev_src = input.source(hl2, "STDev Source", group="Chop")
// chop_stdev_length = input.int(12, "STDev Length", minval=1, group="Chop")
// chop_atr = chop(length=chop_length, atr_length=chop_atr_length, stdev_length=chop_atrwo_stdev_length, stdev_mult=chop_atrwo_stdev_mult)
// chop_stdev = chop_stdev(length=chop_length, src=chop_stdev_src, stdev_length=chop_stdev_length)
// plot(chop_atr, "CHOP ATR", color=color.teal)
// plot(chop_stdev, "CHOP STD", color=color.blue)
// band1 = hline(61.8, "Upper Band", color=#C0C0C0, linestyle=hline.style_dashed)
// band0 = hline(38.2, "Lower Band", color=#C0C0C0, linestyle=hline.style_dashed)
// fill(band1, band0, color=#996B1920, title="Background")
// hline(50, "Center", color=color.gray, linestyle=hline.style_dashed)
|
FunctionCosineSimilarity | https://www.tradingview.com/script/GJdeNt95-FunctionCosineSimilarity/ | 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 Cosine Similarity method.
library("FunctionCosineSimilarity")
import RicardoSantos/DebugConsole/6 as console
[__T, __C] = console.init(25)
// @function Measure the similarity of 2 vectors.
// @param sample_a float array, values.
// @param sample_b float array, values.
// @returns float.
export function (float[] sample_a, float[] sample_b) => //{
int _size_a = array.size(sample_a)
int _size_b = array.size(sample_b)
//
switch
(_size_a < 1) => runtime.error('FunctionCosineSimilarity -> function(): "sample_a" has invalid size.')
(_size_b < 1) => runtime.error('FunctionCosineSimilarity -> function(): "sample_b" has invalid size.')
(_size_a != _size_b) => runtime.error('FunctionCosineSimilarity -> function(): "sample_a" and "sample_a" size is not symmetric.')
//
float _dot = 0.0
float _norm_a = 0.0
float _norm_b = 0.0
for _i = 0 to _size_a-1
float _ai = array.get(sample_a, _i)
float _bi = array.get(sample_b, _i)
_dot += _ai * _bi
_norm_a += math.pow(_ai, 2.0)
_norm_b += math.pow(_bi, 2.0)
_dot / (math.sqrt(_norm_a) * math.sqrt(_norm_b))
//{ usage
// var a = array.new_float(10)
// var b = array.new_float(10)
// array.unshift(a, nz(close/ta.ema(close, 10), 0.0)), array.pop(a)
// array.unshift(b, float(math.sin(bar_index%10))), array.pop(b)
// cs = function(a, b)
// [m, u, l]= ta.bb(cs, input(200), input(2.0))
// plot(cs)
// plot(m), plot(u), plot(l)
console.queue_one(__C, str.format('{0}', function(array.from(3.0, 2, 0, 5), array.from(1.0, 0, 0, 0))))
//{ remarks:
// https://stackoverflow.com/questions/520241/how-do-i-calculate-the-cosine-similarity-of-two-vectors
// https://www.geeksforgeeks.org/cosine-similarity/
//}}}
// @function Dissimilarity helper function.
// @param cosim float, cosine similarity value (0 > 1)
// @returns float
export diss (float cosim) => 1.0 - cosim
console.update(__T, __C) |
MakeLoveNotWar | https://www.tradingview.com/script/3Kvi7zHy-MakeLoveNotWar/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 58 | library | 5 | MPL-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 Make Love Not War, place a flag of support on your chart!
library(title='MakeLoveNotWar', overlay=true)
// @function Make Love Not War function.
// @param pos string, position.
// @param text_size string, text size.
// @returns table.
export flag (simple string pos=position.top_right, simple string text_size=size.normal) =>
var table _T = table.new(pos, 2, 3)
color _blue = #0057B8
color _yellow = #FFD700
table.cell(_T, 0, 0, '', bgcolor=_blue)
table.cell(_T, 1, 0, '', bgcolor=_blue)
table.cell(_T, 0, 1, '', bgcolor=_yellow)
table.cell(_T, 1, 1, '', bgcolor=_yellow)
table.cell(_T, 0, 2, 'Make Love', text_color=_blue, text_size=text_size)
table.cell(_T, 1, 2, ' Not War!', text_color=_yellow, text_size=text_size)
flag() |
Cayoshi_Library | https://www.tradingview.com/script/iZcjz6AV/ | Naruephat | https://www.tradingview.com/u/Naruephat/ | 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/
// © Naruephat
//@version=5
// @description TODO: add library description here
library("Cayoshi_Library")
//เรียกใช้ library
//import Naruephat/Cayoshi_Library/1 as fuLi
//Copy ส่วนล่างไปใช้
// แสดงหน้ายิ้ม แพ้ ชนะ
// ==========================================================================================================================================================================================================================================================
//Win_Loss_Showa = input.bool(true , 'show Win loss')
//[win,loss,equal] = fuLi.Win_Loss_Show()
//plotchar( Win_Loss_Showa ? win : na ,location = location.abovebar ,color = color.new(color.green, 0), char='☺' , size = size.normal) //==
//plotchar( Win_Loss_Showa ? loss : na ,location = location.belowbar , color = color.new(color.red, 0), char='☹' , size = size.small) //==
//plotchar( Win_Loss_Showa ? equal : na ,location = location.belowbar , color = color.new(color.orange, 0), char='☹' , size = size.small) //==
//แสดงผล Backtest
// ==========================================================================================================================================================================================================================================================
//show_Net = input.bool(true,'Show Net', inline = 'Lnet')
//position_ = input.string('top_right','Position', options = ['top_right','middle_right','bottom_right','top_center','middle_center','bottom_center','middle_left','bottom_left'] , inline = 'Lnet')
//size_i = input.string('auto','size', options = ['auto','tiny','small','normal'] , inline = 'Lnet')
//color_Net = input.color(color.blue,"" , inline = 'Lnet')
//fuLi.NetProfit_Show(show_Net , position_ , size_i, color_Net )
//กำหนดระยะเวลา หรือ แท่งบาร์ในการ Backtest
//---------------------------------------------------------------------------------------------------------------
//Back_Test = input.bool(false , '═════ Bar Back Test ═════')
//Back_Test_bar_start = input.int(0, 'count back bar start',inline = 'btes' , minval = 0)
//Back_Test_step_start = input.int(100 , 'count step start' ,inline = 'btes' , minval = 0)
//Back_Test_bar_end = input.int(0 , 'count back bar end',inline = 'bte' , minval = 0)
//Back_Test_step_end = input.int(100 , 'count step end' ,inline = 'bte' , minval = 0)
//G0 = 'Set Test Date'
//i_dateFilter = input.bool(false, "═════ Date Range Filtering ═════" ,group = G0)
//i_fromYear = input.int(2021, "From Year", minval = 1900 ,inline = 'd1',group = G0)
//i_fromMonth = input.int(5, "From Month", minval = 1, maxval = 12,inline = 'd2',group = G0)
//i_fromDay = input.int(10, "From Day", minval = 1, maxval = 31,inline = 'd3',group = G0)
//i_toYear = input.int(2023, "To Year", minval = 1900,inline = 'd1',group = G0)
//i_toMonth = input.int(12, "To Month", minval = 1, maxval = 12,inline = 'd2',group = G0)
//i_toDay = input.int(31, "To Day", minval = 1, maxval = 31,inline = 'd3',group = G0)
//
//Back_test = fuLi.Count_Bar_Back_Test( Back_Test , Back_Test_bar_start, Back_Test_step_start, Back_Test_bar_end, Back_Test_step_end , i_dateFilter, i_fromYear, i_fromMonth, i_fromDay, i_toYear, i_toMonth, i_toDay )
//---------------------------------------------------------------------------------------------------------------
export Win_Loss_Show() =>
//==
var entryP = 0. //==
var exitP = 0. //==
//==
if(ta.change(strategy.position_size) and strategy.position_size == 0) //==
//==
entryP := nz(strategy.closedtrades.entry_price(strategy.closedtrades-1)) //==
exitP := nz(strategy.closedtrades.exit_price(strategy.closedtrades-1)) //==
buy_entryP = entryP //==
sell_exitP = exitP //==
var buy_SELL = 2 //==
buy_SELL := strategy.position_size > 0 ? 0 : strategy.position_size < 0 ? 1 : 2
win = nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy_entryP < sell_exitP
loss = nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy_entryP > sell_exitP
equal = nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy_entryP == sell_exitP
[win,loss,equal]
export NetProfit_Show(bool show_Net ,string position_ ,string size_i,color color_Net ) =>
//show_Net = true
//position_ = input.string('top_right','Position', options = ['top_right','middle_right','bottom_right','top_center','middle_center','bottom_center','middle_left','bottom_left'] , inline = 'Lnet')
//size_i = input.string('auto','size', options = ['auto','tiny','small','normal'] , inline = 'Lnet')
//color_Net = input.color(color.blue,"" , inline = 'Lnet')
percenProfit = (strategy.netprofit / strategy.initial_capital ) *100
colprofit = percenProfit < 0 ? color.red : color.white
profitFac = strategy.grossprofit / strategy.grossloss
percenwin = (strategy.wintrades / strategy.closedtrades) * 100
Netprofit = str.tostring(strategy.netprofit,'#,###.##') +'\n'+str.tostring(percenProfit,'#,###.##')+' % '
win = str.tostring(percenwin,'#.##')+' % '
profitFactor = str.tostring(profitFac,'#.###')
close_Trad = str.tostring(strategy.closedtrades,'#,###') + '\n' + 'W: '+str.tostring(strategy.wintrades)+' |L: '+ str.tostring(strategy.losstrades)
max_drawdown =str.tostring( strategy.max_drawdown,'#,###.##')
tra = 80
position_CH = position_ == 'bottom_right' ? position.bottom_right :
position_ == 'bottom_left' ? position.bottom_left :
position_ == 'bottom_center' ? position.bottom_center :
position_ == 'middle_right' ? position.middle_right :
position_ == 'middle_left' ? position.middle_left :
position_ == 'middle_center' ? position.middle_center :
position_ == 'top_right' ? position.top_right :
position_ == 'top_center' ? position.top_center : position.bottom_right
size_ = size_i == 'auto' ? size.auto :
size_i == 'tiny' ? size.tiny :
size_i == 'small' ? size.small :
size_i == 'small' ? size.normal : size.auto
if show_Net
table table_Net = table.new(position_CH , 5,50 ,border_color = color.black, border_width = 1 )
table.cell(table_Net, 0,1, 'Netprofit',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) )
table.cell(table_Net, 1,1, 'CloseTrad',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) )
table.cell(table_Net, 2,1, 'Win',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) )
table.cell(table_Net, 3,1, 'Factor',text_size =size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) )
table.cell(table_Net, 4,1, 'Drawdown',text_size = size_ , bgcolor = color.new(color_Net,tra),text_color =color.new(color.white,0) )
table.cell(table_Net, 0, 2, Netprofit,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(colprofit,0))
table.cell(table_Net, 1, 2, close_Trad,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(color.white,0))
table.cell(table_Net, 2, 2, win ,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(color.white,0) )
table.cell(table_Net, 3, 2, profitFactor,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(colprofit,0))
table.cell(table_Net, 4, 2, max_drawdown,text_size = size_ , bgcolor = color.new(color.black,30),text_color =color.new(color.red,0))
export Count_Bar_Back_Test(bool Back_Test ,int Back_Test_bar_start,int Back_Test_step_start,int Back_Test_bar_end, int Back_Test_step_end ,bool i_dateFilter,int i_fromYear,int i_fromMonth,int i_fromDay,int i_toYear,int i_toMonth,int i_toDay ) =>
count_backtest_bar_start = Back_Test ? ( Back_Test_bar_start * Back_Test_step_start) : 0
count_backtest_bar_end = Back_Test ? last_bar_index - ( Back_Test_bar_end* Back_Test_step_end) : last_bar_index
BarBackTEST = bar_index >= count_backtest_bar_start and bar_index <= count_backtest_bar_end
maxbar = last_bar_index / Back_Test_step_start
fromDate = timestamp(i_fromYear, i_fromMonth, i_fromDay, 00, 00)
toDate = time < timestamp(i_toYear, i_toMonth, i_toDay, 23, 59) ? time : timestamp(i_toYear, i_toMonth, i_toDay, 23, 59)
date_start_entry = i_dateFilter ? fromDate < time ? time : fromDate : time
var begin = date_start_entry
days = (toDate - begin) / (24 * 60 * 60 * 1000)
mess1 = str.tostring(days, "#.0 days /") + str.tostring(days/30, "#.0 month /") + str.tostring( strategy.closedtrades / days, "#.0 ") + 'ครั้งต่อวัน'
mess2 = Back_Test ? count_backtest_bar_start > last_bar_index ? ('start ' + str.tostring( count_backtest_bar_start,'#,###.##') +'....Over Bar' +' MAX:'+ str.tostring(maxbar,'#,###') ) : ('start ' + str.tostring( count_backtest_bar_start,'#,###.##') +' MAX:'+ str.tostring(maxbar,'#,###') ) : 'start 0 Bar MAX:'+ str.tostring(maxbar,'#,###')
mess3 = ( Back_Test ? ('end ' + str.tostring(last_bar_index ,'#,###.##') +' - ' + str.tostring( Back_Test_bar_end* Back_Test_step_end) + ' = ' + str.tostring(count_backtest_bar_end ,'#,###.##') ) : 'end ' +str.tostring(count_backtest_bar_end ,'#,###.##') ) + ' Bar'
table table_countbar = table.new(position.bottom_right, 1,50 ,border_color = color.orange)
table.cell(table_countbar,0, 0, mess1, bgcolor =color.new(color.blue,80),text_color =color.new(color.white,0) )
table.cell(table_countbar, 0, 1, mess2, bgcolor = color.new(color.red,80),text_color = count_backtest_bar_start > last_bar_index ? color.new(color.red,0) : color.new(color.white,15) )
table.cell(table_countbar, 0, 2, mess3, bgcolor = color.new(color.red,80),text_color =color.new(color.white,0) )
x = BarBackTEST and (not i_dateFilter or (time >= fromDate and time <= toDate))
//use_ts = input.bool(false, 'use TS' ,group = 'ts')
//sl = input.float(8, title = "stop loss %%",step = 0.1)
//tp1 = input.float(5, title = "take profit 1 %%" ,step = 0.1)
//tp2 = input.float(5, title = "take profit 2 %%" ,step = 0.1)
//tp3 = input.float(11, title = "take profit 3 %%" ,step = 0.1)
//activateTrailingOnThirdStep = input(false, title = "activate trailing on third stage (tp3 is amount, tp2 is offset level)")
export percen(float pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
export curProfitInPts() =>
if strategy.position_size > 0
(high - strategy.position_avg_price) / syminfo.mintick
else if strategy.position_size < 0
(strategy.position_avg_price - low) / syminfo.mintick
else
0
export calcStopLossPrice(float OffsetPts) =>
var float price = 0.
if strategy.position_size > 0
//ราคาเปิด -
price := strategy.position_avg_price - OffsetPts * syminfo.mintick
else if strategy.position_size < 0
price := strategy.position_avg_price + OffsetPts * syminfo.mintick
else
price := na
export calcProfitTrgtPrice(float OffsetPts) =>
calcStopLossPrice(-OffsetPts)
export getCurrentStage(float tp1 ,float tp2) =>
var stage = 0
if strategy.position_size == 0
stage := 0
if stage == 0 and strategy.position_size != 0
stage := 1
else if stage == 1 and curProfitInPts() >= tp1// 5
stage := 2
else if stage == 2 and curProfitInPts() >= tp2//10
stage := 3
stage
export calcTrailingAmountLevel(float points) =>
var float level = na
level := calcProfitTrgtPrice(points)
if not na(level)
if strategy.position_size > 0
if not na(level[1])
level := math.max(level[1], level)
if not na(level)
level := math.max(high, level)
else if strategy.position_size < 0
if not na(level[1])
level := math.min(level[1], level)
if not na(level)
level := math.min(low, level)
export calcTrailingOffsetLevel(float points, float offset) =>
float result = na
amountLevel = calcTrailingAmountLevel(points)
if strategy.position_size > 0
trailActiveDiff = amountLevel - calcProfitTrgtPrice(points)
if trailActiveDiff > 0
result := trailActiveDiff + calcProfitTrgtPrice(offset)
else if strategy.position_size < 0
trailActiveDiff = calcProfitTrgtPrice(points) - amountLevel
if trailActiveDiff > 0
result := calcProfitTrgtPrice(offset) - trailActiveDiff
result
export trailing_3step(float tp1_,float tp2_,float tp3_,bool activateTrailingOnThirdStep,float sl_ ) =>
var float tp1 = 0.
tp1 := percen(tp1_)
var float tp2 = 0.
tp2 := percen(tp2_)
var float tp3 = 0.
tp3 := percen(tp3_)
var float sl = 0.
sl := percen(sl_)
float stopLevel = na
float trailOffsetLevel = na
float c1 = calcTrailingAmountLevel(tp3)
float c2 = calcProfitTrgtPrice(tp3)
float profitLevel = activateTrailingOnThirdStep ? c1 : c2
curStage = getCurrentStage(tp1,tp2)
if curStage == 1
stopLevel := calcStopLossPrice(sl)
strategy.exit("x", loss = sl, profit = tp3, comment = "sl or tp3")
else if curStage == 2
stopLevel := calcStopLossPrice(0)
strategy.exit("x", stop = stopLevel, profit = tp3, comment = "breakeven or tp3")
else if curStage == 3
stopLevel := calcStopLossPrice(-tp1)
if activateTrailingOnThirdStep
strategy.exit("x", stop = stopLevel, trail_points = tp3, trail_offset = tp3-tp2, comment = "stop tp1 or trailing tp3 with offset tp2")
else
strategy.exit("x", stop = stopLevel, profit = tp3, comment = "tp1 or tp3")
else
strategy.cancel("x")
|
bytime | https://www.tradingview.com/script/qgXywape-bytime/ | hapharmonic | https://www.tradingview.com/u/hapharmonic/ | 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/
// © hapharmonic
//@version=5
// @description TODO: add library description here
library("bytime", overlay=true)
// @function TODO: to do something at the specified time.
// @returns TODO: ////Return =>> ht = hour , mt = minute , st = second ,Dt = Day, Mt = month, Yt = year , dateTime = full time format./////////////
whatIsTheTime(_dst,T) =>
TZ = T
DST = _dst ? 1 : 0
utcTime = 7 * 3600000 + timenow
[math.floor(utcTime / 3600000) % 24, math.floor(utcTime / 60000) % 60, math.floor(utcTime / 1000) % 60, dayofmonth(int(utcTime), TZ), month(int(utcTime), TZ), year(int(utcTime), TZ), dayofweek(int(utcTime), TZ)]
export Gtime(string gmtSelect) =>
[h, m, s, D, M, Y, A] = whatIsTheTime(false,gmtSelect)
ht = h < 10 ? '0' + str.tostring(h) : str.tostring(h)
mt = m < 10 ? '0' + str.tostring(m) : str.tostring(m)
st = s < 10 ? '0' + str.tostring(s) : str.tostring(s)
Dt = D < 10 ? '0' + str.tostring(D) : str.tostring(D)
Mt = M < 10 ? '0' + str.tostring(M) : str.tostring(M)
Yt = str.tostring(Y)
dateTime = Dt + '/' + Mt + '/' + Yt + '-' + ht + ':' + mt + ':' + st
[ht,mt,st,Dt,Mt,Yt,dateTime]
///////////////////////////////////////////////////////////////////
/////////////////////////////example///////////////////////////////
//Note : Remember to always add import when you call our library and change Gtime() to Timeset.Gtime() is used to access internal data.
// import hapharmonic/bytime/1 as Timeset
// [ht,mt,st,Dt,Mt,Yt,dateTime]=Timeset.Gtime()
///////////////////////////////////////////////////////////////////
gmtSelect = input.string(title="Select Local Time Zone", defval="GMT+7", options=["GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1", "GMT", "GMT+1", "GMT+2", "GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT+13"])
TH = input.string('07','Hr:',inline='T',group='timefilter')
TM = input.string('00','Min:',inline='T',group='timefilter')
TS = input.string('00','Sec:',inline='T',group='timefilter')
////Return =>> ht = hour , mt = minute , st = second ,Dt = Day, Mt = month, Yt = year , dateTime = full time format./////////////
[ht,mt,st,Dt,Mt,Yt,dateTime]=Gtime(gmtSelect)
/////////////Set a time to trigger an alert./////////////
ck = false
///hour : minute : second
if ht == TH and mt == TM and st == TS
//some action
//...
//.
ck := true
alertcondition(ck, title="Alert Test...",message= "Time = {{timenow}}\n{{exchange}}:{{ticker}}\nprice = {{close}}\nvolume = {{volume}}")
label l = label.new(bar_index+5,close,text=dateTime,color=color.black,
style=label.style_label_left,textcolor=color.white,
textalign=text.align_left,size=size.huge)
label.delete(l[1])
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
|
[e2] Drawing Library :: Horizontal Ray | https://www.tradingview.com/script/WRHeq9cf-e2-Drawing-Library-Horizontal-Ray/ | e2e4mfck | https://www.tradingview.com/u/e2e4mfck/ | 146 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © e2e4mfck
//@version=5
// @description e2's drawing library.
library("e2hray", overlay = true)
// —————————— hray() {
// @function Horizontal ray.
// @param condition Boolean condition that defines the initial point of a ray.
// @param level Ray price level.
// @param color Ray color.
// @param extend (optional) Default value true, current ray levels extend to the right, if false - up to the current bar.
// @param hist_lines (optional) Default value true, shows historical ray levels that were revisited, default is dashed lines. To avoid alert problems set to 'false' before creating alerts.
// @param alert_message (optional) Default value string(na), if declared, enables alerts that fire when price revisits a line, using the text specified.
// @param alert_delay (optional) Default value int(0), if declared, represents the delay in minutes to validate the level. Alerts won't trigger if the ray is broken during 'delay'.
// @param style (optional) Default value 'line.style_solid'.
// @param hist_style (optional) Default value 'line.style_dashed'.
// @param width (optional) Default value int(1), ray width in pixel.
// @param hist_width (optional) Default value int(1), historical ray width in pixels.
// @returns void
export hray(bool condition, float level, color color, bool extend = true, bool hist_lines = true, string alert_message = na, int alert_delay = 0, string style = line.style_solid, string hist_style = line.style_dashed, int width = 1, int hist_width = 1) =>
var line[] hrays = array.new_line()
var line[] histHrays = array.new_line()
var int delay = alert_delay * 60 * 1000 // MS_IN_MIN
if condition
array.push(hrays, line.new(time[1], level, time, level, xloc = xloc.bar_time, color = color, width = width, style = style))
for [i, hray] in hrays
float price = line.get_y1(hray)
int since = line.get_x1(hray)
line.set_x2(hray, time_close)
bool broken = price < close[1] ? low <= price : high >= price
if broken
if hist_lines
histHray = line.copy(hray), line.set_extend(histHray, extend.none), line.set_style(histHray, hist_style), line.set_width(histHray, hist_width), array.unshift(histHrays, histHray)
line.delete(hray)
if (time - since > delay) and (not na(alert_message))
alert(alert_message, alert.freq_once_per_bar)
else if extend
line.set_extend(hray, extend.right) // }
// —————————— hrays() examples {
// ————— • Example 1. Single horizontal ray from the dynamic input. {
// inputTime = input.time(timestamp("20 Jul 2021 00:00 +0300"), "Date", confirm = true)
// inputPrice = input.price(54, 'Price Level', confirm = true)
// hray(time == inputTime, inputPrice, color.blue, alert_message = 'Ray level re-test!')
// var label mark = label.new(inputTime, inputPrice, 'Selected point to start the ray', xloc.bar_time) // }
// ————— • Example 2. Multiple horizontal rays on the moving averages cross. {
// Intrabar Cross Value Function Library from @RicardoSantos https://www.tradingview.com/u/RicardoSantos/
import RicardoSantos/FunctionIntrabarCrossValue/1 as icv
float sma1 = ta.sma(close, 20)
float sma2 = ta.sma(close, 50)
bullishCross = ta.crossover( sma1, sma2)
bearishCross = ta.crossunder(sma1, sma2)
plot(sma1, 'sma1', color.purple)
plot(sma2, 'sma2', color.blue)
crossValue = icv.intrabar_cross_value(sma1, sma2)
// // 2a. We can use 2 function calls to distinguish long and short sides.
// hray(bullishCross, crossValue, color.green, alert_message = 'Bullish Cross Level Broken!', alert_delay = 10)
// hray(bearishCross, crossValue, color.red, alert_message = 'Bearish Cross Level Broken!', alert_delay = 10)
// 2b. Or a single call for both bullish and bearish side with a dynamic color.
hray(bullishCross or bearishCross, crossValue, bullishCross ? color.green : color.red) // }
// ————— • Example 3. Horizontal ray at the all time highs with an alert. alert_delay = 10 to prevent the alert trigger on consecutive break of ath {
// var float ath = 0, ath := math.max(high, ath)
// bool newAth = ta.change(ath)
// hray(nz(newAth[1]), high[1], color.orange, alert_message = 'All Time Highs Tested!', alert_delay = 10) // } // } |
eStrategy | https://www.tradingview.com/script/41vjd1gn-eStrategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 47 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=5
// @description Library contains methods which can help build custom strategy for continuous investment plans and also compare it with systematic buy and hold.
library("eStrategy")
// @function Calculates max equity, current drawdown from equity ATH and max drawdown
// @param equity Present equity value
// @returns equityAth - Equity all time high
// drawdown - Present drawdown percentage from equity ATH
// maxDrawdown - Max drawdown percentage
export getEquityAthAndDrawdown(float equity)=>
var equityAth = 0.0
var maxDrawdown = 0.0
equityAth := math.max(equityAth, equity)
drawdown = (equityAth - equity)*100/equityAth
maxDrawdown := math.max(maxDrawdown, nz(drawdown,0))
[equityAth, drawdown, maxDrawdown]
// @function Calculates average cash holding percent for strategy
// @param cash Present cash holding
// @param equity Present equity value
// @returns currentCashPercent - Cash Percent of Equity
// avgCashPercent - Average cash percent of equity
export getAverageCashPercent(float cash, float equity)=>
var counter = 0
var cashPercent = 0.0
currentCashPercent = 0.0
if(equity > 0)
counter += 1
currentCashPercent := 100*cash/equity
cashPercent += currentCashPercent
avgCashPercent = cashPercent/counter
[currentCashPercent, avgCashPercent]
// @function Depicts systematic buy and hold over period of time
// @param startYear Year on which SIP is started
// @param initialDeposit Initial one time investment at the start
// @param depositFrequency Frequency of recurring deposit - can be monthly or weekly
// @param recurringDeposit Recurring deposit amount
// @param buyPrice Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
// @returns totalInvestment - initial + recurring deposits
// totalQty - Quantity of units held for given instrument
// totalEquity - Present equity
export sip(simple int startYear = 2010, simple float initialDeposit = 10000,
simple string depositFrequency ="monthly", simple float recurringDeposit=1000,
float buyPrice = high, float dividends = 0) =>
var totalQty = 0.0
var totalInvestment = 0.0
var cash = 0.0
term = depositFrequency == "monthly"? month : weekofyear
var started = false
changeOfTerm = ta.change(term)!=0
recDep = changeOfTerm? recurringDeposit : 0
if(year >= startYear)
cash += dividends
if(changeOfTerm)
bnhAmount = (started ? recDep : initialDeposit) + cash
cash := 0
started := true
bnhQty = bnhAmount/buyPrice
totalInvestment += bnhAmount
totalQty += bnhQty
totalEquity = close*totalQty
[totalInvestment, totalQty, totalEquity]
// @function Allows users to define custom strategy and enhance systematic buy and hold by adding take profit and reloads
// @param startYear Year on which Strategy is started
// @param initialDeposit Initial one time investment at the start
// @param depositFrequency Frequency of recurring deposit - can be monthly or weekly
// @param recurringDeposit Recurring deposit amount
// @param buyPrice Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
// @param sellPrice Indicatinve sell price. Use low to be conservative. high, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
// @param initialInvestmentPercent percent of amount to invest from the initial depost. Keep rest of them as cash
// @param recurringInvestmentPercent percent of amount to invest from recurring deposit. Keep rest of them as cash
// @param signal can be 1, -1 or 0. 1 means buy/reload. -1 means take profit and 0 means neither.
// @param tradePercent percent of amount to trade when signal is not 0. If taking profit, it will sell the percent from existing position. If reloading, it will buy with percent from cash reserve
// @returns totalInvestment - initial + recurring deposits
// totalQty - Quantity of units held for given instrument
// totalCash = Amount of cash held
// totalEquity - Overall equity = totalQty*close + totalCash
export customStrategy(simple int startYear = 2010, simple float initialDeposit = 10000,
simple string depositFrequency ="monthly", simple float recurringDeposit=1000,
float buyPrice = high, float sellPrice = low,
simple float initialInvestmentPercent=50, simple float recurringInvestmentPercent=50, int signal=0, float tradePercent=50,
float dividends = 0) =>
var totalCash = 0.0
var totalQty = 0.0
var totalInvestment = 0.0
var cumulativePercentCash = 0.0
term = depositFrequency == "monthly"? month : weekofyear
var counter = 0
changeOfTerm = ta.change(term)!=0
recDep = changeOfTerm? recurringDeposit : 0
if(year >= startYear)
totalCash += dividends
if(changeOfTerm)
investAmount = (counter == 0 ? initialDeposit : recDep)
buyAmount = signal == 0 ? (counter == 0 ? initialDeposit*initialInvestmentPercent/100 : recDep*recurringInvestmentPercent/100) : 0
cashAmount = investAmount - buyAmount
buyQty = buyAmount/buyPrice
totalInvestment += investAmount
totalQty += buyQty
totalCash += cashAmount
if(counter!=0 and signal != 0)
if(signal == 1)
buyAmount = totalCash*tradePercent/100
buyQty = buyAmount/buyPrice
totalQty += buyQty
totalCash -= buyAmount
if(signal == -1)
sellQty = totalQty*tradePercent/100
sellAmount = sellQty*sellPrice
totalQty -= sellQty
totalCash += sellAmount
counter += 1
totalEquity = totalCash + close*totalQty
[totalInvestment, totalQty, totalCash, totalEquity]
// Coding example using sip
startYear = input.int(2010, maxval=2999, minval=0, title='Start Year', group='Inital Investment', tooltip='Year on which investment is started', confirm=true)
initialDeposit = input.float(10000, "Deposit", minval=0, step=5000, group="Inital Investment", tooltip='Initial one time deposit to start with', confirm=true)
recurringDepositFrequency = input.string("monthly", "Frequency", group="Recurring Investment", options=["monthly", "weekly"], tooltip="Periodic investment frequency", confirm=true)
recurringDeposit = input.float(1000, "Deposit", step=1000, minval=0, group="Recurring Investment", tooltip="Periodic investment", confirm=true)
buyPrice = input.source(high, "Buy Price", group="Buy and Hold")
strategyInvestPercent = input.float(80, "Regular investiment Percent", group="Strategy", step=10)
dipPercent = input.float(5, "Dip Percent", group="Strategy", step=5)
dipQty = input.float(30, "Dip Qty Percent", group="Strategy", step=10)
dipQtyIncrements = input.float(10, "Dip Qty Multiplier", group="Strategy", step=5)
buyPriceStrategy = input.source(high, "Buy Price", group="Strategy")
sellPriceStrategy = input.source(low, "Sell Price", group="Strategy")
dividends = nz(request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, ignore_invalid_symbol=true))
[totalInvestment, buyAndHoldQty, bnhEquity] = sip(startYear, initialDeposit, recurringDepositFrequency, recurringDeposit, buyPrice, dividends)
[bEquityAth, bDrawdown, bMaxDrawdown] = getEquityAthAndDrawdown(bnhEquity)
var ath = high
ath := math.max(ath, high)
distanceFromAth = (ath-close)*100/ath
distanceNumber = distanceFromAth < dipPercent? 0 :
distanceFromAth < dipPercent*2? 1 :
distanceFromAth < dipPercent*3? 2 :
distanceFromAth < dipPercent*4? 3 :
distanceFromAth < dipPercent*5? 4 :
distanceFromAth < dipPercent*6? 5 : 6
signal = ta.change(distanceNumber) > 0? 1: 0
qtyPercent = signal == 6? 100 : signal == 1? dipQty+dipQtyIncrements*(signal-1) : 0
[_totalInvestment, totalQty, totalCash, totalEquity] = customStrategy(startYear, initialDeposit, recurringDepositFrequency, recurringDeposit, buyPriceStrategy, sellPriceStrategy,
strategyInvestPercent, strategyInvestPercent, signal, qtyPercent, dividends)
[sEquityAth, sDrawdown, sMaxDrawdown] = getEquityAthAndDrawdown(totalEquity)
[currentCashPercent, avgCashPercent] = getAverageCashPercent(totalCash, totalEquity)
plot(totalEquity, "Strategy", color=color.new(color.yellow, 80), style=plot.style_area)
plot(bnhEquity, "Buy and Hold", color=color.new(color.green, 80), style=plot.style_area)
plot(totalInvestment, "Investment", color=color.new(color.purple, 80), style=plot.style_area)
var stats = table.new(position=position.top_right, columns=3, rows=7, border_width=1)
table.cell(stats, 1, 0, "Buy and Hold", bgcolor=color.teal, text_color=color.white)
table.cell(stats, 2, 0, "Strategy", bgcolor=color.teal, text_color=color.white)
table.cell(stats, 0, 1, "Equity", bgcolor=color.maroon, text_color=color.white)
table.cell(stats, 0, 2, "Max Equity", bgcolor=color.maroon, text_color=color.white)
table.cell(stats, 0, 3, "Drawdown", bgcolor=color.maroon, text_color=color.white)
table.cell(stats, 0, 4, "Max Drawdown", bgcolor=color.maroon, text_color=color.white)
table.cell(stats, 0, 5, "ROI", bgcolor=color.maroon, text_color=color.white)
table.cell(stats, 0, 6, "Average Cash Percent", bgcolor=color.maroon, text_color=color.white)
roiBnh = bnhEquity*100/totalInvestment
table.cell(stats, 1, 1, str.tostring(bnhEquity), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 1, 2, str.tostring(bEquityAth), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 1, 3, str.tostring(bDrawdown), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 1, 4, str.tostring(bMaxDrawdown), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 1, 5, str.tostring(roiBnh), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 1, 6, str.tostring(0), bgcolor=color.aqua, text_color=color.black)
roiStrategy = totalEquity*100/totalInvestment
table.cell(stats, 2, 1, str.tostring(totalEquity), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 2, 2, str.tostring(sEquityAth), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 2, 3, str.tostring(sDrawdown), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 2, 4, str.tostring(sMaxDrawdown), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 2, 5, str.tostring(roiStrategy), bgcolor=color.aqua, text_color=color.black)
table.cell(stats, 2, 6, str.tostring(avgCashPercent), bgcolor=color.aqua, text_color=color.black)
|
RVSI | https://www.tradingview.com/script/2Hre7Bm1-RVSI/ | MightyZinger | https://www.tradingview.com/u/MightyZinger/ | 43 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MightyZinger
//@version=5
// @description This Library contains functions that calculate all types of "Relative Volume Strength Index (MZ RVSI)" depending upon unique volume oscillator. Achieved RVSI value can be used for divergence in volume or to adapt dynamic length in Moving Averages.
library("RVSI", overlay=false)
// @function Relative Volume Strength Index based on TFS Volume Oscillator
// @param vol_src Volume Source
// @param vol_Len Volume Legth for TFS Volume Oscillato
// @param rvsiLen Period of Relative Volume Strength Index
// @param _open Ticker Open Value
// @param _close Ticker Close Value
// @returns Relative Volume Strength Index value based on TFS Volume Oscillator
export rvsi_tfs(float vol_src, simple int vol_Len, simple int rvsiLen, float _open, float _close) =>
float result = 0
nVolAccum = math.sum((_close > _open ? vol_src : _close < _open ? -vol_src : 0) ,vol_Len)
result := nVolAccum / vol_Len
var float rvsi = 0.0
// MA of Volume Oscillator Source
volMA = ta.sma(result , rvsiLen)
// RSI of Volume Oscillator Data
rsivol = ta.rsi(volMA, rvsiLen)
rvsi := ta.hma(rsivol, rvsiLen)
rvsi
// @function Relative Volume Strength Index based on On Balance Volume
// @param vol_src Volume Source to Calculate On Balance Volume
// @param rvsiLen Period of Relative Volume Strength Index
// @param _close Ticker Close Value
// @returns Relative Volume Strength Index value based on On Balance Volume
export rvsi_obv(float vol_src, float _close, simple int rvsiLen) =>
float result = 0
result := ta.cum(math.sign(ta.change(_close)) * vol_src)
var float rvsi = 0.0
// MA of Volume Oscillator Source
volMA = ta.sma(result , rvsiLen)
// RSI of Volume Oscillator Data
rsivol = ta.rsi(volMA, rvsiLen)
rvsi := ta.hma(rsivol, rvsiLen)
rvsi
// @function Relative Volume Strength Index based on Klinger Volume Oscillator
// @param vol_src Volume Source
// @param FastX Volume Fast Length
// @param SlowX Volume Slow Length
// @param rvsiLen Period of Relative Volume Strength Index
// @param _close Ticker Close Value
// @returns Relative Volume Strength Index value based on Klinger Volume Oscillator
export rvsi_kvo(float vol_src, float _close, simple int FastX, simple int SlowX, simple int rvsiLen) =>
float result = 0
xTrend = _close > _close[1] ? vol_src * 100 : -vol_src * 100
xFast = ta.ema(xTrend, FastX)
xSlow = ta.ema(xTrend, SlowX)
result := xFast - xSlow
var float rvsi = 0.0
// MA of Volume Oscillator Source
volMA = ta.sma(result , rvsiLen)
// RSI of Volume Oscillator Data
rsivol = ta.rsi(volMA, rvsiLen)
rvsi := ta.hma(rsivol, rvsiLen)
rvsi
// @function Relative Volume Strength Index based on Volume Zone Oscillator
// @param vol_src Volume Source
// @param zLen Volume Legth for Volume Zone Oscillator
// @param rvsiLen Period of Relative Volume Strength Index
// @param _close Ticker Close Value
// @returns Relative Volume Strength Index value based on Volume Zone Oscillator
export rvsi_vzo(float vol_src, float _close, simple int zLen, simple int rvsiLen) =>
float result = 0
var float _z = 0.0
vp = _close > _close[1] ? vol_src : _close < _close[1] ? -vol_src : _close == _close[1] ? 0 : 0
result := 100 * (ta.ema(vp, zLen) / ta.ema(vol_src, zLen))
var float rvsi = 0.0
// MA of Volume Oscillator Source
volMA = ta.sma(result , rvsiLen)
// RSI of Volume Oscillator Data
rsivol = ta.rsi(volMA, rvsiLen)
rvsi := ta.hma(rsivol, rvsiLen)
rvsi
// @function Relative Volume Strength Index based on Cumulative Volume Oscillator with On Balance Volume as Calculations Source
// @param vol_src Volume Source
// @param ema1len EMA Fast Length
// @param ema2len EMA Slow Length
// @param rvsiLen Period of Relative Volume Strength Index
// @returns Relative Volume Strength Index value based on Cumulative Volume Oscillator with On Balance Volume as Calculations Source
export rvsi_cvo_obv(simple int ema1len, simple int ema2len, simple int rvsiLen) =>
float result = 0
cv = ta.obv
ema1 = ta.ema(cv,ema1len)
ema2 = ta.ema(cv,ema2len)
result := ema1 - ema2
var float rvsi = 0.0
// MA of Volume Oscillator Source
volMA = ta.sma(result , rvsiLen)
// RSI of Volume Oscillator Data
rsivol = ta.rsi(volMA, rvsiLen)
rvsi := ta.hma(rsivol, rvsiLen)
rvsi
// @function Relative Volume Strength Index based on Cumulative Volume Oscillator with Price Volume Trend as Calculations Source
// @param vol_src Volume Source
// @param FastX EMA Fast Length
// @param SlowX EMA Slow Length
// @param rvsiLen Period of Relative Volume Strength Index
// @returns Relative Volume Strength Index value based on Cumulative Volume Oscillator with Price Volume Trend as Calculations Source
export rvsi_cvo_pvt(simple int ema1len, simple int ema2len, simple int rvsiLen) =>
float result = 0
cv = ta.pvt
ema1 = ta.ema(cv,ema1len)
ema2 = ta.ema(cv,ema2len)
result := ema1 - ema2
var float rvsi = 0.0
// MA of Volume Oscillator Source
volMA = ta.sma(result , rvsiLen)
// RSI of Volume Oscillator Data
rsivol = ta.rsi(volMA, rvsiLen)
rvsi := ta.hma(rsivol, rvsiLen)
rvsi
// @function Relative Volume Strength Index based on Cumulative Volume Oscillator with Cumulative Volume Delta as Calculations Source
// @param vol_src Volume Source
// @param FastX EMA Fast Length
// @param SlowX EMA Slow Length
// @param rvsiLen Period of Relative Volume Strength Index
// @param _open Ticker Open Value
// @param _close Ticker Close Value
// @param _high Ticker High Value
// @param _low Ticker Low Value
// @returns Relative Volume Strength Index value based on Cumulative Volume Oscillator with Cumulative Volume Delta as Calculations Source
export rvsi_cvo_cvd(float vol_src, simple int ema1len, simple int ema2len, simple int rvsiLen, float _open, float _high, float _low, float _close) =>
float result = 0
float ctl = na
tw = _high - math.max(_open, _close)
bw = math.min(_open, _close) - _low
body = math.abs(_close - _open)
rate_up = 0.5 * (tw + bw + (_open <= _close ? 2 * body : 0)) / (tw + bw + body)
rate_up := nz(rate_up) == 0 ? 0.5 : rate_up
deltaup = vol_src * rate_up
rate_dn = 0.5 * (tw + bw + (_open > _close ? 2 * body : 0)) / (tw + bw + body)
rate_dn := nz(rate_dn) == 0 ? 0.5 : rate_dn
deltadown = vol_src * rate_dn
delta = _close >= _open ? deltaup : -deltadown
cumdelta = ta.cum(delta)
ctl := cumdelta
cv = ctl
ema1 = ta.ema(cv,ema1len)
ema2 = ta.ema(cv,ema2len)
result := ema1 - ema2
var float rvsi = 0.0
// MA of Volume Oscillator Source
volMA = ta.sma(result , rvsiLen)
// RSI of Volume Oscillator Data
rsivol = ta.rsi(volMA, rvsiLen)
rvsi := ta.hma(rsivol, rvsiLen)
rvsi
// RVSI IndicatorPlot
mz_rvsi_tfs = rvsi_tfs(volume, 30, 14, open, close)
mz_rvsi_obv = rvsi_obv(volume, close, 14)
mz_rvsi_kvo = rvsi_kvo(volume, close, 50, 200, 14)
mz_rvsi_vzo = rvsi_vzo(volume, close, 21, 14)
mz_rvsi_cvo_obv = rvsi_cvo_obv(8, 21, 14)
mz_rvsi_cvo_pvt = rvsi_cvo_pvt(8, 21, 14)
mz_rvsi_cvo_cvd = rvsi_cvo_cvd(volume, 8, 21, 14, open, high, low, close)
plot(mz_rvsi_tfs, "MZ RVSI TFS", color.green, 2)
plot(mz_rvsi_obv, "MZ RVSI OBV", color.yellow, 2)
plot(mz_rvsi_kvo, "MZ RVSI KVO", color.red, 2)
plot(mz_rvsi_vzo, "MZ RVSI VZO", color.maroon, 2)
plot(mz_rvsi_cvo_obv, "MZ RVSI CVO:OBV", color.aqua, 2)
plot(mz_rvsi_cvo_pvt, "MZ RVSI CVO:PVT", color.purple, 2)
plot(mz_rvsi_cvo_cvd, "MZ RVSI CVO:CVD", color.lime, 2)
TopBand = 80
LowBand = 20
MidBand = 50
hline(TopBand, color=color.red,linestyle=hline.style_dotted, linewidth=2)
hline(LowBand, color=color.green, linestyle=hline.style_dotted, linewidth=2)
hline(MidBand, color=color.lime, linestyle=hline.style_dotted, linewidth=1)
|
TS_FFA | https://www.tradingview.com/script/ZCOhIT5N/ | emreyavuz84 | https://www.tradingview.com/u/emreyavuz84/ | 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/
// © emreyavuz84
//@version=5
// @description : Common Library for EY84 indicators
library("TS_FFA")
export labeling(string _sym_name, float _series) =>
//TODO: get and integrate Label to the graph
var _label = label.new(0,_series, text=_sym_name, style=label.style_none,textalign=text.align_right,textcolor=color.lime,size=size.normal)
label.set_x(_label, 0)
label.set_xloc(_label, time, xloc.bar_time)
label.set_y(_label, _series)
export timeFrameMultiplier(string tfp) =>
var _tfp = tfp
_tfpm =1.0
switch _tfp
"120" =>
_tfpm := 1
"180" =>
_tfpm := 1.5
"240" =>
_tfpm := 2
"360" =>
_tfpm := 3
"D" =>
_tfpm := 1
"W" =>
_tfpm := 84
"45" =>
_tfpm :=1*0.75
"30" =>
_tfpm :=1*0.5
"15" =>
_tfpm :=1*0.25
"5" =>
_tfpm :=1*0.083
"1" =>
_tfpm :=1*0.016
[_tfpm]
// @function : function returns statisticly predefined values for fib and profit percents on MOST
// @param sring _x: gets the tickername
// @returns : Fib and Profit Percent values will be returned
export splitter(string _x) =>
var _tickername = str.split(_x,"USDT.P")
_fp = 2.0
_pp = 4.0
switch array.get(_tickername,0)
"1000SHIB" =>
_pp:= 4.5
_fp:= 2
"1000BTTC" =>
_pp:= 1
_fp:= 1
"1000XEC" =>
_pp:= 5
_fp:= 2
"1INCH" =>
_pp:= 3
_fp:= 2
"AAVE" =>
_pp:= 3
_fp:= 3
"ADA" =>
_pp:= 4
_fp:= 2
"AKRO" =>
_pp:= 3
_fp:= 1
"ALGO" =>
_pp:= 2
_fp:= 1
"ALICE" =>
_pp:= 6
_fp:= 2
"ALPHA" =>
_pp:= 2
_fp:= 1
"ANC" =>
_pp:= 4
_fp:= 2
"ANKR" =>
_pp:= 2
_fp:= 1
"ANT" =>
_pp:= 5
_fp:= 4
"APE" =>
_pp:= 2
_fp:= 3
"API3" =>
_pp:= 4
_fp:= 2
"AR" =>
_pp:= 3
_fp:= 2
"ARPA" =>
_pp:= 5
_fp:= 4
"ATA" =>
_pp:= 3
_fp:= 1
"ATLASPERP" =>
_pp:= 5
_fp:= 2
"ATOM" =>
_pp:= 4
_fp:= 1
"AUDIO" =>
_pp:= 3.5
_fp:= 2
"AVAX" =>
_pp:= 4
_fp:= 1
"AXS" =>
_pp:= 4
_fp:= 1
"BAKE" =>
_pp:= 6
_fp:= 2
"BAL" =>
_pp:= 3
_fp:= 2
"BAND" =>
_pp:= 2
_fp:= 2
"BAT" =>
_pp:= 2
_fp:= 2
"BCH" =>
_pp:= 4
_fp:= 2
"BEL" =>
_pp:= 4
_fp:= 2
"BLZ" =>
_pp:= 1.5
_fp:= 2
"BNB" =>
_pp:= 3
_fp:= 2
"BTCDOM" =>
_pp:= 1
_fp:= 2
"BTC" =>
_pp:= 4
_fp:= 2
"BTS" =>
_pp:= 6
_fp:= 2
"C98" =>
_pp:= 5
_fp:= 2
"CELO" =>
_pp:= 4
_fp:= 1
"CELR" =>
_pp:= 3
_fp:= 1
"CHR" =>
_pp:= 6
_fp:= 2
"CHZ" =>
_pp:= 5
_fp:= 2
"COMP" =>
_pp:= 3
_fp:= 2
"COTI" =>
_pp:= 3
_fp:= 2
"CRV" =>
_pp:= 5
_fp:= 2
"CTK" =>
_pp:= 1
_fp:= 1
"CTSI" =>
_pp:= 4
_fp:= 2
"CVC" =>
_pp:= 7
_fp:= 2
"DASH" =>
_pp:= 1
_fp:= 1
"DEFI" =>
_pp:= 2
_fp:= 2
"DENT" =>
_pp:= 4
_fp:= 1
"DGB" =>
_pp:= 2
_fp:= 3
"DODO" =>
_pp:= 3
_fp:= 2
"DOGE" =>
_pp:= 6
_fp:= 2
"DOT" =>
_pp:= 3
_fp:= 2
"DYDX" =>
_pp:= 5.5
_fp:= 1
"EGLD" =>
_pp:= 5
_fp:= 1
"ENJ" =>
_pp:= 2.5
_fp:= 2
"ENS" =>
_pp:= 4
_fp:= 2
"EOS" =>
_pp:= 4.5
_fp:= 2
"ETC" =>
_pp:= 5
_fp:= 1
"ETH" =>
_pp:= 1.5
_fp:= 2
"FIL" =>
_pp:= 3
_fp:= 2
"FLM" =>
_pp:= 3
_fp:= 2
"FLOW" =>
_pp:= 3
_fp:= 3
"FTM" =>
_pp:= 5
_fp:= 2
"GALA" =>
_pp:= 5
_fp:= 2
"GMT" =>
_pp:= 8
_fp:= 2
"GRT" =>
_pp:= 3
_fp:= 2
"GTC" =>
_pp:= 2
_fp:= 2
"HBAR" =>
_pp:= 3
_fp:= 1
"HNT" =>
_pp:= 3
_fp:= 1
"HOT" =>
_pp:= 4
_fp:= 1
"ICP" =>
_pp:= 4
_fp:= 1
"ICX" =>
_pp:= 3
_fp:= 2
"IMX" =>
_pp:= 5
_fp:= 1
"IOST" =>
_pp:= 5
_fp:= 2
"IOTA" =>
_pp:= 5
_fp:= 2
"IOTX" =>
_pp:= 5
_fp:= 2
"KAVA" =>
_pp:= 3
_fp:= 2
"KLAY" =>
_pp:= 1
_fp:= 1
"KNC" =>
_pp:= 2
_fp:= 2
"KSM" =>
_pp:= 5
_fp:= 2
"LINA" =>
_pp:= 3
_fp:= 3
"LINK" =>
_pp:= 2
_fp:= 2
"LIT" =>
_pp:= 5
_fp:= 2
"LPT" =>
_pp:= 4
_fp:= 2
"LRC" =>
_pp:= 2
_fp:= 2
"LTC" =>
_pp:= 4
_fp:= 3
"LUNA" =>
_pp:= 6
_fp:= 3.5
"MANA" =>
_pp:= 5
_fp:= 2
"MASK" =>
_pp:= 4
_fp:= 2
"MATIC" =>
_pp:= 5
_fp:= 3
"MKR" =>
_pp:= 5
_fp:= 2
"MTL" =>
_pp:= 6
_fp:= 3
"NEAR" =>
_pp:= 5
_fp:= 4
"NEO" =>
_pp:= 6
_fp:= 4
"NKN" =>
_pp:= 6
_fp:= 2
"OCEAN" =>
_pp:= 2
_fp:= 3
"OGN" =>
_pp:= 4
_fp:= 2
"OMG" =>
_pp:= 4
_fp:= 2
"ONE" =>
_pp:= 2
_fp:= 2
"ONT" =>
_pp:= 3
_fp:= 3
"QTUM" =>
_pp:= 3
_fp:= 4
"RAY" =>
_pp:= 3
_fp:= 3
"REEF" =>
_pp:= 4
_fp:= 3
"REN" =>
_pp:= 3
_fp:= 2
"RLC" =>
_pp:= 2
_fp:= 4
"ROSE" =>
_pp:= 5
_fp:= 5
"RSR" =>
_pp:= 7
_fp:= 5
"RUNE" =>
_pp:= 4
_fp:= 4
"RVN" =>
_pp:= 2
_fp:= 1
"SAND" =>
_pp:= 5
_fp:= 2
"SC" =>
_pp:= 4
_fp:= 2
"SFP" =>
_pp:= 4
_fp:= 2
"SKL" =>
_pp:= 4
_fp:= 2
"SNX" =>
_pp:= 2
_fp:= 2
"SOL" =>
_pp:= 4
_fp:= 2
"SRM" =>
_pp:= 4
_fp:= 2
"STMX" =>
_pp:= 3
_fp:= 2
"STORJ" =>
_pp:= 4
_fp:= 2
"SUSHI" =>
_pp:= 4
_fp:= 2
"SXP" =>
_pp:= 5
_fp:= 2
"THETA" =>
_pp:= 3
_fp:= 2
"TLM" =>
_pp:= 3
_fp:= 2
"TOMO" =>
_pp:= 2
_fp:= 3
"TRB" =>
_pp:= 2
_fp:= 3
"TRX" =>
_pp:= 3
_fp:= 3
"UNFI" =>
_pp:= 4
_fp:= 4
"UNI" =>
_pp:= 4
_fp:= 4
"VET" =>
_pp:= 4
_fp:= 2
"WAVES" =>
_pp:= 4
_fp:= 2
"XEM" =>
_pp:= 2
_fp:= 2
"XLM" =>
_pp:= 4
_fp:= 2
"XMR" =>
_pp:= 2
_fp:= 2
"XRP" =>
_pp:= 5
_fp:= 2
"XTZ" =>
_pp:= 4
_fp:= 2
"YFI" =>
_pp:= 2
_fp:= 1
"YFII" =>
_pp:= 2
_fp:= 2
"ZEC" =>
_pp:= 3
_fp:= 2
"ZEN" =>
_pp:= 3
_fp:= 3
"ZIL" =>
_pp:= 4
_fp:= 2
"ZRX" =>
_pp:= 3
_fp:= 3
[_fp,_pp]
// @function : function returns statisticly predefined values for fib and profit percents on MOST
// @param sring _x: gets the tickername
// @returns : Fib and Profit Percent values will be returned
export vwma_splitter(string _x) =>
var _tickername = str.split(_x,"USDT")
_fp = 2.0
_pp = 4.0
switch array.get(_tickername,0)
"1000SHIB" =>
_pp:= 4.5
_fp:= 2
"1000XEC" =>
_pp:= 6
_fp:= 2
"1INCH" =>
_pp:= 3
_fp:= 2
"AAVE" =>
_pp:= 3
_fp:= 3
"ADA" =>
_pp:= 8
_fp:= 2
"AKRO" =>
_pp:= 3
_fp:= 3
"ALGO" =>
_pp:= 3
_fp:= 2
"ALICE" =>
_pp:= 6
_fp:= 2
"ALPHA" =>
_pp:= 5
_fp:= 1
"ANKR" =>
_pp:= 3
_fp:= 1
"AR" =>
_pp:= 3
_fp:= 2
"ARPA" =>
_pp:= 3
_fp:= 1
"ATA" =>
_pp:= 3
_fp:= 1
"ATLASPERP" =>
_pp:= 5
_fp:= 2
"ATOM" =>
_pp:= 7
_fp:= 2
"AUDIO" =>
_pp:= 3.5
_fp:= 2
"AVAX" =>
_pp:= 5.5
_fp:= 2
"AXS" =>
_pp:= 4.5
_fp:= 2
"BAKE" =>
_pp:= 6
_fp:= 2
"BAL" =>
_pp:= 3
_fp:= 2
"BAND" =>
_pp:= 2
_fp:= 2.5
"BAT" =>
_pp:= 2
_fp:= 2
"BCH" =>
_pp:= 4
_fp:= 2
"BEL" =>
_pp:= 4
_fp:= 2
"BLZ" =>
_pp:= 1.5
_fp:= 2
"BNB" =>
_pp:= 3
_fp:= 2
"BTCDOM" =>
_pp:= 1
_fp:= 2
"BTC" =>
_pp:= 3
_fp:= 1
"BTS" =>
_pp:= 3
_fp:= 1
"BTT" =>
_pp:= 3
_fp:= 1
"BZRX" =>
_pp:= 3
_fp:= 2
"C98" =>
_pp:= 5
_fp:= 2
"CELO" =>
_pp:= 3
_fp:= 2
"CELR" =>
_pp:= 3
_fp:= 1
"CHR" =>
_pp:= 3
_fp:= 1
"CHZ" =>
_pp:= 5
_fp:= 2
"COMP" =>
_pp:= 3
_fp:= 2
"COTI" =>
_pp:= 3
_fp:= 2
"CRV" =>
_pp:= 5
_fp:= 2
"CTK" =>
_pp:= 1
_fp:= 2
"CTSI" =>
_pp:= 4
_fp:= 2
"CVC" =>
_pp:= 7
_fp:= 2
"DASH" =>
_pp:= 1
_fp:= 1
"DEFI" =>
_pp:= 2
_fp:= 2
"DENT" =>
_pp:= 4
_fp:= 2
"DGB" =>
_pp:= 3
_fp:= 2
"DODO" =>
_pp:= 3
_fp:= 2
"DOGE" =>
_pp:= 6
_fp:= 2
"DOT" =>
_pp:= 3
_fp:= 2
"DYDX" =>
_pp:= 5
_fp:= 1
"EGLD" =>
_pp:= 5
_fp:= 1
"ENJ" =>
_pp:= 5
_fp:= 1
"ENS" =>
_pp:= 3
_fp:= 1
"EOS" =>
_pp:= 2
_fp:= 2
"ETC" =>
_pp:= 3
_fp:= 2
"ETH" =>
_pp:= 3
_fp:= 1
"FIL" =>
_pp:= 3
_fp:= 2
"FLM" =>
_pp:= 3
_fp:= 2
"FTM" =>
_pp:= 5
_fp:= 2
"GALA" =>
_pp:= 5
_fp:= 2
"GRT" =>
_pp:= 3
_fp:= 2
"GTC" =>
_pp:= 4
_fp:= 2
"HBAR" =>
_pp:= 2
_fp:= 1
"HIGH" =>
_pp:= 8
_fp:= 2
"HNT" =>
_pp:= 1
_fp:= 2
"HOT" =>
_pp:= 3
_fp:= 2
"ICP" =>
_pp:= 2
_fp:= 1
"ICX" =>
_pp:= 3
_fp:= 2
"IOST" =>
_pp:= 5
_fp:= 2
"IOTA" =>
_pp:= 5
_fp:= 2
"IOTX" =>
_pp:= 5
_fp:= 2
"KAVA" =>
_pp:= 5
_fp:= 2
"KEEP" =>
_pp:= 2
_fp:= 1
"KLAY" =>
_pp:= 5
_fp:= 4
"KNC" =>
_pp:= 2
_fp:= 1
"KSM" =>
_pp:= 3
_fp:= 2
"LINA" =>
_pp:= 5
_fp:= 4
"LINK" =>
_pp:= 2
_fp:= 2
"LIT" =>
_pp:= 5
_fp:= 2
"LPT" =>
_pp:= 2
_fp:= 1
"LRC" =>
_pp:= 2
_fp:= 2
"LTC" =>
_pp:= 2
_fp:= 1
"LUNA" =>
_pp:= 7
_fp:= 2
"MANA" =>
_pp:= 5
_fp:= 2
"MASK" =>
_pp:= 4
_fp:= 2
"MATIC" =>
_pp:= 5
_fp:= 3
"MKR" =>
_pp:= 3
_fp:= 1
"MTL" =>
_pp:= 2
_fp:= 1
"NEAR" =>
_pp:= 5
_fp:= 3
"NEO" =>
_pp:= 6
_fp:= 4
"NKN" =>
_pp:= 5
_fp:= 3
"NU" =>
_pp:= 4
_fp:= 1
"OCEAN" =>
_pp:= 2
_fp:= 1
"OGN" =>
_pp:= 4
_fp:= 2
"OMG" =>
_pp:= 4
_fp:= 2
"ONE" =>
_pp:= 2
_fp:= 1
"ONT" =>
_pp:= 2
_fp:= 1
"QTUM" =>
_pp:= 3
_fp:= 4
"RAY" =>
_pp:= 3
_fp:= 3
"REEF" =>
_pp:= 3
_fp:= 1
"REN" =>
_pp:= 3
_fp:= 2
"REQ" =>
_pp:= 5
_fp:= 4
"RLC" =>
_pp:= 2
_fp:= 1
"RSR" =>
_pp:= 2
_fp:= 1
"RUNE" =>
_pp:= 3
_fp:= 1
"RVN" =>
_pp:= 3
_fp:= 1
"SAND" =>
_pp:= 5
_fp:= 2
"SC" =>
_pp:= 4
_fp:= 2
"SFP" =>
_pp:= 4
_fp:= 2
"SKL" =>
_pp:= 4
_fp:= 2
"SNX" =>
_pp:= 8
_fp:= 3
"SOL" =>
_pp:= 4
_fp:= 2
"SRM" =>
_pp:= 4
_fp:= 2
"STMX" =>
_pp:= 3
_fp:= 2
"STORJ" =>
_pp:= 4
_fp:= 2
"SUSHI" =>
_pp:= 4
_fp:= 2
"SXP" =>
_pp:= 5
_fp:= 2
"THETA" =>
_pp:= 3
_fp:= 2
"TLM" =>
_pp:= 3
_fp:= 2
"TOMO" =>
_pp:= 2
_fp:= 1
"TRB" =>
_pp:= 6
_fp:= 3
"TRU" =>
_pp:= 5
_fp:= 2
"TRX" =>
_pp:= 3
_fp:= 3
"UNFI" =>
_pp:= 2
_fp:= 1
"UNI" =>
_pp:= 2
_fp:= 1
"VET" =>
_pp:= 2
_fp:= 1
"WAVES" =>
_pp:= 4
_fp:= 2
"XEM" =>
_pp:= 2
_fp:= 2
"XLM" =>
_pp:= 4
_fp:= 2
"XMR" =>
_pp:= 1
_fp:= 4
"XRP" =>
_pp:= 5
_fp:= 2
"XTZ" =>
_pp:= 4
_fp:= 2
"YFI" =>
_pp:= 8
_fp:= 4
"YFII" =>
_pp:= 2
_fp:= 2
"ZEC" =>
_pp:= 3
_fp:= 2
"ZEN" =>
_pp:= 3
_fp:= 3
"ZIL" =>
_pp:= 2
_fp:= 1
"ZRX" =>
_pp:= 7
_fp:= 3
[_fp,_pp]
// @function : function returns statisticly predefined values on daily-basis for fib and profit percents on MOST
// @param sring _x: gets the tickername
// @returns : Fib and Profit Percent values will be returned
export daily_perp_splitter(string _x) =>
var _tickername = str.split(_x,"USDT.P")
_fp = 4.0
_pp = 8.0
switch array.get(_tickername,0)
"1000SHIB" =>
_pp:= 10
_fp:= 5
"1INCH" =>
_pp:= 12
_fp:= 7
"AAVE" =>
_pp:= 6
_fp:= 3
"ADA" =>
_pp:= 20
_fp:= 10
"ALGO" =>
_pp:= 10
_fp:= 6
"AR" =>
_pp:= 9
_fp:= 9
"APE" =>
_pp:= 6
_fp:= 9
"AVAX" =>
_pp:= 10
_fp:= 4
"AXS" =>
_pp:= 15
_fp:= 10
"BAT" =>
_pp:= 8
_fp:= 2
"BNB" =>
_pp:= 9
_fp:= 6
"BNX" =>
_pp:= 13
_fp:= 4
"BTC" =>
_pp:= 8
_fp:= 2
"CHR" =>
_pp:= 15
_fp:= 10
"ETH" =>
_pp:= 18
_fp:= 24
"ETC" =>
_pp:= 10
_fp:= 5
"FLM" =>
_pp:= 9
_fp:= 6
"FTM" =>
_pp:= 6
_fp:= 9
"GMT" =>
_pp:= 10
_fp:= 5
"LTC" =>
_pp:= 11
_fp:= 4
"MATIC" =>
_pp:= 20
_fp:= 9
"MKR" =>
_pp:= 8
_fp:= 2
"NEAR" =>
_pp:= 18
_fp:= 10
"OP" =>
_pp:= 10
_fp:= 5
"SFP" =>
_pp:= 10
_fp:= 5
"SNX" =>
_pp:= 3
_fp:= 9
"SOL" =>
_pp:= 14
_fp:= 3
"TRB" =>
_pp:= 5
_fp:= 7
"XRP" =>
_pp:= 14
_fp:= 10
var _busdticker = str.split(_x,"BUSD.P")
switch array.get(_busdticker,0)
"AAVE" =>
_pp:= 6
_fp:= 3
"ADA" =>
_pp:= 20
_fp:= 10
"ALGO" =>
_pp:= 10
_fp:= 6
"AR" =>
_pp:= 9
_fp:= 9
"APE" =>
_pp:= 6
_fp:= 9
"AVAX" =>
_pp:= 10
_fp:= 4
"AXS" =>
_pp:= 15
_fp:= 10
"BAT" =>
_pp:= 8
_fp:= 2
"BNB" =>
_pp:= 9
_fp:= 6
"BNX" =>
_pp:= 13
_fp:= 4
"BTC" =>
_pp:= 8
_fp:= 2
"CHR" =>
_pp:= 15
_fp:= 10
"ETH" =>
_pp:= 18
_fp:= 24
"ETC" =>
_pp:= 10
_fp:= 5
"FLM" =>
_pp:= 9
_fp:= 6
"FTM" =>
_pp:= 6
_fp:= 9
"GMT" =>
_pp:= 10
_fp:= 5
"LTC" =>
_pp:= 11
_fp:= 4
"MATIC" =>
_pp:= 20
_fp:= 9
"MKR" =>
_pp:= 8
_fp:= 2
"NEAR" =>
_pp:= 18
_fp:= 10
"OP" =>
_pp:= 10
_fp:= 5
"SNX" =>
_pp:= 3
_fp:= 9
"SOL" =>
_pp:= 14
_fp:= 3
"TRB" =>
_pp:= 5
_fp:= 7
"XRP" =>
_pp:= 14
_fp:= 10
[_fp,_pp]
// @function : function returns statisticly predefined values on daily-basis for fib and profit percents on MOST
// @param sring _x: gets the tickername
// @returns : Fib and Profit Percent values will be returned
export daily_splitter(string _x) =>
var _tickername = str.split(_x,"USDT")
_fp = 4.0
_pp = 8.0
switch array.get(_tickername,0)
"1INCH" =>
_pp:= 12
_fp:= 7
"AAVE" =>
_pp:= 6
_fp:= 3
"ADA" =>
_pp:= 20
_fp:= 10
"AR" =>
_pp:= 9
_fp:= 9
"APE" =>
_pp:= 6
_fp:= 9
"AVAX" =>
_pp:= 10
_fp:= 4
"AXS" =>
_pp:= 15
_fp:= 10
"BNB" =>
_pp:= 9
_fp:= 6
"BNX" =>
_pp:= 13
_fp:= 4
"BTC" =>
_pp:= 8
_fp:= 2
"CHR" =>
_pp:= 15
_fp:= 10
"ETH" =>
_pp:= 18
_fp:= 24
"ETC" =>
_pp:= 10
_fp:= 5
"FLM" =>
_pp:= 9
_fp:= 6
"FTM" =>
_pp:= 6
_fp:= 9
"GMT" =>
_pp:= 10
_fp:= 5
"LTC" =>
_pp:= 11
_fp:= 4
"MATIC" =>
_pp:= 20
_fp:= 9
"NEAR" =>
_pp:= 18
_fp:= 10
"OP" =>
_pp:= 10
_fp:= 5
"SHIB" =>
_pp:= 10
_fp:= 5
"SOL" =>
_pp:= 14
_fp:= 3
"SFP" =>
_pp:= 10
_fp:= 5
"SLP" =>
_pp:= 10
_fp:= 5
"SNX" =>
_pp:= 3
_fp:= 9
"TRB" =>
_pp:= 5
_fp:= 7
"WING" =>
_pp:= 10
_fp:= 6
"XRP" =>
_pp:= 14
_fp:= 10
[_fp,_pp]
|
harmonicpatterns1 | https://www.tradingview.com/script/JNXJUeOI-harmonicpatterns1/ | CryptoArch_ | https://www.tradingview.com/u/CryptoArch_/ | 17 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed correction © CryptoArch_
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
// @description harmonicpatterns: methods required for calculation of harmonic patterns. Correction for https://www.tradingview.com/script/t1rxQm9k-harmonicpatterns/ library (missing export in line 303)
library("harmonicpatterns1")
isInRange(ratio, min, max)=> ratio >= min and ratio <= max
// @function isGartleyPattern: Checks for harmonic pattern Gartley
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Gartley. False otherwise.
export isGartleyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.618 * err_min
xabMax = 0.618 * err_max
abcMin = 0.382 * err_min
abcMax = 0.886 * err_max
bcdMin = 1.272 * err_min
bcdMax = 1.618 * err_max
xadMin = 0.786 * err_min
xadMax = 0.786 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isBatPattern: Checks for harmonic pattern Bat
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Bat. False otherwise.
export isBatPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.50 * err_max
abcMin = 0.382 * err_min
abcMax = 0.886 * err_max
bcdMin = 1.618 * err_min
bcdMax = 2.618 * err_max
xadMin = 0.886 * err_min
xadMax = 0.886 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isButterflyPattern: Checks for harmonic pattern Butterfly
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Butterfly. False otherwise.
export isButterflyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.786 * err_min
xabMax = 0.786 * err_max
abcMin = 0.382 * err_min
abcMax = 0.886 * err_max
bcdMin = 1.618 * err_min
bcdMax = 2.618 * err_max
xadMin = 1.272
xadMax = 1.618
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isCrabPattern: Checks for harmonic pattern Crab
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Crab. False otherwise.
export isCrabPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
abcMin = 0.382 * err_min
abcMax = 0.886 * err_max
bcdMin = 2.24 * err_min
bcdMax = 3.618 * err_max
xadMin = 1.618 * err_min
xadMax = 1.618 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isDeepCrabPattern: Checks for harmonic pattern DeepCrab
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is DeepCrab. False otherwise.
export isDeepCrabPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.886 * err_min
xabMax = 0.886 * err_max
abcMin = 0.382 * err_min
abcMax = 0.886 * err_max
bcdMin = 2.00 * err_min
bcdMax = 3.618 * err_max
xadMin = 1.618 * err_min
xadMax = 1.618 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isCypherPattern: Checks for harmonic pattern Cypher
// @param xabRatio AB/XA
// @param axcRatio XC/AX
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Cypher. False otherwise.
export isCypherPattern(float xabRatio, float axcRatio, float xcdRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
axcMin = 1.13 * err_min
axcMax = 1.414 * err_max
xcdMin = 0.786 * err_min
xcdMax = 0.786 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(axcRatio, axcMin, axcMax) and
isInRange(xcdRatio, xcdMin, xcdMax)
// @function isSharkPattern: Checks for harmonic pattern Shark
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Shark. False otherwise.
export isSharkPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.446 * err_min
xabMax = 0.618 * err_max
abcMin = 1.13 * err_min
abcMax = 1.618 * err_max
bcdMin = 1.618 * err_min
bcdMax = 2.236 * err_max
xadMin = 0.886 * err_min
xadMax = 0.886 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isNenStarPattern: Checks for harmonic pattern Nenstar
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Nenstar. False otherwise.
export isNenStarPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
abcMin = 1.414 * err_min
abcMax = 2.140 * err_max
bcdMin = 1.272 * err_min
bcdMax = 2.0 * err_max
xadMin = 1.272 * err_min
xadMax = 1.272 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isAntiNenStarPattern: Checks for harmonic pattern Anti NenStar
// @param xabRatio - AB/XA
// @param abcRatio - BC/AB
// @param bcdRatio - CD/BC
// @param xadRatio - AD/XA
// @param err_min - Minumum error threshold
// @param err_max - Maximum error threshold
// @returns True if the pattern is Anti NenStar. False otherwise.
export isAntiNenStarPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.5 * err_min
xabMax = 0.786 * err_max
abcMin = 0.467 * err_min
abcMax = 0.707 * err_max
bcdMin = 1.618 * err_min
bcdMax = 2.618 * err_max
xadMin = 0.786 * err_min
xadMax = 0.786 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isAntiSharkPattern: Checks for harmonic pattern Anti Shark
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Anti Shark. False otherwise.
export isAntiSharkPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.446 * err_min
xabMax = 0.618 * err_max
abcMin = 0.618 * err_min
abcMax = 0.886 * err_max
bcdMin = 1.618 * err_min
bcdMax = 2.618 * err_max
xadMin = 1.13 * err_min
xadMax = 1.13 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isAntiCypherPattern: Checks for harmonic pattern Anti Cypher
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Anti Cypher. False otherwise.
export isAntiCypherPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.5 * err_min
xabMax = 0.786 * err_max
abcMin = 0.467 * err_min
abcMax = 0.707 * err_max
bcdMin = 1.618 * err_min
bcdMax = 2.618 * err_max
xadMin = 1.272 * err_min
xadMax = 1.272 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isAntiCrabPattern: Checks for harmonic pattern Anti Crab
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Anti Crab. False otherwise.
export isAntiCrabPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.276 * err_min
xabMax = 0.446 * err_max
abcMin = 1.128 * err_min
abcMax = 2.618 * err_max
bcdMin = 1.618 * err_min
bcdMax = 2.618 * err_max
xadMin = 0.618 * err_min
xadMax = 0.618 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isAntiButterflyPattern: Checks for harmonic pattern Anti Butterfly
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Anti Butterfly. False otherwise.
export isAntiButterflyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
abcMin = 1.127 * err_min
abcMax = 2.618 * err_max
bcdMin = 1.272 * err_min
bcdMax = 1.272 * err_max
xadMin = 0.618
xadMax = 0.786
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isAntiBatPattern: Checks for harmonic pattern Anti Bat
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Anti Bat. False otherwise.
export isAntiBatPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.618 * err_max
abcMin = 1.128 * err_min
abcMax = 2.618 * err_max
bcdMin = 2.0 * err_min
bcdMax = 2.618 * err_max
xadMin = 1.128 * err_min
xadMax = 1.128 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isAntiGartleyPattern: Checks for harmonic pattern Anti Gartley
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Anti Gartley. False otherwise.
export isAntiGartleyPattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.618 * err_min
xabMax = 0.786 * err_max
abcMin = 1.127 * err_min
abcMax = 2.618 * err_max
bcdMin = 1.618 * err_min
bcdMax = 1.618 * err_max
xadMin = 1.272 * err_min
xadMax = 1.272 * err_max
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isNavarro200Pattern: Checks for harmonic pattern Navarro200
// @param xabRatio AB/XA
// @param abcRatio BC/AB
// @param bcdRatio CD/BC
// @param xadRatio AD/XA
// @param err_min Minumum error threshold
// @param err_max Maximum error threshold
// @returns True if the pattern is Navarro200. False otherwise.
export isNavarro200Pattern(float xabRatio, float abcRatio, float bcdRatio, float xadRatio, float err_min=0.92, float err_max=1.08, bool enable=true) =>
xabMin = 0.382 * err_min
xabMax = 0.786 * err_max
abcMin = 0.886 * err_min
abcMax = 1.127 * err_max
bcdMin = 0.886 * err_min
bcdMax = 3.618 * err_max
xadMin = 0.886
xadMax = 1.127
enable and
isInRange(xabRatio, xabMin, xabMax) and
isInRange(abcRatio, abcMin, abcMax) and
isInRange(bcdRatio, bcdMin, bcdMax) and
isInRange(xadRatio, xadMin, xadMax)
// @function isHarmonicPattern: Checks for harmonic patterns
// @param x X coordinate value
// @param a A coordinate value
// @param c B coordinate value
// @param c C coordinate value
// @param d D coordinate value
// @param flags flags to check patterns. Send empty array to enable all
// @param errorPercent Error threshold
// @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
export isHarmonicPattern(float x, float a, float b, float c, float d,
simple bool[] flags, simple int errorPercent = 8)=>
ignoreFlags = array.size(flags) == 0
err_min = (100 - errorPercent) / 100
err_max = (100 + errorPercent) / 100
xabRatio = math.abs(b - a) / math.abs(x - a)
abcRatio = math.abs(c - b) / math.abs(a - b)
bcdRatio = math.abs(d - c) / math.abs(b - c)
xadRatio = math.abs(d - a) / math.abs(x - a)
axcRatio = math.abs(c - x) / math.abs(a - x)
xcdRatio = math.abs(c - d) / math.abs(x - c)
patternArray = array.new_bool()
patternLabelArray = array.new_string()
array.push(patternArray, isGartleyPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 0)))
array.push(patternArray, isBatPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 1)))
array.push(patternArray, isButterflyPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 2)))
array.push(patternArray, isCrabPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 3)))
array.push(patternArray, isDeepCrabPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 4)))
array.push(patternArray, isSharkPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 5)))
array.push(patternArray, isCypherPattern( xabRatio, axcRatio, xcdRatio, err_min, err_max, ignoreFlags or array.get(flags, 6)))
array.push(patternArray, isNenStarPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 7)))
array.push(patternArray, isAntiNenStarPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 8)))
array.push(patternArray, isAntiSharkPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 9)))
array.push(patternArray, isAntiCypherPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 10)))
array.push(patternArray, isAntiCrabPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 11)))
array.push(patternArray, isAntiButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 12)))
array.push(patternArray, isAntiBatPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 13)))
array.push(patternArray, isAntiGartleyPattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 14)))
array.push(patternArray, isNavarro200Pattern( xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max, ignoreFlags or array.get(flags, 15)))
array.push(patternLabelArray, "Gartley")
array.push(patternLabelArray, "Bat")
array.push(patternLabelArray, "Butterfly")
array.push(patternLabelArray, "Crab")
array.push(patternLabelArray, "DeepCrab")
array.push(patternLabelArray, "Shark")
array.push(patternLabelArray, "Cypher")
array.push(patternLabelArray, "NenStar")
array.push(patternLabelArray, "Anti NenStar")
array.push(patternLabelArray, "Anti Shark")
array.push(patternLabelArray, "Anti Cypher")
array.push(patternLabelArray, "Anti Crab")
array.push(patternLabelArray, "Anti Butterfly")
array.push(patternLabelArray, "Anti Bat")
array.push(patternLabelArray, "Anti Gartley")
array.push(patternLabelArray, "Navarro200")
[patternArray, patternLabelArray] |
LibraryCOT | https://www.tradingview.com/script/ysFf2OTq-LibraryCOT/ | TradingView | https://www.tradingview.com/u/TradingView/ | 134 | library | 5 | MPL-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
// +------------------------------+------------------------+
// | Legacy (COT) Metric Names | Directions |
// +------------------------------+------------------------+
// | Open Interest | No direction |
// | Noncommercial Positions | Long, Short, Spreading |
// | Commercial Positions | Long, Short |
// | Total Reportable Positions | Long, Short |
// | Nonreportable Positions | Long, Short |
// | Traders Total | No direction |
// | Traders Noncommercial | Long, Short, Spreading |
// | Traders Commercial | Long, Short |
// | Traders Total Reportable | Long, Short |
// | Concentration Gross LT 4 TDR | Long, Short |
// | Concentration Gross LT 8 TDR | Long, Short |
// | Concentration Net LT 4 TDR | Long, Short |
// | Concentration Net LT 8 TDR | Long, Short |
// +------------------------------+------------------------+
// +-----------------------------------+------------------------+
// | Disaggregated (COT2) Metric Names | Directions |
// +-----------------------------------+------------------------+
// | Open Interest | No Direction |
// | Producer Merchant Positions | Long, Short |
// | Swap Positions | Long, Short, Spreading |
// | Managed Money Positions | Long, Short, Spreading |
// | Other Reportable Positions | Long, Short, Spreading |
// | Total Reportable Positions | Long, Short |
// | Nonreportable Positions | Long, Short |
// | Traders Total | No Direction |
// | Traders Producer Merchant | Long, Short |
// | Traders Swap | Long, Short, Spreading |
// | Traders Managed Money | Long, Short, Spreading |
// | Traders Other Reportable | Long, Short, Spreading |
// | Traders Total Reportable | Long, Short |
// | Concentration Gross LE 4 TDR | Long, Short |
// | Concentration Gross LE 8 TDR | Long, Short |
// | Concentration Net LE 4 TDR | Long, Short |
// | Concentration Net LE 8 TDR | Long, Short |
// +-----------------------------------+------------------------+
// +-------------------------------+------------------------+
// | Financial (COT3) Metric Names | Directions |
// +-------------------------------+------------------------+
// | Open Interest | No Direction |
// | Dealer Positions | Long, Short, Spreading |
// | Asset Manager Positions | Long, Short, Spreading |
// | Leveraged Funds Positions | Long, Short, Spreading |
// | Other Reportable Positions | Long, Short, Spreading |
// | Total Reportable Positions | Long, Short |
// | Nonreportable Positions | Long, Short |
// | Traders Total | No Direction |
// | Traders Dealer | Long, Short, Spreading |
// | Traders Asset Manager | Long, Short, Spreading |
// | Traders Leveraged Funds | Long, Short, Spreading |
// | Traders Other Reportable | Long, Short, Spreading |
// | Traders Total Reportable | Long, Short |
// | Concentration Gross LE 4 TDR | Long, Short |
// | Concentration Gross LE 8 TDR | Long, Short |
// | Concentration Net LE 4 TDR | Long, Short |
// | Concentration Net LE 8 TDR | Long, Short |
// +-------------------------------+------------------------+
// @description This library provides tools to help Pine programmers fetch Commitment of Traders (COT) data for futures.
library("LibraryCOT", false)
isNotEmpty(simple string str) =>
bool result = str != ""
// @function Accepts a futures root and returns the relevant CFTC code.
// @param root Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
// @returns The <CFTCCode> part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
export rootToCFTCCode(simple string root) =>
switch root
"ZC" => "002602"
"ZO" => "004603"
"ZS" => "005602"
"ZL" => "007601"
"ZB" => "020601"
"UB" => "020604"
"ZM" => "026603"
"TN" => "043607"
"ZR" => "039601"
"ZQ" => "045601"
"DC" => "052641"
"6E" => "099741"
"6J" => "097741"
"RY" => "399741"
"RP" => "299741"
"6M" => "095741"
"6S" => "092741"
"6R" => "089741"
"6C" => "090741"
"6N" => "112741"
"6B" => "096742"
"6L" => "102741"
"6Z" => "122741"
"RX" => "124606"
"AW" => "221602"
"BTC" => "133741"
"MBT" => "133742"
"CB" => "050642"
"GDK" => "052644"
"CSC" => "063642"
"SI" => "084691"
"GC" => "088691"
"PL" => "076651"
"PA" => "075651"
"HE" => "054642"
"LE" => "057642"
"LBS" => "058643"
"DY" => "052645"
"GF" => "061641"
"GNF" => "052642"
"UFV" => "251607"
"SR1" => "134742"
"SR3" => "134741"
"MGC" => "088695"
"SDA" => "43874A"
"DX" => "098662"
"CC" => "073732"
"SB" => "080732"
"KC" => "083731"
"CT" => "033661"
"A8K" => "06665T"
"6A" => "232741"
"CC" => "073732"
"CT" => "033661"
"OJ" => "040701"
"MME" => "244042"
"SP" => "138741"
"XK" => "005603"
"RTY" => "239742"
"AUP" => "191693"
"EDP" => "191696"
"ES" => "13874A"
"ZF" => "044601"
"ZN" => "043602"
"ZT" => "042601"
"ZW" => "001602"
"KE" => "001612"
"BWF" => "00160F"
"CUP" => "085692"
"NKT" => "240741"
"NIT" => "240743"
"HRC" => "192651"
"BUS" => "257652"
"MNQ" => "209747"
"CRB" => "111A34"
"S5M" => "021A65"
"CU" => "025651"
"A7E" => "06665B"
"WCW" => "067A75"
"BZ" => "06765T"
"HTT" => "0676A5"
"CSX" => "06765A"
"B0" => "06665O"
"AC0" => "06665P"
"AD0" => "06665Q"
"A7Q" => "06665R"
"A1R" => "06665G"
"AZ1" => "025608"
"MTF" => "024656"
"TTF" => "023B98"
"VX" => "1170E1"
"EMD" => "33874A"
"CL" => "067651"
"NG" => "023651"
"HP" => "03565C"
"NPG" => "023A56"
"XAP" => "138748"
"XAE" => "138749"
"XAF" => "13874C"
"XAV" => "13874E"
"XAI" => "13874F"
"XAU" => "13874J"
"MNC" => "03265J"
"HO" => "022651"
"A80" => "06665W"
"NQ" => "209742"
"QMW" => "001626"
"YM" => "124603"
"ETH" => "146021"
"ND" => "20974+"
"GE" => "132741"
"HH" => "023A55"
"WTT" => "067A71"
"RB" => "111659"
=> ""
// @function Converts a currency string to its corresponding CFTC code.
// @param curr Currency code, e.g., "USD" for US Dollar.
// @returns The <CFTCCode> corresponding to the currency, if one exists.
export currencyToCFTCCode(simple string currency) =>
switch currency
"BTC" => "133741"
"USD" => "098662"
"EUR" => "099741"
"JPY" => "097741"
"MXN" => "095741"
"CHF" => "092741"
"RUB" => "089741"
"CAD" => "090741"
"NZD" => "112741"
"GBP" => "096742"
"BRL" => "102741"
"ZAR" => "122741"
"AUD" => "232741"
"ETH" => "146021"
=> ""
// @function Returns the <includeOptions> part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
// @param includeOptions A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
// @returns The <includeOptions> part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
export optionsToTicker(simple bool includeOptions) =>
includeOptions ? "FO" : "F"
// @function Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
// @param metricName One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
// @param metricDirection Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Valid values vary with metrics. Invalid values will cause a runtime error.
// @returns The <metricCode><metricDirection> part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction", or "TC_L" for "Traders Commercial" and "Long".
export metricNameAndDirectionToTicker(simple string metricName, simple string metricDirection) =>
metricCode =
switch metricName
"Asset Manager Positions" => "AMP"
"Commercial Positions" => "CP"
"Concentration Gross LE 4 TDR" => "CON_GROSS_LE_4"
"Concentration Gross LE 8 TDR" => "CON_GROSS_LE_8"
"Concentration Gross LT 4 TDR" => "CON_GROSS_LT_4"
"Concentration Gross LT 8 TDR" => "CON_GROSS_LT_8"
"Concentration Net LE 4 TDR" => "CON_NET_LE_4"
"Concentration Net LE 8 TDR" => "CON_NET_LE_8"
"Concentration Net LT 4 TDR" => "CON_NET_LT_4"
"Concentration Net LT 8 TDR" => "CON_NET_LT_8"
"Dealer Positions" => "DP"
"Leveraged Funds Positions" => "LMP"
"Managed Money Positions" => "MMP"
"Noncommercial Positions" => "NCP"
"Nonreportable Positions" => "NRP"
"Open Interest" => "OI"
"Other Reportable Positions" => "ORP"
"Producer Merchant Positions" => "PMR"
"Swap Positions" => "SP"
"Total Reportable Positions" => "TRP"
"Traders Asset Manager" => "TAM"
"Traders Commercial" => "TC"
"Traders Dealer" => "TD"
"Traders Leveraged Funds" => "TLM"
"Traders Managed Money" => "TMM"
"Traders Noncommercial" => "TNC"
"Traders Other Reportable" => "TOR"
"Traders Producer Merchant" => "TPM"
"Traders Swap" => "TS"
"Traders Total" => "TT"
"Traders Total Reportable" => "TTR"
=> runtime.error(str.format("Unrecognized metric: `{0}`", metricName)), na
if metricDirection == "No direction"
if metricName != "Open Interest" and metricName != "Traders Total"
runtime.error(str.format("`{0}` direction is not applicable for `{1}`", metricDirection, metricName))
else if metricDirection == "Spreading"
isIncorrect =
switch metricName
"Commercial Positions" => true
"Total Reportable Positions" => true
"Nonreportable Positions" => true
"Traders Commercial" => true
"Traders Total Reportable" => true
"Concentration Gross LT 4 TDR" => true
"Concentration Gross LT 8 TDR" => true
"Concentration Net LT 4 TDR" => true
"Concentration Net LT 8 TDR" => true
"Concentration Gross LE 4 TDR" => true
"Concentration Gross LE 8 TDR" => true
"Concentration Net LE 4 TDR" => true
"Concentration Net LE 8 TDR" => true
"Producer Merchant Positions" => true
"Traders Producer Merchant" => true
=> false
if isIncorrect
runtime.error(str.format("`{0}` direction is not applicable for `{1}`", metricDirection, metricName))
else if metricName == "Open Interest" or metricName == "Traders Total"
runtime.error(str.format("`{0}` direction is not applicable for `{1}`", metricDirection, metricName))
directionCode =
switch metricDirection
"Long" => "_L"
"Short" => "_S"
"Spreading" => "_SPREAD"
"No direction" => ""
=> runtime.error(str.format("Unrecognized metric direction: `{0}`", metricDirection)), na
metricCode + directionCode
// @function Converts a metric type into one component required to build a valid COT ticker ID. See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
// @param metricType Metric type. Accepted values are: "All", "Old", "Other".
// @returns The <metricType> part of a COT ticker.
export typeToTicker(simple string metricType) =>
switch metricType
"All" => ""
"Old" => "_OLD"
"Other" => "_OTHER"
=> runtime.error(str.format("Unrecognized metric type: `{0}`", metricType)), na
// @function Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`. Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
// @param mode A string determining how the function will work. Valid values are:
// "Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
// "Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
// "Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
// "Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
// @param convertToCOT "bool" value that, when `true`, causes the function to return a CFTC code. Otherwise, the root or currency information is returned. Optional. The default is `true`.
// @returns If `convertToCOT` is `true`, the <CFTCCode> part of a COT ticker ID string. If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
export convertRootToCOTCode(simple string mode, simple bool convertToCOT = true) =>
hasRoot = syminfo.root != syminfo.ticker
root = rootToCFTCCode(syminfo.root)
baseCurrency = currencyToCFTCCode(syminfo.basecurrency)
mainCurrency = currencyToCFTCCode(syminfo.currency)
result = switch mode
"Auto" =>
switch
hasRoot and isNotEmpty(root) => convertToCOT ? root : syminfo.root
isNotEmpty(baseCurrency) => convertToCOT ? baseCurrency : syminfo.basecurrency
isNotEmpty(mainCurrency) => convertToCOT ? mainCurrency : syminfo.currency
=> ""
"Root" => convertToCOT ? root : syminfo.root
"Base currency" => convertToCOT ? baseCurrency : syminfo.basecurrency
"Currency" => convertToCOT ? mainCurrency : syminfo.currency
=> ""
if result == ""
runtime.error(str.format("Could not find relevant COT data based on the current symbol and the source search mode `{0}`", mode))
result
// @function Returns a valid TradingView ticker for the COT symbol with specified parameters.
// @param COTType A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
// @param CTFCCode The <CFTCCode> for the asset, e.g., wheat futures (root "ZW") have the code "001602".
// @param includeOptions A boolean value. 'true' if the symbol should include options and 'false' otherwise.
// @param metricName One of the metric names listed in this library's chart.
// @param metricDirection Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction".
// @param metricType Type of the metric. Possible values: "All", "Old", and "Other".
// @returns A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
export COTTickerid(simple string COTType, simple string CFTCCode, simple bool includeOptions, simple string metricName, simple string metricDirection, simple string metricType) =>
typeCode = switch COTType
"Legacy" => ""
"Disaggregated" => "2"
"Financial" => "3"
=> runtime.error("Unknown `COTType`: " + COTType), na
invalidType = if COTType == "Legacy"
switch metricName
"Open Interest" => false
"Traders Total" => false
"Traders Noncommercial" => false
"Noncommercial Positions" => false
"Commercial Positions" => false
"Total Reportable Positions" => false
"Nonreportable Positions" => false
"Traders Commercial" => false
"Traders Total Reportable" => false
"Concentration Gross LT 4 TDR" => false
"Concentration Gross LT 8 TDR" => false
"Concentration Net LT 4 TDR" => false
"Concentration Net LT 8 TDR" => false
else if COTType == "Financial"
switch metricName
"Open Interest" => false
"Traders Total" => false
"Managed Money Positions" => false
"Other Reportable Positions" => false
"Swap Positions" => false
"Traders Managed Money" => false
"Traders Other Reportable" => false
"Traders Swap" => false
"Concentration Gross LE 4 TDR" => false
"Concentration Gross LE 8 TDR" => false
"Concentration Net LE 4 TDR" => false
"Concentration Net LE 8 TDR" => false
"Nonreportable Positions" => false
"Producer Merchant Positions" => false
"Traders Producer Merchant" => false
"Total Reportable Positions" => false
"Traders Total Reportable" => false
else if COTType == "Disaggregared"
switch metricName
"Open Interest" => false
"Traders Total" => false
"Asset Manager Positions" => false
"Dealer Positions" => false
"Leveraged Funds Positions" => false
"Other Reportables Positions" => false
"Traders Asset Manager" => false
"Traders Dealer" => false
"Traders Leveraged Funds" => false
"Traders Other Reportables" => false
"Concentration Gross LE 4 TDR" => false
"Concentration Gross LE 8 TDR" => false
"Concentration Net LE 4 TDR" => false
"Concentration Net LE 8 TDR" => false
"Nonreportable Positions" => false
"Total Reportable Positions" => false
"Traders Total Reportable" => false
if invalidType
runtime.error(str.format("The `{0}` metric is not applicable for the `{1}` COT type", metricName, COTType))
str.format("COT{0}:{1}_{2}_{3}{4}", typeCode, CFTCCode, optionsToTicker(includeOptions), metricNameAndDirectionToTicker(metricName, metricDirection), typeToTicker(metricType))
// ————— Example plot
exampleTicker = COTTickerid(
COTType = "Legacy",
CFTCCode = convertRootToCOTCode("Auto"),
includeOptions = false,
metricName = "Open Interest",
metricDirection = "No direction",
metricType = "All")
s1 = request.security(exampleTicker, "1D", close)
plot(s1, style = plot.style_stepline_diamond)
|
FunctionMinkowskiDistance | https://www.tradingview.com/script/jtQtg2QC-FunctionMinkowskiDistance/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 33 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Method for Minkowski Distance,
// The Minkowski distance or Minkowski metric is a metric in a normed vector space
// which can be considered as a generalization of both the Euclidean distance and
// the Manhattan distance.
// It is named after the German mathematician Hermann Minkowski.
// reference: https://en.wikipedia.org/wiki/Minkowski_distance
library("FunctionMinkowskiDistance")
// @function Minkowsky Distance for single points.
// @param point_ax float, x value of point a.
// @param point_ay float, y value of point a.
// @param point_bx float, x value of point b.
// @param point_by float, y value of point b.
// @param p_value float, p value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
// @returns float
export double (float point_ax, float point_ay, float point_bx, float point_by, float p_value=1.0) => //{
//sum the vector diference:
float _sum = math.pow(math.abs(point_ax - point_bx), p_value) + math.pow(math.abs(point_ay - point_by), p_value)
//root it:
math.pow(_sum, (1.0 / p_value))
//{ usage:
p = input.float(1.0)
md1 = double(10, 10, 20, 20, 1)
md2 = double(10, 10, 20, 20, 2)
mdx = double(10, 10, 20, 20, p)
h = ta.valuewhen(high >= ta.highest(10), high, 0)
b = ta.valuewhen(high >= ta.highest(10), bar_index, 0)
mdn = double(h, b, close, bar_index, p)
plot(series=md1, title="MD1 - Manhattan D", color=color.blue)
plot(series=md2, title="MD2 - Euclidean", color=color.red)
plot(series=mdx, title="MDX - input: p", color=color.navy)
plot(series=mdn, title="MDN - distance to when higher high", color=color.purple)
//{ reference:
// https://www.cs.indiana.edu/~predrag/classes/2010springi211/week3_w.pdf
// https://www.geeksforgeeks.org/minkowski-distance-python/
// https://towardsdatascience.com/importance-of-distance-metrics-in-machine-learning-modelling-e51395ffe60d
//}}}
// @function Minkowsky Distance for N dimensions.
// @param point_x float array, point x dimension attributes.
// @param point_y float array, point y dimension attributes.
// @param p_value float, p value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
// @returns float
export ndim (float[] point_x, float[] point_y, float p_value=1.0) => //{
int _size_x = array.size(point_x)
int _size_y = array.size(point_y)
//
switch
(_size_x < 1) => runtime.error('FunctionMinkowskiDistance -> array(): invalid size array.')
(_size_x != _size_y) => runtime.error('FunctionMinkowskiDistance -> array(): invalid size array.')
//
//sum the vector diference:
float _sum = 0.0
for _i = 0 to (_size_x - 1)
float _xi = array.get(point_x, _i)
float _yi = array.get(point_y, _i)
_sum += math.pow(math.abs(_xi - _yi), p_value)
//root it:
math.pow(_sum, (1.0 / p_value))
//{ usage:
// point_x = array.from(10.0)
// point_y = array.from(20.0)
// point_x = array.from(10.0, 10.0)
// point_y = array.from(20.0, 20)
point_x = array.from(10.0, 2, 4, -1, 0, 9, 1)
point_y = array.from(14.0, 7, 11, 5, 2, 2, 18)
nd = ndim(point_x, point_y, p)
plot(series=nd, title="ND - multiple dimension distance", color=color.yellow)
//{ reference:
// https://www.mikulskibartosz.name/minkowski-distance-explained/
// https://www.statology.org/minkowski-distance-in-r/
//}}}
|
timeUtils | https://www.tradingview.com/script/Ktb7BHp5-timeUtils/ | zions | https://www.tradingview.com/u/zions/ | 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/
// © zions
//@version=5
// @description Utils for time series
library("timeUtils", overlay=false)
// @function Calculates how many full trading days left until the end of the current month. (It doesn't take into account market holidays)
// @returns int[] series of the remaining trading days until the end of the month.
export tradingDaysTillEndOfMonth() =>
int[] daysInMonth = array.from(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
DaysOfCurrentMonth = array.get(daysInMonth, month(time)-1)
if month(time) == 2 and year(time) % 4 == 0 // Compensate February with 29 days
DaysOfCurrentMonth += 1
weekendDaysTillEndofmonth = (math.floor((DaysOfCurrentMonth - dayofmonth(time) + dayofweek(time))/7)) + (math.floor((DaysOfCurrentMonth - dayofmonth(time) + dayofweek(time)-1)/7))
tradingDaysTillEndofmonth = DaysOfCurrentMonth - dayofmonth(time) - weekendDaysTillEndofmonth[0]
// @function Check if the current bar is inside the time range
// @returns bool[] series contains true for the bars that are inside the time range, false otherwise
export insideDateRange(int fromYear, int fromMonth=1, int fromDay=1, int toYear, int toMonth=12, int toDay=31) =>
start = timestamp(fromYear, fromMonth, fromDay)
end = timestamp(toYear, toMonth, toDay, 23, 59)
inRange = time > start and time < end
|
ArrayExt | https://www.tradingview.com/script/zcZW9eIM-ArrayExt/ | TheBacktestGuy | https://www.tradingview.com/u/TheBacktestGuy/ | 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/
// © wallneradam
//@version=5
// @description Array extensions: get/set, distance sorting, multi-array sorting
library("ArrayExt", overlay=true)
/////////////
// Get/Set //
/////////////
//
// Get elements from the array
//
// @function Get element from the array at index, or na if index not found
// @param a The array
// @param idx The array index to get
// @returns The array item if exists or na
export get(bool[] a, int idx) =>
n = array.size(a)
bool res = na
if idx < n
res := array.get(a, idx)
res
// @function Get element from the array at index, or na if index not found
// @param a The array
// @param idx The array index to get
// @returns The array item if exists or na
export get(int[] a, int idx) =>
n = array.size(a)
int res = na
if idx < n
res := array.get(a, idx)
res
// @function Get element from the array at index, or na if index not found
// @param a The array
// @param idx The array index to get
// @returns The array item if exists or na
export get(float[] a, int idx) =>
n = array.size(a)
float res = na
if idx < n
res := array.get(a, idx)
res
// @function Get element from the array at index, or na if index not found
// @param a The array
// @param idx The array index to get
// @returns The array item if exists or na
export get(string[] a, int idx) =>
n = array.size(a)
string res = na
if idx < n
res := array.get(a, idx)
res
// @function Get element from the array at index, or na if index not found
// @param a The array
// @param idx The array index to get
// @returns The array item if exists or na
export get(color[] a, int idx) =>
n = array.size(a)
color res = na
if idx < n
res := array.get(a, idx)
res
// @function Get element from the array at index, or na if index not found
// @param a The array
// @param idx The array index to get
// @returns The array item if exists or na
export get(line[] a, int idx) =>
n = array.size(a)
line res = na
if idx < n
res := array.get(a, idx)
res
//
// Set elements in the array
//
// @function Set array item at index, if array has no index at the specified index, the array is filled with na
// @param a The array
// @param idx The array index to set
// @param val The value to be set
export set(int[] a, int idx, simple int val) =>
while idx >= array.size(a)
array.push(a, na)
array.set(a, idx, val)
// @function Set array item at index, if array has no index at the specified index, the array is filled with na
// @param a The array
// @param idx The array index to set
// @param val The value to be set
export set(float[] a, int idx, simple float val) =>
while idx >= array.size(a)
array.push(a, na)
array.set(a, idx, val)
// @function Set array item at index, if array has no index at the specified index, the array is filled with na
// @param a The array
// @param idx The array index to set
// @param val The value to be set
export set(bool[] a, int idx, simple bool val) =>
while idx >= array.size(a)
array.push(a, na)
array.set(a, idx, val)
// @function Set array item at index, if array has no index at the specified index, the array is filled with na
// @param a The array
// @param idx The array index to set
// @param val The value to be set
export set(string[] a, int idx, simple string val) =>
while idx >= array.size(a)
array.push(a, na)
array.set(a, idx, val)
// @function Set array item at index, if array has no index at the specified index, the array is filled with na
// @param a The array
// @param idx The array index to set
// @param val The value to be set
export set(color[] a, int idx, simple color val) =>
while idx >= array.size(a)
array.push(a, na)
array.set(a, idx, val)
// @function Set array item at index, if array has no index at the specified index, the array is filled with na
// @param a The array
// @param idx The array index to set
// @param val The value to be set
export set(line[] a, int idx, simple line val) =>
while idx >= array.size(a)
array.push(a, na)
array.set(a, idx, val)
//////////////
// Sortting //
//////////////
//
// Distance sorting
//
// @function Sort arrays by distance from a source (Inner helper function which works without types)
// @param array The array to be sorted
// @param dist_from The sorting is based on the distance of this source
// @param reverse Reversed order if true
// @returns Array of old indexes
_dist_sort(array, float dist_from, bool reverse = false) =>
n = array.size(array)
index_array = array.new_int(n)
if n > 0
for i = 0 to n - 1
array.set(index_array, i, i)
n -= 1
for i = 0 to n > 0 ? n - 1 : na
for j = 0 to n - i - 1
t = array.get(array, j)
t1 = array.get(array, j + 1)
if (not reverse and math.abs(t - dist_from) > math.abs(t1 - dist_from)) or (reverse and math.abs(t - dist_from) < math.abs(t1 - dist_from))
array.set(array, j, t1)
array.set(array, j + 1, t)
// Sort indexes of the original order
_ti = array.get(index_array, j)
array.set(index_array, j, array.get(index_array, j + 1))
array.set(index_array, j + 1, _ti)
index_array
// @function Sort arrays by distance from a source
// @param array The array to be sorted
// @param dist_from The sorting is based on the distance of this source
// @param reverse Reversed order if true
// @returns Array of old indexes
dist_sort(int[] array, float dist_from, bool reverse) => _dist_sort(array, dist_from, reverse)
// @function Sort arrays by distance from a source
// @param array The array to be sorted
// @param dist_from The sorting is based on the distance of this source
// @param reverse Reversed order if true
// @returns Array of old indexes
dist_sort(float[] array, float dist_from, bool reverse) => _dist_sort(array, dist_from, reverse)
// @function Sort arrays by distance from a source
// @param array The array to be sorted
// @param dist_from The sorting is based on the distance of this source
// @param reverse Reversed order if true
// @returns Array of old indexes
//
// Multi sort
//
// @function Sort arrays together (Inner helper function which works without types)
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source
// @param reverse Reversed order if true
// @returns Array of old indexes
_multisort(base_array, second_array, float dist_from = na, bool reverse = false) =>
n = array.size(base_array)
index_array = array.new_int(n)
if n > 0
for i = 0 to n - 1
array.set(index_array, i, i)
n -= 1
for i = 0 to n > 0 ? n - 1 : na
for j = 0 to n - i - 1
t = array.get(base_array, j)
t1 = array.get(base_array, j + 1)
if (na(dist_from) and (not reverse ? t > t1 : t < t1)) or (not na(dist_from) and (not reverse ? math.abs(t - dist_from) > math.abs(t1 - dist_from) : math.abs(t - dist_from) < math.abs(t1 - dist_from)))
array.set(base_array, j, t1)
array.set(base_array, j + 1, t)
_t = array.get(second_array, j)
array.set(second_array, j, array.get(second_array, j + 1))
array.set(second_array, j + 1, _t)
// Sort indexes of the original order
_ti = array.get(index_array, j)
array.set(index_array, j, array.get(index_array, j + 1))
array.set(index_array, j + 1, _ti)
index_array
// The same for strings
_str_multisort(string[] base_array, second_array, bool reverse = false) =>
n = array.size(base_array)
index_array = array.new_int(n)
if n > 0
for i = 0 to n - 1
array.set(index_array, i, i)
n -= 1
for i = 0 to n > 0 ? n - 1 : na
for j = 0 to n - i - 1
t = array.get(base_array, j)
t1 = array.get(base_array, j + 1)
ta = array.from(t, t1)
array.sort(ta, not reverse ? order.ascending: order.descending)
if t1 == array.get(ta, 0)
array.set(base_array, j, t1)
array.set(base_array, j + 1, t)
_t = array.get(second_array, j)
array.set(second_array, j, array.get(second_array, j + 1))
array.set(second_array, j + 1, _t)
// Sort indexes of the original order
_ti = array.get(index_array, j)
array.set(index_array, j, array.get(index_array, j + 1))
array.set(index_array, j + 1, _ti)
index_array
// @function Reorder array based on indexes array (Inner helper function which works without types)
// @param index_array The array of indexes of the new order
// @param array The array to be reorder
_reorder(index_array, array) =>
n = array.size(index_array)
ta = array.copy(array)
if n > 0
for i = 0 to n > 0 ? n - 1 : na
idx = array.get(index_array, i)
array.set(array, i, array.get(ta, idx))
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(int[] base_array, int[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(int[] base_array, float[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(int[] base_array, bool[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(int[] base_array, string[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(int[] base_array, color[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(int[] base_array, line[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(float[] base_array, int[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(float[] base_array, float[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(float[] base_array, bool[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(float[] base_array, string[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(float[] base_array, color[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param dist_from If specified, the sorting is based on the distance of the specified source like 'close'
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(float[] base_array, line[] second_array, float dist_from = na, bool reverse = false) => _multisort(base_array, second_array, dist_from, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(string[] base_array, int[] second_array, bool reverse = false) => _str_multisort(base_array, second_array, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(string[] base_array, float[] second_array, bool reverse = false) => _str_multisort(base_array, second_array, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(string[] base_array, bool[] second_array, bool reverse = false) => _str_multisort(base_array, second_array, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(string[] base_array, string[] second_array, bool reverse = false) => _str_multisort(base_array, second_array, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(string[] base_array, color[] second_array, bool reverse = false) => _str_multisort(base_array, second_array, reverse)
// @function Sort arrays together
// @param base_array The base array to sort
// @param second array The second array elements swaped the same way as base array
// @param reverse Reversed order if true
// @returns Array of old indexes
export multisort(string[] base_array, line[] second_array, bool reverse = false) => _str_multisort(base_array, second_array, reverse)
// @function Reorder array based on indexes
// @param index_array The array of indexes of the new order
// @param array The array to be reorder
export reorder(int[] indexes, int[] array) => _reorder(indexes, array)
// @function Reorder array based on indexes
// @param index_array The array of indexes of the new order
// @param array The array to be reorder
export reorder(int[] indexes, float[] array) => _reorder(indexes, array)
// @function Reorder array based on indexes
// @param index_array The array of indexes of the new order
// @param array The array to be reorder
export reorder(int[] indexes, bool[] array) => _reorder(indexes, array)
// @function Reorder array based on indexes
// @param index_array The array of indexes of the new order
// @param array The array to be reorder
export reorder(int[] indexes, string[] array) => _reorder(indexes, array)
// @function Reorder array based on indexes
// @param index_array The array of indexes of the new order
// @param array The array to be reorder
export reorder(int[] indexes, color[] array) => _reorder(indexes, array)
// @function Reorder array based on indexes
// @param index_array The array of indexes of the new order
// @param array The array to be reorder
export reorder(int[] indexes, line[] array) => _reorder(indexes, array)
//////////
// Test //
//////////
//
// Sort number arrays
//
a1 = array.from(11, 5, 36, 0.1, 12.3, 44)
a2 = array.from(0, 1, 2, 3, 4, 5)
a3 = array.from(10, 11, 12, 13, 14, 15)
// Sorting 2 arrays
idxs = multisort(a1, a2, reverse=true)
// Sort more arrays if necessary
reorder(idxs, a3)
//
// Sort strings
//
a11 = array.from("c", "b", "a", "w", "arr", "sort")
a12 = array.from(0, 1, 2, 3, 4, 5)
multisort(a11, a12)
//
// Miltisort by distance
//
a21 = array.from(close[1], close[2], close[3], close[4], close[5], close[6])
a22 = array.from(0, 1, 2, 3, 4, 5)
multisort(a21, a22, close)
//
// Print data to data window
//
plotchar(get(a1, 0), "a1[0]", "", location.top, size=size.tiny, color=color.gray)
plotchar(get(a1, 1), "a1[1]", "", location.top, size=size.tiny, color=color.gray)
plotchar(get(a1, 2), "a1[2]", "", location.top, size=size.tiny, color=color.gray)
plotchar(get(a1, 3), "a1[3]", "", location.top, size=size.tiny, color=color.gray)
plotchar(get(a1, 4), "a1[4]", "", location.top, size=size.tiny, color=color.gray)
plotchar(get(a1, 5), "a1[5]", "", location.top, size=size.tiny, color=color.gray)
plotchar(get(a2, 0), "a2[0]", "", location.top, size=size.tiny, color=color.blue)
plotchar(get(a2, 1), "a2[1]", "", location.top, size=size.tiny, color=color.blue)
plotchar(get(a2, 2), "a2[2]", "", location.top, size=size.tiny, color=color.blue)
plotchar(get(a2, 3), "a2[3]", "", location.top, size=size.tiny, color=color.blue)
plotchar(get(a2, 4), "a2[4]", "", location.top, size=size.tiny, color=color.blue)
plotchar(get(a2, 5), "a2[5]", "", location.top, size=size.tiny, color=color.blue)
plotchar(get(a3, 0), "a3[0]", "", location.top, size=size.tiny, color=color.orange)
plotchar(get(a3, 1), "a3[1]", "", location.top, size=size.tiny, color=color.orange)
plotchar(get(a3, 2), "a3[2]", "", location.top, size=size.tiny, color=color.orange)
plotchar(get(a3, 3), "a3[3]", "", location.top, size=size.tiny, color=color.orange)
plotchar(get(a3, 4), "a3[4]", "", location.top, size=size.tiny, color=color.orange)
plotchar(get(a3, 5), "a3[5]", "", location.top, size=size.tiny, color=color.orange)
plotchar(get(a12, 0), "a12[0]", "", location.top, size=size.tiny, color=color.green)
plotchar(get(a12, 1), "a12[1]", "", location.top, size=size.tiny, color=color.green)
plotchar(get(a12, 2), "a12[2]", "", location.top, size=size.tiny, color=color.green)
plotchar(get(a12, 3), "a12[3]", "", location.top, size=size.tiny, color=color.green)
plotchar(get(a12, 4), "a12[4]", "", location.top, size=size.tiny, color=color.green)
plotchar(get(a12, 5), "a12[5]", "", location.top, size=size.tiny, color=color.green)
plotchar(get(a22, 0), "a22[0]", "", location.top, size=size.tiny, color=color.red)
plotchar(get(a22, 1), "a22[1]", "", location.top, size=size.tiny, color=color.red)
plotchar(get(a22, 2), "a22[2]", "", location.top, size=size.tiny, color=color.red)
plotchar(get(a22, 3), "a22[3]", "", location.top, size=size.tiny, color=color.red)
plotchar(get(a22, 4), "a22[4]", "", location.top, size=size.tiny, color=color.red)
plotchar(get(a22, 5), "a22[5]", "", location.top, size=size.tiny, color=color.red)
|
FunctionBlackScholes | https://www.tradingview.com/script/H3nlQz2A-FunctionBlackScholes/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 54 | library | 5 | MPL-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 Some methods for the Black Scholes Options Model, which demonstrates several approaches to the valuation of a European call.
library("FunctionBlackScholes")
// reference:
// https://people.math.sc.edu/Burkardt/py_src/black_scholes/black_scholes.html
// https://people.math.sc.edu/Burkardt/py_src/black_scholes/black_scholes.py
import RicardoSantos/Probability/1 as prob
import RicardoSantos/ArrayExtension/2 as ae
import RicardoSantos/ArrayGenerate/1 as ag
import RicardoSantos/DebugConsole/6 as console
[__T, __C] = console.init(25)
// @function Simulates the behavior of an asset price over time.
// @param s0 float, asset price at time 0.
// @param mu float, growth rate.
// @param sigma float, volatility.
// @param t1 float, time to expiry date.
// @param n int, time steps to expiry date.
// @returns option values at each equal timed step (0 -> t1)
export asset_path (float s0, float mu, float sigma, float t1, int n) => //{
float _dt = t1 / n
float[] _r = ag.normal_distribution(n, 0.0, 1.0)
// float[] _arg = array.new_float(n)
// float _a = math.pow(mu - sigma, 2.0) * _dt + sigma * math.sqrt(_dt)
// float _cumprod = 1.0
// float[] _s = array.new_float(n)
// for _i = 0 to (n - 1)
// float _ri = array.get(_r, _i)
// float _ai = math.exp(_a * _ri)
// _cumprod *= _ai
// array.set(_arg, _i, _ai)
// array.set(_s, _i, s0 * _cumprod)
// // insert the initial price on the start:
// array.unshift(_s, s0)
float[] _s = array.new_float(n+1, s0)
float _p = s0
for _i = 1 to n
_p *= math.exp((mu - math.pow(sigma, 2.0)) * _dt + sigma * math.sqrt(_dt) * array.get(_r, _i-1))
array.set(_s, _i, _p)
_p
//{ usage
_s
s0 = 2.0
mu = 0.1
sigma = 0.3
n = 100
t1 = 1.0
path = asset_path(s0, mu, sigma, t1, n)
str = '---<> asset_path() <>---'
str += str.format('\n The asset price at time 0, S0 = {0}', s0)
str += str.format('\n The asset expected growth rate MU = {0}', mu)
str += str.format('\n The asset volatility SIGMA = {0}', sigma)
str += str.format('\n The expiry date T1 = {0}', t1)
str += str.format('\n The number of time steps N = {0}', n)
str += str.format('\n {0}\n', str.tostring(path, '#.000'))
str += str.format('\n {0}\n', array.get(path, 100))
console.queue_one(__C, str)
//}}
// @function Uses the binomial method for a European call.
// @param s0 float, asset price at time 0.
// @param e float, exercise price.
// @param r float, interest rate.
// @param sigma float, volatility.
// @param t1 float, time to expiry date.
// @param m int, time steps to expiry date.
// @returns option value at time 0.
export binomial (float s0, float e, float r, float sigma, float t1, int m) => //{
float _dt = t1 / float(m)
float _a = 0.5 * (math.exp(-r * _dt) + math.exp((r + math.pow(sigma, 2.0)) * _dt))
float _sqrt = math.sqrt(math.pow(_a, 2.0) - 1.0)
float _d = (_a - _sqrt)
float _u = (_a + _sqrt)
float _p = (math.exp(r * _dt) - _d) / (_u - _d)
float[] _w = array.new_float(m + 1)
for _i = 0 to m
array.set(_w, _i, math.max(0.0, s0 * math.pow(_d, m - _i) * math.pow(_u, _i) - e))
// Trace backwards to get the option value at time 0.
for _n = m-2 to -1
for _i = 0 to (_n + 1)
float _wi = array.get(_w, _i)
float _wi1 = array.get(_w, _i + 1)
array.set(_w, _i, (1.0 - _p) * _wi + _p * _wi1)
for _i = 0 to m-1
float _wi = array.get(_w, _i)
array.set(_w, _i, math.exp(- r * t1) * _wi)
array.get(_w, 0)
//{
b_s0 = 2.0
b_e = 1.0
b_r = 0.05
b_sigma = 0.25
b_t1 = 3.0
b_m = 256
b_opt = binomial(b_s0, b_e, b_r, b_sigma, b_t1, b_m)
b_str = '---<> binomial() <>---'
b_str += str.format('\n asset price at time 0 (S0) = {0}', b_s0)
b_str += str.format('\n exercise price (E) = {0}', b_e)
b_str += str.format('\n interest rate (R) = {0}', b_r)
b_str += str.format('\n asset volatility (SIGMA) = {0}', b_sigma)
b_str += str.format('\n expiry date (T1) = {0}', b_t1)
b_str += str.format('\n number of time steps (M) = {0}', b_m)
b_str += str.format('\n {0}\n', b_opt)
console.queue_one(__C, b_str)
//}
// @function Evaluates the Black-Scholes formula for a European call.
// @param s0 float, asset price at time 0.
// @param t0 float, time at which the price is known.
// @param e float, exercise price.
// @param r float, interest rate.
// @param sigma float, volatility.
// @param t1 float, time to expiry date.
// @returns option value at time 0.
export bsf (float s0, float t0, float e, float r, float sigma, float t1) => //{
float _tau = t1 - t0
if 0.0 < _tau
float _sqrtau = math.sqrt(_tau)
float _d1 = (math.log(s0 / e) + (r + 0.5 * math.pow(sigma, 2.0)) * _tau) / (sigma * _sqrtau)
float _d2 = _d1 - sigma * _sqrtau
float _sqrt2 = math.sqrt(2.0)
float _n1 = 0.5 * (1.0 + prob.erf(_d1 / _sqrt2))
float _n2 = 0.5 * (1.0 + prob.erf(_d2 / _sqrt2))
s0 * _n1 - e * math.exp(-r * _tau) * _n2
else
math.max(0.0, s0 - e)
//{
bsf_s0 = 2.0
bsf_t0 = 0.0
bsf_e = 1.0
bsf_r = 0.05
bsf_sigma = 0.25
bsf_t1 = 3.0
bsf_opt = bsf(bsf_s0, bsf_t0, bsf_e, bsf_r, bsf_sigma, bsf_t1)
bsf_str = '---<> bsf() <>---'
bsf_str += str.format('\n asset price at time 0 (S0) = {0}', bsf_s0)
bsf_str += str.format('\n last known date (S0) = {0}', bsf_t0)
bsf_str += str.format('\n exercise price (E) = {0}', bsf_e)
bsf_str += str.format('\n interest rate (R) = {0}', bsf_r)
bsf_str += str.format('\n asset volatility (SIGMA) = {0}', bsf_sigma)
bsf_str += str.format('\n expiry date (T1) = {0}', bsf_t1)
bsf_str += str.format('\n {0}\n', bsf_opt)
console.queue_one(__C, bsf_str)
//}
// @function Forward difference method to value a European call option.
// @param e float, exercise price.
// @param r float, interest rate.
// @param sigma float, volatility.
// @param t1 float, time to expiry date.
// @param nx int, number of space steps in interval (0, L).
// @param nt int, number of time steps.
// @param smax float, maximum value of S to consider.
// @returns option values for the european call, float array of size ((nx-1) * (nt+1)).
export forward (float e, float r, float sigma, float t1, int nx, int nt, float smax) => //{
float _dt = t1 / float(nt)
float _dx = smax / float(nx)
float[] _a = array.new_float(nx)
float[] _b = array.new_float(nx)
float[] _c = array.new_float(nx)
for _i = 0 to (nx - 1)
array.set(_b, _i, 1.0 - r * _dt - _dt * math.pow(sigma * (_i + 1), 2.0))
for _i = 0 to (nx - 2)
array.set(_c, _i, 0.5 * _dt * math.pow(sigma * (_i + 1), 2.0) + 0.5 * _dt * r * (_i + 1.0))
for _i = 1 to (nx - 1)
array.set(_a, _i, 0.5 * _dt * math.pow(sigma * (_i + 1), 2.0) - 0.5 * _dt * r * (_i + 1))
float[] _u = array.new_float((nx-1)*(nt+1))
float _u0 = 0.0
for _i = 0 to (nx-2)
_u0 += _dx
array.set(_u, ae.index_2d_to_1d(nx-1, nt+1, _i, 0), math.max(0.0, _u0 - e))
for _j = 0 to (nt-1)
float _t = float(_j) * t1 / float(nt)
float _p = 0.5 * _dt * (nx - 1) * (math.pow(sigma, 2.0) * (nx - 1) + r) * (smax - e * math.exp(-r * _t))
for _i = 0 to (nx-2)
float _bi = array.get(_b, _i)
float _uij = array.get(_u, ae.index_2d_to_1d(nx-1, nt+1, _i, _j))
array.set(_u, ae.index_2d_to_1d(nx-1, nt+1, _i, _j + 1), _bi * _uij)
for _i = 0 to (nx-3)
float _ci = array.get(_c, _i)
float _uij1 = array.get(_u, ae.index_2d_to_1d(nx-1, nt+1, _i, _j+1))
float _ui1j = array.get(_u, ae.index_2d_to_1d(nx-1, nt+1, _i+1, _j))
array.set(_u, ae.index_2d_to_1d(nx-1, nt+1, _i, _j + 1), _uij1 + _ci * _ui1j)
for _i = 1 to (nx-2)
float _ai = array.get(_a, _i)
float _uij1 = array.get(_u, ae.index_2d_to_1d(nx-1, nt+1, _i, _j+1))
float _u1ij = array.get(_u, ae.index_2d_to_1d(nx-1, nt+1, _i-1, _j))
array.set(_u, ae.index_2d_to_1d(nx-1, nt+1, _i, _j + 1), _uij1 + _ai * _u1ij)
float _unx2 = array.get(_u, ae.index_2d_to_1d(nx-1, nt+1, nx - 2, _j+1))
array.set(_u, ae.index_2d_to_1d(nx-1, nt+1, nx - 2, _j+1), _unx2 + _p)
_u
//{
for_e = 4.0
for_r = 0.03
for_sigma = 0.5
for_t1 = 1.0
for_nx = 11
for_nt = 29
for_smax = 10.0
for_opt = forward(for_e, for_r, for_sigma, for_t1, for_nx, for_nt, for_smax)
for_str = '---<> forward() <>---'
for_str += str.format('\n exercise price (E) = {0}', for_e)
for_str += str.format('\n interest rate (R) = {0}', for_r)
for_str += str.format('\n asset volatility (SIGMA) = {0}', for_sigma)
for_str += str.format('\n expiry date (T1) = {0}', for_t1)
for_str += str.format('\n number of space steps (nx) = {0}', for_nx)
for_str += str.format('\n number of time steps (nt) = {0}', for_nt)
for_str += str.format('\n max value to consider (smax) = {0}', for_smax)
// for_str += str.format('\n {0}\n', str.tostring(for_opt, '#.###'))
for_str += '\n [ '
for _i = 0 to for_nx-2
for_str += str.tostring(array.get(for_opt, ae.index_2d_to_1d(for_nx-1, for_nt+1, _i, for_nt)), '#.000') + (_i != for_nx-2 ? ', ' : ' ]\n')
// for_str += str.format('\n {0}\n', array.get(for_opt, array.size(for_opt)-1))
console.queue_one(__C, for_str)
//}
// @function Uses Monte Carlo valuation on a European call.
// @param s0 float, asset price at time 0.
// @param e float, exercise price.
// @param r float, interest rate.
// @param sigma float, volatility.
// @param t1 float, time to expiry date.
// @param m int, time steps to expiry date.
// @returns confidence interval for the estimated range of valuation.
export mc (float s0, float e, float r, float sigma, float t1, int m) => //{
float[] _u = ag.normal_distribution(m, 0.0, 1.0)
float[] _pvals = array.new_float(m, 0.0)
for _i = 0 to (m - 1)
float _ui = array.get(_u, _i)
float _si = s0 * math.exp((r - 0.5 * math.pow(sigma, 2.0)) * t1 + sigma * math.sqrt(t1) * _ui)
array.set(_pvals, _i, math.exp(-r * t1) * math.max(0.0, _si - e))
float _pmean = array.avg(_pvals)
float _std = array.stdev(_pvals)
float _width = 1.96 * _std / math.sqrt(float(m))
array.from(_pmean - _width, _pmean + _width) // confidence interval
//{
mc_s0 = 2.0
mc_e = 1.0
mc_r = 0.05
mc_sigma = 0.25
mc_t1 = 3.0
mc_m = 100
mc_opt = mc(mc_s0, mc_e, mc_r, mc_sigma, mc_t1, mc_m)
mc_str = '---<> mc() <>---'
mc_str += str.format('\n asset price at time 0 (S0) = {0}', mc_s0)
mc_str += str.format('\n exercise price (E) = {0}', mc_e)
mc_str += str.format('\n interest rate (R) = {0}', mc_r)
mc_str += str.format('\n asset volatility (SIGMA) = {0}', mc_sigma)
mc_str += str.format('\n expiry date (T1) = {0}', mc_t1)
mc_str += str.format('\n number of time steps (M) = {0}', mc_m)
mc_str += str.format('\n {0}\n', str.tostring(mc_opt, '#.000'))
console.queue_one(__C, mc_str)
//}
console.update(__T, __C) |
statistics | https://www.tradingview.com/script/J4cWYceC-statistics/ | maartenheremans | https://www.tradingview.com/u/maartenheremans/ | 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/
// © maartenheremans
//@version=5
// @description General statistics library.
library("statistics")
// @function The "error function" encountered in integrating the normal
// distribution (which is a normalized form of the Gaussian function).
//
// @param x The input series.
//
// @returns The Error Function evaluated for each element of x.
export erf(float x) =>
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.031405429
p = 0.3275911
sign = (x < 0 ? -1 : 1)
ax = math.abs(x)/math.sqrt(2)
t = 1/(1 + (p*ax))
y = 1 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t * math.exp(-ax*ax)
(sign*y)
// @fucntion The 'complementary error function'.
//
// @param x The input series
//
// @returns The Complementary Error Function evaluated for each alement of x.
export erfc(float x) =>
1 - erf(x)
// @function Calculates the sum of the reciprocals of the series.
// For each element 'elem' in the series:
// sum += 1/elem
// Should the element be 0, the reciprocal value of 0 is used instead
// of NA.
//
// @param src The input series.
// @param len The length for the sum.
//
// @returns The sum of the resciprocals of 'src' for 'len' bars back.
export sumOfReciprocals(float src, int len) =>
math.sum((src != 0 ? 1.0/src : 0), len)
// @function The mean of the series.
// (wrapper around ta.sma).
//
// @param src The input series.
// @param len The length for the mean.
//
// @returns The mean of 'src' for 'len' bars back.
export mean(float src, int len) =>
ta.sma(src, len)
// @function The mean of the series.
// (wrapper around ta.sma).
//
// @param src The input series.
// @param len The length for the average.
//
// @returns The average of 'src' for 'len' bars back.
export average(float src, int len) =>
ta.sma(src, len)
// @function The Geometric Mean of the series.
//
// The geometric mean is most important when using data representing
// percentages, ratios, or rates of change. It cannot be used for
// negative numbers
//
// Since the pure mathematical implementation generates a very large
// intermediate result, we performed the calculation in log space:
// https://buzzardsbay.org/special-topics/calculating-geometric-mean/
//
// @param src The input series.
// @param len The length for the geometricMean.
//
// @returns The geometric mean of 'src' for 'len' bars back.
export geometricMean(float src, int len) =>
math.exp(1/len * math.sum(math.log(src), len))
// @function The Harmonic Mean of the series.
//
// The harmonic mean is most applicable to time changes and, along
// with the geometric mean, has been used in economics for price
// analysis. It is more difficult to calculate; therefore, it is less
// popular than eiter of the other averages.
//
// 0 values are ignored in the calculation.
//
// @param src The input series.
// @param len The length for the harmonicMean.
//
// @returns The harmonic mean of 'src' for 'len' bars back.
export harmonicMean(float src, int len) =>
1/len * sumOfReciprocals(src, len)
// @function The median of the series.
// (a wrapper around ta.median)
//
// @param src The input series.
// @param len The length for the median.
//
// @returns The median of 'src' for 'len' bars back.
export median(float src, int len) =>
ta.median(src, len)
// @function The variance of the series.
//
// @param src The input series.
// @param len The length for the variance.
// @param biased Wether to use the biased calculation (for a population), or the
// unbiased calculation (for a sample set). [Default = true].
//
// @returns The variance of 'src' for 'len' bars back.
export variance(float src, int len, bool biased = true) =>
ta.variance(src, len, biased)
// @function The standard deviation of the series.
//
// @param src The input series.
// @param len The length for the stdev.
// @param biased Wether to use the biased calculation (for a population), or the
// unbiased calculation (for a sample set). [Default = true].
//
// @returns The standard deviation of 'src' for 'len' bars back.
export stdev(float src, int len, bool biased = true) =>
ta.stdev(src, len, biased)
// @function The skew of the series.
//
// Skewness measures the amount of distortion from a symmetric
// distribution, making the curve appear to be short on the left
// (lower prices) and extended to the right (higher prices). The
// extended side, either left or right is called the tail, and a
// longer tail to the right is called positive skewness. Negative
// skewness has the tail extending towards the left.
//
// @param src The input series.
// @param len The length for the skewness.
//
// @returns The skewness of 'src' for 'len' bars back.
export skewness(float src, int len) =>
r = math.log(src/src[1])
m = mean(r, len)
(1/len * math.sum(math.pow(r-m, 3), len)) / math.pow(1/len * math.sum(math.pow(r-m, 2), len), 3/2)
// @function The kurtosis of the series.
//
// Kurtosis describes the peakedness or flatness of a distribution.
// This can be used as an unbiased assessment of whether prices are
// trending or moving sideways. Trending prices will ocver a wider
// range and thus a flatter distribution (kurtosis < 3; negative
// kurtosis). If prices are range-bound, there will be a clustering
// around the mean and we have positive kurtosis (kurtosis > 3)
//
// @param src The input series.
// @param len The length for the kurtosis.
//
// @returns The kurtosis of 'src' for 'len' bars back.
export kurtosis(float src, int len) =>
r = math.log(src/src[1])
m = mean(r, len)
((1/len * math.sum(math.pow(r-m, 4), len)) / math.pow(1/len * math.sum(math.pow(r-m, 2), len), 2))
// @function The normalized kurtosis of the series.
// kurtosis > 0 --> positive kurtosis --> trending
// kurtosis < 0 --> negative krutosis --> range-bound
//
// @param src The input series.
// @param len The length for the excessKurtosis.
//
// @returns The excessKurtosis of 'src' for 'len' bars back.
export excessKurtosis(float src, int len) =>
kurtosis(src, len) - 3
// @function Calculates the probability mass for the value according to the
// src and length. It calculates the probability for value to be
// present in the normal distribution calculated for src and length.
//
// @param src The input series.
// @param len The length for the normDist.
// @param value The series of values to calculate the normal distance for
//
// @returns The normal distance of 'value' to 'src' for 'len' bars back.
export normDist(float src, int len, float value) =>
m = mean(src, len)
v = variance(src, len)
div = math.sqrt(math.pi * 2) * math.sqrt(v)
pwr = math.pow(value - m, 2) / (2 * v) * -1
ePwr = math.pow(math.e, pwr)
(1 / div) * ePwr
// @function Calculates the cumulative probability mass for the value according
// to the src and length. It calculates the cumulative probability for
// value to be present in the normal distribution calculated for src
// and length.
//
// @param src The input series.
// @param len The length for the normDistCumulative.
// @param value The series of values to calculate the cumulative normal distance
// for
//
// @returns The cumulative normal distance of 'value' to 'src' for 'len' bars
// back.
export normDistCumulative(float src, int len, float value) =>
m = median(src, len)
v = stdev(src, len)
sqrt2 = math.sqrt(2)
(0.5) * (1 + erf((value - m) / (v * sqrt2)))
// @function Returns then z-score of objective to the series src.
// It returns the number of stdev's the objective is away from the
// mean(src, len)
//
// @param src The input series.
// @param len The length for the zScore.
// @param value The series of values to calculate the cumulative normal distance
// for
//
// @returns The z-score of objectiv with respect to src and len.
export zScore(float src, int len, float objective) =>
(objective - mean(src, len)) / stdev(src, len)
// @function Calculates the efficiency ratio of the series.
//
// It measures the noise of the series. The lower the number, the
// higher the noise.
//
// @param src The input series.
// @param len The length for the efficiency ratio.
//
// @returns The efficiency ratio of 'src' for 'len' bars back.
export er(float src, int len) =>
spc = math.sum(math.abs(src[0] - src[1]), len)
math.abs(src[len-1]-src[0])/spc
// @function Calculates the efficiency ratio of the series.
//
// It measures the noise of the series. The lower the number, the
// higher the noise.
//
// @param src The input series.
// @param len The length for the efficiency ratio.
//
// @returns The efficiency ratio of 'src' for 'len' bars back.
export efficiencyRatio(float src, int len) =>
er(src, len)
// @function Calculates the efficiency ratio of the series.
//
// It measures the noise of the series. The lower the number, the
// higher the noise.
//
// @param src The input series.
// @param len The length for the efficiency ratio.
//
// @returns The efficiency ratio of 'src' for 'len' bars back.
export fractalEfficiency(float src, int len) =>
er(src, len)
// @function Calculates the Mean Squared Error of the series.
//
// @param src The input series.
// @param len The length for the mean squared error.
//
// @returns The mean squared error of 'src' for 'len' bars back.
export mse(float src, int len, float other) =>
mean(math.pow((src - other), 2), len)
// @function Calculates the Mean Squared Error of the series.
//
// @param src The input series.
// @param len The length for the mean squared error.
//
// @returns The mean squared error of 'src' for 'len' bars back.
export meanSquaredError(float src, int len, float other) =>
mse(src, len, other)
// @function Calculates the Root Mean Squared Error of the series.
//
// @param src The input series.
// @param len The length for the root mean squared error.
//
// @returns The root mean squared error of 'src' for 'len' bars back.
export rmse(float src, int len, float other) =>
math.sqrt(mse(src, len, other))
// @function Calculates the Root Mean Squared Error of the series.
//
// @param src The input series.
// @param len The length for the root mean squared error.
//
// @returns The root mean squared error of 'src' for 'len' bars back.
export rootMeanSquaredError(float src, int len, float other) =>
rmse(src, len, other)
// @function Calculates the Mean Absolute Error of the series.
//
// @param src The input series.
// @param len The length for the mean absolute error.
//
// @returns The mean absolute error of 'src' for 'len' bars back.
export mae(float src, int len, float other) =>
mean(math.abs((src - other)), len)
// @function Calculates the Mean Absolute Error of the series.
//
// @param src The input series.
// @param len The length for the mean absolute error.
//
// @returns The mean absolute error of 'src' for 'len' bars back.
export meanAbsoluteError(float src, int len, float other) =>
mae(src, len, other)
//plot(close)
plot(er(close, 100))
|
ObjectStack | https://www.tradingview.com/script/w66bV0Op-ObjectStack/ | cryptolinx | https://www.tradingview.com/u/cryptolinx/ | 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/
// © cryptolinx - jango_blockchained
//@version=5
// @description
library("ObjectStack", false)
// ▪ Library Export ────
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ──── Init helper function. Recommanded, not required {
export init() =>
var label [] xLABEL = array.new_label(), var label [] fLABEL = array.new_label()
var line [] xLINE = array.new_line(), var line [] fLINE = array.new_line()
var box [] xBOX = array.new_box(), var box [] fBOX = array.new_box()
var linefill [] xFILL = array.new_linefill(), var linefill [] fFILL = array.new_linefill()
var table [] TABLE = array.new_table(), //
[xLABEL, fLABEL, xLINE, fLINE, xBOX, fBOX, xFILL, fFILL, TABLE]
// }
// ──── Push object into corr. array. Equivalent to array.push() {
export push(series label [] _stack, series label _obj) => array.push(_stack, _obj)
export push(series line [] _stack, series line _obj) => array.push(_stack, _obj)
export push(series linefill [] _stack, series linefill _obj) => array.push(_stack, _obj)
export push(series box [] _stack, series box _obj) => array.push(_stack, _obj)
export push(series table [] _stack, series table _obj) => array.push(_stack, _obj)
// }
// ──── Get next stack index {
export nextIndex(series label [] _stack) => int(array.size(_stack))
export nextIndex(series line [] _stack) => int(array.size(_stack))
export nextIndex(series box [] _stack) => int(array.size(_stack))
export nextIndex(series linefill [] _stack) => int(array.size(_stack))
export nextIndex(series table [] _stack) => int(array.size(_stack))
// }
// ──── Delete forwarding stacks {
export delete(series line [] _arr) =>
if array.size(_arr) > 0
for i = 0 to array.size(_arr) - 1 by 1
line.delete(array.get(_arr, i))
array.clear(_arr)
// ──
export delete(series label [] _arr) =>
if array.size(_arr) > 0
for i = 0 to array.size(_arr) - 1 by 1
label.delete(array.get(_arr, i))
array.clear(_arr)
// ──
export delete(series box [] _arr) =>
if array.size(_arr) > 0
for i = 0 to array.size(_arr) - 1 by 1
box.delete(array.get(_arr, i))
array.clear(_arr)
// ──
export delete(series linefill [] _arr) =>
if array.size(_arr) > 0
for i = 0 to array.size(_arr) - 1 by 1
linefill.delete(array.get(_arr, i))
array.clear(_arr)
// ──
export delete(series table [] _arr) =>
if array.size(_arr) > 0
for i = 0 to array.size(_arr) - 1 by 1
table.delete(array.get(_arr, i))
array.clear(_arr)
// }
// ──── Fixed stack: clean oldest entries {
export cleanOldest(series line [] _arrFix, series line [] _arrFor, series int _max = 500, series int _maxFixedPercent = 75) =>
int arrFixSize = array.size(_arrFix), int arrForSize = array.size(_arrFor)
int maxFixed = math.min(math.ceil(_max * _maxFixedPercent / 100), math.abs(_max - arrForSize))
if arrFixSize > 0 and arrFixSize > maxFixed
for i = (arrFixSize - maxFixed - 1) to 0 by 1
line.delete(array.get(_arrFix, i)), array.remove(_arrFix, i)
// ──
export cleanOldest(series label [] _arrFix, series label [] _arrFor, series int _max = 500, series int _maxFixedPercent = 75) =>
int arrFixSize = array.size(_arrFix), int arrForSize = array.size(_arrFor)
int maxFixed = math.min(math.ceil(_max * _maxFixedPercent / 100), math.abs(_max - arrForSize))
if arrFixSize > 0 and arrFixSize > maxFixed
for i = (arrFixSize - maxFixed - 1) to 0 by 1
label.delete(array.get(_arrFix, i)), array.remove(_arrFix, i)
// ──
export cleanOldest(series box [] _arrFix, series box [] _arrFor, series int _max = 500, series int _maxFixedPercent = 75) =>
int arrFixSize = array.size(_arrFix), int arrForSize = array.size(_arrFor)
int maxFixed = math.min(math.ceil(_max * _maxFixedPercent / 100), math.abs(_max - arrForSize))
if arrFixSize > 0 and arrFixSize > maxFixed
for i = (arrFixSize - maxFixed - 1) to 0 by 1
box.delete(array.get(_arrFix, i)), array.remove(_arrFix, i)
// ──
export cleanOldest(series linefill [] _arrFix, series linefill [] _arrFor, series int _max = 500, series int _maxFixedPercent = 75) =>
int arrFixSize = array.size(_arrFix), int arrForSize = array.size(_arrFor)
int maxFixed = math.min(math.ceil(_max * _maxFixedPercent / 100), math.abs(_max - arrForSize))
if arrFixSize > 0 and arrFixSize > maxFixed
for i = (arrFixSize - maxFixed - 1) to 0 by 1
linefill.delete(array.get(_arrFix, i)), array.remove(_arrFix, i)
// ──
export cleanOldest(series table [] _arrFix, series table [] _arrFor, series int _max = 350, series int _maxFixedPercent = 75) =>
int arrFixSize = array.size(_arrFix), int arrForSize = array.size(_arrFor)
int maxFixed = math.min(math.ceil(_max * _maxFixedPercent / 100), math.abs(_max - arrForSize))
if arrFixSize > 0 and arrFixSize > maxFixed
for i = (arrFixSize - maxFixed - 1) to 0 by 1
table.delete(array.get(_arrFix, i)), array.remove(_arrFix, i)
// }
// ──
export cleanOldest(series string [] _arrReg, series label [] _arrFixed, series int _max = 400) =>
int arrRegSize = array.size(_arrReg), int ctr = 0
if arrRegSize > _max
for i = (arrRegSize - _max) to 0 by 1
label.delete(array.get(_arrFixed, ctr)), array.set(_arrFixed, ctr, na), ctr += 1
// }
// ──── Get Registry Index By Object Title {
export getIndexByTitle(series string [] _arrReg, series string _title) => int _return = array.indexof(_arrReg, _title)
// }
// ──── Get Next Registry Index {
export getNextIndex(series string [] _arrReg) => int _return = array.size(_arrReg)
// }
// ──── Show Last {
export getSeriesTitle(series string _title) => var int ctr = 0, ctr += 1, string(str.format('{0}_{1}_{2}', _title, ctr, timenow))
// }
// ──── Show Last {
export showLast(series int _bars) => bool(bar_index > (last_bar_index - (_bars <= 0 ? last_bar_index : _bars)))
// }
// ──── All-In-One Function - labelFix (eq. to label.new) {
export labelFixed(series string _title = na, series int _offsetX = na, series float _y = na, series string _text = na, series string _xloc = xloc.bar_index,
series string _yloc = yloc.price, series color _color = color.blue, series string _style = label.style_label_center, series color _textcolor = color.white,
series string _size = size.normal, series string _textalign = text.align_center, series string _tooltip = na, series int _max = 400) =>
string sTitle = getSeriesTitle(_title), var int max = _max, var label [] LABELS = array.new_label(5000, na), var string [] REG = array.new_string(), label labelId = na
int index = getIndexByTitle(REG, sTitle), cleanOldest(REG, LABELS, max)
if index == -1
labelId := label.new(x = bar_index + _offsetX, y = _y, text = _text, color = _color, xloc = _xloc, yloc = _yloc, style = _style, textcolor = _textcolor, size = _size, textalign = _textalign, tooltip = _tooltip)
index := getNextIndex(REG), array.push(REG, sTitle), array.set(LABELS, index, labelId)
else if index > -1
labelId := array.get(LABELS, index)
[label(labelId), LABELS, REG]
// ──── ** New ** All-In-One Function - labelForward (eq. to label.new) {
export labelForward(series string _title, series int _offsetX = na, series float _y = na, series string _text = na, series string _xloc = xloc.bar_index,
series string _yloc = yloc.price, series color _color = color.blue, series string _style = label.style_label_center, series color _textcolor = color.white,
series string _size = size.normal, series string _textalign = text.align_center, series string _tooltip = na, series int _max = 100) =>
string sTitle = getSeriesTitle(_title), var label [] LABELS = array.new_label(5000, na), var string [] REG = array.new_string(), label labelId = na
int index = getIndexByTitle(REG, sTitle), cleanOldest(REG, LABELS, _max)
if index == -1
labelId := label.new(x = bar_index + _offsetX, y = _y, text = _text, color = _color, xloc = _xloc, yloc = _yloc, style = _style, textcolor = _textcolor, size = _size, textalign = _textalign, tooltip = _tooltip)
index := getNextIndex(REG), array.push(REG, sTitle), array.set(LABELS, index, labelId)
else if index > -1
labelId := array.get(LABELS, index), label.set_x(labelId, bar_index + _offsetX)
[label(labelId), LABELS, REG]
// }
// ▪ EXAMPLE ────
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ! LIMITATION: Libraries are limited to ~100 objects. Indicator and strategies coming up with 500 objects for each type, by default.
// ! If there is an official description, please let me know! :)
// !
// ! INDICATOR EXAMPLE https://www.tradingview.com/script/Pm3zSRnd/
// ──── Declare before indicator() / strategy() tag {
var int MaxLabelsCount = 50 //, var int MaxLinesCount = 100, var int MaxBoxesCount = 100
var int MaxFixedLabelsPercent = 80
// }
// ──── Init {
[xLABEL, fLABEL, xLINE, fLINE, _, _, _, _, _] = init()
// --
delete(fLABEL), delete(fLINE) //, delete(fBOX)
// }
// ──── Fixed Labels (xLABEL) (left-locked) {
var __BARS = input.int(0,"Show Last", minval = 0, maxval = 10000, step = 50, tooltip = '0 = Show All')
//--
var int ctr = 0
if bar_index % 25 == 1 and showLast(__BARS)
ctr += 1, push(xLABEL, label.new(x=bar_index, y=0, text=str.format("FIXED (@xLABEL)\n{0}\n\nBar_Index: {1}\n\nRecursive Array_Index: {2}", ctr, bar_index, '###'), color=color.blue, textcolor=color.white, style=ctr % 2 == 1 ? label.style_label_down : label.style_label_up))
// }
// ──── Forwarding Labels (fLABEL) (right-locked) {
int labelIndex = na
if barstate.islast
push(fLABEL, label.new(bar_index + 10, 0, text=str.format("FORWARD 1 (@fLABEL)\n\nShow Last: {0} bars\n\nChange Input 'Show Last'!", (__BARS == 0 ? "0 = All" : str.tostring(__BARS))), color=color.red, textcolor=color.white, style=label.style_label_right))
// --
labelIndex := nextIndex(fLABEL)
push(fLABEL, label.new(bar_index + 15, 0, text="", color=color.orange, textcolor=color.black, style=label.style_label_left))
// }
// ──── Debug: before {
plotchar(array.size(fLABEL),"fLABEL before",char='',color=#FFFFFF00)
plotchar(array.size(xLABEL),"xLABEL before",char='',color=#FFFFFF00)
// }
// ──── After all object calls, we need to clean our fixed object stacks {
cleanOldest(xLINE, fLINE) // Use default values for _max and _maxFixedPercent
cleanOldest(xLABEL, fLABEL, MaxLabelsCount, MaxFixedLabelsPercent)
// }
// ──── Debug: after {
plotchar(array.size(fLABEL),"fLABEL after",char='',color=#FFFFFF00)
plotchar(array.size(xLABEL),"xLABEL after",char='',color=#FFFFFF00)
// }
// ──── Only for example {
if barstate.islast
label.set_text(array.get(fLABEL, labelIndex), str.format("FORWARD 2 (@fLABEL)\n\nMax Labels Count: {6}\nMax Fixed Labels Percent: {7} %\nMax Fixed Labels Amount: {8}\n\n Current Fixed Labels Amount: {0}\nCurrent Fixed Label Index Range: {3} - {4}\nCurrent Forwarding Label Amount: {1}\nTotal Label Amount: {2}\nCurrent bar_index: {5}",
array.size(xLABEL), array.size(fLABEL), (array.size(xLABEL) + array.size(fLABEL)), (ctr - array.size(xLABEL)), ctr, bar_index, MaxLabelsCount, MaxFixedLabelsPercent, (MaxLabelsCount * MaxFixedLabelsPercent / 100)))
for i = 0 to array.size(xLABEL) - 1 by 1
string rString = label.get_text(array.get(xLABEL, i))
label.set_text(array.get(xLABEL, i), str.substring(rString, 0, str.length(rString) - 3) + str.tostring(i,"000"))
// }
// ──── } #EOF |
FunctionPatternDecomposition | https://www.tradingview.com/script/zzxuAOKs-FunctionPatternDecomposition/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 54 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Methods for decomposing price into common grid/matrix patterns.
library(title='FunctionPatternDecomposition')
// reference:
// https://jackschaedler.github.io/handwriting-recognition/
import RicardoSantos/FunctionPeakDetection/2 as peakdetection
import RicardoSantos/ArrayExtension/2 as ae
// Helper function to rescale the 500 limit to the right of current bar_index
X(points)=>int(500/points)
// @function Helper for converting series to array.
// @param source float, data series.
// @param length int, size.
// @returns float array.
export series_to_array (float source, int length) =>
float[] _data = array.new_float(length, float(na))
for _i = (length-1) to 0
if bar_index[_i] >= 0
array.set(_data, _i, source[_i])
_data
// @function Smooth data sample into 2d points.
// @param data float array, source data.
// @param rate float, default=0.25, the rate of smoothness to apply.
// @returns tuple with 2 float arrays.
export smooth_data_2d (float[] data, float rate=0.25) => //{
int _size = array.size(data)
//
float _ir = 1.0 - rate
float[] _X = array.new_float(_size, 0.0)
float[] _Y = array.copy(data)
//
if _size > 1
for _i = 1 to (_size - 1)
float _yi1 = array.get(_Y, _i - 1)
float _yi0 = array.get(_Y, _i)
array.set(_X, _i, rate * (_i - 1) + _ir * _i)
array.set(_Y, _i, rate * _yi1 + _ir * _yi0)
[_X, _Y]
//{ usage
// data = array.from(100.0, 300.0, 500.0, 200.0, 100.0, 200.0, 300.0, 600.0, 100.0)
length = input(10)
var data = array.new_float(length, close), array.push(data, close), array.shift(data)
[x, y] = smooth_data_2d(data, 0.7)
if barstate.islastconfirmedhistory
for _i = 1 to array.size(data)-1
line.new(int((_i-1)*X(length)), array.get(data, _i-1), int(_i*X(length)), array.get(data, _i), color=color.gray)
line.new(int(array.get(x, _i-1)*X(length)), array.get(y, _i-1), int(array.get(x, _i)*X(length)), array.get(y, _i), color=color.silver)
//}}
// @function Thin the number of points.
// @param data_x float array, points x value.
// @param data_y float array, points y value.
// @param rate float, default=2.0, minimum threshold rate of sample stdev to accept points.
// @returns tuple with 2 float arrays.
export thin_points (float[] data_x, float[] data_y, float rate=2.0) => //{
// modified rate to be a multiplier of the data standard deviation as to accomodate any values
int _size = array.size(data_x)
float _xt = array.get(data_x, 0)
float _yt = array.get(data_y, 0)
float[] _X = array.new_float(1, _xt)
float[] _Y = array.new_float(1, _yt)
if _size > 1
float _xd = array.stdev(data_x)
float _yd = array.stdev(data_y)
for _i = 1 to (_size - 1)
float _xi = array.get(data_x, _i)
float _yi = array.get(data_y, _i)
if ((_xi-_xt) >= ( _xd * rate)) or ((_yi-_yt) >= ( _yd * rate))
array.push(_X, _xi), _xt := _xi
array.push(_Y, _yi), _yt := _yi
[_X, _Y]
//{ usage:
[tx, ty] = thin_points(x, y, input(defval=1.0, title='thin'))
if barstate.islastconfirmedhistory
for _i = 1 to array.size(tx)-1
line.new(int(array.get(tx, _i-1)*X(length)), array.get(ty, _i-1), int(array.get(tx, _i)*X(length)), array.get(ty, _i), color=color.yellow)
//}}
// @function Extract the direction each point faces.
// @param data_x float array, points x value.
// @param data_y float array, points y value.
// @returns float array.
export extract_point_direction (float[] data_x, float[] data_y) => //{
// modified rate to be a multiplier of the data standard deviation as to normalize value discrepancy
// directional data is stored as (-1: down, 0: right, 1:up)
int _size = array.size(data_x)
float[] _direction = array.new_float(_size, na)
if _size > 1
float _xd = array.stdev(data_x)
float _yd = array.stdev(data_y)
for _i = 1 to (_size - 1)
float _xir = (array.get(data_x, _i) - array.get(data_x, _i - 1)) / _xd
float _yir = (array.get(data_y, _i) - array.get(data_y, _i - 1)) / _yd
if _xir >= math.abs(_yir)
array.set(_direction, _i, 0.0)
else
if _yir >= 0
array.set(_direction, _i, +1.0)
else
array.set(_direction, _i, -1.0)
_direction
//{ usage
_d = extract_point_direction(tx, ty)
if barstate.islastconfirmedhistory
for _i = 1 to array.size(_d)-1
_y = array.get(ty, _i)
_style = switch (array.get(_d, _i))
(+1.0) => label.style_triangleup
(-1.0) => label.style_triangledown
=> label.style_diamond
label.new(int(array.get(tx, _i)*X(length)), _y, str.tostring(_y), style=_style)
//}}
// @function ...
// @param data_x float array, points x value.
// @param data_y float array, points y value.
// @param rate float, minimum threshold rate of data y stdev.
// @returns tuple with 2 float arrays.
export find_corners (float[] data_x, float[] data_y, float rate) => //{
float _delta = array.stdev(data_y) * rate
[ph, pl] = peakdetection.function(data_x, data_y, _delta)
//{ usage:
[ph, pl] = find_corners(tx, ty, input(defval=1.0, title='corners'))
if barstate.islastconfirmedhistory
label.new(bar_index, 400.0, str.format('top: {0}\nbot: {1}', str.tostring(ph), str.tostring(pl)))
//}}
// @function transforms points data to a constrained sized matrix format.
// @param data_x float array, points x value.
// @param data_y float array, points y value.
// @param m_size int, default=10, size of the matrix.
// @returns flat 2d pseudo matrix.
export grid_coordinates (float[] data_x, float[] data_y, int m_size=10) => //{
int _size_x = array.size(data_x)
int _size_y = array.size(data_y)
// pattern size properties:
float _min_x = array.min(data_x)
float _max_x = array.max(data_x)
float _min_y = array.min(data_y)
float _max_y = array.max(data_y)
// need to add some extra space on the range edges to accomodate the high/low value
float _rx = (1.01 * _max_x - _min_x * 0.99)
float _ry = (1.01 * _max_y - _min_y * 0.99)
float[] _m = array.new_float(m_size * m_size, 0.0)
for _i = 0 to (_size_x - 1)
float _xi = array.get(data_x, _i)
float _yi = array.get(data_y, _i)
int _x_idx = math.floor(((_xi - _min_x) / _rx) * m_size)
int _y_idx = math.floor(((_yi - _min_y) / _ry) * m_size)
int _2d1 = ae.index_2d_to_1d(m_size, m_size, _x_idx, m_size-_y_idx-1)
_mxy = array.get(_m, _2d1)
array.set(_m, _2d1, _mxy + 1)
_m
// { usage
msize = input(10)
m = grid_coordinates(tx, ty, msize)
tab = table.new(position.bottom_left, msize, msize)
for _i = 0 to msize-1
for _j = 0 to msize-1
_v = array.get(m, ae.index_2d_to_1d(msize, msize, _i, _j))
_c = _v > 0 ? color.silver : color.gray
table.cell(tab, _i, _j, str.tostring(_v), text_color=_c)
//}
|
WIPNNetwork | https://www.tradingview.com/script/eXYloxSF-WIPNNetwork/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 53 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Method for a generalized Neural Network.
library("WIPNNetwork")
// reference:
// https://blog.primen.dk/understanding-backpropagation/
// https://ml-cheatsheet.readthedocs.io/en/latest/backpropagation.html
// https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
// https://www.anotsorandomwalk.com/backpropagation-example-with-numbers-step-by-step/
// https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/
// https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
// https://cedar.buffalo.edu/~srihari/CSE574/Chap5/Chap5.3-BackProp.pdf
import RicardoSantos/FunctionNNLayer/2 as layer
import RicardoSantos/MLLossFunctions/1 as loss
import RicardoSantos/MLActivationFunctions/1 as activation
// @function helper method to generate random weights of (A * B) size.
// @param previous_size int, number of nodes on the left.
// @param next_size int, number of nodes on the right.
// @returns float array.
generate_random_weights (int previous_size, int next_size) => //{
_weights = matrix.new<float>(next_size, previous_size)
for _i = 0 to next_size-1
for _j = 0 to previous_size-1
matrix.set(_weights, _i, _j, math.random() * 2.0 - 1.0)
_weights
//}
mprint (M, format='0.000') => //{
_rows = matrix.rows(M)
_cols = matrix.columns(M)
_s = ''
for _i = 0 to _rows-1
_s += '[ '
for _j = 0 to _cols-1
_s += ((_j == _rows-1) ? '-> ': '') + str.tostring(matrix.get(M, _i, _j), format) + ' '
_s += ']\n'
_s
//}
to_column_matrix (float[] a) => //{
_m = matrix.new<float>()
matrix.add_col(_m, 0, a)
_m
//}
// @function helper method to propagate the signals forward.
// @param inputs float array, network inputs.
// @param weights float array, network weights.
// @param layer_sizes int array, layer sizes.
// @param weights_max_width int, the maximum row size of the weights matrix.
// @returns float array.
propagate_forward (float[] inputs, matrix<float> weights, int[] layer_sizes, string[] layer_functions, float[] layer_bias) => //{
// TODO: might be good to remove output layer from loop? (inputs -> (loop hidden to hidden) -> outputs)
// : missing alpha, scale parameterfor activation functions that might require it..
string _debug = '\n Forward Propagation:'
int _size_i = array.size(inputs)
int _size_ls = array.size(layer_sizes)
int _size_lb = array.size(layer_bias)
// use default parameters if empty array is provided:
float[] _layer_bias = _size_lb > 0 ? layer_bias : array.new_float(_size_ls, 1.0)
// * process (input -> 1st hidden layer) or (input -> output layer):
// TODO: bias, alpha, scale for each layer.
float[] _layer_outputs = layer.function(
inputs = inputs,
weights = matrix.submatrix(weights, 0, array.get(layer_sizes, 0), 0, _size_i),
activation_function = array.get(layer_functions, 0),
bias = array.get(_layer_bias, 0), alpha = na, scale = na
)
_debug += str.format('\n Current Layer: {0}, Current Layer size: {1}, Previous Layer size: {2}, Base index: {3}, f(): {4}, b: {5}', 0, array.get(layer_sizes, 0), _size_i, 0, array.get(layer_functions, 0), array.get(_layer_bias, 0))
// if theres more than 1 (hidden layer + output)
// * process hidden and outputs:
if _size_ls > 1
float[] _layer_output = _layer_outputs
for _layer = 1 to _size_ls - 1
// find the base level of current layer weights:
// base = (sum of nodes up to previous layer) * (max weights in a node)
// (weights in layer) = base + (previous layer nodes) * (current layer nodes)
int _previous_layer_size = array.get(layer_sizes, _layer - 1)
int _this_layer_size = array.get(layer_sizes, _layer)
int _w_base_idx = array.sum(array.slice(layer_sizes, 0, _layer))
matrix<float> _layer_weights = matrix.submatrix(weights, _w_base_idx, _w_base_idx + _this_layer_size, 0, _previous_layer_size) //resize_weights_matrix(array.slice(weights, _w_base_idx, _w_base_idx + weights_max_width * _this_layer_size), weights_max_width, _previous_layer_size)
// process hidden and output layer:
// TODO: bias, alpha, scale for each layer.
_layer_output := layer.function(
inputs = _layer_output,
weights = _layer_weights,
activation_function = array.get(layer_functions, _layer),
bias=array.get(_layer_bias, _layer), alpha=na, scale=na
)
array.concat(_layer_outputs, _layer_output)
_debug += str.format('\n Current Layer: {0}, Current Layer size: {1}, Previous Layer size: {2}, Base index: {3}, f(): {4}, b: {5}', _layer, _this_layer_size, _previous_layer_size, _w_base_idx, array.get(layer_functions, _layer), array.get(_layer_bias, _layer))
[_layer_outputs, _debug]
//}
// @function Generalized Neural Network Method.
// @param x TODO: add parameter x description here
// @returns TODO: add what function returns
export network (
float[] inputs, float[] targets, matrix<float> weights,
int[] layer_sizes, float[] layer_biases, string[] layer_functions,
string loss_function='mse', float learning_rate=0.01
) => //{
// TODO: Layer activation function extra parameters.
// int _weights_max_width = array.max(layer_sizes) // highest number of nodes on each layer as base for weight rectangle matrix slicing.
int _total_nodes = array.sum(layer_sizes)
int _size_i = array.size(inputs)
int _size_t = array.size(targets)
int _size_ls = array.size(layer_sizes)
int _size_lb = array.size(layer_biases)
int _size_lf = array.size(layer_functions)
int _Wrows = matrix.rows(weights)
int _Wcols = matrix.columns(weights)
// TODO: rework error messages.
switch
(_size_i < 1) => runtime.error('FunctionNNetwork -> network(): "inputs" has wrong size.')
(_size_t < 1) => runtime.error('FunctionNNetwork -> network(): "targets" has wrong size.')
// (_size_w < 1) => runtime.error('FunctionNNetwork -> network(): "weights" has wrong size.')
(_size_ls < 1) => runtime.error('FunctionNNetwork -> network(): "layer_sizes" has wrong size.')
(_size_lb < 1) => runtime.error('FunctionNNetwork -> network(): "layer_biases" has wrong size.')
(_size_lf < 1) => runtime.error('FunctionNNetwork -> network(): "layer_functions" has wrong size.')
(_size_t != array.get(layer_sizes, _size_ls - 1)) => runtime.error('FunctionNNetwork -> network(): "targets" size does not match output layer size in "layer_sizes"')
(na(loss_function)) => runtime.error('FunctionNNetwork -> network(): "loss_function" is invalid.') //temp just for use sake
(na(learning_rate)) => runtime.error('FunctionNNetwork -> network(): "learning_rate" is invalid.') //temp just for use sake
//
// propagate forward:
[_layer_outputs, _debug] = propagate_forward(inputs, weights, layer_sizes, layer_functions, layer_biases)
// _layer_outputs = array.new<float>(10), _debug=''
//
// propagate backward:
// error:
// TODO: function selection:
float _output_error = loss.mse(targets, array.slice(_layer_outputs, _total_nodes - (array.get(layer_sizes, _size_ls - 1)), _total_nodes))
// reference for delta rule: https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
// node_delta_error = (nodeoutput - nodetarget) * derivative(nodeoutput)
// update_weight = weight - learning_rate * node_error_delta
//
// reference: https://cedar.buffalo.edu/~srihari/CSE574/Chap5/Chap5.3-BackProp.pdf
// Weight = weight + (learning rate * node output error * node weight input)
//##########################################################################
// Work in progress...
//##########################################################################
// * calculate delta from output layer:
float _output_delta = _output_error * activation.derivative(array.get(layer_functions, _size_ls-1), _output_error)
_debug += str.format('\n Output Error: {0}, Delta: {1}', _output_error, _output_delta)
float[] _node_errors = array.new_float(0)//_total_nodes) // #######################################
float[] _error_deltas = array.new_float(_total_nodes)
int _last_delta_idx = -1
// * process the error delta for the output layer:
float[] _layer_deltas = array.new_float(_size_ls, 0.0)
array.set(_layer_deltas, _size_ls-1, _output_delta)
_debug += '\n\n Back Propagation:'
for _layer_idx = (_size_ls - 1) to 0
int _this_layer_size = array.get(layer_sizes, _layer_idx)
int _previous_layer_size = _layer_idx == 0 ? _size_i : array.get(layer_sizes, _layer_idx - 1)
int _number_of_nodes_up_to_this_layer = array.sum(array.slice(layer_sizes, 0, _layer_idx))
// matrix<float> _layer_weights = matrix.submatrix(weights, _number_of_nodes_up_to_this_layer, (_number_of_nodes_up_to_this_layer + _this_layer_size), 0, _Wcols) //array.slice(weights, _weights_max_width * _number_of_nodes_up_to_this_layer, _weights_max_width * (_number_of_nodes_up_to_this_layer + _this_layer_size))
string _layer_function = array.get(layer_functions, _layer_idx)
//**********************************************************************>
// dot product of layer weights and layer_delta
float _current_layer_delta = array.get(_layer_deltas, _layer_idx)
float _layer_error = 0.0
for _j = 0 to _Wcols - 1
_layer_error += matrix.get(weights, _number_of_nodes_up_to_this_layer, _j) * _current_layer_delta
//**********************************************************************<
_debug += str.format('\n Layer: {0}, Current size: {1}, Previous Size: {2}, e: {3}, weights:\n', _layer_idx, _this_layer_size, _previous_layer_size, _layer_error)
// * calculate node output derivative:
for _node_idx = 0 to (_this_layer_size - 1)
float _node_output = array.get(_layer_outputs, _number_of_nodes_up_to_this_layer + _node_idx)
float _node_derivative = activation.derivative(_layer_function, _node_output)
if _layer_idx > 0
array.set(_layer_deltas, _layer_idx - 1, _layer_error * _node_derivative)//*********************
float _node_target = 1.0 //##########################
float[] _node_inputs = _layer_idx == 0 ? inputs : array.slice(_layer_outputs, _number_of_nodes_up_to_this_layer - _previous_layer_size, _number_of_nodes_up_to_this_layer)
//calculate layer error
//update weight
for _weight_idx = 0 to (_previous_layer_size - 1)
float _weight = matrix.get(weights, _number_of_nodes_up_to_this_layer + _node_idx, _weight_idx)
switch (_layer_idx)
(_size_ls - 1) => _node_target := array.get(targets, _node_idx)
=> _node_target := array.get(_node_inputs, _weight_idx)
float _error_delta = (_node_output - _node_target) * _node_derivative
_weight += learning_rate * _error_delta
_debug += str.format(' {0} ', _weight)
matrix.set(weights, _number_of_nodes_up_to_this_layer + _node_idx, _weight_idx, _weight) //###########################
[_layer_outputs, _layer_deltas, _debug]
//{ usage:
// 7, 5 = i3, h5 h3 o2
var float[] inputs = array.from(0.0, 1, 2)
var float[] expected_outputs = array.from(1.0, 0.0)
var matrix<float> weights = generate_random_weights(5, 10)
// weights = array.from(
// 0.000, 0.001, 0.002, float(na), float(na),
// 0.003, 0.004, 0.005, float(na), float(na),
// 0.006, 0.007, 0.008, float(na), float(na),
// 0.009, 0.010, 0.011, float(na), float(na),
// 0.012, 0.013, 0.014, float(na), float(na),
// 0.100, 0.101, 0.102, 0.103, 0.104,
// 0.105, 0.106, 0.107, 0.108, 0.109,
// 0.110, 0.111, 0.112, 0.113, 0.114,
// 0.200, 0.201, 0.202, float(na), float(na),
// 0.203, 0.204, 0.205, float(na), float(na),
// 0.206, 0.207, 0.208, float(na), float(na)
// )
// H H O
var int[] layer_sizes = array.from( 5, 3, 2)
var float[] layer_biases = array.from( 1.0, 1.0, 1.0)
var string[] layer_functions = array.from('sigmoid', 'sigmoid', 'sigmoid')
[o, d, _debug] = network(inputs, expected_outputs, weights, layer_sizes, layer_biases, layer_functions, 'mse')
//
if true//islastconfirmedhistory
var label la = label.new(bar_index, 0.0, '')
label.set_x(la, bar_index), label.set_text(la, str.format('output:{0}\ndelta:{1}\nweights:{2}, \n{3}', str.tostring(o), str.tostring(d), matrix.elements_count(weights), _debug))
// print NN to table:
var table T = table.new(position.bottom_right, 7, 3, bgcolor=#000000, frame_color=color.black, frame_width=2, border_width=2, border_color=color.gray)
// run a simple NN forward cycle once:
_wh1 = matrix.submatrix(weights, 0, 5, 0, 3)// next, previous, layers
_wh2 = matrix.submatrix(weights, 5, 8, 0, 5)
_wo = matrix.submatrix(weights, 8, 10, 0, 3)
_h1 = array.slice(o, 0, 5)//function(i, _wh1) // 1st hidden layer with 4 nodes, from inputs
_h2 = array.slice(o, 5, 8)//function(h1, _wh2) // 2nd level hidden layer with 5 nodes , from first hidden
_o = array.slice(o, 8, 10)//function(h2, _wo) // output layer with 3 nodes
// label.new(bar_index, 0.0, str.tostring(matrix.mult(matrix.transpose(_wh1), i)))
//
table.cell(T, 0, 0, 'Input:', text_color=color.silver, text_halign=text.align_right)
table.cell(T, 1, 0, 'Hidden 1:', text_color=color.silver, text_halign=text.align_right),
table.cell(T, 3, 0, 'Hidden 2:', text_color=color.silver, text_halign=text.align_right)
table.cell(T, 5, 0, 'output:', text_color=color.silver, text_halign=text.align_right)
table.cell(T, 0, 1, '', text_color=color.silver, text_halign=text.align_right)
table.cell(T, 1, 1, 'weights:', text_color=color.silver, text_halign=text.align_right),
table.cell(T, 2, 1, 'node:', text_color=color.silver, text_halign=text.align_right),
table.cell(T, 3, 1, 'weights:', text_color=color.silver, text_halign=text.align_right)
table.cell(T, 4, 1, 'node:', text_color=color.silver, text_halign=text.align_right),
table.cell(T, 5, 1, 'weights:', text_color=color.silver, text_halign=text.align_right)
table.cell(T, 6, 1, 'node:', text_color=color.silver, text_halign=text.align_right),
table.merge_cells(T, 1, 0, 2, 0)
table.merge_cells(T, 3, 0, 4, 0)
table.merge_cells(T, 5, 0, 6, 0)
table.cell(T, 0, 2, str.tostring(to_column_matrix(inputs), '0.000'), text_color=color.silver, text_halign=text.align_left)
table.cell(T, 1, 2, str.tostring(_wh1, '0.000'), text_color=color.silver, text_halign=text.align_left)
table.cell(T, 2, 2, str.tostring(to_column_matrix(_h1), '0.000'), text_color=color.silver, text_halign=text.align_left)
table.cell(T, 3, 2, str.tostring(_wh2, '0.000'), text_color=color.silver, text_halign=text.align_left)
table.cell(T, 4, 2, str.tostring(to_column_matrix(_h2), '0.000'), text_color=color.silver, text_halign=text.align_left)
table.cell(T, 5, 2, str.tostring(_wo, '0.000'), text_color=color.silver, text_halign=text.align_left)
table.cell(T, 6, 2, str.tostring(to_column_matrix(_o), '0.000'), text_color=color.silver, text_halign=text.align_left)
//{ remarks:
//}}}
|
FunctionWeekofmonth | https://www.tradingview.com/script/6CQ2olfy-FunctionWeekofmonth/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 40 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Week of Month function.
library(title='FunctionWeekofmonth')
// @function Week of month for provided unix time.
// @param utime int, unix timestamp.
// @returns int
export weekofmonth(int utime) => //{
int _year = year(utime)
int _month = month(utime)
int _yweek = weekofyear(utime)
int _sweek = weekofyear(timestamp(_year, _month, 1, 0, 0, 0))
_o = _yweek - _sweek + 1
if _o > 0
_o
else
math.round(dayofmonth(utime) / 7) + 1
//{ usage:
m = weekofmonth(input.time(timestamp('2021-01-01')))
m2 = weekofmonth(time)
plot(m, title='M', color=color.silver)
plot(m2, title='M', color=color.yellow)
//}} |
Logger Library For Pinescript (Logging and Debugging) | https://www.tradingview.com/script/aeH4cdXM-Logger-Library-For-Pinescript-Logging-and-Debugging/ | CyberMensch | https://www.tradingview.com/u/CyberMensch/ | 46 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © paragjyoti2012
//@version=5
// @description
// // This is a logging library for Pinescript. It is aimed to help developers testing and debugging scripts with a simple to use logger function.
// // Pinescript lacks a native logging implementation. This library would be helpful to mitigate this insufficiency.
// // This library uses table to print outputs into its view. It is simple, customizable and robust.
// // You can start using it's .log() method just like any other logging method in other languages.
// //////////////////
// USAGE
// //////////////////
// Importing the Library
// ---------------------
// import paragjyoti2012/LoggerLib/<version_no> as Logger
// .init() : Initializes the library and returns the logger pointer. (Later will be used as a function parameter)
// .initTable: Initializes the Table View for the Logger and returns the table id. (Later will be used as a function parameter)
// parameters:
// logger: The logger pointer got from .init()
// max_rows_count: Number of Rows to display in the Logger Table (default is 10)
// offset: The offset value for the rows (Used for scrolling the view)
// position: Position of the Table View
// Values could be:
// left
// right
// top-right
// (default is left)
// size: Font Size of content
// Values could be:
// small
// normal
// large
// (default is small)
// hide_date: Wheter to hide the Date/Time column in the Logger (default is false)
// stickyRows: Some logs could be sticked at the bottom of the logs. This type of of logs will be updated without adding more to the list of logs.
// These kind of logs will be helpful to log at the last bar or logs that needs constant attention.
// Maximum recommended rows is 5. Default is set to 0, so it won't show sticky logs without explicitly setting it.
// To log a sticky log, you need to pass the stickPosition parameter (ranging from 1 to 5) for the .log() method.
// returns: Table
// example usage of .initTable()
// import paragjyoti2012/LoggerLib/1 as Logger
// var logger=Logger.init()
// var logTable=Logger.initTable(logger, max_rows_count=20, offset=0, position="top-right")
// -------------------
// LOGGING
// -------------------
// .log() : Logging Method
// params: (string message, string[] logger, table table_id, string type="message")
// logger: pass the logger pointer from .init()
// table_id: pass the table pointer from .initTable()
// message: The message to log
// type: Type of the log message
// Values could be:
// message
// warning
// error
// info
// success
// (Default is message)
//
// stickPosition: To show logs as sticky logs (Some logs could be sticked at the bottom of the logs, this type of of logs will be updated without adding more to the list of logs.)
// You need to pass the stickPosition parameter. It is the position number that you want to display the log at the bottom of the list. (Ranging from 1 to 5)
// If you want to stick the log at position 3, you need to pass 3 as stickPosition.
// returns: void
// ///////////////////////////////////////
// Full Boilerplate For Using In Indicator
// ///////////////////////////////////////
// offset=input.int(0,"Offset",minval=0)
// size=input.string("small","Font Size",options=["normal","small","large"])
// rows=input.int(15,"No Of Rows")
// position=input.string("left","Position",options=["left","right","top-right"])
// hide_date=input.bool(false,"Hide Time")
// import paragjyoti2012/LoggerLib/5 as Logger
// var logger=Logger.init()
// var logTable=Logger.initTable(logger,rows,offset,position,size,hide_date)
// rsi=ta.rsi(close,14)
// [macd,signal,hist]=ta.macd(close,12,26,9)
// if(ta.crossunder(close,34000))
// Logger.log("Dropped Below 34000",logger,logTable,"warning")
// if(ta.crossunder(close,35000))
// Logger.log("Dropped Below 35000",logger,logTable)
// if(ta.crossover(close,38000))
// Logger.log("Crossed 38000",logger,logTable,"info")
// if(ta.crossunder(rsi,20))
// Logger.log("RSI Below 20",logger,logTable,"error")
// if(ta.crossover(macd,signal))
// Logger.log("Macd Crossed Over Signal",logger,logTable)
// if(ta.crossover(rsi,80))
// Logger.log("RSI Above 80",logger,logTable,"success")
// /////////////////////
// For any assistance using this library or reporting issues, please write in the comment section below.
// I will try my best to guide you and update the library. Thanks :)
// /////////////////////
library("LoggerLib")
// library("LogLib_Pvt")
import paragjyoti2012/STR_Dictionary_Lib/7 as DictLib
export init()=>
obj=DictLib.init("barIndex=,time=,message=,type=,rows=,size=,hide_date=,offset=,stickyRows=")
DictLib.initStack(obj)
export initTable(string[] logger, int max_rows_count=10, int offset=0, string position="left", string size="small", bool hide_date=false,int stickyRows=0)=>
_stickyRows=stickyRows+2
mytable=table.new(position=="right"?position.bottom_right:position=="top-right"?position.top_right:position.bottom_left, hide_date?2:3, max_rows_count + 1 + (stickyRows? _stickyRows+1:0), border_width = 1)
if(max_rows_count!=10)
DictLib.setIntElement(logger,0,"rows", max_rows_count)
if(size!="small")
DictLib.setElement(logger,0,"size", size)
if(hide_date)
DictLib.setElement(logger,0,"hide_date", "true")
if(offset)
DictLib.setIntElement(logger,0,"offset", offset)
if(stickyRows)
DictLib.setIntElement(logger,0,"stickyRows",_stickyRows)
for i=0 to _stickyRows-1
sticky_obj=DictLib.init("barIndex=,time=,message=,type=")
DictLib.insertToStack(logger,sticky_obj,1)
mytable
renderCell(logger,log_index,table_id,cell_id,tb_size,show_date)=>
msgtype = DictLib.getElement(logger,log_index,"type")
color msg_color = switch msgtype
'message' => #cccccc
'warning' => #F5AC4E
'error' => #DD4224
'success' => #00c121
'info' => #02d0fd
=> na
color txt_color = switch msgtype
'message' => #000000
'warning' => #000000
'error' => #ffffff
'success' => #ffffff
'info' => #000000
=> na
timestr=DictLib.getElement(logger,log_index,"time")
msg=DictLib.getElement(logger,log_index,"message")
barindex=DictLib.getElement(logger,log_index,"barIndex")
table.cell(table_id, 0, cell_id , msg, bgcolor = msg_color, text_size = tb_size, text_color=txt_color)
table.cell(table_id, 1, cell_id , barindex, bgcolor = msg_color, text_size = tb_size, text_color=txt_color)
if(show_date)
table.cell(table_id, 2, cell_id , timestr, bgcolor = msg_color, text_size = tb_size, text_color=txt_color)
export log(string message, string[] logger, table table_id, string type="message", int stickPosition=0) =>
obj=DictLib.init("barIndex=,time=,message=,type=")
tm=str.tostring(year) + "-" + str.tostring(month) + "-" + str.tostring(dayofmonth) + " | " + str.tostring(hour) + ":" + str.tostring(minute) + (timeframe.isseconds? ":" + str.tostring(second):"")
_stickPosition=stickPosition+2
stickyRows=0
if(DictLib.getElement(logger,0,"stickyRows")!="")
stickyRows:=DictLib.getIntElement(logger,0,"stickyRows")
DictLib.setInt(obj,"barIndex", bar_index)
DictLib.set(obj,"time", tm)
DictLib.set(obj,"message", message)
DictLib.set(obj,"type", type)
if(stickyRows and stickPosition)
DictLib.updateStack(logger,obj,_stickPosition)
else
DictLib.insertToStack(logger,obj,stickyRows+1)
max_rows_count=10
size="small"
show_date=true
offset=0
if(DictLib.getElement(logger,0,"rows")!="")
max_rows_count:=DictLib.getIntElement(logger,0,"rows")
if(DictLib.getElement(logger,0,"size")!="")
size:=DictLib.getElement(logger,0,"size")
if(DictLib.getElement(logger,0,"hide_date")=="true")
show_date:=false
if(DictLib.getElement(logger,0,"offset")!="")
offset:=DictLib.getIntElement(logger,0,"offset")
tb_size=size=="small"?size.small:size=="large"?size.large:size.normal
table.cell(table_id, 0, 0, "Log", bgcolor = color.black, text_size = tb_size,text_color=color.white)
table.cell(table_id, 1, 0, "Bar #", bgcolor = color.black, text_size = tb_size,text_color=color.white)
if(show_date)
table.cell(table_id, 2, 0, "Time", bgcolor = color.black, text_size = tb_size,text_color=color.white)
for row_id = 1 to max_rows_count
log_index = row_id + offset + stickyRows
if(log_index>array.size(logger)-1)
break
cell_id=math.min(max_rows_count+1,array.size(logger)-stickyRows)-row_id
renderCell(logger,log_index,table_id,cell_id,tb_size,show_date)
if(stickyRows)
table.cell(table_id, 0, max_rows_count+1)
table.cell(table_id, 0, max_rows_count+2, "Sticky Log", bgcolor = color.black, text_size = tb_size,text_color=color.white)
table.cell(table_id, 1, max_rows_count+2, " ", bgcolor = color.black, text_size = tb_size,text_color=color.white)
if(show_date)
table.cell(table_id, 2, max_rows_count+2, " ", bgcolor = color.black, text_size = tb_size,text_color=color.white)
for s_row_id = 3 to stickyRows
log_index = s_row_id
cell_id=max_rows_count+1+s_row_id
renderCell(logger,log_index,table_id,cell_id,tb_size,show_date)
|
FunctionNNPerceptron | https://www.tradingview.com/script/SurirnkK-FunctionNNPerceptron/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 33 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos
//@version=5
// @description Perceptron Function for Neural networks.
library(title='FunctionNNPerceptron')
// reference:
// https://www.educba.com/perceptron-learning-algorithm/
// https://blog.primen.dk/basic-neural-network-model-insights/
// https://ml-cheatsheet.readthedocs.io/en/latest/activation_functions.html
// https://en.wikipedia.org/wiki/Artificial_neural_network
// https://blog.primen.dk/basic-neural-network-code-example-java/
import RicardoSantos/MLActivationFunctions/1 as activation
// @function generalized perceptron node for Neural Networks.
// @param inputs float array, the inputs of the perceptron.
// @param weights float array, the weights for inputs.
// @param bias float, default=1.0, the default bias of the perceptron.
// @param activation_function string, default='sigmoid', activation function applied to the output.
// @param alpha float, default=na, if required for activation.
// @param scale float, default=na, if required for activation.
// @outputs float
export function (float[] inputs, float[] weights, string activation_function='sigmoid', float bias=1.0, float alpha=na, float scale=na) => //{
int _size_i = array.size(inputs)
float _sum = bias
for _i = 0 to _size_i-1
_sum += array.get(inputs, _i) * array.get(weights, _i)
activation.function(activation_function, _sum, alpha, scale)
//{ usage:
string activation = input.string(defval='sigmoid', options=['binary step', 'linear', 'sigmoid', 'tahn', 'relu', 'leaky relu', 'relu 6', 'softmax', 'softplus', 'softsign', 'elu', 'selu', 'exponential'])
var float bias = 0.50
float y = close/close[1]
float[] x = array.from(y, y[1], y[2], y[3], y[4])
float[] w = array.from(0.8, -0.7, -0.5, -0.3, -0.5)
float p = function (x, w, activation, bias)
plot(p)
//{ remarks:
//}}}
|