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
|
---|---|---|---|---|---|---|---|---|
Sprenkle 1964 Option Pricing Model w/ Num. Greeks [Loxx] | https://www.tradingview.com/script/3ERjyUcZ-Sprenkle-1964-Option-Pricing-Model-w-Num-Greeks-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Sprenkle 1964 Option Pricing Model w/ Num. Greeks [Loxx]",
shorttitle ="S1964OPMNG [Loxx]",
overlay = true,
max_lines_count = 500, precision = 4)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
import loxx/loxxexpandedsourcetypes/4
color darkGreenColor = #1B7E02
string callString = "Call"
string putString = "Put"
string Continuous = "Continuous"
string PeriodRate = "Period Rate"
string Annual = "Annual"
string SemiAnnual = "Semi-Annual"
string Quaterly = "Quaterly"
string Monthly = "Monthly"
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
array<float> sarr = array.new<float>(per, 0)
for i = 0 to per - 1
array.set(sarr, i, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
nd(float x)=>
float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi)
out
// Boole's Rule
Boole(float StartPoint, float EndPoint, int n)=>
float[] X = array.new<float>(n + 1 , 0)
float[] Y = array.new<float>(n + 1 , 0)
float delta_x = (EndPoint - StartPoint) / n
for i = 0 to n
array.set(X, i, StartPoint + i * delta_x)
array.set(Y, i, nd(array.get(X, i)))
float sum = 0
for t = 0 to (n - 1) / 4
int ind = 4 * t
sum += (1 / 45.0) *
(14 * array.get(Y, ind)
+ 64 * array.get(Y, ind + 1)
+ 24 * array.get(Y, ind + 2)
+ 64 * array.get(Y, ind + 3)
+ 14 * array.get(Y, ind + 4))
* delta_x
sum
// N(0,1) cdf by Boole's Rule
cnd(float x)=>
float out = Boole(-10.0, x, 240)
out
// adaptation from Espen Gaarder Haug
// Sprenkle formula
convertingToCCRate(float r, float Compoundings)=>
float ConvertingToCCRate = 0
if Compoundings == 0
ConvertingToCCRate := r
else
ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings)
ConvertingToCCRate
Sprenkle(string callputflg, float S, float x, float T, float rho,float k, float v)=>
float d1 = 0
float d2 = 0
float Sprenkle = 0
d1 := (math.log(S / x) + (rho + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if callputflg == callString
Sprenkle := S * math.exp(rho * T) * cnd(d1) - (1 - k) * x * cnd(d2)
else
Sprenkle := (1 - k) * x * cnd(-d2) - S * math.exp(rho * T) * cnd(-d1)
Sprenkle
eSprenkle(string outputflg, string callputflg, float S, float x, float T, float rho, float k, float v, float dSin)=>
float dS = 0
if na(dSin)
dS := 0.01
float eSprenkle = 0
if outputflg == "p"
eSprenkle := Sprenkle(callputflg, S, x, T, rho, k, v)
else if outputflg == "d"
eSprenkle := (Sprenkle(callputflg, S + dS, x, T, rho, k, v)
- Sprenkle(callputflg, S - dS, x, T, rho, k, v)) / (2 * dS)
else if outputflg == "e"
eSprenkle := (Sprenkle(callputflg, S + dS, x, T, rho, k, v)
- Sprenkle(callputflg, S - dS, x, T, rho, k, v))
/ (2 * dS) * S / Sprenkle(callputflg, S, x, T, rho, k, v)
else if outputflg == "g"
eSprenkle := (Sprenkle(callputflg, S + dS, x, T, rho, k, v)
- 2 * Sprenkle(callputflg, S, x, T, rho, k, v)
+ Sprenkle(callputflg, S - dS, x, T, rho, k, v)) / math.pow(dS, 2)
else if outputflg == "gv"
eSprenkle := (Sprenkle(callputflg, S + dS, x, T, rho, k, v + 0.01)
- 2 * Sprenkle(callputflg, S, x, T, rho, k, v + 0.01)
+ Sprenkle(callputflg, S - dS, x, T, rho, k, v + 0.01)
- Sprenkle(callputflg, S + dS, x, T, rho, k, v - 0.01)
+ 2 * Sprenkle(callputflg, S, x, T, rho, k, v - 0.01)
- Sprenkle(callputflg, S - dS, x, T, rho, k, v - 0.01)) / (2 * 0.01 * math.pow(dS ,2)) / 100
else if outputflg == "gp"
eSprenkle := S / 100 * (Sprenkle(callputflg, S + dS, x, T, rho, k, v)
- 2 * Sprenkle(callputflg, S, x, T, rho, k, v)
+ Sprenkle(callputflg, S - dS, x, T, rho, k, v)) / math.pow(dS, 2)
else if outputflg == "tg"
eSprenkle := (Sprenkle(callputflg, S, x, T + 1 / 365, rho, k, v)
- 2 * Sprenkle(callputflg, S, x, T, rho, k, v)
+ Sprenkle(callputflg, S, x, T - 1 / 365, rho, k, v)) / math.pow(1 / 365, 2)
else if outputflg == "dddv"
eSprenkle := 1 / (4 * dS * 0.01) * (Sprenkle(callputflg, S + dS, x, T, rho, k, v + 0.01)
- Sprenkle(callputflg, S + dS, x, T, rho, k, v - 0.01)
- Sprenkle(callputflg, S - dS, x, T, rho, k, v + 0.01) + Sprenkle(callputflg, S - dS, x, T, rho, k, v - 0.01)) / 100
else if outputflg == "v"
eSprenkle := (Sprenkle(callputflg, S, x, T, rho, k, v + 0.01)
- Sprenkle(callputflg, S, x, T, rho, k, v - 0.01)) / 2
else if outputflg == "vv"
eSprenkle := (Sprenkle(callputflg, S, x, T, rho, k, v + 0.01)
- 2 * Sprenkle(callputflg, S, x, T, rho, k, v)
+ Sprenkle(callputflg, S, x, T, rho, k, v - 0.01)) / math.pow(0.01, 2) / 10000
else if outputflg == "vp"
eSprenkle := v / 0.1 * (Sprenkle(callputflg, S, x, T, rho, k, v + 0.01)
- Sprenkle(callputflg, S, x, T, rho, k, v - 0.01)) / 2
else if outputflg == "dvdv"
eSprenkle := (Sprenkle(callputflg, S, x, T, rho, k, v + 0.01)
- 2 * Sprenkle(callputflg, S, x, T, rho, k, v)
+ Sprenkle(callputflg, S, x, T, rho, k, v - 0.01))
else if outputflg == "t"
if T <= (1 / 365)
eSprenkle := Sprenkle(callputflg, S, x, 1E-05, rho, k, v) - Sprenkle(callputflg, S, x, T, rho, k, v)
else
eSprenkle := Sprenkle(callputflg, S, x, T - 1 / 365, rho, k, v) - Sprenkle(callputflg, S, x, T, rho, k, v)
else if outputflg == "r"
eSprenkle := (Sprenkle(callputflg, S, x, T, rho + 0.01, k, v)
- Sprenkle(callputflg, S, x, T, rho - 0.01, k, v)) / 2
else if outputflg == "k"
eSprenkle := (Sprenkle(callputflg, S, x, T, rho, k + 0.01, v)
- Sprenkle(callputflg, S, x, T, rho, k - 0.01, v)) / 2
else if outputflg == "s"
eSprenkle := 1 / math.pow(dS, 3) * (Sprenkle(callputflg, S + 2 * dS, x, T, rho, k, v)
- 3 * Sprenkle(callputflg, S + dS, x, T, rho, k, v)
+ 3 * Sprenkle(callputflg, S, x, T, rho, k, v)
- Sprenkle(callputflg, S - dS, x, T, rho, k, v))
else if outputflg == "dx"
eSprenkle := (Sprenkle(callputflg, S, x + dS, T, rho, k, v)
- Sprenkle(callputflg, S, x - dS, T, rho, k, v)) / (2 * dS)
else if outputflg == "dxdx" // Gamma
eSprenkle := (Sprenkle(callputflg, S, x + dS, T, rho, k, v)
- 2 * Sprenkle(callputflg, S, x, T, rho, k, v)
+ Sprenkle(callputflg, S, x - dS, T, rho, k, v)) / math.pow(dS, 2)
eSprenkle
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Spot Price Settings")
srcin = input.string("Close", "Spot Price", group= "Spot Price Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
float K = input.float(275, "Strike Price", group = "Basic Settings")
string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings")
string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings")
float rho = input.float(6., "% Average Growth Rate", group = "Rates Settings") / 100
string rhocmp = input.string(Continuous, "% Average Growth Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float kv = input.float(0., "% Market Risk Aversion Adjustment", group = "Rates Settings") / 100
string kvcmp = input.string(Continuous, "% Market Risk Aversion Adjustment Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float v = input.float(40., "% Volatility", group = "Rates Settings") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Historical Volatility Settings", tooltip = "Not used in calculation. This is here for comparison to implied volatility")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Historical Volatility Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
string txtsize = input.string("Auto", title = "Expiry Second", options = ["Small", "Normal", "Tiny", "Auto", "Large"], group = "UI Options")
string outsize = switch txtsize
"Small"=> size.small
"Normal"=> size.normal
"Tiny"=> size.tiny
"Auto"=> size.auto
"Large"=> size.large
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float rhocmpvalue = switch rhocmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float kvcmpvalue = switch kvcmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
sideout = side == "Long" ? 1 : -1
kouta = convertingToCCRate(rho, rhocmpvalue)
koutb = convertingToCCRate(kv, kvcmpvalue)
price = eSprenkle("p", OpType, spot, K, T, kouta, koutb, v, na)
Delta = eSprenkle("d", OpType, spot, K, T, kouta, koutb, v, na) * sideout
Elasticity = eSprenkle("e", OpType, spot, K, T, kouta, koutb, v, na) * sideout
Gamma = eSprenkle("g", OpType, spot, K, T, kouta, koutb, v, na) * sideout
DgammaDvol = eSprenkle("gv", OpType, spot, K, T, kouta, koutb, v, na) * sideout
GammaP = eSprenkle("gp", OpType, spot, K, T, kouta, koutb, v, na) * sideout
Vega = eSprenkle("v", OpType, spot, K, T, kouta, koutb, v, na) * sideout
DvegaDvol = eSprenkle("dvdv", OpType, spot, K, T, kouta, koutb, v, na) * sideout
VegaP = eSprenkle("vp", OpType, spot, K, T, kouta, koutb, v, na) * sideout
Theta = eSprenkle("t", OpType, spot, K, T, kouta, koutb, v, na) * sideout
RhoexpectedRoR = eSprenkle("r", OpType, spot, K, T, kouta, koutb, v, na) * sideout
RiskAversion = eSprenkle("k", OpType, spot, K, T, kouta, koutb, v, na) * sideout
DDeltaDvol = eSprenkle("dddv", OpType, spot, K, T, kouta, koutb, v, na) * sideout
Speed = eSprenkle("s", OpType, spot, K, T, kouta, koutb, v, na) * sideout
DeltaX = eSprenkle("dx", OpType, spot, K, T, kouta, koutb, v, na) * sideout
RiskNeutralDensity = eSprenkle("dxdx", OpType, spot, K, T, kouta, koutb, v, na) * sideout
var testTable = table.new(position = position.middle_right, columns = 1, rows = 32, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = "Sprenkle 1964 Option Pricing Model", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 1, text = "Option Type: " + OpType, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 2, text = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 3, text = "Spot Price: " + str.tostring(spot, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 4, text = "Strike Price: " + str.tostring(K, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 5, text = "% Average Growth Rate: " + str.tostring(rho * 100, "##.##") + "%\n" + "Compounding Type: " + rhocmp + "\nCC Rate: " + str.tostring(kouta * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 6, text = "% Market Risk Averaion Adjustment: " + str.tostring(kv * 100, "##.##") + "%\n" + "Compounding Type: " + kvcmp + "\nCC Carry: " + str.tostring(koutb * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 7, text = "% Volatility (annual): " + str.tostring(v * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 8, text = "Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 9, text = "Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 10, text = "Calculated Values", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 11, text = "Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 12, text = "Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 13, text = "Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 14, text = OpType + " Option Price", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 15, text = "Price: " + str.tostring(price, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 16, text = "Numerical Option Sensitivities", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 17, text = "Delta Δ: " + str.tostring(Delta, "##.#####"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 18, text = "Elasticity Λ: " + str.tostring(Elasticity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 19, text = "Gamma Γ: " + str.tostring(Gamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 20, text = "DGammaDvol: " + str.tostring(DgammaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 21, text = "GammaP Γ: " + str.tostring(GammaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 22, text = "Vega: " + str.tostring(Vega, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 23, text = "DVegaDvol: " + str.tostring(DvegaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 24, text = "VegaP: " + str.tostring(VegaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 25, text = "Theta Θ (1 day): " + str.tostring(Theta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 26, text = "DDeltaDvol: " + str.tostring(DDeltaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 27, text = "Rho Expected Rate of Return: " + str.tostring(RhoexpectedRoR, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 28, text = "Risk Aversion: " + str.tostring(RiskAversion, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 29, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 30, text = "Strike Delta: " + str.tostring(DeltaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 31, text = "Risk Neutral Density: " + str.tostring(RiskNeutralDensity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) |
Color Changing Moving Average | https://www.tradingview.com/script/MZCtIj1s-Color-Changing-Moving-Average/ | jessebadry | https://www.tradingview.com/u/jessebadry/ | 42 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jessebadry
//@version=5
indicator(title="Color Changing Moving Average", shorttitle="Colored MA", overlay=true)
//inputs
i_lookback = input.int(2, "Angle Period", minval = 1)
i_atrPeriod = input.int(10, "ATR Period", minval = 1)
i_angleLevel = input.int(6, "Angle Level", minval = 1)
len = input.int(21, minval=1, title="Length")
src = input.source(close, title="Source")
offset = input.int(title="Offset",defval=0, minval=-500, maxval=500)
type=input.bool(true, "Use EMA? (Off=SMA)")
//output
out=type? ta.ema(src, len) : ta.sma(src, len)
//color change
f_angle(_src, _lookback, _atrPeriod) =>
rad2degree = 180 / 3.141592653589793238462643 //pi
ang = rad2degree * math.atan((_src[0] - _src[_lookback]) / ta.atr(_atrPeriod)/_lookback)
ang
f_ma(type, _src, _len) =>
float result = 0
if type=="SMA" // Simple
result := ta.sma(_src, _len)
if type=="EMA" // Exponential
result := ta.ema(_src, _len)
result
_ma_type = type ? "EMA" : "SMA"
_ma = f_ma(_ma_type, src, len)
_angle = f_angle(_ma, i_lookback, i_atrPeriod)
color_H = _angle > 0 ? color.lime : _angle < 0 ? color.red : color.gray
//trend color change
colsh= _angle>0 ? #00ff00 : na
colsh2= _angle<0? #ff0000 : na
//no trend color change
colsh3= _angle==0 ? #9598a1 : na
colsh4= _angle==0 ? #9598a1 : na
//plots
//no rsi plot
// plot(rsifil? na : out, color=col, linewidth=3, offset=offset)
//BG line plot
// plot(_angle==0? out:na, color=#9598a1, linewidth=3, offset=offset)
// //trend line plot
plot(out, color=colsh, linewidth=3, offset=offset)
plot(out, color=colsh2, linewidth=3, offset=offset)
|
Standard Deviation Histogram (SDH) | https://www.tradingview.com/script/K55stqP2-Standard-Deviation-Histogram-SDH/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 49 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
// Only good for stocks as far as I have tested.
//@version=5
indicator("Standard Deviation Histogram", "SDH", false, precision = 2)
std_val(float src = close, int len = 200) => //{
z = (src - ta.sma(src, len))/ta.stdev(src, len)
src = input.source(close, "Source")
len = input.int(20, "Length")
smo = input.bool(false, "Smoothing", inline = "smooth")
sml = input.int(3, "", 2, inline = "smooth")
col_grow_below = input.color(#FFCDD2, "Low Color", inline = "low")
col_fall_below = input.color(#FF5252, "", inline = "low")
col_fall_above = input.color(#B2DFDB, "High Color", inline = "high")
col_grow_above = input.color(#26A69A, "", inline = "high")
dev = std_val(src, len)
hist = smo ? ta.sma(dev, sml) : dev
hist_col = hist >= 0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)
plot(hist, "Standard Deviation", hist_col, style = plot.style_columns)
|
ICT Index Schedule | https://www.tradingview.com/script/OFmA0F0k-ICT-Index-Schedule/ | toodegrees | https://www.tradingview.com/u/toodegrees/ | 577 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © toodegrees
//@version=5
indicator("ICT Index Schedule", overlay=true)
//––––. Functions
is_newbar(sess) =>
t = time("D", sess, "America/New_York")
na(t[1]) and not na(t) or t[1] < t
is_session(sess) =>
not na(time(timeframe.period, sess, "America/New_York"))
is_tf = not timeframe.isweekly and not timeframe.ismonthly
isMon() =>
dayofweek(time('1'), "America/New_York") == dayofweek.monday
isTue() =>
dayofweek(time('1'), "America/New_York") == dayofweek.tuesday
isWed() =>
dayofweek(time('1'), "America/New_York") == dayofweek.wednesday
isThu() =>
dayofweek(time('1'), "America/New_York") == dayofweek.thursday
isFri() =>
dayofweek(time('1'), "America/New_York") == dayofweek.friday
isSat() =>
dayofweek(time('1'), "America/New_York") == dayofweek.saturday
isSun() =>
dayofweek(time('1'), "America/New_York") == dayofweek.sunday
///////////////////
//––––. Settings //
///////////////////
////––. Key Levels / Times
showDays = input.bool(true, title="Show Days of The Week")
_kzMode = input.string("Line", title="Kill Zone Look", options=["Background", "Line"])
kzMode = _kzMode == "Background"
//Previous Day's Low / High
pdC = input.color(color.orange, inline='pd', title='', group='General')
showHL = input.bool(true, title="Previous Day Low/High", inline='pd', group='General')
nyHL = input.bool(false, title='NY Time?', inline='pd', group='General', tooltip='Use New York Time Daily Lows and Highs, from Midnight NY time instead of Daily Candle open time.')
//Midnight
mC = input.color(color.gray, title="", inline="mid", group='General')
midnightColor = color.new(mC, 75)
midnightON = input.bool(true, title='Midnight', inline="mid", group='General')
midnight = "0000-0001:1234567"
showMidPrice = input.bool(true, title='Open Price', inline="mid", group='General')
//Equities
eC = input.color(color.white, title="", inline="eq", group='General')
equitiesColor = color.new(eC, 85)
equitiesON = input.bool(true, title='Equities', inline='eq', group='General')
equities = "0930-0931:1234567"
////––. Sessions
//London
LC = input.color(color.purple, title="", inline="lonS", group='LONDON')
LondonColor = color.new(LC, 90)
londonON = input.bool(true, inline='lonS',title='Session', group='LONDON')
london = "0200-1100:1234567"
londonOpen = "0200-0201:1234567"
showLNOpenPrice = input.bool(true, title='Open', inline='lonS', group='LONDON')
londonKZON = input.bool(true,title='KZ',inline="lonS", group='LONDON')
londonKZ = "0200-0500:1234567"
//New York
NYC = input.color(color.green, title="", inline='nyS', group='NEW YORK')
NYColor = color.new(NYC, 90)
nyON = input.bool(true, inline='nyS',title="Session", group='NEW YORK')
ny = "0800-1700:1234567"
_ny = "0830-1700:1234567"
NYColorOpen = color.new(NYC, 70)
nyOpen = "0830-0831:1234567"
showNYOpenPrice = input.bool(true, title='Algo Open', inline='nyS', group='NEW YORK')
nyAMKZON = input.bool(true, inline='nyS',title='AM KZ', group='NEW YORK')
nyAMKZ = "0830-1100:1234567"
nyPMKZON = input.bool(true, inline='nyS',title='PM KZ', group='NEW YORK')
nyPMKZ = "1330-1600:1234567"
//Resetter
reset = "1700-0000:1234567"
////////////////
//––––. Logic //
////////////////
////––. isTime?
isReset = not is_session(reset)
//Midnight
isMidnight = is_newbar(midnight) and is_tf
bgcolor(isMidnight and midnightON ? midnightColor : na,
title="Midnight Line",
editable=false)
//Equisties
isEquities = is_newbar(equities) and is_tf
bgcolor(isEquities and equitiesON ? equitiesColor : na,
title="Equities Open Line",
editable=false)
//London
isLondon = is_session(london)and is_tf
bgcolor(isLondon and londonON ? LondonColor : na,
title="London Session",
editable=false)
isLondonOpen = is_session(londonOpen)
isLondonKZ = is_session(londonKZ) and is_tf
bgcolor((kzMode and isLondonKZ and londonKZON) ? LondonColor : na,
title="London Kill Zone",
editable=false)
plotshape((not kzMode) and isLondonKZ and londonKZON,
color=LC,
style=shape.square,
location=location.bottom,
size=size.auto,
title="London Kill Zone",
editable=false)
//New York
isNewYork = is_session(ny)and is_tf
bgcolor(isNewYork and nyON ? NYColor : na,
title="New York Session",
editable=false)
_isNewYork = is_session(_ny)and is_tf //used to display algo open
isNewYorkOpen = is_session(nyOpen)
isNewYorkAM = is_session(nyAMKZ) and is_tf
bgcolor((kzMode and isNewYorkAM and nyAMKZON) ? NYColor : na,
title="New York AM Kill Zone",
editable=false)
plotshape((not kzMode) and isNewYorkAM and nyAMKZON,
color=NYC,
style=shape.square,
location=location.bottom,
size=size.auto,
title="New York AM Kill Zone",
editable=false)
isNewYorkPM = is_session(nyPMKZ) and is_tf
bgcolor((kzMode and isNewYorkPM and nyPMKZON) ? NYColor : na,
title="New York PM Kill Zone",
editable=false)
plotshape((not kzMode) and isNewYorkPM and nyPMKZON,
color=NYC,
style=shape.square,
location=location.bottom,
size=size.auto,
title="New York PM Kill Zone",
editable=false)
////––. Days of the Week
textColor = color.new(color.black, 30)
plotchar(isMidnight and isMon() and is_tf and showDays,
'Mon', 'M', location.bottom,
textColor,
size=size.tiny,
offset=0,
editable=false)
plotchar(isMidnight and isTue() and is_tf and showDays,
'Tue', 'T', location.bottom,
textColor,
size=size.tiny,
offset=0,
editable=false)
plotchar(isMidnight and isWed() and is_tf and showDays,
'Wed', 'W', location.bottom,
textColor,
size=size.tiny,
offset=0,
editable=false)
plotchar(isMidnight and isThu() and is_tf and showDays,
'Thu', 'T', location.bottom,
textColor,
size=size.tiny,
offset=0,
editable=false)
plotchar(isMidnight and isFri() and is_tf and showDays,
'Fri', 'F', location.bottom,
textColor,
size=size.tiny,
offset=0,
editable=false)
plotchar(isMidnight and isSat() and is_tf and showDays,
'Sat', 'S', location.bottom,
textColor,
size=size.tiny,
offset=0,
editable=false)
plotchar(isMidnight and isSun() and is_tf and showDays,
'Sun', 'S', location.bottom,
textColor,
size=size.tiny,
offset=0,
editable=false)
////––. Price Levels
var float prevDayLow = na
var float prevDayHigh = na
var float _nyLow = na
var float _nyHigh = na
_nyLow := isMidnight[1] ? low : (low < _nyLow ? low : _nyLow)
_nyHigh := isMidnight[1] ? high : (high > _nyHigh ? high : _nyHigh)
prevDayLow := isMidnight ? (nyHL ? _nyLow : request.security(syminfo.tickerid, "1D", low)) : prevDayLow
prevDayHigh := isMidnight ? (nyHL ? _nyHigh : request.security(syminfo.tickerid, "1D", high)) : prevDayHigh
plot(showHL and isReset ? prevDayLow : na,
color=pdC,
linewidth=1,
title='PDL',
style=plot.style_linebr)
plot(showHL and isReset ? prevDayHigh : na,
color=pdC,
linewidth=1,
title='PDH',
style=plot.style_linebr)
var float midnightPrice = na
midnightPrice := isMidnight ? open : midnightPrice
plot(showMidPrice and isReset ? midnightPrice : na,
color=mC,
linewidth=1,
title='Midnight Price',
style=plot.style_linebr)
var float openLNPrice = na
openLNPrice := isLondonOpen ? open : openLNPrice
plot(showLNOpenPrice and isLondon ? openLNPrice : na,
color=LC,
linewidth=1,
title='London Open Price',
style=plot.style_linebr)
var float openNYPrice = na //This will not show on all timeframes
openNYPrice := isNewYorkOpen ? open : openNYPrice
plot(showNYOpenPrice and _isNewYork ? openNYPrice : na,
color=NYC,
linewidth=1,
title='New York Open Price',
style=plot.style_linebr) |
Black-76 Options on Futures [Loxx] | https://www.tradingview.com/script/VpsGfVA5-Black-76-Options-on-Futures-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 22 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Black-76 Options on Futures [Loxx]",
shorttitle ="B76OF [Loxx]",
overlay = true,
max_lines_count = 500, precision = 4)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
import loxx/loxxexpandedsourcetypes/4
import loxx/cnd/1
color darkGreenColor = #1B7E02
string callString = "Call"
string putString = "Put"
string Continuous = "Continuous"
string PeriodRate = "Period Rate"
string Annual = "Annual"
string SemiAnnual = "Semi-Annual"
string Quaterly = "Quaterly"
string Monthly = "Monthly"
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
array<float> sarr = array.new<float>(per, 0)
for i = 0 to per - 1
array.set(sarr, i, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
nd(float x)=>
float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi)
out
convertingToCCRate(float r, float Compoundings)=>
float ConvertingToCCRate = 0
if Compoundings == 0
ConvertingToCCRate := r
else
ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings)
ConvertingToCCRate
// DDeltaDvol also known as vanna
GDdeltaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GDdeltaDvol = 0
d1 := (math.log(S / x) + (b + v * v / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDdeltaDvol := -math.exp((b - r) * T) * d2 / v * nd(d1)
GDdeltaDvol
GBlackScholes(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float gBlackScholes = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if CallPutFlag == callString
gBlackScholes := S * math.exp((b - r) * T) * cnd.CND1(d1) - x * math.exp(-r * T) * cnd.CND1(d2)
else
gBlackScholes := x * math.exp(-r * T) * cnd.CND1(-d2) - S * math.exp((b - r) * T) * cnd.CND1(-d1)
gBlackScholes
// Gamma for the generalized Black and Scholes formula
GGamma(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GGamma = math.exp((b - r) * T) * nd(d1) / (S * v * math.sqrt(T))
GGamma
// GammaP for the generalized Black and Scholes formula
GGammaP(float S, float x, float T, float r, float b, float v)=>
GGammaP = S * GGamma(S, x, T, r, b, v) / 100
GGammaP
// Delta for the generalized Black and Scholes formula
GDelta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GDelta = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GDelta := math.exp((b - r) * T) * cnd.CND1(d1)
else
GDelta := -math.exp((b - r) * T) * cnd.CND1(-d1)
GDelta
// StrikeDelta for the generalized Black and Scholes formula
GStrikeDelta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d2 = 0
float GStrikeDelta = 0
d2 := (math.log(S / x) + (b - math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GStrikeDelta := -math.exp(-r * T) * cnd.CND1(d2)
else
GStrikeDelta := math.exp(-r * T) * cnd.CND1(-d2)
GStrikeDelta
// Elasticity for the generalized Black and Scholes formula
GElasticity(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
GElasticity = GDelta(CallPutFlag, S, x, T, r, b, v) * S / GBlackScholes(CallPutFlag, S, x, T, r, b, v)
GElasticity
// Risk Neutral Denisty for the generalized Black and Scholes formula
GRiskNeutralDensity(float S, float x, float T, float r, float b, float v)=>
float d2 = 0
d2 := (math.log(S / x) + (b - math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GRiskNeutralDensity = math.exp(-r * T) * nd(d2) / (x * v * math.sqrt(T))
GRiskNeutralDensity
// Theta for the generalized Black and Scholes formula
GTheta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GTheta = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if CallPutFlag == callString
GTheta := -S * math.exp((b - r) * T) * nd(d1) * v / (2 * math.sqrt(T)) - (b - r) * S * math.exp((b - r) * T) * cnd.CND1(d1) - r * x * math.exp(-r * T) * cnd.CND1(d2)
else
GTheta := -S * math.exp((b - r) * T) * nd(d1) * v / (2 * math.sqrt(T)) + (b - r) * S * math.exp((b - r) * T) * cnd.CND1(-d1) + r * x * math.exp(-r * T) * cnd.CND1(-d2)
GTheta
// Vega for the generalized Black and Scholes formula
GVega(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GVega = S * math.exp((b - r) * T) * nd(d1) * math.sqrt(T)
GVega
// VegaP for the generalized Black and Scholes formula
GVegaP(float S, float x, float T, float r, float b, float v)=>
GVegaP = v / 10 * GVega(S, x, T, r, b, v)
GVegaP
// DvegaDvol/Vomma for the generalized Black and Scholes formula
GDvegaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDvegaDvol = GVega(S, x, T, r, b, v) * d1 * d2 / v
GDvegaDvol
// Rho for the generalized Black and Scholes formula for all options except futures
GRho(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = (math.log(S / x) + (b + v *v / 2) * T) / (v * math.sqrt(T))
float d2 = d1 - v * math.sqrt(T)
float GRho = 0
if CallPutFlag == callString
GRho := T * x * math.exp(-r * T) * cnd.CND1(d2)
else
GRho := -T * x * math.exp(-r * T) * cnd.CND1(-d2)
GRho
// Rho for the generalized Black and Scholes formula for Futures option
GRhoFO(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
GRhoFO = -T * GBlackScholes(CallPutFlag, S, x, T, r, 0, v)
GRhoFO
// Rho2/Phi for the generalized Black and Scholes formula
GPhi(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GPhi = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GPhi := -T * S * math.exp((b - r) * T) * cnd.CND1(d1)
else
GPhi := T * S * math.exp((b - r) * T) * cnd.CND1(-d1)
GPhi
// Carry rf sensitivity for the generalized Black and Scholes formula
GCarry(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GCarry = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GCarry := T * S * math.exp((b - r) * T) * cnd.CND1(d1)
else
GCarry := -T * S * math.exp((b - r) * T) * cnd.CND1(-d1)
GCarry
// DgammaDspot/Speed for the generalized Black and Scholes formula
GDgammaDspot(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GDgammaDspot = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GDgammaDspot := -GGamma(S, x, T, r, b, v) * (1 + d1 / (v * math.sqrt(T))) / S
GDgammaDspot
// DgammaDvol/Zomma for the generalized Black and Scholes formula
GDgammaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GDgammaDvol = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDgammaDvol := GGamma(S, x, T, r, b, v) * ((d1 * d2 - 1) / v)
GDgammaDvol
CGBlackScholes(string OutPutFlag, string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float output = 0
float CGBlackScholes = 0
if OutPutFlag == "p" // Value
CGBlackScholes := GBlackScholes(CallPutFlag, S, x, T, r, b, v)
//DELTA GREEKS
else if OutPutFlag == "d" // Delta
CGBlackScholes := GDelta(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "dddv" // DDeltaDvol
CGBlackScholes := GDdeltaDvol(S, x, T, r, b, v) / 100
else if OutPutFlag == "e" // Elasticity
CGBlackScholes := GElasticity(CallPutFlag, S, x, T, r, b, v)
//GAMMA GREEKS
else if OutPutFlag == "g" // Gamma
CGBlackScholes := GGamma(S, x, T, r, b, v)
else if OutPutFlag == "gp" // GammaP
CGBlackScholes := GGammaP(S, x, T, r, b, v)
else if OutPutFlag == "s" // 'DgammaDspot/speed
CGBlackScholes := GDgammaDspot(S, x, T, r, b, v)
else if OutPutFlag == "gv" // 'DgammaDvol/Zomma
CGBlackScholes := GDgammaDvol(S, x, T, r, b, v) / 100
//VEGA GREEKS
else if OutPutFlag == "v" // Vega
CGBlackScholes := GVega(S, x, T, r, b, v) / 100
else if OutPutFlag == "dvdv" // DvegaDvol/Vomma
CGBlackScholes := GDvegaDvol(S, x, T, r, b, v) / 10000
else if OutPutFlag == "vp" // VegaP
CGBlackScholes := GVegaP(S, x, T, r, b, v)
//THETA GREEKS
else if OutPutFlag == "t" // Theta
CGBlackScholes := GTheta(CallPutFlag, S, x, T, r, b, v) / 365
//RATE/CARRY GREEKS
else if OutPutFlag == "r" // Rho
CGBlackScholes := GRho(CallPutFlag, S, x, T, r, b, v) / 100
else if OutPutFlag == "f" // Phi/Rho2
CGBlackScholes := GPhi(CallPutFlag, S, x, T, r, b, v) / 100
else if OutPutFlag == "fr" // Rho futures option
CGBlackScholes := GRhoFO(CallPutFlag, S, x, T, r, b, v) / 100
//'PROB GREEKS
else if OutPutFlag == "dx" // 'StrikeDelta
CGBlackScholes := GStrikeDelta(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "dxdx" // 'Risk Neutral Density
CGBlackScholes := GRiskNeutralDensity(S, x, T, r, b, v)
CGBlackScholes
gBlackScholesImpVolBisection(string CallPutFlag, float S, float x, float T, float r, float b, float cm)=>
float vLow = 0
float vHigh= 0
float vi = 0
float cLow = 0
float cHigh = 0
float epsilon = 0
int counter = 0
float gBlackScholesImpVolBisection = 0
vLow := 0.005
vHigh := 4
epsilon := 1E-08
cLow := GBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := GBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
while math.abs(cm - GBlackScholes(CallPutFlag, S, x, T, r, b, vi)) > epsilon
counter += 1
if counter == 100
gBlackScholesImpVolBisection := 0
break
if GBlackScholes(CallPutFlag, S, x, T, r, b, vi) < cm
vLow := vi
else
vHigh := vi
cLow := GBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := GBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
gBlackScholesImpVolBisection := vi
gBlackScholesImpVolBisection
gVega(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GVega = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GVega := S * math.exp((b - r) * T) * nd(d1) * math.sqrt(T)
GVega
gImpliedVolatilityNR(string CallPutFlag, float S, float x, float T, float r, float b, float cm, float epsilon)=>
float vi = 0
float ci = 0
float vegai = 0
float minDiff = 0
float GImpliedVolatilityNR = 0
vi := math.sqrt(math.abs(math.log(S / x) + r * T) * 2 / T)
ci := GBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
while math.abs(cm - ci) >= epsilon and math.abs(cm - ci) <= minDiff
vi := vi - (ci - cm) / vegai
ci := GBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
if math.abs(cm - ci) < epsilon
GImpliedVolatilityNR := vi
else
GImpliedVolatilityNR := 0
GImpliedVolatilityNR
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Spot Price Settings")
srcin = input.string("Close", "Spot Price", group= "Spot Price Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
float K = input.float(275, "Strike Price", group = "Basic Settings")
string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings")
string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings")
float rf = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100
string rhocmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float v = input.float(40., "% Volatility", group = "Rates Settings") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Historical Volatility Settings", tooltip = "Not used in calculation. This is here for comparison to implied volatility")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Historical Volatility Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
string txtsize = input.string("Auto", title = "Expiry Second", options = ["Small", "Normal", "Tiny", "Auto", "Large"], group = "UI Options")
string outsize = switch txtsize
"Small"=> size.small
"Normal"=> size.normal
"Tiny"=> size.tiny
"Auto"=> size.auto
"Large"=> size.large
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float rhocmpvalue = switch rhocmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
sideout = side == "Long" ? 1 : -1
kouta = convertingToCCRate(rf, rhocmpvalue)
price = CGBlackScholes("p", OpType, spot, K, T, kouta, 0, v)
Delta = CGBlackScholes("d", OpType, spot, K, T, kouta, 0, v) * sideout
Elasticity = CGBlackScholes("e", OpType, spot, K, T, kouta, 0, v) * sideout
Gamma = CGBlackScholes("g", OpType, spot, K, T, kouta, 0, v) * sideout
DgammaDvol = CGBlackScholes("gv", OpType, spot, K, T, kouta, 0, v) * sideout
GammaP = CGBlackScholes("gp", OpType, spot, K, T, kouta, 0, v) * sideout
Vega = CGBlackScholes("v", OpType, spot, K, T, kouta, 0, v) * sideout
DvegaDvol = CGBlackScholes("dvdv", OpType, spot, K, T, kouta, 0, v) * sideout
VegaP = CGBlackScholes("vp", OpType, spot, K, T, kouta, 0, v) * sideout
Theta = CGBlackScholes("t", OpType, spot, K, T, kouta, 0, v) * sideout
RhoFutures = CGBlackScholes("fr", OpType, spot, K, T, kouta, 0, v) * sideout
DDeltaDvol = CGBlackScholes("dddv", OpType, spot, K, T, kouta, 0, v) * sideout
Speed = CGBlackScholes("s", OpType, spot, K, T, kouta, 0, v) * sideout
DeltaX = CGBlackScholes("dx", OpType, spot, K, T, kouta, 0, v) * sideout
RiskNeutralDensity = CGBlackScholes("dxdx", OpType, spot, K, T, kouta, 0, v) * sideout
impvolbi = gBlackScholesImpVolBisection(OpType, spot, K, T, kouta, 0, price)
impvolnewt = gImpliedVolatilityNR(OpType, spot, K, T, kouta, 0, price, 0.00001)
var testTable = table.new(position = position.middle_right, columns = 2, rows = 17, bgcolor = color.gray, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = "Black-76 Options on Futures", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 1, text = "Option Type: " + OpType, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 2, text = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 3, text = "Spot Price: " + str.tostring(spot, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 4, text = "Strike Price: " + str.tostring(K, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 5, text = "% Risk-free Rate: " + str.tostring(rf * 100, "##.##") + "%\n" + "Compounding Type: " + rhocmp + "\nCC Rate: " + str.tostring(kouta * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 6, text = "% Volatility (annual): " + str.tostring(v * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 7, text = "Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 8, text = "Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 9, text = "Calculated Values", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 10, text = "Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 11, text = "Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 12, text = "Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 13, text = "Implied Volatility Calculation", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 14, text = "Implied Volatility Bisection: " + str.tostring(impvolbi * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 15, text = "Implied Volatility Newton Raphson: " + str.tostring(impvolnewt * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 0, text = "Option Ouputs", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 1, text = "Price: " + str.tostring(price, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 2, text = "Analytical Greeks", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 3, text = "Delta Δ: " + str.tostring(Delta, "##.#####"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 4, text = "Elasticity Λ: " + str.tostring(Elasticity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 5, text = "Gamma Γ: " + str.tostring(Gamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 6, text = "DGammaDvol: " + str.tostring(DgammaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 7, text = "GammaP Γ: " + str.tostring(GammaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 8, text = "Vega: " + str.tostring(Vega, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 9, text = "DVegaDvol: " + str.tostring(DvegaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 10, text = "VegaP: " + str.tostring(VegaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 11, text = "Theta Θ (1 day): " + str.tostring(Theta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 12, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFutures, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 13, text = "DDeltaDvol: " + str.tostring(DDeltaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 14, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 15, text = "Strike Delta: " + str.tostring(DeltaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 1, row = 16, text = "Risk Neutral Density: " + str.tostring(RiskNeutralDensity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
|
Generalized Black-Scholes-Merton Option Pricing Formula [Loxx] | https://www.tradingview.com/script/mKNkV192-Generalized-Black-Scholes-Merton-Option-Pricing-Formula-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Generalized Black-Scholes-Merton Option Pricing Formula [Loxx]",
shorttitle ="GBSMOPF [Loxx]",
overlay = true,
max_lines_count = 500, precision = 4)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
import loxx/loxxexpandedsourcetypes/4
color darkGreenColor = #1B7E02
string callString = "Call"
string putString = "Put"
string Continuous = "Continuous"
string PeriodRate = "Period Rate"
string Annual = "Annual"
string SemiAnnual = "Semi-Annual"
string Quaterly = "Quaterly"
string Monthly = "Monthly"
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
array<float> sarr = array.new<float>(per, 0)
for i = 0 to per - 1
array.set(sarr, i, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
nd(float x)=>
float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi)
out
// Boole's Rule
Boole(float StartPoint, float EndPoint, int n)=>
float[] X = array.new<float>(n + 1 , 0)
float[] Y = array.new<float>(n + 1 , 0)
float delta_x = (EndPoint - StartPoint) / n
for i = 0 to n
array.set(X, i, StartPoint + i * delta_x)
array.set(Y, i, nd(array.get(X, i)))
float sum = 0
for t = 0 to (n - 1) / 4
int ind = 4 * t
sum += (1 / 45.0) *
(14 * array.get(Y, ind)
+ 64 * array.get(Y, ind + 1)
+ 24 * array.get(Y, ind + 2)
+ 64 * array.get(Y, ind + 3)
+ 14 * array.get(Y, ind + 4))
* delta_x
sum
// N(0,1) cdf by Boole's Rule
cnd(float x)=>
float out = Boole(-10.0, x, 240)
out
convertingToCCRate(float r, float Compoundings)=>
float ConvertingToCCRate = 0
if Compoundings == 0
ConvertingToCCRate := r
else
ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings)
ConvertingToCCRate
gBlackScholes(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float gBlackScholes = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if CallPutFlag == callString
gBlackScholes := S * math.exp((b - r) * T) * cnd(d1) - x * math.exp(-r * T) * cnd(d2)
else
gBlackScholes := x * math.exp(-r * T) * cnd(-d2) - S * math.exp((b - r) * T) * cnd(-d1)
gBlackScholes
gBlackScholesNGreeks(string OutPutFlag, string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float dS = 0.01
float gBlackScholesNGreeks = 0
if OutPutFlag == "p" //' Value
gBlackScholesNGreeks := gBlackScholes(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "d" // 'Delta
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v)
- gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v)) / (2 * dS)
else if OutPutFlag == "dP" // 'Delta
dS := 0.25
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S * (1 + dS), x, T, r, b, v)
- gBlackScholes(CallPutFlag, S * (1 - dS), x, T, r, b, v)) * 2 / S
else if OutPutFlag == "e" // 'Elasticity
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v)
- gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v)) / (2 * dS) * S
/ gBlackScholes(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "g" // 'Gamma
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v)
- 2 * gBlackScholes(CallPutFlag, S, x, T, r, b, v)
+ gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v)) / math.pow(dS, 2)
else if OutPutFlag == "gv" // 'DGammaDVol
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v + 0.01)
- 2 * gBlackScholes(CallPutFlag, S, x, T, r, b, v + 0.01)
+ gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v + 0.01)
- gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v - 0.01)
+ 2 * gBlackScholes(CallPutFlag, S, x, T, r, b, v - 0.01)
- gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v - 0.01))
/ (2 * 0.01 * math.pow(dS, 2)) / 100
else if OutPutFlag == "gp" // 'GammaP
gBlackScholesNGreeks := S / 100 * (gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v)
- 2 * gBlackScholes(CallPutFlag, S, x, T, r, b, v)
+ gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v)) / math.pow(dS, 2)
else if OutPutFlag == "dddv" // 'DDeltaDvol
gBlackScholesNGreeks := 1 / (4 * dS * 0.01) * (gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v + 0.01)
- gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v - 0.01)
- gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v + 0.01)
+ gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v - 0.01)) / 100
else if OutPutFlag == "v" // 'Vega
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x, T, r, b, v + 0.01)
- gBlackScholes(CallPutFlag, S, x, T, r, b, v - 0.01)) / 2
else if OutPutFlag == "vp" // 'VegaP
gBlackScholesNGreeks := v / 0.1 * (gBlackScholes(CallPutFlag, S, x, T, r, b, v + 0.01)
- gBlackScholes(CallPutFlag, S, x, T, r, b, v - 0.01)) / 2
else if OutPutFlag == "dvdv" // 'DvegaDvol
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x, T, r, b, v + 0.01)
- 2 * gBlackScholes(CallPutFlag, S, x, T, r, b, v)
+ gBlackScholes(CallPutFlag, S, x, T, r, b, v - 0.01))
else if OutPutFlag == "t" // 'Theta
if T <= (1 / 365)
gBlackScholesNGreeks := gBlackScholes(CallPutFlag, S, x, 1E-05, r, b, v)
- gBlackScholes(CallPutFlag, S, x, T, r, b, v)
else
gBlackScholesNGreeks := gBlackScholes(CallPutFlag, S, x, T - 1 / 365, r, b, v)
- gBlackScholes(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "r" // 'Rho
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x, T, r + 0.01, b + 0.01, v)
- gBlackScholes(CallPutFlag, S, x, T, r - 0.01, b - 0.01, v)) / 2
else if OutPutFlag == "fr" // 'Futures options rf
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x, T, r + 0.01, 0, v)
- gBlackScholes(CallPutFlag, S, x, T, r - 0.01, 0, v)) / 2
else if OutPutFlag == "f" // 'Rho2
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x, T, r, b - 0.01, v)
- gBlackScholes(CallPutFlag, S, x, T, r, b + 0.01, v)) / 2
else if OutPutFlag == "b" // 'Carry
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x, T, r, b + 0.01, v)
- gBlackScholes(CallPutFlag, S, x, T, r, b - 0.01, v)) / 2
else if OutPutFlag == "s" // 'Speed
gBlackScholesNGreeks := 1 / math.pow(dS, 3) * (gBlackScholes(CallPutFlag, S
+ 2 * dS, x, T, r, b, v) - 3 * gBlackScholes(CallPutFlag, S + dS, x, T, r, b, v)
+ 3 * gBlackScholes(CallPutFlag, S, x, T, r, b, v)
- gBlackScholes(CallPutFlag, S - dS, x, T, r, b, v))
else if OutPutFlag == "dx" // 'Strike Delta
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x + dS, T, r, b, v)
- gBlackScholes(CallPutFlag, S, x - dS, T, r, b, v)) / (2 * dS)
else if OutPutFlag == "dxdx" // 'Gamma
gBlackScholesNGreeks := (gBlackScholes(CallPutFlag, S, x + dS, T, r, b, v)
- 2 * gBlackScholes(CallPutFlag, S, x, T, r, b, v)
+ gBlackScholes(CallPutFlag, S, x - dS, T, r, b, v)) / math.pow(dS, 2)
gBlackScholesNGreeks
gBlackScholesImpVolBisection(string CallPutFlag, float S, float x, float T, float r, float b, float cm)=>
float vLow = 0
float vHigh= 0
float vi = 0
float cLow = 0
float cHigh = 0
float epsilon = 0
int counter = 0
float gBlackScholesImpVolBisection = 0
vLow := 0.005
vHigh := 4
epsilon := 1E-08
cLow := gBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := gBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
while math.abs(cm - gBlackScholes(CallPutFlag, S, x, T, r, b, vi)) > epsilon
counter += 1
if counter == 100
gBlackScholesImpVolBisection := 0
break
if gBlackScholes(CallPutFlag, S, x, T, r, b, vi) < cm
vLow := vi
else
vHigh := vi
cLow := gBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := gBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
gBlackScholesImpVolBisection := vi
gBlackScholesImpVolBisection
gVega(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GVega = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GVega := S * math.exp((b - r) * T) * nd(d1) * math.sqrt(T)
GVega
gImpliedVolatilityNR(string CallPutFlag, float S, float x, float T, float r, float b, float cm, float epsilon)=>
float vi = 0
float ci = 0
float vegai = 0
float minDiff = 0
float GImpliedVolatilityNR = 0
vi := math.sqrt(math.abs(math.log(S / x) + r * T) * 2 / T)
ci := gBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
while math.abs(cm - ci) >= epsilon and math.abs(cm - ci) <= minDiff
vi := vi - (ci - cm) / vegai
ci := gBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
if math.abs(cm - ci) < epsilon
GImpliedVolatilityNR := vi
else
GImpliedVolatilityNR := 0
GImpliedVolatilityNR
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Spot Price Settings")
srcin = input.string("Close", "Spot Price", group= "Spot Price Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
float K = input.float(275, "Strike Price", group = "Basic Settings")
string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings")
string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings")
float rf = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100
string rhocmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float kv = input.float(0., "% Cost of Carry", group = "Rates Settings") / 100
string kvcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float v = input.float(40., "% Volatility", group = "Rates Settings") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Historical Volatility Settings", tooltip = "Not used in calculation. This is here for comparison to implied volatility")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Historical Volatility Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
string txtsize = input.string("Auto", title = "Expiry Second", options = ["Small", "Normal", "Tiny", "Auto", "Large"], group = "UI Options")
string outsize = switch txtsize
"Small"=> size.small
"Normal"=> size.normal
"Tiny"=> size.tiny
"Auto"=> size.auto
"Large"=> size.large
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float rhocmpvalue = switch rhocmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float kvcmpvalue = switch kvcmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
sideout = side == "Long" ? 1 : -1
kouta = convertingToCCRate(rf, rhocmpvalue)
koutb = convertingToCCRate(kv, kvcmpvalue)
price = gBlackScholesNGreeks("p", OpType, spot, K, T, kouta, koutb, v)
Delta = gBlackScholesNGreeks("d", OpType, spot, K, T, kouta, koutb, v) * sideout
Elasticity = gBlackScholesNGreeks("e", OpType, spot, K, T, kouta, koutb, v) * sideout
Gamma = gBlackScholesNGreeks("g", OpType, spot, K, T, kouta, koutb, v) * sideout
DgammaDvol = gBlackScholesNGreeks("gv", OpType, spot, K, T, kouta, koutb, v) * sideout
GammaP = gBlackScholesNGreeks("gp", OpType, spot, K, T, kouta, koutb, v) * sideout
Vega = gBlackScholesNGreeks("v", OpType, spot, K, T, kouta, koutb, v) * sideout
DvegaDvol = gBlackScholesNGreeks("dvdv", OpType, spot, K, T, kouta, koutb, v) * sideout
VegaP = gBlackScholesNGreeks("vp", OpType, spot, K, T, kouta, koutb, v) * sideout
Theta = gBlackScholesNGreeks("t", OpType, spot, K, T, kouta, koutb, v) * sideout
Rho = gBlackScholesNGreeks("r", OpType, spot, K, T, kouta, koutb, v) * sideout
RhoFuturesOption = gBlackScholesNGreeks("fr", OpType, spot, K, T, kouta, koutb, v) * sideout
PhiRho = gBlackScholesNGreeks("f", OpType, spot, K, T, kouta, koutb, v) * sideout
Carry = gBlackScholesNGreeks("b", OpType, spot, K, T, kouta, koutb, v) * sideout
DDeltaDvol = gBlackScholesNGreeks("dddv", OpType, spot, K, T, kouta, koutb, v) * sideout
Speed = gBlackScholesNGreeks("s", OpType, spot, K, T, kouta, koutb, v) * sideout
DeltaX = gBlackScholesNGreeks("dx", OpType, spot, K, T, kouta, koutb, v) * sideout
RiskNeutralDensity = gBlackScholesNGreeks("dxdx", OpType, spot, K, T, kouta, koutb, v) * sideout
impvolbi = gBlackScholesImpVolBisection(OpType, spot, K, T, kouta, koutb, price)
impvolnewt = gImpliedVolatilityNR(OpType, spot, K, T, kouta, koutb, price, 0.00001)
var testTable = table.new(position = position.middle_right, columns = 1, rows = 38, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = "Generalized Black-Scholes-Merton Option Pricing Model", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 1, text = "Option Type: " + OpType, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 2, text = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 3, text = "Spot Price: " + str.tostring(spot, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 4, text = "Strike Price: " + str.tostring(K, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 5, text = "% Risk-free Rate: " + str.tostring(rf * 100, "##.##") + "%\n" + "Compounding Type: " + rhocmp + "\nCC Rate: " + str.tostring(kouta * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 6, text = "% Cost of Carry: " + str.tostring(kv * 100, "##.##") + "%\n" + "Compounding Type: " + kvcmp + "\nCC Carry: " + str.tostring(koutb * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 7, text = "% Volatility (annual): " + str.tostring(v * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 8, text = "Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 9, text = "Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 10, text = "Calculated Values", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 11, text = "Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 12, text = "Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 13, text = "Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 14, text = OpType + " Option Price", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 15, text = "Forward Price: " + str.tostring(spot * math.exp(koutb * T), format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 16, text = "Price: " + str.tostring(price, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 17, text = "Numerical Option Sensitivities", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 18, text = "Delta Δ: " + str.tostring(Delta, "##.#####"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 19, text = "Elasticity Λ: " + str.tostring(Elasticity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 20, text = "Gamma Γ: " + str.tostring(Gamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 21, text = "DGammaDvol: " + str.tostring(DgammaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 22, text = "GammaP Γ: " + str.tostring(GammaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 23, text = "Vega: " + str.tostring(Vega, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 24, text = "DVegaDvol: " + str.tostring(DvegaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 25, text = "VegaP: " + str.tostring(VegaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 26, text = "Theta Θ (1 day): " + str.tostring(Theta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 27, text = "Rho ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 28, text = "Rho Futures Option ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 29, text = "Phi/Rho2: " + str.tostring(PhiRho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 30, text = "Carry: " + str.tostring(Carry, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 31, text = "DDeltaDvol: " + str.tostring(DDeltaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 32, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 33, text = "Strike Delta: " + str.tostring(DeltaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 34, text = "Risk Neutral Density: " + str.tostring(RiskNeutralDensity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 35, text = "Implied Volatility Calculation", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 36, text = "Implied Volatility Bisection: " + str.tostring(impvolbi * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 37, text = "Implied Volatility Newton Raphson: " + str.tostring(impvolnewt * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
|
Hull Butterfly Oscillator [LuxAlgo] | https://www.tradingview.com/script/xtuVIaa8-Hull-Butterfly-Oscillator-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 4,219 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Hull Butterfly Oscillator [LuxAlgo]", "Hull Butterfly Oscillator [LuxAlgo]")
//-----------------------------------------------------------------------------}
//Settings
//----------------------------------------------------a-------------------------{
length = input(14)
mult = input(2., 'Levels Multiplier')
src = input(close)
//Style
bull_css_0 = input.color(color.new(#0cb51a, 50), 'Bullish Gradient'
, inline = 'inline0'
, group = 'Style')
bull_css_1 = input.color(#0cb51a, ''
, inline = 'inline0'
, group = 'Style')
bear_css_0 = input.color(color.new(#ff1100, 50), 'Bearish Gradient'
, inline = 'inline1'
, group = 'Style')
bear_css_1 = input.color(#ff1100, ''
, inline = 'inline1'
, group = 'Style')
//-----------------------------------------------------------------------------}
//Normalization variables
//-----------------------------------------------------------------------------{
var short_len = int(length / 2)
var hull_len = int(math.sqrt(length))
var den1 = short_len * (short_len + 1) / 2
var den2 = length * (length + 1) / 2
var den3 = hull_len * (hull_len + 1) / 2
//-----------------------------------------------------------------------------}
//Hull coefficients
//-----------------------------------------------------------------------------{
var lcwa_coeffs = array.new_float(hull_len, 0)
var hull_coeffs = array.new_float(0)
if barstate.isfirst
//Linearly combined WMA coeffs
for i = 0 to length-1
sum1 = math.max(short_len - i, 0)
sum2 = length - i
array.unshift(lcwa_coeffs, 2 * (sum1 / den1) - (sum2 / den2))
//Zero padding of linearly combined WMA coeffs
for i = 0 to hull_len-2
array.unshift(lcwa_coeffs, 0)
//WMA convolution of linearly combined WMA coeffs
for i = hull_len to array.size(lcwa_coeffs)-1
sum3 = 0.
for j = i-hull_len to i-1
sum3 += array.get(lcwa_coeffs, j) * (i - j)
array.unshift(hull_coeffs, sum3 / den3)
//-----------------------------------------------------------------------------}
//Hull squeeze oscillator
//-----------------------------------------------------------------------------{
var os = 0
var len = array.size(hull_coeffs)-1
hma = 0.
inv_hma = 0.
for i = 0 to len
hma += src[i] * array.get(hull_coeffs, i)
inv_hma += src[len-i] * array.get(hull_coeffs, i)
hso = hma - inv_hma
cmean = ta.cum(math.abs(hso)) / bar_index * mult
os := ta.cross(hso, cmean) or ta.cross(hso, -cmean) ? 0
: hso < hso[1] and hso > cmean ? -1
: hso > hso[1] and hso < -cmean ? 1
: os
//-----------------------------------------------------------------------------}
//Plot
//-----------------------------------------------------------------------------{
//Colors
css0 = color.from_gradient(hso, 0, cmean, bull_css_0, bull_css_1)
css1 = color.from_gradient(hso, -cmean, 0, bear_css_1, bear_css_0)
css = hso > 0 ? css0 : css1
//Oscillator line/histogram
plot(hso, 'Hull Butterfly', css
, style = plot.style_histogram)
plot(hso, 'Hull Butterfly', chart.fg_color)
//Dots
plot(os > os[1] and os == 1 ? hso : na, 'Bullish Dot'
, bull_css_1
, 2
, plot.style_circles)
plot(os < os[1] and os == -1 ? hso : na, 'Bearish Dot'
, bear_css_1
, 2
, plot.style_circles)
//Levels
plot(cmean, color = color.gray, editable = false)
plot(cmean / 2, color = color.gray, editable = false)
plot(-cmean / 2, color = color.gray, editable = false)
plot(-cmean, color = color.gray, editable = false)
//-----------------------------------------------------------------------------}
|
Moving Averages based on higher Timeframes | https://www.tradingview.com/script/7YRmVFwD-Moving-Averages-based-on-higher-Timeframes/ | Patternscalper | https://www.tradingview.com/u/Patternscalper/ | 56 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
// -----------------------------------------------------------------
// | ©patternscalper |
// | / |
// | / |
// | /\ / |
// | / \ / |
// | / \ / |
// | / \/ |
// | /\ / |
// | / \ /\ / |
// | / \ / \ /\ / |
// | / \/ \ / \ / |
// | / \/ \ / |
// | / \/ |
// |\ / |
// | \ / |
// | \ /\ / |
// | \ / \ / |
// | \ / \/ |
// | \/ |
// -----------------------------------------------------------------
indicator("Moving Averages based on higher Timeframes", "Moving Averages HTF", overlay = true)
// <--------------------------------->
// <---------- User Inputs ---------->
// <--------------------------------->
var GRP1 = "Moving Average 1"
bool i_enableMA1 = input.bool(true, "Enable MA 1", inline = "1", group = GRP1)
i_smoothMA1 = input(defval = true, title = "Smooth Line", inline = "1", group = GRP1)
string i_typeMA1 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP1)
i_srcMA1 = input(close, "Source", inline = "2", group = GRP1)
i_lenMA1 = input.int(50, "Length", minval = 2, maxval = 999, inline = "3", group = GRP1)
i_tfMA1 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP1)
i_lineWidthMA1 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP1)
i_lineColorMA1 = input(defval = #00FFFF, title = "Line Color", inline = "4", group = GRP1)
float ma1 = switch i_typeMA1
"SMA" => ta.sma(i_srcMA1, i_lenMA1)
"EMA" => ta.ema(i_srcMA1, i_lenMA1)
"WMA" => ta.wma(i_srcMA1, i_lenMA1)
"HMA" => ta.hma(i_srcMA1, i_lenMA1)
"RMA" => ta.rma(i_srcMA1, i_lenMA1)
var GRP2 = "Moving Average 2"
bool i_enableMA2 = input.bool(true, "Enable MA 2", inline = "1", group = GRP2)
i_smoothMA2 = input(defval = true, title = "Smooth Line", inline = "1", group = GRP2)
string i_typeMA2 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP2)
i_srcMA2 = input(close, "Source", inline = "2", group = GRP2)
i_lenMA2 = input.int(200, "Length", minval = 2, maxval = 999, inline = "3", group = GRP2)
i_tfMA2 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP2)
i_lineWidthMA2 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP2)
i_lineColorMA2 = input(defval = #FF00FF, title = "Line Color", inline = "4", group = GRP2)
float ma2 = switch i_typeMA2
"SMA" => ta.sma(i_srcMA2, i_lenMA2)
"EMA" => ta.ema(i_srcMA2, i_lenMA2)
"WMA" => ta.wma(i_srcMA2, i_lenMA2)
"HMA" => ta.hma(i_srcMA2, i_lenMA2)
"RMA" => ta.rma(i_srcMA2, i_lenMA2)
var GRP3 = "Moving Average 3"
bool i_enableMA3 = input.bool(false, "Enable MA 3", inline = "1", group = GRP3)
i_smoothMA3 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP3)
string i_typeMA3 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP3)
i_srcMA3 = input(close, "Source", inline = "2", group = GRP3)
i_lenMA3 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP3)
i_tfMA3 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP3)
i_lineWidthMA3 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP3)
i_lineColorMA3 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP3)
float ma3 = switch i_typeMA3
"SMA" => ta.sma(i_srcMA3, i_lenMA3)
"EMA" => ta.ema(i_srcMA3, i_lenMA3)
"WMA" => ta.wma(i_srcMA3, i_lenMA3)
"HMA" => ta.hma(i_srcMA3, i_lenMA3)
"RMA" => ta.rma(i_srcMA3, i_lenMA3)
var GRP4 = "Moving Average 4"
bool i_enableMA4 = input.bool(false, "Enable MA 4", inline = "1", group = GRP4)
i_smoothMA4 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP4)
string i_typeMA4 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP4)
i_srcMA4 = input(close, "Source", inline = "2", group = GRP4)
i_lenMA4 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP4)
i_tfMA4 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP4)
i_lineWidthMA4 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP4)
i_lineColorMA4 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP4)
float ma4 = switch i_typeMA4
"SMA" => ta.sma(i_srcMA4, i_lenMA4)
"EMA" => ta.ema(i_srcMA4, i_lenMA4)
"WMA" => ta.wma(i_srcMA4, i_lenMA4)
"HMA" => ta.hma(i_srcMA4, i_lenMA4)
"RMA" => ta.rma(i_srcMA4, i_lenMA4)
var GRP5 = "Moving Average 5"
bool i_enableMA5 = input.bool(false, "Enable MA 5", inline = "1", group = GRP5)
i_smoothMA5 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP5)
string i_typeMA5 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP5)
i_srcMA5 = input(close, "Source", inline = "2", group = GRP5)
i_lenMA5 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP5)
i_tfMA5 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP5)
i_lineWidthMA5 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP5)
i_lineColorMA5 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP5)
float ma5 = switch i_typeMA5
"SMA" => ta.sma(i_srcMA5, i_lenMA5)
"EMA" => ta.ema(i_srcMA5, i_lenMA5)
"WMA" => ta.wma(i_srcMA5, i_lenMA5)
"HMA" => ta.hma(i_srcMA5, i_lenMA5)
"RMA" => ta.rma(i_srcMA5, i_lenMA5)
var GRP6 = "Moving Average 6"
bool i_enableMA6 = input.bool(false, "Enable MA 6", inline = "1", group = GRP6)
i_smoothMA6 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP6)
string i_typeMA6 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP6)
i_srcMA6 = input(close, "Source", inline = "2", group = GRP6)
i_lenMA6 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP6)
i_tfMA6 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP6)
i_lineWidthMA6 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP6)
i_lineColorMA6 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP6)
float ma6 = switch i_typeMA6
"SMA" => ta.sma(i_srcMA6, i_lenMA6)
"EMA" => ta.ema(i_srcMA6, i_lenMA6)
"WMA" => ta.wma(i_srcMA6, i_lenMA6)
"HMA" => ta.hma(i_srcMA6, i_lenMA6)
"RMA" => ta.rma(i_srcMA6, i_lenMA6)
var GRP7 = "Moving Average 7"
bool i_enableMA7 = input.bool(false, "Enable MA 7", inline = "1", group = GRP7)
i_smoothMA7 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP7)
string i_typeMA7 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP7)
i_srcMA7 = input(close, "Source", inline = "2", group = GRP7)
i_lenMA7 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP7)
i_tfMA7 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP7)
i_lineWidthMA7 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP7)
i_lineColorMA7 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP7)
float ma7 = switch i_typeMA7
"SMA" => ta.sma(i_srcMA7, i_lenMA7)
"EMA" => ta.ema(i_srcMA7, i_lenMA7)
"WMA" => ta.wma(i_srcMA7, i_lenMA7)
"HMA" => ta.hma(i_srcMA7, i_lenMA7)
"RMA" => ta.rma(i_srcMA7, i_lenMA7)
var GRP8 = "Moving Average 8"
bool i_enableMA8 = input.bool(false, "Enable MA 8", inline = "1", group = GRP8)
i_smoothMA8 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP8)
string i_typeMA8 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP8)
i_srcMA8 = input(close, "Source", inline = "2", group = GRP8)
i_lenMA8 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP8)
i_tfMA8 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP8)
i_lineWidthMA8 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP8)
i_lineColorMA8 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP8)
float ma8 = switch i_typeMA8
"SMA" => ta.sma(i_srcMA8, i_lenMA8)
"EMA" => ta.ema(i_srcMA8, i_lenMA8)
"WMA" => ta.wma(i_srcMA8, i_lenMA8)
"HMA" => ta.hma(i_srcMA8, i_lenMA8)
"RMA" => ta.rma(i_srcMA8, i_lenMA8)
var GRP9 = "Moving Average 9"
bool i_enableMA9 = input.bool(false, "Enable MA 9", inline = "1", group = GRP9)
i_smoothMA9 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP9)
string i_typeMA9 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP9)
i_srcMA9 = input(close, "Source", inline = "2", group = GRP9)
i_lenMA9 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP9)
i_tfMA9 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP9)
i_lineWidthMA9 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP9)
i_lineColorMA9 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP9)
float ma9 = switch i_typeMA9
"SMA" => ta.sma(i_srcMA9, i_lenMA9)
"EMA" => ta.ema(i_srcMA9, i_lenMA9)
"WMA" => ta.wma(i_srcMA9, i_lenMA9)
"HMA" => ta.hma(i_srcMA9, i_lenMA9)
"RMA" => ta.rma(i_srcMA9, i_lenMA9)
var GRP10 = "Moving Average 10"
bool i_enableMA10 = input.bool(false, "Enable MA 10", inline = "1", group = GRP10)
i_smoothMA10 = input(defval = false, title = "Smooth Line", inline = "1", group = GRP10)
string i_typeMA10 = input.string("EMA", "MA Type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], inline = "2", group = GRP10)
i_srcMA10 = input(close, "Source", inline = "2", group = GRP10)
i_lenMA10 = input.int(100, "Length", minval = 2, maxval = 999, inline = "3", group = GRP10)
i_tfMA10 = input.timeframe("", title = "Timeframe", inline = "3", group = GRP10)
i_lineWidthMA10 = input.int(defval = 1, title = "Line Width", options = [1, 2, 3, 4], inline = "4", group = GRP10)
i_lineColorMA10 = input(defval = #0000FF, title = "Line Color", inline = "4", group = GRP10)
float ma10 = switch i_typeMA10
"SMA" => ta.sma(i_srcMA10, i_lenMA10)
"EMA" => ta.ema(i_srcMA10, i_lenMA10)
"WMA" => ta.wma(i_srcMA10, i_lenMA10)
"HMA" => ta.hma(i_srcMA10, i_lenMA10)
"RMA" => ta.rma(i_srcMA10, i_lenMA10)
// <------------------------------------------>
// <---------- Step Moving Averages ---------->
// <------------------------------------------>
stepMA1 = i_enableMA1 ? request.security(syminfo.tickerid, i_tfMA1, ma1, gaps=barmerge.gaps_off) : na
stepMA2 = i_enableMA1 ? request.security(syminfo.tickerid, i_tfMA2, ma2, gaps=barmerge.gaps_off) : na
stepMA3 = i_enableMA3 ? request.security(syminfo.tickerid, i_tfMA3, ma3, gaps=barmerge.gaps_off) : na
stepMA4 = i_enableMA4 ? request.security(syminfo.tickerid, i_tfMA4, ma4, gaps=barmerge.gaps_off) : na
stepMA5 = i_enableMA5 ? request.security(syminfo.tickerid, i_tfMA5, ma5, gaps=barmerge.gaps_off) : na
stepMA6 = i_enableMA6 ? request.security(syminfo.tickerid, i_tfMA6, ma6, gaps=barmerge.gaps_off) : na
stepMA7 = i_enableMA7 ? request.security(syminfo.tickerid, i_tfMA7, ma7, gaps=barmerge.gaps_off) : na
stepMA8 = i_enableMA8 ? request.security(syminfo.tickerid, i_tfMA8, ma8, gaps=barmerge.gaps_off) : na
stepMA9 = i_enableMA9 ? request.security(syminfo.tickerid, i_tfMA9, ma9, gaps=barmerge.gaps_off) : na
stepMA10 = i_enableMA10 ? request.security(syminfo.tickerid, i_tfMA10, ma10, gaps=barmerge.gaps_off) : na
// <-------------------------------------------->
// <---------- Smooth Moving Averages ---------->
// <-------------------------------------------->
smoothMA1 = i_enableMA1 ? request.security(syminfo.tickerid, i_tfMA1, ma1, gaps=barmerge.gaps_on) : na
smoothMA2 = i_enableMA2 ? request.security(syminfo.tickerid, i_tfMA2, ma2, gaps=barmerge.gaps_on) : na
smoothMA3 = i_enableMA3 ? request.security(syminfo.tickerid, i_tfMA3, ma3, gaps=barmerge.gaps_on) : na
smoothMA4 = i_enableMA4 ? request.security(syminfo.tickerid, i_tfMA4, ma4, gaps=barmerge.gaps_on) : na
smoothMA5 = i_enableMA5 ? request.security(syminfo.tickerid, i_tfMA5, ma5, gaps=barmerge.gaps_on) : na
smoothMA6 = i_enableMA6 ? request.security(syminfo.tickerid, i_tfMA6, ma6, gaps=barmerge.gaps_on) : na
smoothMA7 = i_enableMA7 ? request.security(syminfo.tickerid, i_tfMA7, ma7, gaps=barmerge.gaps_on) : na
smoothMA8 = i_enableMA8 ? request.security(syminfo.tickerid, i_tfMA8, ma8, gaps=barmerge.gaps_on) : na
smoothMA9 = i_enableMA9 ? request.security(syminfo.tickerid, i_tfMA9, ma9, gaps=barmerge.gaps_on) : na
smoothMA10 = i_enableMA10 ? request.security(syminfo.tickerid, i_tfMA10, ma10, gaps=barmerge.gaps_on) : na
// <------------------------------------------>
// <---------- Plot Moving Averages ---------->
// <------------------------------------------>
plot(i_smoothMA1 ? smoothMA1 : stepMA1, color = i_lineColorMA1, linewidth = i_lineWidthMA1, title = "Moving Average 1")
plot(i_smoothMA2 ? smoothMA2 : stepMA2, color = i_lineColorMA2, linewidth = i_lineWidthMA2, title = "Moving Average 2")
plot(i_smoothMA3 ? smoothMA3 : stepMA3, color = i_lineColorMA3, linewidth = i_lineWidthMA3, title = "Moving Average 3")
plot(i_smoothMA4 ? smoothMA4 : stepMA4, color = i_lineColorMA4, linewidth = i_lineWidthMA4, title = "Moving Average 4")
plot(i_smoothMA5 ? smoothMA5 : stepMA5, color = i_lineColorMA5, linewidth = i_lineWidthMA5, title = "Moving Average 5")
plot(i_smoothMA6 ? smoothMA6 : stepMA6, color = i_lineColorMA6, linewidth = i_lineWidthMA6, title = "Moving Average 6")
plot(i_smoothMA7 ? smoothMA7 : stepMA7, color = i_lineColorMA7, linewidth = i_lineWidthMA7, title = "Moving Average 7")
plot(i_smoothMA8 ? smoothMA8 : stepMA8, color = i_lineColorMA8, linewidth = i_lineWidthMA8, title = "Moving Average 8")
plot(i_smoothMA9 ? smoothMA9 : stepMA9, color = i_lineColorMA9, linewidth = i_lineWidthMA9, title = "Moving Average 9")
plot(i_smoothMA10 ? smoothMA10 : stepMA10, color = i_lineColorMA10, linewidth = i_lineWidthMA10, title = "Moving Average 10") |
SPX and Federal Net Liquidity difference | https://www.tradingview.com/script/R9pp2zAV-SPX-and-Federal-Net-Liquidity-difference/ | TaxShields | https://www.tradingview.com/u/TaxShields/ | 71 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TaxShields
// Fed Net Liquidity indicator from © jlb05013
//@version=5
indicator("Fed Net Liquidity Indicator", overlay=false)
i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M'])
fed_bal = request.security('FRED:WALCL', i_res, close)/1e9 // millions
tga = request.security('FRED:WTREGEN', i_res, close)/1e9 // billions
rev_repo = request.security('FRED:RRPONTSYD', i_res, close)/1e9 // billions
//plot(fed_bal)
//plot(tga)
//plot(rev_repo)
net_liquidity = (fed_bal - (tga + rev_repo)) / 1.1 - 1625
Difference = close - net_liquidity
plot(Difference, color=color.red)
plot(250, style=plot.style_line)
plot(-250, style=plot.style_line) |
HH-LL ZZ | https://www.tradingview.com/script/nlZhcXgF-HH-LL-ZZ/ | fikira | https://www.tradingview.com/u/fikira/ | 1,299 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fikira
//@version=5
indicator("HH-LL ZZ", shorttitle='H²L²Z²', max_lines_count=500, max_labels_count=500, max_bars_back=1000, overlay=true)
cl = input.string( 'close' , 'source for level breach', options=['H/L', 'close'] )
cnt = input.int ( 3 , 'x breaches' , minval=1, maxval=10 )
style = input.string(line.style_solid, 'line style' , options=[line.style_solid, line.style_dotted, line.style_dashed])
showLev = input.bool ( false , 'show levels breaches' )
showS_R = input.bool ( false , 'show Support/Resistance' )
ds = input.bool ( false , 'remove repaint warning' )
lab = input.bool ( false , 'labels' )
lin = input.bool ( true , 'lines' )
var line [] lines = array.new<line> ()
var label[] labels = array.new<label>()
var float levelH = high
var float levelL = low
var int countLL = 0
var int countHH = 0
var int dir = 0
bool h = false
bool l = false
getSet(l, i) =>
if array.size(labels) > i -1
getX = label.get_x(array.get(labels, i)), getY = label.get_y(array.get(labels, i))
line.set_xy1(l, getX, getY), line.set_xy2(l, getX +1, getY)
if array.size(lines) > 500
line.delete(array.pop(lines))
if array.size(labels) > 500
label.delete(array.pop(labels))
if barstate.isfirst
array.unshift(labels, label.new(bar_index, hl2))
if (cl == 'H/L' ? low : close) < levelL
countLL += 1
if countLL == cnt
l := true
countHH := 0
countLL := 0
levelL := low
levelH := high
if dir > -1
array.unshift(labels, label.new(bar_index, low, style=label.style_label_up, color=lab ? #FF0000 : color.new(color.blue, 100)))
if array.size(labels) > 1
array.unshift(lines , line.new (label.get_x(array.get(labels, 1)), label.get_y(array.get(labels, 1)), bar_index, low, color=lin ? #FF0000 : color.new(color.blue, 100), style=style))
dir := -1
if array.size(labels) > 2
label.set_color(array.get(labels, 2), lab ? color.yellow : color.new(color.blue, 100))
if array.size(lines) > 2
line.set_color (array.get(lines , 2), lin ? color.yellow : color.new(color.blue, 100))
else
label.set_xy(array.get(labels, 0), bar_index, low)
line.set_xy2(array.get(lines , 0), bar_index, low)
if array.size(labels) > 2
hi = low
bx = 0
for i = 0 to bar_index - label.get_x(array.get(labels, 2))
if high[i] > hi
hi := high[i]
bx := bar_index - i
label.set_xy(array.get(labels, 1), bx, hi)
line.set_xy2(array.get(lines , 1), bx, hi)
line.set_xy1(array.get(lines , 0), bx, hi)
if (cl == 'H/L' ? high : close) > levelH
countHH += 1
if countHH == cnt
h := true
countHH := 0
countLL := 0
levelL := low
levelH := high
if dir < 1
array.unshift(labels, label.new(bar_index, high, style=label.style_label_down, color=lab ? #FF0000 : color.new(color.blue, 100)))
if array.size(labels) > 1
array.unshift(lines , line.new (label.get_x(array.get(labels, 1)), label.get_y(array.get(labels, 1)), bar_index, high, color=lin ? #FF0000 : color.new(color.blue, 100), style=style))
dir := 1
if array.size(labels) > 2
label.set_color(array.get(labels, 2), lab ? color.yellow : color.new(color.blue, 100))
if array.size(lines) > 2
line.set_color (array.get(lines , 2), lin ? color.yellow : color.new(color.blue, 100))
else
label.set_xy(array.get(labels, 0), bar_index, high)
line.set_xy2(array.get(lines , 0), bar_index, high)
if array.size(labels) > 2
lo = high
bx = 0
for i = 0 to bar_index - label.get_x(array.get(labels, 2))
if low [i] < lo
lo := low[i]
bx := bar_index - i
label.set_xy(array.get(labels, 1), bx, lo)
line.set_xy2(array.get(lines , 1), bx, lo)
line.set_xy1(array.get(lines , 0), bx, lo)
if barstate.islastconfirmedhistory and not ds
var tab = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color.new(color.blue, 75), border_width = 1)
table.cell(table_id = tab, column = 0, row = 0, text = "Red labels and lines could possibly repaint!", text_color= #FF0000, text_size = size.small, text_font_family = font.family_monospace)
plotshape(showLev and h, style=shape.circle, location=location.abovebar, color=color.lime, size=size.tiny, display=display.pane)
plotshape(showLev and l, style=shape.circle, location=location.belowbar, color=color.blue, size=size.tiny, display=display.pane)
var line l0 = line.new(na, na, na, na, extend=extend.right, style=line.style_dotted, color=color.new(#FF0000 , 25))
var line l1 = line.new(na, na, na, na, extend=extend.right, style=line.style_dotted, color=color.new(#FF0000 , 25))
var line l2 = line.new(na, na, na, na, extend=extend.right, style=line.style_dotted, color=color.new(color.blue, 0))
var line l3 = line.new(na, na, na, na, extend=extend.right, style=line.style_dotted, color=color.new(color.blue, 0))
if barstate.islast and showS_R
getSet(l0, 0), getSet(l1, 1)
getSet(l2, 2), getSet(l3, 3)
|
Generalized Black-Scholes-Merton w/ Analytical Greeks [Loxx] | https://www.tradingview.com/script/foImvlF1-Generalized-Black-Scholes-Merton-w-Analytical-Greeks-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 31 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Generalized Black-Scholes-Merton w/ Analytical Greeks [Loxx]",
shorttitle ="GBSMAG [Loxx]",
overlay = true,
max_lines_count = 500, precision = 4)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
import loxx/loxxexpandedsourcetypes/4
color darkGreenColor = #1B7E02
string callString = "Call"
string putString = "Put"
string Continuous = "Continuous"
string PeriodRate = "Period Rate"
string Annual = "Annual"
string SemiAnnual = "Semi-Annual"
string Quaterly = "Quaterly"
string Monthly = "Monthly"
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
array<float> sarr = array.new<float>(per, 0)
for i = 0 to per - 1
array.set(sarr, i, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
CNDEV(float U)=>
float x = 0
float r = 0
float CNDEV = 0
array<float> A = array.new<float>(4, 0)
array.set(A, 0, 2.50662823884)
array.set(A, 1, -18.61500062529)
array.set(A, 2, 41.39119773534)
array.set(A, 3, -25.44106049637)
array<float> b = array.new<float>(4, 0)
array.set(b, 0, -8.4735109309)
array.set(b, 1, 23.08336743743)
array.set(b, 2, -21.06224101826)
array.set(b, 3, 3.13082909833)
array<float> c = array.new<float>(9, 0)
array.set(c, 0, 0.337475482272615)
array.set(c, 1, 0.976169019091719)
array.set(c, 2, 0.160797971491821)
array.set(c, 3, 0.0276438810333863)
array.set(c, 4, 0.0038405729373609)
array.set(c, 5, 0.0003951896511919)
array.set(c, 6, 3.21767881767818E-05)
array.set(c, 7, 2.888167364E-07)
array.set(c, 8, 3.960315187E-07)
x := U - 0.5
if math.abs(x) < 0.92
r := x * x
r := x * ((array.get(A, 3) * r + array.get(A, 2)) * r + array.get(A, 1) * r + array.get(A, 0))
/ ((((array.get(b, 3) * r + array.get(b, 2)) * r + array.get(b, 1)) * r + array.get(b, 0)) * r + 1)
CNDEV := r
else
r := x >= 0 ? 1 - U : U
r := math.log(-math.log(r))
r := array.get(c, 0) + r * (array.get(c, 1) + r * (array.get(c, 2) + r * (array.get(c, 3) + r + (array.get(c, 4)
+ r * (array.get(c, 5) + r * (array.get(c, 6) + r * (array.get(c, 7) + r * array.get(c, 8))))))))
r := x < 0 ? -r : r
CNDEV := r
CNDEV
nd(float x)=>
float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi)
out
// Boole's Rule
Boole(float StartPoint, float EndPoint, int n)=>
float[] X = array.new<float>(n + 1 , 0)
float[] Y = array.new<float>(n + 1 , 0)
float delta_x = (EndPoint - StartPoint) / n
for i = 0 to n
array.set(X, i, StartPoint + i * delta_x)
array.set(Y, i, nd(array.get(X, i)))
float sum = 0
for t = 0 to (n - 1) / 4
int ind = 4 * t
sum += (1 / 45.0) *
(14 * array.get(Y, ind)
+ 64 * array.get(Y, ind + 1)
+ 24 * array.get(Y, ind + 2)
+ 64 * array.get(Y, ind + 3)
+ 14 * array.get(Y, ind + 4))
* delta_x
sum
// N(0,1) cdf by Boole's Rule
cnd(float x)=>
float out = Boole(-10.0, x, 240)
out
convertingToCCRate(float r, float Compoundings)=>
float ConvertingToCCRate = 0
if Compoundings == 0
ConvertingToCCRate := r
else
ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings)
ConvertingToCCRate
// DDeltaDvol also known as vanna
GDdeltaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GDdeltaDvol = 0
d1 := (math.log(S / x) + (b + v * v / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDdeltaDvol := -math.exp((b - r) * T) * d2 / v * nd(d1)
GDdeltaDvol
GBlackScholes(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float gBlackScholes = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if CallPutFlag == callString
gBlackScholes := S * math.exp((b - r) * T) * cnd(d1) - x * math.exp(-r * T) * cnd(d2)
else
gBlackScholes := x * math.exp(-r * T) * cnd(-d2) - S * math.exp((b - r) * T) * cnd(-d1)
gBlackScholes
// Gamma for the generalized Black and Scholes formula
GGamma(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GGamma = math.exp((b - r) * T) * nd(d1) / (S * v * math.sqrt(T))
GGamma
// GammaP for the generalized Black and Scholes formula
GGammaP(float S, float x, float T, float r, float b, float v)=>
GGammaP = S * GGamma(S, x, T, r, b, v) / 100
GGammaP
// Delta for the generalized Black and Scholes formula
GDelta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GDelta = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GDelta := math.exp((b - r) * T) * cnd(d1)
else
GDelta := -math.exp((b - r) * T) * cnd(-d1)
GDelta
// StrikeDelta for the generalized Black and Scholes formula
GStrikeDelta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d2 = 0
float GStrikeDelta = 0
d2 := (math.log(S / x) + (b - math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GStrikeDelta := -math.exp(-r * T) * cnd(d2)
else
GStrikeDelta := math.exp(-r * T) * cnd(-d2)
GStrikeDelta
// Elasticity for the generalized Black and Scholes formula
GElasticity(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
GElasticity = GDelta(CallPutFlag, S, x, T, r, b, v) * S / GBlackScholes(CallPutFlag, S, x, T, r, b, v)
GElasticity
// Risk Neutral Denisty for the generalized Black and Scholes formula
GRiskNeutralDensity(float S, float x, float T, float r, float b, float v)=>
float d2 = 0
d2 := (math.log(S / x) + (b - math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GRiskNeutralDensity = math.exp(-r * T) * nd(d2) / (x * v * math.sqrt(T))
GRiskNeutralDensity
// Theta for the generalized Black and Scholes formula
GTheta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GTheta = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if CallPutFlag == callString
GTheta := -S * math.exp((b - r) * T) * nd(d1) * v / (2 * math.sqrt(T)) - (b - r) * S * math.exp((b - r) * T) * cnd(d1) - r * x * math.exp(-r * T) * cnd(d2)
else
GTheta := -S * math.exp((b - r) * T) * nd(d1) * v / (2 * math.sqrt(T)) + (b - r) * S * math.exp((b - r) * T) * cnd(-d1) + r * x * math.exp(-r * T) * cnd(-d2)
GTheta
// Vega for the generalized Black and Scholes formula
GVega(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GVega = S * math.exp((b - r) * T) * nd(d1) * math.sqrt(T)
GVega
// VegaP for the generalized Black and Scholes formula
GVegaP(float S, float x, float T, float r, float b, float v)=>
GVegaP = v / 10 * GVega(S, x, T, r, b, v)
GVegaP
// DvegaDvol/Vomma for the generalized Black and Scholes formula
GDvegaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDvegaDvol = GVega(S, x, T, r, b, v) * d1 * d2 / v
GDvegaDvol
// Rho for the generalized Black and Scholes formula for all options except futures
GRho(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
float GRho = 0
if CallPutFlag == callString
GRho := T * x * math.exp(-r * T) * cnd(d2)
else
GRho := -T * x * math.exp(-r * T) * cnd(-d2)
GRho
// Rho for the generalized Black and Scholes formula for Futures option
GRhoFO(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
GRhoFO = -T * GBlackScholes(CallPutFlag, S, x, T, r, 0, v)
GRhoFO
// Rho2/Phi for the generalized Black and Scholes formula
GPhi(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GPhi = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GPhi := -T * S * math.exp((b - r) * T) * cnd(d1)
else
GPhi := T * S * math.exp((b - r) * T) * cnd(-d1)
GPhi
// Carry rf sensitivity for the generalized Black and Scholes formula
GCarry(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GCarry = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GCarry := T * S * math.exp((b - r) * T) * cnd(d1)
else
GCarry := -T * S * math.exp((b - r) * T) * cnd(-d1)
GCarry
// DgammaDspot/Speed for the generalized Black and Scholes formula
GDgammaDspot(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GDgammaDspot = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GDgammaDspot := -GGamma(S, x, T, r, b, v) * (1 + d1 / (v * math.sqrt(T))) / S
GDgammaDspot
// DgammaDvol/Zomma for the generalized Black and Scholes formula
GDgammaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GDgammaDvol = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDgammaDvol := GGamma(S, x, T, r, b, v) * ((d1 * d2 - 1) / v)
GDgammaDvol
CGBlackScholes(string OutPutFlag, string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float output = 0
float CGBlackScholes = 0
if OutPutFlag == "p" // Value
CGBlackScholes := GBlackScholes(CallPutFlag, S, x, T, r, b, v)
//DELTA GREEKS
else if OutPutFlag == "d" // Delta
CGBlackScholes := GDelta(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "dddv" // DDeltaDvol
CGBlackScholes := GDdeltaDvol(S, x, T, r, b, v) / 100
else if OutPutFlag == "e" // Elasticity
CGBlackScholes := GElasticity(CallPutFlag, S, x, T, r, b, v)
//GAMMA GREEKS
else if OutPutFlag == "g" // Gamma
CGBlackScholes := GGamma(S, x, T, r, b, v)
else if OutPutFlag == "gp" // GammaP
CGBlackScholes := GGammaP(S, x, T, r, b, v)
else if OutPutFlag == "s" // 'DgammaDspot/speed
CGBlackScholes := GDgammaDspot(S, x, T, r, b, v)
else if OutPutFlag == "gv" // 'DgammaDvol/Zomma
CGBlackScholes := GDgammaDvol(S, x, T, r, b, v) / 100
//VEGA GREEKS
else if OutPutFlag == "v" // Vega
CGBlackScholes := GVega(S, x, T, r, b, v) / 100
else if OutPutFlag == "dvdv" // DvegaDvol/Vomma
CGBlackScholes := GDvegaDvol(S, x, T, r, b, v) / 10000
else if OutPutFlag == "vp" // VegaP
CGBlackScholes := GVegaP(S, x, T, r, b, v)
//THETA GREEKS
else if OutPutFlag == "t" // Theta
CGBlackScholes := GTheta(CallPutFlag, S, x, T, r, b, v) / 365
//RATE/CARRY GREEKS
else if OutPutFlag == "r" // Rho
CGBlackScholes := GRho(CallPutFlag, S, x, T, r, b, v) / 100
else if OutPutFlag == "fr" // Rho futures option
CGBlackScholes := GRhoFO(CallPutFlag, S, x, T, r, b, v) / 100
else if OutPutFlag == "b" // Carry Rho
CGBlackScholes := GCarry(CallPutFlag, S, x, T, r, b, v) / 100
else if OutPutFlag == "f" // Phi/Rho2
CGBlackScholes := GPhi(CallPutFlag, S, x, T, r, b, v) / 100
//'PROB GREEKS
else if OutPutFlag == "dx" // 'StrikeDelta
CGBlackScholes := GStrikeDelta(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "dxdx" // 'Risk Neutral Density
CGBlackScholes := GRiskNeutralDensity(S, x, T, r, b, v)
CGBlackScholes
gBlackScholesImpVolBisection(string CallPutFlag, float S, float x, float T, float r, float b, float cm)=>
float vLow = 0
float vHigh= 0
float vi = 0
float cLow = 0
float cHigh = 0
float epsilon = 0
int counter = 0
float gBlackScholesImpVolBisection = 0
vLow := 0.005
vHigh := 4
epsilon := 1E-08
cLow := GBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := GBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
while math.abs(cm - GBlackScholes(CallPutFlag, S, x, T, r, b, vi)) > epsilon
counter += 1
if counter == 100
gBlackScholesImpVolBisection := 0
break
if GBlackScholes(CallPutFlag, S, x, T, r, b, vi) < cm
vLow := vi
else
vHigh := vi
cLow := GBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := GBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
gBlackScholesImpVolBisection := vi
gBlackScholesImpVolBisection
gVega(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GVega = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GVega := S * math.exp((b - r) * T) * nd(d1) * math.sqrt(T)
GVega
gImpliedVolatilityNR(string CallPutFlag, float S, float x, float T, float r, float b, float cm, float epsilon)=>
float vi = 0
float ci = 0
float vegai = 0
float minDiff = 0
float GImpliedVolatilityNR = 0
vi := math.sqrt(math.abs(math.log(S / x) + r * T) * 2 / T)
ci := GBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
while math.abs(cm - ci) >= epsilon and math.abs(cm - ci) <= minDiff
vi := vi - (ci - cm) / vegai
ci := GBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
if math.abs(cm - ci) < epsilon
GImpliedVolatilityNR := vi
else
GImpliedVolatilityNR := 0
GImpliedVolatilityNR
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Spot Price Settings")
srcin = input.string("Close", "Spot Price", group= "Spot Price Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
float K = input.float(275, "Strike Price", group = "Basic Settings")
string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings")
string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings")
float rf = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100
string rhocmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float kv = input.float(0., "% Cost of Carry", group = "Rates Settings") / 100
string kvcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float v = input.float(40., "% Volatility", group = "Rates Settings") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Historical Volatility Settings", tooltip = "Not used in calculation. This is here for comparison to implied volatility")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Historical Volatility Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
string txtsize = input.string("Auto", title = "Expiry Second", options = ["Small", "Normal", "Tiny", "Auto", "Large"], group = "UI Options")
string outsize = switch txtsize
"Small"=> size.small
"Normal"=> size.normal
"Tiny"=> size.tiny
"Auto"=> size.auto
"Large"=> size.large
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float rhocmpvalue = switch rhocmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float kvcmpvalue = switch kvcmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
sideout = side == "Long" ? 1 : -1
kouta = convertingToCCRate(rf, rhocmpvalue)
koutb = convertingToCCRate(kv, kvcmpvalue)
price = CGBlackScholes("p", OpType, spot, K, T, kouta, koutb, v)
Delta = CGBlackScholes("d", OpType, spot, K, T, kouta, koutb, v) * sideout
Elasticity = CGBlackScholes("e", OpType, spot, K, T, kouta, koutb, v) * sideout
Gamma = CGBlackScholes("g", OpType, spot, K, T, kouta, koutb, v) * sideout
DgammaDvol = CGBlackScholes("gv", OpType, spot, K, T, kouta, koutb, v) * sideout
GammaP = CGBlackScholes("gp", OpType, spot, K, T, kouta, koutb, v) * sideout
Vega = CGBlackScholes("v", OpType, spot, K, T, kouta, koutb, v) * sideout
DvegaDvol = CGBlackScholes("dvdv", OpType, spot, K, T, kouta, koutb, v) * sideout
VegaP = CGBlackScholes("vp", OpType, spot, K, T, kouta, koutb, v) * sideout
Theta = CGBlackScholes("t", OpType, spot, K, T, kouta, koutb, v) * sideout
Rho = CGBlackScholes("r", OpType, spot, K, T, kouta, koutb, v) * sideout
RhoFuturesOption = CGBlackScholes("fr", OpType, spot, K, T, kouta, koutb, v) * sideout
PhiRho = CGBlackScholes("f", OpType, spot, K, T, kouta, koutb, v) * sideout
Carry = CGBlackScholes("b", OpType, spot, K, T, kouta, koutb, v) * sideout
DDeltaDvol = CGBlackScholes("dddv", OpType, spot, K, T, kouta, koutb, v) * sideout
Speed = CGBlackScholes("s", OpType, spot, K, T, kouta, koutb, v) * sideout
DeltaX = CGBlackScholes("dx", OpType, spot, K, T, kouta, koutb, v) * sideout
RiskNeutralDensity = CGBlackScholes("dxdx", OpType, spot, K, T, kouta, koutb, v) * sideout
impvolbi = gBlackScholesImpVolBisection(OpType, spot, K, T, kouta, koutb, price)
impvolnewt = gImpliedVolatilityNR(OpType, spot, K, T, kouta, koutb, price, 0.00001)
var testTable = table.new(position = position.middle_right, columns = 1, rows = 38, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = "Generalized Black-Scholes-Merton Option Pricing Model", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 1, text = "Option Type: " + OpType, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 2, text = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 3, text = "Spot Price: " + str.tostring(spot, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 4, text = "Strike Price: " + str.tostring(K, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 5, text = "% Risk-free Rate: " + str.tostring(rf * 100, "##.##") + "%\n" + "Compounding Type: " + rhocmp + "\nCC Rate: " + str.tostring(kouta * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 6, text = "% Cost of Carry: " + str.tostring(kv * 100, "##.##") + "%\n" + "Compounding Type: " + kvcmp + "\nCC Carry: " + str.tostring(koutb * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 7, text = "% Volatility (annual): " + str.tostring(v * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 8, text = "Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 9, text = "Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 10, text = "Calculated Values", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 11, text = "Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 12, text = "Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 13, text = "Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 14, text = OpType + " Option Price", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 15, text = "Forward Price: " + str.tostring(spot * math.exp(koutb * T), format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 16, text = "Price: " + str.tostring(price, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 17, text = "Analytical Greeks", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 18, text = "Delta Δ: " + str.tostring(Delta, "##.#####"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 19, text = "Elasticity Λ: " + str.tostring(Elasticity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 20, text = "Gamma Γ: " + str.tostring(Gamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 21, text = "DGammaDvol: " + str.tostring(DgammaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 22, text = "GammaP Γ: " + str.tostring(GammaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 23, text = "Vega: " + str.tostring(Vega, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 24, text = "DVegaDvol: " + str.tostring(DvegaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 25, text = "VegaP: " + str.tostring(VegaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 26, text = "Theta Θ (1 day): " + str.tostring(Theta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 27, text = "Rho ρ: " + str.tostring(rf, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 28, text = "Rho Futures Option ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 29, text = "Phi/Rho2: " + str.tostring(PhiRho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 30, text = "Carry: " + str.tostring(Carry, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 31, text = "DDeltaDvol: " + str.tostring(DDeltaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 32, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 33, text = "Strike Delta: " + str.tostring(DeltaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 34, text = "Risk Neutral Density: " + str.tostring(RiskNeutralDensity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 35, text = "Implied Volatility Calculation", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 36, text = "Implied Volatility Bisection: " + str.tostring(impvolbi * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 37, text = "Implied Volatility Newton Raphson: " + str.tostring(impvolnewt * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
|
Black-Scholes 1973 OPM on Non-Dividend Paying Stocks [Loxx] | https://www.tradingview.com/script/FRZfgQ7U-Black-Scholes-1973-OPM-on-Non-Dividend-Paying-Stocks-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 12 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Black-Scholes 1973 OPM on Non-Dividend Paying Stocks [Loxx]",
shorttitle ="BS1973OPMNDPS [Loxx]",
overlay = true,
max_lines_count = 500, precision = 4)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
import loxx/loxxexpandedsourcetypes/4
import loxx/cnd/1
color darkGreenColor = #1B7E02
string callString = "Call"
string putString = "Put"
string Continuous = "Continuous"
string PeriodRate = "Period Rate"
string Annual = "Annual"
string SemiAnnual = "Semi-Annual"
string Quaterly = "Quaterly"
string Monthly = "Monthly"
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
array<float> sarr = array.new<float>(per, 0)
for i = 0 to per - 1
array.set(sarr, i, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
nd(float x)=>
float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi)
out
convertingToCCRate(float r, float Compoundings)=>
float ConvertingToCCRate = 0
if Compoundings == 0
ConvertingToCCRate := r
else
ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings)
ConvertingToCCRate
// DDeltaDvol also known as vanna
GDdeltaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GDdeltaDvol = 0
d1 := (math.log(S / x) + (b + v * v / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDdeltaDvol := -math.exp((b - r) * T) * d2 / v * nd(d1)
GDdeltaDvol
GBlackScholes(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float gBlackScholes = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if CallPutFlag == callString
gBlackScholes := S * math.exp((b - r) * T) * cnd.CND1(d1) - x * math.exp(-r * T) * cnd.CND1(d2)
else
gBlackScholes := x * math.exp(-r * T) * cnd.CND1(-d2) - S * math.exp((b - r) * T) * cnd.CND1(-d1)
gBlackScholes
// Gamma for the generalized Black and Scholes formula
GGamma(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GGamma = math.exp((b - r) * T) * nd(d1) / (S * v * math.sqrt(T))
GGamma
// GammaP for the generalized Black and Scholes formula
GGammaP(float S, float x, float T, float r, float b, float v)=>
GGammaP = S * GGamma(S, x, T, r, b, v) / 100
GGammaP
// Delta for the generalized Black and Scholes formula
GDelta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GDelta = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GDelta := math.exp((b - r) * T) * cnd.CND1(d1)
else
GDelta := -math.exp((b - r) * T) * cnd.CND1(-d1)
GDelta
// StrikeDelta for the generalized Black and Scholes formula
GStrikeDelta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d2 = 0
float GStrikeDelta = 0
d2 := (math.log(S / x) + (b - math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GStrikeDelta := -math.exp(-r * T) * cnd.CND1(d2)
else
GStrikeDelta := math.exp(-r * T) * cnd.CND1(-d2)
GStrikeDelta
// Elasticity for the generalized Black and Scholes formula
GElasticity(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
GElasticity = GDelta(CallPutFlag, S, x, T, r, b, v) * S / GBlackScholes(CallPutFlag, S, x, T, r, b, v)
GElasticity
// Risk Neutral Denisty for the generalized Black and Scholes formula
GRiskNeutralDensity(float S, float x, float T, float r, float b, float v)=>
float d2 = 0
d2 := (math.log(S / x) + (b - math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GRiskNeutralDensity = math.exp(-r * T) * nd(d2) / (x * v * math.sqrt(T))
GRiskNeutralDensity
// Theta for the generalized Black and Scholes formula
GTheta(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GTheta = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
if CallPutFlag == callString
GTheta := -S * math.exp((b - r) * T) * nd(d1) * v / (2 * math.sqrt(T)) - (b - r) * S * math.exp((b - r) * T) * cnd.CND1(d1) - r * x * math.exp(-r * T) * cnd.CND1(d2)
else
GTheta := -S * math.exp((b - r) * T) * nd(d1) * v / (2 * math.sqrt(T)) + (b - r) * S * math.exp((b - r) * T) * cnd.CND1(-d1) + r * x * math.exp(-r * T) * cnd.CND1(-d2)
GTheta
// Vega for the generalized Black and Scholes formula
GVega(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GVega = S * math.exp((b - r) * T) * nd(d1) * math.sqrt(T)
GVega
// VegaP for the generalized Black and Scholes formula
GVegaP(float S, float x, float T, float r, float b, float v)=>
GVegaP = v / 10 * GVega(S, x, T, r, b, v)
GVegaP
// DvegaDvol/Vomma for the generalized Black and Scholes formula
GDvegaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDvegaDvol = GVega(S, x, T, r, b, v) * d1 * d2 / v
GDvegaDvol
// Rho for the generalized Black and Scholes formula for all options except futures
GRho(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = (math.log(S / x) + (b + v *v / 2) * T) / (v * math.sqrt(T))
float d2 = d1 - v * math.sqrt(T)
float GRho = 0
if CallPutFlag == callString
GRho := T * x * math.exp(-r * T) * cnd.CND1(d2)
else
GRho := -T * x * math.exp(-r * T) * cnd.CND1(-d2)
GRho
// Rho for the generalized Black and Scholes formula for Futures option
GRhoFO(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
GRhoFO = -T * GBlackScholes(CallPutFlag, S, x, T, r, 0, v)
GRhoFO
// Rho2/Phi for the generalized Black and Scholes formula
GPhi(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GPhi = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GPhi := -T * S * math.exp((b - r) * T) * cnd.CND1(d1)
else
GPhi := T * S * math.exp((b - r) * T) * cnd.CND1(-d1)
GPhi
// Carry rf sensitivity for the generalized Black and Scholes formula
GCarry(string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GCarry = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
if CallPutFlag == callString
GCarry := T * S * math.exp((b - r) * T) * cnd.CND1(d1)
else
GCarry := -T * S * math.exp((b - r) * T) * cnd.CND1(-d1)
GCarry
// DgammaDspot/Speed for the generalized Black and Scholes formula
GDgammaDspot(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GDgammaDspot = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GDgammaDspot := -GGamma(S, x, T, r, b, v) * (1 + d1 / (v * math.sqrt(T))) / S
GDgammaDspot
// DgammaDvol/Zomma for the generalized Black and Scholes formula
GDgammaDvol(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float d2 = 0
float GDgammaDvol = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
d2 := d1 - v * math.sqrt(T)
GDgammaDvol := GGamma(S, x, T, r, b, v) * ((d1 * d2 - 1) / v)
GDgammaDvol
CGBlackScholes(string OutPutFlag, string CallPutFlag, float S, float x, float T, float r, float b, float v)=>
float output = 0
float CGBlackScholes = 0
if OutPutFlag == "p" // Value
CGBlackScholes := GBlackScholes(CallPutFlag, S, x, T, r, b, v)
//DELTA GREEKS
else if OutPutFlag == "d" // Delta
CGBlackScholes := GDelta(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "dddv" // DDeltaDvol
CGBlackScholes := GDdeltaDvol(S, x, T, r, b, v) / 100
else if OutPutFlag == "e" // Elasticity
CGBlackScholes := GElasticity(CallPutFlag, S, x, T, r, b, v)
//GAMMA GREEKS
else if OutPutFlag == "g" // Gamma
CGBlackScholes := GGamma(S, x, T, r, b, v)
else if OutPutFlag == "gp" // GammaP
CGBlackScholes := GGammaP(S, x, T, r, b, v)
else if OutPutFlag == "s" // 'DgammaDspot/speed
CGBlackScholes := GDgammaDspot(S, x, T, r, b, v)
else if OutPutFlag == "gv" // 'DgammaDvol/Zomma
CGBlackScholes := GDgammaDvol(S, x, T, r, b, v) / 100
//VEGA GREEKS
else if OutPutFlag == "v" // Vega
CGBlackScholes := GVega(S, x, T, r, b, v) / 100
else if OutPutFlag == "dvdv" // DvegaDvol/Vomma
CGBlackScholes := GDvegaDvol(S, x, T, r, b, v) / 10000
else if OutPutFlag == "vp" // VegaP
CGBlackScholes := GVegaP(S, x, T, r, b, v)
//THETA GREEKS
else if OutPutFlag == "t" // Theta
CGBlackScholes := GTheta(CallPutFlag, S, x, T, r, b, v) / 365
//RATE/CARRY GREEKS
else if OutPutFlag == "r" // Rho
CGBlackScholes := GRho(CallPutFlag, S, x, T, r, b, v) / 100
//'PROB GREEKS
else if OutPutFlag == "dx" // 'StrikeDelta
CGBlackScholes := GStrikeDelta(CallPutFlag, S, x, T, r, b, v)
else if OutPutFlag == "dxdx" // 'Risk Neutral Density
CGBlackScholes := GRiskNeutralDensity(S, x, T, r, b, v)
CGBlackScholes
gBlackScholesImpVolBisection(string CallPutFlag, float S, float x, float T, float r, float b, float cm)=>
float vLow = 0
float vHigh= 0
float vi = 0
float cLow = 0
float cHigh = 0
float epsilon = 0
int counter = 0
float gBlackScholesImpVolBisection = 0
vLow := 0.005
vHigh := 4
epsilon := 1E-08
cLow := GBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := GBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
while math.abs(cm - GBlackScholes(CallPutFlag, S, x, T, r, b, vi)) > epsilon
counter += 1
if counter == 100
gBlackScholesImpVolBisection := 0
break
if GBlackScholes(CallPutFlag, S, x, T, r, b, vi) < cm
vLow := vi
else
vHigh := vi
cLow := GBlackScholes(CallPutFlag, S, x, T, r, b, vLow)
cHigh := GBlackScholes(CallPutFlag, S, x, T, r, b, vHigh)
vi := vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow)
gBlackScholesImpVolBisection := vi
gBlackScholesImpVolBisection
gVega(float S, float x, float T, float r, float b, float v)=>
float d1 = 0
float GVega = 0
d1 := (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T))
GVega := S * math.exp((b - r) * T) * nd(d1) * math.sqrt(T)
GVega
gImpliedVolatilityNR(string CallPutFlag, float S, float x, float T, float r, float b, float cm, float epsilon)=>
float vi = 0
float ci = 0
float vegai = 0
float minDiff = 0
float GImpliedVolatilityNR = 0
vi := math.sqrt(math.abs(math.log(S / x) + r * T) * 2 / T)
ci := GBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
while math.abs(cm - ci) >= epsilon and math.abs(cm - ci) <= minDiff
vi := vi - (ci - cm) / vegai
ci := GBlackScholes(CallPutFlag, S, x, T, r, b, vi)
vegai := gVega(S, x, T, r, b, vi)
minDiff := math.abs(cm - ci)
if math.abs(cm - ci) < epsilon
GImpliedVolatilityNR := vi
else
GImpliedVolatilityNR := 0
GImpliedVolatilityNR
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Spot Price Settings")
srcin = input.string("Close", "Spot Price", group= "Spot Price Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
float K = input.float(275, "Strike Price", group = "Basic Settings")
string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings")
string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings")
float rf = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100
string rhocmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings")
float v = input.float(40., "% Volatility", group = "Rates Settings") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Historical Volatility Settings", tooltip = "Not used in calculation. This is here for comparison to implied volatility")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Historical Volatility Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
string txtsize = input.string("Auto", title = "Expiry Second", options = ["Small", "Normal", "Tiny", "Auto", "Large"], group = "UI Options")
string outsize = switch txtsize
"Small"=> size.small
"Normal"=> size.normal
"Tiny"=> size.tiny
"Auto"=> size.auto
"Large"=> size.large
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float rhocmpvalue = switch rhocmp
Continuous=> 0
PeriodRate=> math.max(1 / T, 1)
Annual=> 1
SemiAnnual=> 2
Quaterly=> 4
Monthly=> 12
=> 0
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
sideout = side == "Long" ? 1 : -1
kouta = convertingToCCRate(rf, rhocmpvalue)
price = CGBlackScholes("p", OpType, spot, K, T, kouta, kouta, v)
Delta = CGBlackScholes("d", OpType, spot, K, T, kouta, kouta, v) * sideout
Elasticity = CGBlackScholes("e", OpType, spot, K, T, kouta, kouta, v) * sideout
Gamma = CGBlackScholes("g", OpType, spot, K, T, kouta, kouta, v) * sideout
DgammaDvol = CGBlackScholes("gv", OpType, spot, K, T, kouta, kouta, v) * sideout
GammaP = CGBlackScholes("gp", OpType, spot, K, T, kouta, kouta, v) * sideout
Vega = CGBlackScholes("v", OpType, spot, K, T, kouta, kouta, v) * sideout
DvegaDvol = CGBlackScholes("dvdv", OpType, spot, K, T, kouta, kouta, v) * sideout
VegaP = CGBlackScholes("vp", OpType, spot, K, T, kouta, kouta, v) * sideout
Theta = CGBlackScholes("t", OpType, spot, K, T, kouta, kouta, v) * sideout
Rho = CGBlackScholes("r", OpType, spot, K, T, kouta, kouta, v) * sideout
DDeltaDvol = CGBlackScholes("dddv", OpType, spot, K, T, kouta, kouta, v) * sideout
Speed = CGBlackScholes("s", OpType, spot, K, T, kouta, kouta, v) * sideout
DeltaX = CGBlackScholes("dx", OpType, spot, K, T, kouta, kouta, v) * sideout
RiskNeutralDensity = CGBlackScholes("dxdx", OpType, spot, K, T, kouta, kouta, v) * sideout
impvolbi = gBlackScholesImpVolBisection(OpType, spot, K, T, kouta, kouta, price)
impvolnewt = gImpliedVolatilityNR(OpType, spot, K, T, kouta, kouta, price, 0.00001)
var testTable = table.new(position = position.middle_right, columns = 1, rows = 34, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = "Black-Scholes 1973 Options on Non-Dividend Paying Stocks", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 1, text = "Option Type: " + OpType, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 2, text = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 3, text = "Spot Price: " + str.tostring(spot, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 4, text = "Strike Price: " + str.tostring(K, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 5, text = "% Risk-free Rate: " + str.tostring(rf * 100, "##.##") + "%\n" + "Compounding Type: " + rhocmp + "\nCC Rate: " + str.tostring(kouta * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 6, text = "% Volatility (annual): " + str.tostring(v * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 7, text = "Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 8, text = "Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 9, text = "Calculated Values", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 10, text = "Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 11, text = "Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 12, text = "Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 13, text = OpType + " Option Price", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 14, text = "Forward Price: " + str.tostring(spot * math.exp(kouta * T), format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 15, text = "Price: " + str.tostring(price, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 16, text = "Analytical Greeks", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 17, text = "Delta Δ: " + str.tostring(Delta, "##.#####"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 18, text = "Elasticity Λ: " + str.tostring(Elasticity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 19, text = "Gamma Γ: " + str.tostring(Gamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 20, text = "DGammaDvol: " + str.tostring(DgammaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 21, text = "GammaP Γ: " + str.tostring(GammaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 22, text = "Vega: " + str.tostring(Vega, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 23, text = "DVegaDvol: " + str.tostring(DvegaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 24, text = "VegaP: " + str.tostring(VegaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 25, text = "Theta Θ (1 day): " + str.tostring(Theta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 26, text = "Rho ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 27, text = "DDeltaDvol: " + str.tostring(DDeltaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 28, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 29, text = "Strike Delta: " + str.tostring(DeltaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 30, text = "Risk Neutral Density: " + str.tostring(RiskNeutralDensity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 31, text = "Implied Volatility Calculation", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 32, text = "Implied Volatility Bisection: " + str.tostring(impvolbi * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
table.cell(table_id = testTable, column = 0, row = 33, text = "Implied Volatility Newton Raphson: " + str.tostring(impvolnewt * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
|
SMA 10/20/50 by Bull Bear Investing Baby | https://www.tradingview.com/script/S9XlKGEx-SMA-10-20-50-by-Bull-Bear-Investing-Baby/ | BullBearInvesting | https://www.tradingview.com/u/BullBearInvesting/ | 12 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Vinvest2020
//@version=4
// Pine Script v4
// @author V Invest
// study(title, shortitle, overlay, format, precision)
// https://www.tradingview.com/pine-script-docs/en/v4/annotations/study_annoation.html
study(shorttitle="SMA 10/20/50 by BBA Baby", title="SMA 10/20/50 by Bull Bear Investing Baby", overlay=true)
// MAPeriod is a variable used to stor the indicator lookback period. In this case, from the input
// input - https://www.tradingview.com/pine-script-docs/en/v4/annotations/Script_inputs.html
MA1Period = input(10, title="1MA")
MA2Period = input(20, title="2MA")
MA3Period = input(50, title="3MA")
// MA is a variable used to store the actual moving average value. In this case, from the sma() buil-in function
// sma - https://www.tradingview.com/pine-script-reference/v4/#fun_sma
MA1 = sma(close, MA1Period)
MA2 = sma(close, MA2Period)
MA3 = sma(close, MA3Period)
// plot - This will draw the information on the chart
// plot - https://www.tradingview.com/pine-script-docs/en/v4/annotations/plot_autotion.html
plot(MA1, color=#66ff00, linewidth=1)
plot(MA2, color=#FF0000, linewidth=1)
plot(MA3, color=#0000FF, linewidth=1) |
Invest-Long : Script for quick checks before investing | https://www.tradingview.com/script/SLIYfZ01-Invest-Long-Script-for-quick-checks-before-investing/ | rvc8280 | https://www.tradingview.com/u/rvc8280/ | 60 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rvc8280
//@version=5
indicator("LongTerm Investing",shorttitle="Longterm", overlay = true)
// Chec kon Daily, Weekly, Monthly time frames
tf1 = "1D"
tf2 = "1W"
tf3 = "1M"
var stats = table.new(position = position.bottom_right, columns = 18, rows = 18, bgcolor = color.white, border_width = 1, border_color=color.black, frame_color=color.black, frame_width=1)
table.cell(table_id = stats, column = 0, row = 0 , text = "D-RSI ", text_color=color.black)
table.cell(table_id = stats, column = 0, row = 1 , text = "W-RSI ", text_color=color.black)
table.cell(table_id = stats, column = 0, row = 2 , text = "M-RSI ", text_color=color.black)
expr = ta.rsi(close, 14)
//RSI on all 3 time frames all should be green and D>W>M
rs1 = request.security(syminfo.tickerid , tf1, expr)
rs2 = request.security(syminfo.tickerid , tf2, expr)
rs3 = request.security(syminfo.tickerid , tf3, expr)
table.cell(table_id = stats, column = 1, row = 0 , text = " "+str.tostring(math.round(rs1,1)), bgcolor=color.white, text_color=color.green)
table.cell(table_id = stats, column = 1, row = 1 , text = " " +str.tostring(math.round(rs2,1)), bgcolor=color.white, text_color=color.green)
table.cell(table_id = stats, column = 1, row = 2 , text = " " +str.tostring(math.round(rs3,1)), bgcolor=color.white, text_color=color.green)
get_ma_htf(tf, len)=> request.security(syminfo.tickerid, tf, ta.sma(close, len)[1])
//Check Close is above 20 SMA and 50 SMA on Daily / Weekly / Monthly time frames
d_e_20 = get_ma_htf(tf1, 20)
w_e_20 = get_ma_htf(tf2, 20)
m_e_20 = get_ma_htf(tf3, 20)
d_e_50 = get_ma_htf(tf1, 50)
w_e_50 = get_ma_htf(tf2, 50)
m_e_50 = get_ma_htf(tf3, 50)
table.cell(table_id = stats, column = 2, row = 0 , text = "C>D-20 ", bgcolor=close>d_e_20?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 2, row = 1 , text = "C>W-20 ", bgcolor=close>w_e_20?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 2, row = 2 , text = "C>M-20 ", bgcolor=close>m_e_20?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 3, row = 0 , text = "C>D-50 ", bgcolor=close>d_e_50?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 3, row = 1 , text = "C>W-50 ", bgcolor=close>w_e_50?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 3, row = 2 , text = "C>M-50 ", bgcolor=close>m_e_50?color.green:color.red, text_color=color.white)
//Check SMA 13> SMA 34, SMA 34 > SMA 55 and SMA 20 > SMA 50 on Daily / Weekly time frames
d_e_13 = get_ma_htf(tf1, 13)
d_e_34 = get_ma_htf(tf1, 34)
d_e_55 = get_ma_htf(tf1, 55)
table.cell(table_id = stats, column = 4, row = 0 , text = "D 13>34 ", bgcolor=d_e_13>d_e_34?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 4, row = 1 , text = "D 34>55 ", bgcolor=d_e_34>d_e_55?color.green:color.red, text_color=color.white)
w_e_13 = get_ma_htf(tf2, 13)
w_e_34 = get_ma_htf(tf2, 34)
w_e_55 = get_ma_htf(tf2, 55)
table.cell(table_id = stats, column = 5, row = 0 , text = "W 13>34 ", bgcolor=w_e_13>w_e_34?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 5, row = 1 , text = "W 34>55 ", bgcolor=w_e_34>w_e_55?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 4, row = 2 , text = "D 20>50 ", bgcolor=d_e_20>d_e_50?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 5, row = 2 , text = "W 20>50 ", bgcolor=w_e_20>w_e_50?color.green:color.red, text_color=color.white)
// Check Current close is above Weekly Pivot and Monthly Pivot. And also verify Close is above 4 Week High.
expr_pivot = (high + low + close) / 3.0
wk_piv = request.security(syminfo.tickerid , tf2, expr_pivot[1])
month_piv = request.security(syminfo.tickerid , tf3, expr_pivot[1])
table.cell(table_id = stats, column = 6, row = 0 , text = "C>WK-P", bgcolor=close>wk_piv?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 6, row = 1 , text = "C>Mo-P", bgcolor=close>month_piv?color.green:color.red, text_color=color.white)
expr_4wkhigh = ta.highest(4)
wk4_high = request.security(syminfo.tickerid , tf2, expr_4wkhigh)
table.cell(table_id = stats, column = 6, row = 2 , text = "C>4WK-H", bgcolor=close>wk4_high[1]?color.green:color.red, text_color=color.white)
// Verify Close is above Dail VWMA, Daily VWMA is > Weekly VWMA and Weekly > Monthly.
scrp_tkr = syminfo.ticker
expr_2 = ta.vwma(hlc3, 20)
v_wma(tf) => request.security(scrp_tkr,tf,expr_2)
vwma_D = v_wma('D')
vwma_W = v_wma('W')
vwma_M = v_wma('M')
table.cell(table_id = stats, column = 7, row = 0 , text = "C>D-VWMA", bgcolor=close>vwma_D?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 7, row = 1 , text = "D>W-VWMA", bgcolor=vwma_D>vwma_W?color.green:color.red, text_color=color.white)
table.cell(table_id = stats, column = 7, row = 2 , text = "W>M-VWMA", bgcolor=vwma_W>vwma_M?color.green:color.red, text_color=color.white)
// Similarly you can add more checks based on different time frames
|
Trend Suggestions | https://www.tradingview.com/script/3IU1M6wL-Trend-Suggestions/ | VVVfV | https://www.tradingview.com/u/VVVfV/ | 182 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © VVVfV
//@version=5
indicator(title="Trend Suggestions",shorttitle="Trend Suggestions",overlay=true)
//Notes
//This brings together a number of variables to produce trend predictions that could be utilized as decision-making tools.
//Uses the aforementioned price and volume derivatives
//- A moving average and three weighted moving averages (WMA1, WMA2, WMA3)
//- Super Trend Line (ST)
//- Opening Range Breakout on Five Minutes, Resistance Bands Pocket pivots , support, and price volume
//The Direction is determined by the High and Low Bands of WMAs and the Supertrend Line, which are used to determine the Upper and Lower Lines around the Price. When the price passes below the lower boundary of the band, a downtrend is said to have begun.
//Similarly, for an uptrend, this continues until the price passes over the upper edge of the band. Teal for an uptrend and fuchsia for a downturn area shared by the band to identify the trend.
//The first five minutes of the breakout lines have a tiny buffer augmentation of 11% applied to them.
//Based on what has been observed, support and resistance zones have been somewhat changed from the figures that are often utilized (might work other markets as well)
//The markings that may be seen are as follows:
//- Blue Triangle indicates a pocket pivot with an upward bias;
//- Maroon Triangle indicates a pocket pivot with a downward bias;
//- Teal colored Diamonds indicate price upthrusts and potential trend confirmation locations, depending on success or failure.
//- Similar backdrop color changes that look as vertical shading are also used to identify them.
//- Fuchsia-colored diamonds indicate price declines and a potential trend, depending on whether it persists or fails.
//- Dark green and maroon square boxes indicate potential price reversals in the support and resistance bands, respectively.
//Added the ability to choose the time frame for the opening band
//Added calculation for Candle Strength
//Candle Strength is based on the clos of a bar in relation to its present range, lookback period range, and placement in relation to band
//This is disabled by default to reduce clutter, but it can be enabled if one wants to give the trend status a numerical value.
//It goes without saying that this work is derived from numerous other open-source community initiatives.
//Feel free to adjust anything you'd like, and we appreciate any feedback.
//paramters
FASTERMA = input.int(title='WMA LENGTH FAST (Min 2)', defval=20,minval=2, step=2)
SLOWERMA = input.int(title='WMA LENGTH SLOW (Min 6)', defval=40,minval=6, step=2)
MIDMA = math.round((FASTERMA+SLOWERMA)/2)
//supertrend calculation
Periods = input(title='ATR Period', defval=10)
src = input(hl2, title='Source')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=1.5)
changeATR = input(title='Change ATR Calculation Method ?', defval=true)
atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
up = src - Multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
ST = if trend == 1
up
else
dn
//wma calculation
WMA1 = ta.wma(close, FASTERMA)
WMA2 = ta.wma(close, MIDMA)
WMA3 = ta.wma(close, SLOWERMA)
MAXLINE = math.max(ST,WMA1,WMA2,WMA3)
MINLINE = math.min(ST,WMA1,WMA2,WMA3)
DIRECTION = ta.barssince(close<MINLINE)-ta.barssince(close>MAXLINE)+ta.barssince(close<MAXLINE)-ta.barssince(close>MINLINE)
plotMAXLINE = plot(MAXLINE,"MAXLINE",color = color.new(color.black,10),linewidth = 1,style=plot.style_stepline)
plotMINLINE = plot(MINLINE,"MINLINE",color = color.new(color.black,10),linewidth = 1,style=plot.style_stepline)
fill(plotMAXLINE, plotMINLINE, color = DIRECTION>0?color.new(color.teal, 80):color.new(color.fuchsia, 80))
//Line Based on First 5 Min Range
openbarfrequency = input.string(defval="5",title="Open Range Fequency",options=["5","15","30","45","60","120","240"])
upobon = input(true, title='Opening Range High')
downobon = input(true, title='Opening Range Low')
is_newbar(res) =>
ta.change(time(res)) != 0
adopt(r, s) =>
request.security(syminfo.tickerid, r, s)
//high_range = valuewhen(is_newbar('D'),high,0)
//low_range = valuewhen(is_newbar('D'),low,0)
high_rangeL = ta.valuewhen(is_newbar('D'), high, 0)
low_rangeL = ta.valuewhen(is_newbar('D'), low, 0)
diff = (high_rangeL - low_rangeL) * 0.11
upob = plot(upobon and timeframe.isminutes ? adopt(openbarfrequency, high_rangeL) : na, color=color.new(#009900, 0), linewidth=1, style=plot.style_line)
downob = plot(downobon and timeframe.isminutes ? adopt(openbarfrequency, low_rangeL) : na, color=color.new(#ff0000, 0), linewidth=1, style=plot.style_line)
diffupob = plot(upobon and timeframe.isminutes ? adopt(openbarfrequency, high_rangeL + diff) : na, color=color.new(#009900, 0), linewidth=1, style=plot.style_line)
diffdownob = plot(downobon and timeframe.isminutes ? adopt(openbarfrequency, low_rangeL - diff) : na, color=color.new(#ff0000, 0), linewidth=1, style=plot.style_line)
//pocket pivot
myMaxVolume = volume
greenDay = close > open
myVolume1 = volume[1]
myVolume2 = volume[2]
myVolume3 = volume[3]
myVolume4 = volume[4]
myVolume5 = volume[5]
myVolume6 = volume[6]
myVolume7 = volume[7]
myVolume8 = volume[8]
myVolume9 = volume[9]
//make all upday volumes = 0
if close[1] > open[1]
myVolume1 := 0
myVolume1
if close[2] > open[2]
myVolume2 := 0
myVolume2
if close[3] > open[3]
myVolume3 := 0
myVolume3
if close[4] > open[4]
myVolume4 := 0
myVolume4
if close[5] > open[5]
myVolume5 := 0
myVolume5
if close[6] > open[6]
myVolume6 := 0
myVolume6
if close[7] > open[7]
myVolume7 := 0
myVolume7
if close[8] > open[8]
myVolume8 := 0
myVolume8
if close[9] > open[9]
myVolume9 := 0
myVolume9
// if any down days have volumes greater then the current volume, then it's not a pocket pivot
pocketPivot = myVolume1 < myMaxVolume and myVolume2 < myMaxVolume and myVolume3 < myMaxVolume and myVolume4 < myMaxVolume and myVolume5 < myMaxVolume and myVolume6 < myMaxVolume and myVolume7 < myMaxVolume and myVolume8 < myMaxVolume and myVolume9 < myMaxVolume
pocketPivotDay = pocketPivot and greenDay //only show pocket pivots on up days
plotshape(pocketPivotDay ? 1 : 0, style=shape.triangleup, location=location.belowbar, color=color.new(color.blue, 0), size=size.small)
//pocket pivot Dn
myMaxVolumeD = volume
redDay = close < open
myVolume1D = volume[1]
myVolume2D = volume[2]
myVolume3D = volume[3]
myVolume4D = volume[4]
myVolume5D = volume[5]
myVolume6D = volume[6]
myVolume7D = volume[7]
myVolume8D = volume[8]
myVolume9D = volume[9]
//make all upday volumes = 0
if close[1] < open[1]
myVolume1D := 0
myVolume1D
if close[2] < open[2]
myVolume2D := 0
myVolume2D
if close[3] < open[3]
myVolume3D := 0
myVolume3D
if close[4] < open[4]
myVolume4D := 0
myVolume4D
if close[5] < open[5]
myVolume5D := 0
myVolume5D
if close[6] < open[6]
myVolume6D := 0
myVolume6D
if close[7] < open[7]
myVolume7D := 0
myVolume7D
if close[8] < open[8]
myVolume8D := 0
myVolume8D
if close[9] < open[9]
myVolume9D := 0
myVolume9D
// if any down days have volumes greater then the current volume, then it's not a pocket pivot
pocketPivotD = myVolume1D < myMaxVolumeD and myVolume2D < myMaxVolumeD and myVolume3D < myMaxVolumeD and myVolume4D < myMaxVolumeD and myVolume5D < myMaxVolumeD and myVolume6D < myMaxVolumeD and myVolume7D < myMaxVolumeD and myVolume8D < myMaxVolumeD and myVolume9D < myMaxVolumeD
pocketPivotDayD = pocketPivotD and redDay //only show pocket pivots on dn days
plotshape(pocketPivotDayD ? 1 : 0, style=shape.triangledown, location=location.abovebar, color=color.new(color.maroon, 0), size=size.small)
//support resistance lines
P1 = high - ((high-low)*0.77)
P2 = low + ((high-low)*0.77)
S1 = low - ((high-low)*0.22)
S2 = low - ((high-low)*0.44)
R1 = high + ((high-low)*0.22)
R2 = high + ((high-low)*0.44)
//Checkbox inputs
CPlot = input(title='Plot Central Pivot?', defval=true)
DayS1R1 = input(title='Plot Daiy S1/R1?', defval=true)
DayS2R2 = input(title='Plot Daiy S2/R2?', defval=true)
//******************DAYWISE CPR & PIVOTS**************************
// Getting daywise CPR
DayP1 = request.security(syminfo.tickerid, 'D', P1[1], barmerge.gaps_off, barmerge.lookahead_on)
DayP2 = request.security(syminfo.tickerid, 'D', P2[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks daywse for CPR
P1Colour = DayP1 != DayP1[1] ? na : color.purple
P2Colour = DayP2 != DayP2[1] ? na : color.purple
//Plotting daywise CPR
plot(CPlot ? DayP1 : na, title='P1', color=P1Colour, style=plot.style_line, linewidth=1)
plot(CPlot ? DayP2 : na, title='P2', color=P2Colour, style=plot.style_line, linewidth=1)
// Getting daywise Support levels
DayS1 = request.security(syminfo.tickerid, 'D', S1[1], barmerge.gaps_off, barmerge.lookahead_on)
DayS2 = request.security(syminfo.tickerid, 'D', S2[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for daywise Support levels
DayS1Color = DayS1 != DayS1[1] ? na : color.black
DayS2Color = DayS2 != DayS2[1] ? na : color.black
//Plotting daywise Support levels
PLOTS1 = plot(DayS1R1 ? DayS1 : na, title='D-S1', color=DayS1Color, style=plot.style_line, linewidth=2)
PLOTS2 = plot(DayS2R2 ? DayS2 : na, title='D-S2', color=DayS2Color, style=plot.style_line, linewidth=1)
// Getting daywise Resistance levels
DayR1 = request.security(syminfo.tickerid, 'D', R1[1], barmerge.gaps_off, barmerge.lookahead_on)
DayR2 = request.security(syminfo.tickerid, 'D', R2[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for daywise Support levels
DayR1Color = DayR1 != DayR1[1] ? na : color.maroon
DayR2Color = DayR2 != DayR2[1] ? na : color.maroon
//Plotting daywise Resistance levels
PLOTR1 = plot(DayS1R1 ? DayR1 : na, title='D-R1', color=DayR1Color, style=plot.style_line, linewidth=3)
PLOTR2 = plot(DayS2R2 ? DayR2 : na, title='D-R2', color=DayR2Color, style=plot.style_line, linewidth=2)
fill(PLOTR1, PLOTR2, color=color.new(color.purple, 90), title='R1R2')
fill(PLOTS1, PLOTS2, color=color.new(color.teal, 90), title='S1S2')
//TREND SUGGESTIONS
//backgroundcolor
bgcolor(close>ta.highest(low,SLOWERMA) and close> (ta.highest(high,5)+ta.lowest(high,5))/2 and close > (high+low)/2 and close > WMA3 and (close>DayR2 or close<DayR1) and MAXLINE > MAXLINE[1] and MINLINE > MINLINE[1] and MAXLINE > WMA3 and close > DayP1 and close > DayS1 and close > adopt('5', low_rangeL - diff)? color.new(color.teal, 90) : color.new(color.gray, 100))
plotshape(close>ta.highest(low,SLOWERMA) and close> (ta.highest(high,5)+ta.lowest(high,5))/2 and close > (high+low)/2 and close > WMA3 and (close>DayR2 or close<DayR1) and MAXLINE > MAXLINE[1] and MINLINE > MINLINE[1] and MAXLINE > WMA3 and close > DayP1 and close > DayS1 and close > adopt('5', low_rangeL - diff), style=shape.diamond, color=color.new(color.teal, 0),location=location.bottom,size=size.small)
plotshape(close>ta.lowest(high,SLOWERMA) and close> (ta.highest(low,2)+ta.lowest(low,2))/2 and close > (high+low)/2 and MAXLINE>DayS2 and low < DayS1 and high > DayS2, style=shape.square, color=color.new(#184419, 0),location=location.bottom,size=size.small)
bgcolor(close>ta.lowest(high,SLOWERMA) and close> (ta.highest(low,2)+ta.lowest(low,2))/2 and close > (high+low)/2 and MAXLINE>DayS2 and low < DayS1 and high > DayS2? color.new(color.blue, 90) : color.new(color.gray, 100))
bgcolor(close<ta.lowest(high,SLOWERMA) and close< (ta.highest(low,5)+ta.lowest(low,5))/2 and close < (high+low)/2 and close < WMA3 and (close>DayS1 or close<DayS2) and MAXLINE < MAXLINE[1] and MINLINE < MINLINE[1] and MINLINE < WMA3 and close < DayP2 and close < DayR1 and close < adopt('5', high_rangeL + diff)? color.new(color.fuchsia, 90) : color.new(color.gray, 100))
plotshape(close<ta.lowest(high,SLOWERMA) and close< (ta.highest(low,5)+ta.lowest(low,5))/2 and close < (high+low)/2 and close < WMA3 and (close>DayS1 or close<DayS2) and MAXLINE < MAXLINE[1] and MINLINE < MINLINE[1] and MINLINE < WMA3 and close < DayP2 and close < DayR1 and close < adopt('5', high_rangeL + diff), style=shape.diamond, color=color.new(color.fuchsia, 0),location=location.top,size=size.small)
plotshape(close<ta.highest(low,SLOWERMA) and close< (ta.highest(high,2)+ta.lowest(high,2))/2 and close < (high+low)/2 and MINLINE<DayR2 and high < DayR2 and low > DayR1, style=shape.square, color=color.new(color.maroon, 0),location=location.top,size=size.small)
bgcolor(close<ta.highest(low,SLOWERMA) and close< (ta.highest(high,2)+ta.lowest(high,2))/2 and close < (high+low)/2 and MINLINE<DayR2 and high < DayR2 and low > DayR1? color.new(color.maroon, 90) : color.new(color.gray, 100))
//Candle Strength
candlestrength = input(false, title='Label Candle Strength')
C1TO_PC = close > close[1]?1:-1
C1TO_PH = close > high[1]?1:0
C1TO_PL = close < low[1]?-1:0
C2TO_O = close > open?1:-1
C2TO_H = close == high?1:0
C2TO_L = close == low?-1:0
C2TO_M = close > (high+low)/2?1:-1
C3TO_H = close > math.max(ta.highest(low,5),ta.lowest(high,5))?1:0
C3TO_L = close < math.min(ta.highest(low,5),ta.lowest(high,5))?-1:0
C3TO_M = close > (ta.highest(low,5)+ta.lowest(high,5))/2?1:-1
C4TO_H = close > math.max(ta.highest(low,SLOWERMA),ta.lowest(high,SLOWERMA))?1:0
C4TO_L = close < math.min(ta.highest(low,SLOWERMA),ta.lowest(high,SLOWERMA))?-1:0
C4TO_M = close > (ta.highest(low,SLOWERMA)+ta.lowest(high,SLOWERMA))/2?1:-1
C5TO_H = close > math.max(ta.highest(low,SLOWERMA*2),ta.lowest(high,SLOWERMA*2))?1:0
C5TO_L = close < math.min(ta.highest(low,SLOWERMA*2),ta.lowest(high,SLOWERMA*2))?-1:0
C5TO_M = close > (ta.highest(low,SLOWERMA*2)+ta.lowest(high,SLOWERMA*2))/2?1:-1
C6BNDH = close > MAXLINE?1:-1
C6BNDL = close < MINLINE?-1:1
STRENGTH = math.round((C1TO_PC + C1TO_PH + C1TO_PL + C2TO_O + C2TO_H + C2TO_L + C2TO_M + C3TO_H + C3TO_L + C3TO_M + C4TO_H + C4TO_L + C4TO_M + C5TO_H + C5TO_L + C5TO_M + C6BNDH + C6BNDL)/2)
if candlestrength
LABEL = label.new(bar_index, low-ta.atr(1),str.tostring(STRENGTH),yloc=STRENGTH > 0 ?yloc.belowbar:yloc.abovebar, color=STRENGTH > 0 ? color.rgb(32, 10, 33) : color.rgb(107, 10, 32), textcolor=color.white, style=STRENGTH > 0 ?label.style_label_up : label.style_label_down,size=size.small,text_font_family=font.family_monospace)
//end
|
Market Sessions [Kaspricci] | https://www.tradingview.com/script/CxhIz4HH/ | Kaspricci | https://www.tradingview.com/u/Kaspricci/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kaspricci
//@version=5
indicator("Market Sessions [Kaspricci]", shorttitle="Sessions", precision=0)
grp_title = "Defaul Session Times in GMT"
tooltip_lse = "London Stock Exchange opening hours from 7:00 - 15:30 GMT"
tooltip_nse = "New York Stock Exchange opening hours from 13:30 - 20:00 GMT"
tooltip_jse = "Tokyo Stock Exchange opening hours from 0:00 - 2:30 and 3:30 - 6:00 GMT"
tooltip_sse = "Sydney Stock Exchange opening hours from 23:00 - 05:00 GMT"
lse_session = "0700-1530:23456" // London Stock Exchange - 7:00 to 15:30 GMT
nse_session = "1330-2000:23456" // New York Stock Exchange - 13:30 to 20:00 GMT
tse_session = "0000-0600:23456" // Tokyo Stock Exchange - 0:00 to 2:30, 3:30 to 6:00 GMT
sse_session = "2300-0500:23456" // Sydney Stock Exchange - 23:00 to 05:00 GMT
show_lse_ses = input.bool(true, "", inline="LSE", group=grp_title)
timeframe_lse = input.session(defval=lse_session, group=grp_title, title="London Stock Exchange ---", inline="LSE", tooltip=tooltip_lse)
show_nse_ses = input.bool(true, "", inline="NSE", group=grp_title)
timeframe_nse = input.session(defval=nse_session, group=grp_title, title="New York Stock Exchange -", inline="NSE", tooltip=tooltip_nse)
show_tse_ses = input.bool(true, "", inline="JSE", group=grp_title)
timeframe_tse = input.session(defval=tse_session, group=grp_title, title="Tokyo Stock Exchange -----", inline="JSE", tooltip=tooltip_jse)
show_sse_ses = input.bool(true, "", inline="SSE", group=grp_title)
timeframe_sse = input.session(defval=sse_session, group=grp_title, title="Sydney Stock Exchange ---", inline="SSE", tooltip=tooltip_sse)
lse_time = time(timeframe.period, lse_session, "GMT")
nse_time = time(timeframe.period, nse_session, "GMT")
tse_time = time(timeframe.period, tse_session, "GMT")
sse_time = time(timeframe.period, sse_session, "GMT")
// transparnet line as lower border to avoid chart rescaling
hline(0, editable=false, color=color.new(color.black, 100))
// start position for session bars
float plot_position = -0.5
// top and bottom start position for session lables
float lbl_top_position = -0.2
float lbl_btm_position = -0.8
// London Session
var box lse_lable_box = na
if (show_lse_ses)
lbl_top_position += 1
lbl_btm_position += 1
plot_position += 1
box.delete(lse_lable_box)
lse_lable_box := box.new(last_bar_index+1, lbl_top_position, last_bar_index + 20, lbl_btm_position, text="London", bgcolor=na, border_color=color.new(color.black, 100), text_halign=text.align_left, text_color=color.black)
plot(show_lse_ses and lse_time ? plot_position : na, style=plot.style_linebr, linewidth=10, title="London Session", color=color.new(color.green, 50))
// New York Session
var box nse_lable_box = na
if (show_nse_ses)
lbl_top_position += 1
lbl_btm_position += 1
plot_position += 1
box.delete(nse_lable_box)
nse_lable_box := box.new(last_bar_index+1, lbl_top_position, last_bar_index + 20, lbl_btm_position, text="New York", bgcolor=na, border_color=color.new(color.black, 100), text_halign=text.align_left, text_color=color.black)
plot(show_nse_ses and nse_time ? plot_position : na, style=plot.style_linebr, linewidth=10, title="New York Session", color=color.new(color.blue, 50))
// Tokyo Session
var box tse_lable_box = na
if (show_tse_ses)
lbl_top_position += 1
lbl_btm_position += 1
plot_position += 1
box.delete(tse_lable_box)
tse_lable_box := box.new(last_bar_index+1, lbl_top_position, last_bar_index + 20, lbl_btm_position, text="Tokyo", bgcolor=na, border_color=color.new(color.black, 100), text_halign=text.align_left, text_color=color.black)
plot(show_tse_ses and tse_time ? plot_position : na, style=plot.style_linebr, linewidth=10, title="Tokyo Session", color=color.new(color.red, 50))
// Sydney Session
var box sse_lable_box = na
if (show_sse_ses)
lbl_top_position += 1
lbl_btm_position += 1
plot_position += 1
box.delete(sse_lable_box)
sse_lable_box := box.new(last_bar_index+1, lbl_top_position, last_bar_index + 20, lbl_btm_position, text="Sydney", bgcolor=na, border_color=color.new(color.black, 100), text_halign=text.align_left, text_color=color.black)
plot(show_sse_ses and sse_time ? plot_position : na, style=plot.style_linebr, linewidth=10, title="Sydney Session", color=color.new(color.orange, 50))
// transparent line as upper border to avoid chart rescaling
plot(lbl_top_position + 0.2, color=color.new(color.black, 100))
// last bar index line
var line currentbar = na
line.delete(currentbar[1])
currentbar := line.new(last_bar_index, 0, last_bar_index, lbl_top_position + 0.2, color=color.red, width=1)
|
Absolute KRI [vnhilton] | https://www.tradingview.com/script/bX5gQV3S-Absolute-KRI-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vnhilton
//@version=5
indicator("Absolute KRI [vnhilton]", "Absolute KRI", true, timeframe="", timeframe_gaps=true)
//Main Configuration
enableCandleColors = input.bool(true, "Enable Candle Colors?", "Candle colors for when candle close & candle ohlc is X standard deviations of the distance between close & moving average, away from the moving average")
src = input(close, "Source", tooltip="This will be used in calculating the KRI")
len = input.int(20, "MA Length", 1)
maType = input.string("SMA", "MA Type", ["ALMA", "EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"])
mult = input.float(2.0, "Std. Dev", 0.001, 50, tooltip="Standard Deviations")
kRIStdDevUpBGColor = color.rgb(0, 165, 49, 90)
kRIStdDevDownBGColor = color.rgb(255, 109, 90, 90)
//Moving Average (MA) Selection
ma(src, len, type) =>
switch type
"EMA" => ta.ema(src, len)
"HMA" => ta.hma(src, len)
"RMA" => ta.rma(src, len)
"SMA" => ta.sma(src, len)
"VWMA" => ta.vwma(src, len)
"WMA" => ta.wma(src, len)
//MA Assignment
mA = ma(src, len, maType)
//Calculations
kRI = src - mA
stdDev = mult * ta.stdev(math.abs(kRI), len)
kRIUpColor = math.abs(kRI) > stdDev ? color.rgb(0, 255, 0, 0) : color.rgb(0, 165, 49, 60)
kRIDownColor = math.abs(kRI) > stdDev ? color.rgb(255, 0, 0, 0) : color.rgb(255, 109, 90, 60)
fullyOutsideColor = (open > mA + stdDev and high > mA + stdDev and low > mA + stdDev and close > mA + stdDev) or (open < mA - stdDev and high < mA - stdDev and low < mA - stdDev and close < mA - stdDev) ? close >= open ? color.rgb(0, 0, 0, 1) : color.rgb(0, 0, 0, 0) : na
outsideColor = close > mA + stdDev or close < mA - stdDev ? close >= open ? color.rgb(0, 75, 22, 0) : color.rgb(103, 45, 37, 0) : na
//Plots
plot(stdDev, "Standard Deviation Band", color.rgb(255, 255, 255, 0))
kRILine = plot(math.abs(kRI), "Kairi Relative Index", kRI >= 0 ? kRIUpColor : kRIDownColor, 2)
base = plot(0, "Base", color.rgb(128, 128, 128, 0), style=plot.style_line)
fill(kRILine, base, kRI >= 0 ? kRIStdDevUpBGColor : kRIStdDevDownBGColor, "KRI Background Plot")
barcolor(enableCandleColors ? fullyOutsideColor : na)
barcolor(enableCandleColors ? outsideColor : na)
plotshape(kRI >= 0 and math.abs(kRI) > stdDev and math.abs(kRI[1]) <= stdDev[1], "Uptrend Outside STDDEV", shape.triangleup, location.top, color.rgb(0, 255, 0, 0), size=size.auto)
plotshape(kRI >= 0 and math.abs(kRI) <= stdDev and math.abs(kRI[1]) > stdDev[1], "Uptrend Inside STDDEV", shape.xcross, location.top, color.rgb(0, 165, 49, 60), size=size.auto)
plotshape(kRI < 0 and math.abs(kRI) > stdDev and math.abs(kRI[1]) <= stdDev[1], "Downtrend Outside STDDEV", shape.triangledown, location.top, color.rgb(255, 0, 0, 0), size=size.auto)
plotshape(kRI < 0 and math.abs(kRI) <= stdDev and math.abs(kRI[1]) > stdDev[1], "Downtrend Inside STDDEV", shape.xcross, location.top, color.rgb(255, 109, 90, 60), size=size.auto) |
Fibonacci MAs | https://www.tradingview.com/script/ylS9SN4f-Fibonacci-MAs/ | QuantNomad | https://www.tradingview.com/u/QuantNomad/ | 194 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © QuantNomad
//@version=5
indicator("Fibonacci MAs", overlay = true)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | INPUT |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
maType = input.string( "SMA", title = "Fibonacci Moving Average Type", options = ["SMA", "EMA", "WMA", "HMA", "VWMA", "SMMA", "DEMA"])
maSrce = input.source(close, title = "Moving Average Source")
showOnly = input.int(17, "Enable The First MA Lines Only", minval = 0, maxval = 17)
// Moving Averages
ma2Val = input.int(2, "", minval = 1, inline = "1", group = "Moving Averages")
ma2Col = input.color(#fafa6e, "", inline = "1", group = "Moving Averages")
ma2Shw = input.bool(true, " ", inline = "1", group = "Moving Averages")
ma3Val = input.int(3, "", minval = 1, inline = "1", group = "Moving Averages")
ma3Col = input.color(#dcf768, "", inline = "1", group = "Moving Averages")
ma3Shw = input.bool(true, "", inline = "1", group = "Moving Averages",
tooltip = "The Check Mark to Show/Hide Line, and it's Still Included in Calulation for Average Fibonacci of MAs Line")
ma5Val = input.int(5, "", minval = 1, inline = "2", group = "Moving Averages")
ma5Col = input.color(#bef363, "", inline = "2", group = "Moving Averages")
ma5Shw = input.bool(true, " ", inline = "2", group = "Moving Averages")
ma8Val = input.int(8, "", minval = 1, inline = "2", group = "Moving Averages")
ma8Col = input.color(#9ef05d, "", inline = "2", group = "Moving Averages")
ma8Shw = input.bool(true, "", inline = "2", group = "Moving Averages")
ma13Val = input.int(13, "", minval = 1, inline = "3", group = "Moving Averages")
ma13Col = input.color(#7eeb58, "", inline = "3", group = "Moving Averages")
ma13Shw = input.bool(true, " ", inline = "3", group = "Moving Averages")
ma21Val = input.int(21, "", minval = 1, inline = "3", group = "Moving Averages")
ma21Col = input.color(#5ee754, "", inline = "3", group = "Moving Averages")
ma21Shw = input.bool(true, "", inline = "3", group = "Moving Averages")
ma34Val = input.int(34, "", minval = 1, inline = "4", group = "Moving Averages")
ma34Col = input.color(#4fe260, "", inline = "4", group = "Moving Averages")
ma34Shw = input.bool(true, " ", inline = "4", group = "Moving Averages")
ma55Val = input.int(55, "", minval = 1, inline = "4", group = "Moving Averages")
ma55Col = input.color(#4cdd77, "", inline = "4", group = "Moving Averages")
ma55Shw = input.bool(true, "", inline = "4", group = "Moving Averages")
ma89Val = input.int(89, "", minval = 1, inline = "5", group = "Moving Averages")
ma89Col = input.color(#48d88e, "", inline = "5", group = "Moving Averages")
ma89Shw = input.bool(true, " ", inline = "5", group = "Moving Averages")
ma144Val = input.int(144, "", minval = 1, inline = "5", group = "Moving Averages")
ma144Col = input.color(#45d2a4, "", inline = "5", group = "Moving Averages")
ma144Shw = input.bool(true, "", inline = "5", group = "Moving Averages")
ma233Val = input.int(233, "", minval = 1, inline = "6", group = "Moving Averages")
ma233Col = input.color(#42ccb8, "", inline = "6", group = "Moving Averages")
ma233Shw = input.bool(true, " ", inline = "6", group = "Moving Averages")
ma377Val = input.int(377, "", minval = 1, inline = "6", group = "Moving Averages")
ma377Col = input.color(#3fbfc5, "", inline = "6", group = "Moving Averages")
ma377Shw = input.bool(true, "", inline = "6", group = "Moving Averages")
ma610Val = input.int(610, "", minval = 1, inline = "7", group = "Moving Averages")
ma610Col = input.color(#3fa0bd, "", inline = "7", group = "Moving Averages")
ma610Shw = input.bool(true, " ", inline = "7", group = "Moving Averages")
ma987Val = input.int(987, "", minval = 1, inline = "7", group = "Moving Averages")
ma987Col = input.color(#4183b2, "", inline = "7", group = "Moving Averages")
ma987Shw = input.bool(true, "", inline = "7", group = "Moving Averages")
ma1597Val = input.int(1597, "", minval = 1, inline = "8", group = "Moving Averages")
ma1597Col = input.color(#426aa7, "", inline = "8", group = "Moving Averages")
ma1597Shw = input.bool(true, " ", inline = "8", group = "Moving Averages")
ma2584Val = input.int(2584, "", minval = 1, inline = "8", group = "Moving Averages")
ma2584Col = input.color(#44579c, "", inline = "8", group = "Moving Averages")
ma2584Shw = input.bool(true, "", inline = "8", group = "Moving Averages")
ma4181Val = input.int(4181, "", minval = 1, inline = "9", group = "Moving Averages")
ma4181Col = input.color(#454792, "", inline = "9", group = "Moving Averages")
ma4181Shw = input.bool(true, " ", inline = "9", group = "Moving Averages")
aveShw = input.bool(true, "Show Average Fibonacci of MAs Line",
inline = "0", group = "Moving Averages")
aveCol = input.color(color.rgb(248, 61, 15), "", inline = "0", group = "Moving Averages")
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | CALCULATION |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
maType(len) =>
switch maType
"SMA" => ta.sma (maSrce, len)
"EMA" => ta.ema (maSrce, len)
"WMA" => ta.wma (maSrce, len)
"HMA" => ta.hma (maSrce, len)
"VWMA" => ta.vwma(maSrce, len)
"SMMA" =>
smma = 0.0, sma = ta.sma(maSrce, len)
smma := na(smma[1]) ? sma : (smma[1] * (len - 1) + maSrce) / len
"DEMA" => 2 * ta.ema(maSrce, len) - ta.ema(ta.ema(maSrce, len), len)
=> na
fibMA(num, len) =>
ma = float(na)
if num <= showOnly
ma := maType(len)
ma
// Plot MAs lines
plot(fibMA( 1, ma2Val ), title = "MA №01", color = ma2Shw ? ma2Col : color.new(ma2Col, 100))
plot(fibMA( 2, ma3Val ), title = "MA №02", color = ma3Shw ? ma3Col : color.new(ma3Col, 100))
plot(fibMA( 3, ma5Val ), title = "MA №03", color = ma5Shw ? ma5Col : color.new(ma5Col, 100))
plot(fibMA( 4, ma8Val ), title = "MA №04", color = ma8Shw ? ma8Col : color.new(ma8Col, 100))
plot(fibMA( 5, ma13Val ), title = "MA №05", color = ma13Shw ? ma13Col : color.new(ma13Col, 100))
plot(fibMA( 6, ma21Val ), title = "MA №06", color = ma21Shw ? ma21Col : color.new(ma21Col, 100))
plot(fibMA( 7, ma34Val ), title = "MA №07", color = ma34Shw ? ma34Col : color.new(ma34Col, 100))
plot(fibMA( 8, ma55Val ), title = "MA №08", color = ma55Shw ? ma55Col : color.new(ma55Col, 100))
plot(fibMA( 9, ma89Val ), title = "MA №09", color = ma89Shw ? ma89Col : color.new(ma89Col, 100))
plot(fibMA(10, ma144Val ), title = "MA №10", color = ma144Shw ? ma144Col : color.new(ma144Col, 100))
plot(fibMA(11, ma233Val ), title = "MA №11", color = ma233Shw ? ma233Col : color.new(ma233Col, 100))
plot(fibMA(12, ma377Val ), title = "MA №12", color = ma377Shw ? ma377Col : color.new(ma377Col, 100))
plot(fibMA(13, ma610Val ), title = "MA №13", color = ma610Shw ? ma610Col : color.new(ma610Col, 100))
plot(fibMA(14, ma987Val ), title = "MA №14", color = ma987Shw ? ma987Col : color.new(ma987Col, 100))
plot(fibMA(15, ma1597Val), title = "MA №15", color = ma1597Shw ? ma1597Col : color.new(ma1597Col, 100))
plot(fibMA(16, ma2584Val), title = "MA №16", color = ma2584Shw ? ma2584Col : color.new(ma2584Col, 100))
plot(fibMA(17, ma4181Val), title = "MA №17", color = ma4181Shw ? ma4181Col : color.new(ma4181Col, 100))
// Calculate The Average Fibonacci of MAs Lines
avgFibMA() =>
avgMA = float(na)
if aveShw and showOnly > 0
maArray = array.from(fibMA( 1, ma2Val ), fibMA( 2, ma3Val ),
fibMA( 3, ma5Val ), fibMA( 4, ma8Val ),
fibMA( 5, ma13Val ), fibMA( 6, ma21Val ),
fibMA( 7, ma34Val ), fibMA( 8, ma55Val ),
fibMA( 9, ma89Val ), fibMA(10, ma144Val ),
fibMA(11, ma233Val ), fibMA(12, ma377Val ),
fibMA(13, ma610Val ), fibMA(14, ma987Val ),
fibMA(15, ma1597Val), fibMA(16, ma2584Val),
fibMA(17, ma4181Val))
k = 0
if array.size(maArray) > 0
while k != array.size(maArray)
if na(array.get(maArray, k))
array.remove(maArray, k)
else
k += 1
avgMA := array.sum(maArray)/array.size(maArray)
avgMA
plot(avgFibMA(), title = "Average Fibonacci Lines", color = aveCol, linewidth = 3)
|
two_leg_spread_diff | https://www.tradingview.com/script/GLUaAWeU-two-leg-spread-diff/ | voided | https://www.tradingview.com/u/voided/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © voided
//@version=5
indicator("two_leg_spread_diff")
timeframe = input.timeframe("30", "timeframe")
leg1_sym = input.symbol("RB1!", "leg1_sym")
leg2_sym = input.symbol("HO1!", "leg2_sym")
lag = input.int(46, "lag")
anchor = input.bool(title = "anchor_to_session_start", defval = false)
if anchor and timeframe.isintraday
for i = 0 to 5000
if time[i + 1] - time[i + 2] != time[i + 2] - time[i + 3]
lag := i + 2
break
leg1 = request.security(leg1_sym, timeframe, close)
leg2 = request.security(leg2_sym, timeframe, close)
leg1_log_return = math.log(leg1 / leg1[lag])
leg2_log_return = math.log(leg2 / leg2[lag])
diff = leg1_log_return - leg2_log_return
var diffs = array.new_float()
var acc1 = array.new_int()
var acc2 = array.new_int()
array.push(diffs, diff)
diff_std = array.stdev(diffs)
if diff <= diff_std and diff >= -diff_std
array.push(acc1, 1)
else
array.push(acc1, 0)
if diff <= 2 * diff_std and diff >= 2 * -diff_std
array.push(acc2, 1)
else
array.push(acc2, 0)
plot(diff, color = leg1_log_return > 0 and leg2_log_return < 0 ? color.blue : leg1_log_return < 0 and leg2_log_return > 0 ? color.red : color.gray)
plot(0, color = color.new(color.gray, 50))
plot(diff_std, color = color.new(color.blue, 90))
plot(2 * diff_std, color = color.new(color.red, 90))
plot(-diff_std, color = color.new(color.blue, 90))
plot(2 * -diff_std, color = color.new(color.red, 90))
if barstate.islast
t = table.new(position.top_right, 2, 2)
fmt = "#.##"
table.cell(t, 0, 0, "acc 1")
table.cell(t, 0, 1, "acc 2")
table.cell(t, 1, 0, str.tostring(array.avg(acc1), fmt))
table.cell(t, 1, 1, str.tostring(array.avg(acc2), fmt)) |
Symbols at Highs & Lows | https://www.tradingview.com/script/W9rQ39lF-Symbols-at-Highs-Lows/ | jmosullivan | https://www.tradingview.com/u/jmosullivan/ | 59 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jmosullivan
// @version=5
// Created By jmosullivan
// MM Symbols Highs & Lows
// For the chosen symbols, this shows a table that indicates (a) if price is near the high or low of
// day, and (b) if price has broken above the high and low of yesterday. This can be a great indicator
// that a trend day is occurring in the market. You can customize the indicator to use up to 7 symbols
// of your choice. You can also customize the appearance so that it only displays when all symbols are
// at their highs or lows or have broken yesterday's level. Finally, you can customize the % threshold
// to use when measuring how close to the high/low of day price needs to be in order to be considered
// "at high/low of day".
indicator(title='MM Symbols Highs & Lows', shorttitle="MM Symbols HLs", overlay=true)
import jmosullivan/Table/1
import jmosullivan/Utils/3
// Constants
var COLOR_TRANSPARENT = color.rgb(255,255,255,100)
SPACE = " "
// Configuration
grp4 = "Symbols"
sym1 = input.string(group=grp4, defval="QQQ", title="Symbol 1")
sym2 = input.string(group=grp4, defval="IWM", title="Symbol 2")
sym3 = input.string(group=grp4, defval="XLF", title="Symbol 3")
sym4 = input.string(group=grp4, defval="XLV", title="Symbol 4")
sym5 = input.string(group=grp4, defval="", title="Symbol 5")
sym6 = input.string(group=grp4, defval="", title="Symbol 6")
sym7 = input.string(group=grp4, defval="", title="Symbol 7")
grp = "Today's Highs & Lows"
showHLs = input.string(group=grp, defval="Always", title="When to Show", options=["Always", "When SOME are at highs/lows", "When ALL are at highs/lows", "Never"], tooltip="If you don't want to clutter up your charts, you can choose to only show the highs & lows when one or more of the symbols is within the range % of the high or low of day.")
showHLsContent = input.string(group=grp, defval="% in Range", title="What to Show", options=["Words", "% in Range", "Both"], tooltip="In the table, you can choose to just see the word 'High', 'Low', or 'Mid' indicating where price is in the range, or you can choose to see the current % price is away from the top or bottom of the range, or both.")
threshold100 = input.float(group=grp, defval=10, title="% of Day Range", tooltip='When a symbol is within this percentage of the high or low of day, it is considered to be "at the high" or "at the low".')
threshold = threshold100 / 100
grp2 = "Yesterday's Highs & Lows"
showYesterdayBreaks = input.string(group=grp2, defval="Only on Breaks", title="When to Show", options=["Always", "Only on Breaks", "Never"], tooltip="If you don't want to clutter up your charts, you can choose to only show breaks of yesterday's high/low when they occur, or not show them at all.")
showBreakContent = input.string(group=grp2, defval="Both", title="What to Show", options=["Words", "% from break", "Both"], tooltip="In the table, you can choose to just see the word 'Break' when the high or low of previous day is violated (and 'Held' when not violated), or you can choose to see the current % price is away from the breaking point, or both.")
grp3 = "Appearance"
showHeadings = input.bool(group=grp3, defval=true, inline="title", title="Show Headings")
friendlyTextSize = input.string(group=grp3, defval="Tiny", title="Size / Position ", options=["Tiny", "Small", "Normal", "Large", "Huge"], inline="position and size")
textSize = Utils.getSizeFromString(friendlyTextSize)
friendlyPosition = input.string(group=grp3, defval="Top Right", title="", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], inline="position and size")
position = Utils.getPositionFromString(friendlyPosition)
verticalOffset = input.int(group=grp3, defval=0, title="Vertical Offset", minval=0, maxval=3, step=1, tooltip="The number of row-sized spaces to place the table away from the top or bottom (depending on the position chosen).")
colorBullishText = input.color(group=grp3, defval=color.rgb(5, 72, 8), title="Bullish Text / BG ", inline="1")
colorBullish = input.color(group=grp3, defval=color.rgb(75, 255, 178), title="", inline="1")
colorModerateText = input.color(group=grp3, defval=color.white, title="Moderate Text / BG", inline="2")
colorModerate = input.color(group=grp3, defval=color.rgb(40, 98, 255), title="", inline="2")
colorBearishText = input.color(group=grp3, defval=color.white, title="Bearish Text / BG ", inline="3")
colorBearish = input.color(group=grp3, defval=color.rgb(235, 46, 175), title="", inline="3")
// Types
type Level
string highs = "Highs"
string mids = "Mids"
string lows = "Lows"
string mixed = "Mixed"
type Globals
float threshold = 0
Level level = na
string allAtLevel = ""
int atHighsCount = 0
int atLowsCount = 0
int brokeYhodCount = 0
int brokeYlodCount = 0
type Symbol
string name
float hod = 0
float lod = 0
float last = 0
float yhod = 0
float ylod = 0
bool yhodBreak = false
bool ylodBreak = false
string level = "Mids"
float percentInRange = 0
// Functions
debug(collection, position = position.bottom_left) =>
t = array.from('symbol', 'hod', 'lod', 'yhod', 'ylod', 'yhod break', 'ylod break', 'level', 'percent in range')
m = matrix.new<string>()
matrix.add_row(m, 0, t)
for symbol in collection
matrix.add_row(m, matrix.rows(m), array.from(symbol.name, str.tostring(symbol.hod), str.tostring(symbol.lod), str.tostring(symbol.yhod), str.tostring(symbol.ylod), str.tostring(symbol.yhodBreak), str.tostring(symbol.ylodBreak), str.tostring(symbol.level), str.tostring(symbol.percentInRange)))
Table.fromMatrix(m, position)
requestSymbol(symbolString, globals) =>
[hod, lod, last, yhod, ylod] = request.security(symbolString, 'D', [high, low, close, high[1], low[1]])
Symbol symbol = na
if symbolString != '' and not na(hod)
percentInRange = (last - lod) / (hod - lod)
highThreshold = 1 - globals.threshold
symbol := Symbol.new(
symbolString,
hod,
lod,
last,
yhod,
ylod,
hod > yhod,
lod < ylod,
percentInRange >= highThreshold ? globals.level.highs : percentInRange <= globals.threshold ? globals.level.lows : globals.level.mids,
percentInRange
)
symbol
addSymbol(globals, collection, symbolString) =>
symbol = requestSymbol(symbolString, globals)
if not na(symbol)
// Count the number of symbols out of the mid-range
globals.atHighsCount += symbol.level == globals.level.highs ? 1 : 0
globals.atLowsCount += symbol.level == globals.level.lows ? 1 : 0
// Determine if all of the symbols are at a particular level together
if globals.allAtLevel == ''
globals.allAtLevel := symbol.level
else if globals.allAtLevel != symbol.level and globals.allAtLevel != globals.level.mixed
globals.allAtLevel := globals.level.mixed
// Count how many symbols are above their highs/lows of yesterday
globals.brokeYhodCount += symbol.yhodBreak ? 1 : 0
globals.brokeYlodCount += symbol.ylodBreak ? 1 : 0
// Add the symbol to the collection
array.push(collection, symbol)
// Indicator Logic
// Create a globals object to track information about all of the symbols
level = Level.new()
globals = Globals.new(threshold, level)
// Add all of the symbols to a collection
collection = array.new<Symbol>()
addSymbol(globals, collection, sym1)
addSymbol(globals, collection, sym2)
addSymbol(globals, collection, sym3)
addSymbol(globals, collection, sym4)
addSymbol(globals, collection, sym5)
addSymbol(globals, collection, sym6)
addSymbol(globals, collection, sym7)
// Determine if the highs/lows have been touched by any of the names
var hlsTouched = false
var yhodBreaks = false
var ylodBreaks = false
if session.isfirstbar_regular
hlsTouched := false
yhodBreaks := false
ylodBreaks := false
if not hlsTouched and globals.atHighsCount > 0 or globals.atLowsCount > 0
hlsTouched := true
if not yhodBreaks and globals.brokeYhodCount > 0
yhodBreaks := true
if not ylodBreaks and globals.brokeYlodCount > 0
ylodBreaks := true
someAtHLs = showHLs == "When SOME are at highs/lows" and (globals.atHighsCount > 0 or globals.atLowsCount > 0)
allAtHLs = showHLs == "When ALL are at highs/lows" and globals.allAtLevel != globals.level.mixed
_showHLs = showHLs == "Always" or someAtHLs or allAtHLs
_showYHODBreaks = showYesterdayBreaks == "Always" or (showYesterdayBreaks == "Only on Breaks" and yhodBreaks)
_showYLODBreaks = showYesterdayBreaks == "Always" or (showYesterdayBreaks == "Only on Breaks" and ylodBreaks)
showSymbols = _showHLs or _showYHODBreaks or _showYLODBreaks
// Loop through the collection building a matrix to be rendered
if barstate.islast and timeframe.in_seconds() <= timeframe.in_seconds('D')
m = matrix.new<Table.Cell>()
symArray = array.new<Table.Cell>()
hlArray = array.new<Table.Cell>()
yhodArray = array.new<Table.Cell>()
ylodArray = array.new<Table.Cell>()
color bgColor = na
color textColor = na
if showHeadings
if showSymbols
array.push(symArray, Table.Cell.new('HLs', colorBearish, colorBearishText))
if _showHLs
hlsBullish = globals.atHighsCount > 0 and globals.atLowsCount == 0
hlsBearish = globals.atLowsCount > 0 and globals.atHighsCount == 0
bgColor := hlsBullish ? colorBullish : hlsBearish ? colorBearish : colorModerate
textColor := hlsBullish ? colorBullishText : hlsBearish ? colorBearishText : colorModerateText
array.push(hlArray, Table.Cell.new('Range', bgColor, textColor))
if _showYHODBreaks
bgColor := globals.brokeYhodCount > 0 ? colorBullish : colorModerate
textColor := globals.brokeYhodCount > 0 ? colorBullishText : colorModerateText
array.push(yhodArray, Table.Cell.new('YHOD', bgColor, textColor))
if _showYLODBreaks
bgColor := globals.brokeYlodCount > 0 ? colorBearish : colorModerate
textColor := globals.brokeYlodCount > 0 ? colorBearishText : colorModerateText
array.push(ylodArray, Table.Cell.new('YLOD', bgColor, textColor))
for symbol in collection
if showSymbols
array.push(symArray, Table.Cell.new(str.upper(symbol.name), colorModerate, colorModerateText))
if _showHLs
// Add the HL cell
isBullish = symbol.level == globals.level.highs
isBearish = symbol.level == globals.level.lows
bgColor := isBullish ? colorBullish : isBearish ? colorBearish : colorModerate
textColor := isBullish ? colorBullishText : isBearish ? colorBearishText : colorModerateText
hlTemplate = switch showHLsContent
"Both" => "{0}\n{1,number,percent}"
"Words" => "{0}"
=> "{1,number,percent}"
content = str.format(hlTemplate, symbol.level, symbol.percentInRange)
array.push(hlArray, Table.Cell.new(content, bgColor, textColor))
breakTemplate = switch showBreakContent
"Words" => "{0}"
"Both" => "{0}\n{1,number,#.##%}"
=> "{1,number,#.##%}"
if _showYHODBreaks
// Add the YHOD cell
percentAway = (symbol.last - symbol.yhod) / symbol.yhod
bgColor := symbol.yhodBreak ? colorBullish : colorModerate
textColor := symbol.yhodBreak ? colorBullishText : colorModerateText
word = symbol.yhodBreak ? 'Break' : 'Held'
array.push(yhodArray, Table.Cell.new(str.format(breakTemplate, word, percentAway), bgColor, textColor))
if _showYLODBreaks
// Add the YLOD cell
percentAway = (symbol.last - symbol.ylod) / symbol.ylod
bgColor := symbol.ylodBreak ? colorBearish : colorModerate
textColor := symbol.ylodBreak ? colorBearishText : colorModerateText
word = symbol.ylodBreak ? 'Break' : 'Held'
array.push(ylodArray, Table.Cell.new(str.format(breakTemplate, word, percentAway), bgColor, textColor))
if showSymbols
matrix.add_row(m, 0, symArray)
if _showHLs
matrix.add_row(m, matrix.rows(m), hlArray)
if _showYHODBreaks
matrix.add_row(m, matrix.rows(m), yhodArray)
if _showYLODBreaks
matrix.add_row(m, matrix.rows(m), ylodArray)
// And render the table
if matrix.rows(m) > 0
Table.fromMatrix(m, position, verticalOffset, textSize=textSize, blankCellText="\n") |
GB Gilt Yield Curve | https://www.tradingview.com/script/gCMkgIX4-GB-Gilt-Yield-Curve/ | PigsMightFly | https://www.tradingview.com/u/PigsMightFly/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PigsMightFly
//@version=5
indicator('GB Gilt Yield Curve', 'GBTYC', false, precision=4)
width = input(15, 'Spacing between labels in bars:')
symbols = 11
gb50y = request.security('GB50Y', timeframe.period, close)
gb40y = request.security('GB40Y', timeframe.period, close)
gb30y = request.security('GB30Y', timeframe.period, close)
gb20y = request.security('GB20Y', timeframe.period, close)
gb15y = request.security('GB15Y', timeframe.period, close)
gb10y = request.security('GB10Y', timeframe.period, close)
gb7y = request.security('GB07Y', timeframe.period, close)
gb5y = request.security('GB05Y', timeframe.period, close)
gb3y = request.security('GB03Y', timeframe.period, close)
gb2y = request.security('GB02Y', timeframe.period, close)
gb1y = request.security('GB01Y', timeframe.period, close)
gb6m = request.security('GB06MY', timeframe.period, close)
gb3m = request.security('GB03MY', timeframe.period, close)
gb1m = request.security('GB01MY', timeframe.period, close)
pos(idx) =>
bar_index - (symbols - idx) * width
draw_label(idx, src, txt) =>
var label la = na
label.delete(la)
la := label.new(pos(idx), src, text=txt, color=color.black, style=label.style_label_up, textcolor=color.white)
la
draw_line(idx1, src1, idx2, src2) =>
var line li = na
line.delete(li)
li := line.new(pos(idx1), src1, pos(idx2), src2, color=color.red, width=3)
li
draw_label(0, gb1m, 'GB 1M (' + str.tostring(gb1m) + ')')
draw_label(1, gb3m, 'GB 3M (' + str.tostring(gb3m) + ')')
draw_label(2, gb6m, 'GB 6M (' + str.tostring(gb6m) + ')')
draw_label(3, gb1y, 'GB 1Y (' + str.tostring(gb1y) + ')')
draw_label(4, gb2y, 'GB 2Y (' + str.tostring(gb2y) + ')')
draw_label(5, gb3y, 'GB 3Y (' + str.tostring(gb3y) + ')')
draw_label(6, gb5y, 'GB 5Y (' + str.tostring(gb5y) + ')')
draw_label(7, gb7y, 'GB 7Y (' + str.tostring(gb7y) + ')')
draw_label(8, gb10y, 'GB 10Y (' + str.tostring(gb10y) + ')')
draw_label(9, gb15y, 'GB 15Y (' + str.tostring(gb15y) + ')')
draw_label(10, gb20y, 'GB 20Y (' + str.tostring(gb20y) + ')')
draw_label(11, gb30y, 'GB 30Y (' + str.tostring(gb30y) + ')')
draw_label(12, gb40y, 'GB 40Y (' + str.tostring(gb40y) + ')')
draw_label(13, gb50y, 'GB 50Y (' + str.tostring(gb50y) + ')')
draw_line(0, gb1m, 1, gb3m)
draw_line(1, gb3m, 2, gb6m)
draw_line(2, gb6m, 3, gb1y)
draw_line(3, gb1y, 4, gb2y)
draw_line(4, gb2y, 5, gb3y)
draw_line(5, gb3y, 6, gb5y)
draw_line(6, gb5y, 7, gb7y)
draw_line(7, gb7y, 8, gb10y)
draw_line(8, gb10y, 9, gb15y)
draw_line(9, gb15y, 10, gb20y)
draw_line(10, gb20y, 11, gb30y)
draw_line(11, gb30y, 12, gb40y)
draw_line(12, gb40y, 13, gb50y)
gb10y3m = (gb10y - gb3m) * 100
gb10y2y = (gb10y - gb2y) * 100
p = 'Important spreads:\n\n'
p += '10Y/03M: ' + str.tostring(gb10y3m) + ' bps\n'
p += '10Y/02Y: ' + str.tostring(gb10y2y) + ' bps\n'
draw_label(14, gb30y, p) |
Point Of Control | https://www.tradingview.com/script/CHSsUilC-Point-Of-Control/ | VebhaInvesting | https://www.tradingview.com/u/VebhaInvesting/ | 152 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vebhainvesting
//https://invest.webspacio.com, location to track momentum stocks
//@version=5
indicator('Point Of Control', overlay=true, max_bars_back=252)
length = input.int(title='Near volume length', defval=21, group='POC')
multi = input.int(title='Multiplier', defval=2, group='POC')
momentum_candle = input.float(title='ATR', defval=1.5, step=0.05, group='POC')
vLength = input.int(title='Volume Weighted', defval=63, group='POC')
//Volume Weighted Average
// if timeframe.isweekly vLength := 13
// else if timeframe.ismonthly vLength := 6
vWeight = ta.vwma(close, timeframe.isdaily ? vLength : 26)
vwColor = vWeight > close ? color.red : color.green
plot(vWeight, color=vwColor, linewidth=2, title='Volume Weighted', display=display.none)
//NEAR VOLUME
avg = ta.sma(volume, length)
std = ta.stdev(volume, length)
condition = volume - avg > multi * std
todaysAction = close > hlc3
change = ta.change(close, 1) > 0 and todaysAction ? 1 : -1
support_line = 0.0
resistance_line = 0.0
support_line := condition and change > 0 ? low : support_line[1]
resistance_line := condition and change < 0 ? high : resistance_line[1]
plotshape(support_line, title='Support', style=shape.cross, location=location.absolute, color=color.new(#8191dd, 0))
plotshape(resistance_line, title='Resistance', style=shape.diamond, location=location.absolute, color=color.new(#c18c81, 0))
//Marking Momentum Candle
hiLow = high - low
closeOpen = close - open
chg = math.abs(close / close[1] - 1)
atr = momentum_candle * ta.atr(length)
momentumCandle = math.abs(closeOpen) / hiLow
momentumBull = closeOpen > atr and closeOpen > 0 or hiLow > atr and momentumCandle > 0.55 and closeOpen > 0 and momentumCandle[1] < 0.50 ? 1 : -1
momentumBear = closeOpen > atr and closeOpen < 0 or hiLow > atr and momentumCandle > 0.55 and closeOpen < 0 and momentumCandle[1] < 0.50 ? 1 : -1
barColour = momentumBull > 0 ? color.green : momentumBear > 0 ? color.red : color.rgb(175, 175, 175, 50)
barcolor(color=barColour)
//Fair Value/Price
[macdLine, signalLine, histLine] = ta.macd(close, 21, 63, 11)
dailyPeakValue = 0.07
macdPeak = timeframe.isdaily ? dailyPeakValue : timeframe.isweekly ? dailyPeakValue * 2.2 : timeframe.ismonthly ? dailyPeakValue * 4.2 : 0.035
fairValue = macdLine < close * macdPeak and macdLine > 0 ? 1 : -1
//Momentum Check
cciVal = ta.cci(hlc3, 34)
cciLong = cciVal > 100 ? 1 : -1
cciShort = cciVal < -50 ? 1 : -1
plotshape(series=cciShort > 0, title='Bearish', style=shape.triangledown, color=color.new(color.red, 0), location=location.abovebar, display=display.all)
plotshape(series=cciLong > 0 and macdLine > 0, title='Bullish', style=shape.triangleup, color=color.new(color.green, 0), location=location.belowbar, display=display.all)
//Above Fair Value then display Orange
plotshape(series=fairValue < 0 and macdLine > 0, title='Overvalued', style=shape.cross, color=color.new(color.orange, 0), location=location.abovebar, display=display.all)
//Momentum Check with KC
multiKC = input.int(1, title='Multiplier', group='KC')
exp = input.bool(true, title='Use Exponential MA', group='KC')
BandsStyle = input.string('Average True Range', title='Bands Style', options=['Average True Range', 'True Range', 'Range'], group='KC')
atrlength = input.int(11, 'ATR Length', group='KC')
esma(source, length) =>
s = ta.sma(source, length)
e = ta.ema(source, length)
exp ? e : s
ma = esma(close, length)
rangema = BandsStyle == 'True Range' ? ta.tr(true) : BandsStyle == 'Average True Range' ? ta.atr(atrlength) : ta.rma(high - low, length)
upper = ma + rangema * multiKC
lower = ma - rangema * multiKC
uPlot = plot(upper, color=color.new(color.gray, 0), title='Upper', display=display.all)
lPlot = plot(lower, color=color.new(color.gray, 0), title='Lower', display=display.none)
atrSma = ta.sma(upper / lower, atrlength)
fillBool = atrSma > upper / lower ? 1 : atrSma > upper / lower ? -1 : 0 //good
plot(ma, color=close > ma ? color.green : color.red, title='Basis', style=plot.style_cross, display=display.none)
// Ichimoku Cloud
conversionPeriods = input.int(11, minval=1, title='Conversion Line Length', group='Ichimoku')
basePeriods = input.int(21, minval=1, title='Base Line Length', group='Ichimoku')
laggingSpan2Periods = input.int(63, minval=1, title='Leading Span B Length', group='Ichimoku')
//displacement = input(21, type=input.integer, minval=1, title="Lagging Span",group="Ichimoku")
donchian(len) =>
math.avg(ta.lowest(len), ta.highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
plot(baseLine, color=color.new(#B71C1C, 0), title='Base Line', linewidth=2, display=display.all)
//plot(close, offset = -basePeriods + 1, color=#43A047, title="Lagging Span",display=display.none)
p1 = plot(leadLine1, offset=basePeriods - 1, color=color.new(#A5D6A7, 0), title='Leading Span A', display=display.none)
p2 = plot(leadLine2, offset=basePeriods - 1, color=color.new(#EF9A9A, 0), title='Leading Span B', display=display.none)
fill(p1, p2, color=leadLine1 > leadLine2 ? color.rgb(75, 225, 75, 80) : color.rgb(225, 75, 75, 80))
// The END
|
Candlestick Pattern Criteria and Analysis Indicator | https://www.tradingview.com/script/MzRkVvsT-Candlestick-Pattern-Criteria-and-Analysis-Indicator/ | kurtsmock | https://www.tradingview.com/u/kurtsmock/ | 60 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kurtsmock
//@version=5
indicator(title='Candles', overlay=true, max_lines_count = 500)
import kurtsmock/PD/1 as pd
import kurtsmock/ArrayMatrixHUD/3 as va
rows = 15, cols = 2
varip console = matrix.new<string>(rows,cols,'')
// -- Testing Range Function {
backtest(int _start, int _end, bool _sessions, bool _incWeekends, string _sessPeriod) =>
session = _sessions and _incWeekends ? not na(time(timeframe.period, _sessPeriod + ":1234567")) : _sessions ? not na(time(timeframe.period, _sessPeriod + ":23456")) : true
backtestRange = time >= _start and time <= _end and session ? true : false
backtestRange
// //}
// -- Inputs {
bd = 'Body', rg = "Range"
bull = "Bull Bars", bear = 'Bear Bars', both = 'Both'
sd = 'StDev', avg = 'Average Multiplier', ch = "Select"
o = 'Open', h = 'High', l = 'Low', c = 'Close', z = 'OHLC4'
tck = 'Ticks', pct = 'Percent', pts = "Points"
lt = '(<) Less Than', gt = '(>) Greater Than', th = '(> <) Range Threshold'
hl = "High/Low", oc = "Open/Close", scp = "SCP", val = "Value", hlc = 'HLC3'
cs_g00 = "General Parameters"
c_type = input.string(both, "Candle Type", group = cs_g00, options=[bull, bear, both])
c_src = input.source(open, "External Source", group = cs_g00, tooltip = "Imported signal must be a numerical boolean ('1 or 0') and 'Use Alternate Criteria' switch must be ON.")
cs_g01 = "Candle Attributes"
s_body = input.bool(false, "Use Candle Bodies-----|", group = cs_g01, inline='a')
s_avg = input.bool(false, "Use Average Size", group = cs_g01, inline='a')
s_uWick = input.bool(false, "Use Upper Wick--------|", group = cs_g01, inline='b')
s_lWick = input.bool(false, "Use Lower Wick", group = cs_g01, inline='b')
s_rng = input.bool(false, 'Search in Price Range-|', group = cs_g01, inline='c')
s_time = input.bool(false, 'Search in Time Range', group = cs_g01, inline='c')
s_alt = input.bool(false, "Use Alternate Criteria |", group = cs_g01, inline='d')
s_hlc3 = input.bool(false, 'Use HLC3', group = cs_g01, inline='d')
s_scp = input.bool(false, 'Use Scalar Close Percentage',group = cs_g01, inline='e', tooltip='Scalar Close Percentage (SCP): It\'s the position of the price attribute relative to the scale of the bar range (high - low)\nFormula: (close - low) / (high - low).')
s_lines = input.bool(false, 'Show Lines--------------|', group = cs_g01, inline='f')
s_lCol = input.color(color.orange, "Line Color", group = cs_g01, inline='f')
s_bg = input.bool(false, "Show Sess BG Color----|", group = cs_g01, inline='g')
s_bgCol = input.color(color.new(color.gray, 90), " Bg Color", group = cs_g01, inline='g')
c_barCol = input.color(color.yellow, "Candle Highlight Color", group = cs_g01, inline='h')
cs_g02 = "Candle Body/Range Parameters"
c_bodyCalc = input.string( ch, "Body Quantity", group = cs_g02, options = [tck, pct, pts, ch])
bodyRng = input.string( ch, "Bodies or Range", group = cs_g02, options = [bd, rg, ch], tooltip="Using Range Requires Your Parameters To Be In Ticks or Points. (The range is always 100% of the candle)")
bodyOper = input.string( ch, 'Define Operator: <. >, or > <', group = cs_g02, options = [lt, gt, th, ch])
bodyLtGt = input.int( 0, "Define Limit: '<,' '>,' & '<>'", group = cs_g02, minval = 0, tooltip="Use for Less Than, Greater Than, or High of Threshold\nIf ticks or points, any number of ticks or points.\nIf Pct, any number between 0-100")
bodyLth = input.int( 0, 'Define Lower Threshold', group = cs_g02, minval = 0, tooltip = 'For the Low of the Threshhold')
cs_g03 = "Upper Wick Parameters"
c_uwCalc = input.string( ch, "Upper Wick Quantity", group = cs_g03, options = [tck, pct, pts, ch])
upperOper = input.string( ch, "Define Operator: '<,' '>,' or '><''", group = cs_g03, options = [lt, gt, th, ch])
upperLtGt = input.int( 0, "Define Limit: '<,' '>,' & '<>'", group = cs_g03, minval = 0, tooltip="Use for Less Than, Greater Than, or High of Threshold\nIf ticks or points, any number of ticks or points.\nIf Pct, any number between 0-100")
upperLth = input.int( 0, 'Define Lower Threshold', group = cs_g03, minval = 0, tooltip = 'For the Low of the Threshhold')
cs_g04 = "Lower Wick Parameters"
c_lwCalc = input.string( ch, "Lower Wick Quantity", group = cs_g04, options = [tck, pct, pts, ch])
lowerOper = input.string( ch, "Define Operator: '<,' '>,' or '><''", group = cs_g04, options = [lt, gt, th, ch])
lowerLtGt = input.int( 0, "Define Limit: '<,' '>,' & '<>'", group = cs_g04, minval = 0)
lowerLth = input.int( 0, 'Define Lower Threshold', group = cs_g04, minval = 0)
cs_g05 = "Other Attributes"
c_hlc3Comp = input.string( ch, "HLC3 Comparison Attribute", group = cs_g05, options = [o, c, scp, ch])
c_hlc3Oper = input.string( ch, "HLC3 Operator", group = cs_g05, options = [gt, lt, ch])
c_scpComp = input.string( ch, "SCP Comparison Atrribute", group = cs_g05, options = [val, hlc, ch])
c_scpOper = input.string( ch, "SCP Operator", group = cs_g05, options = [gt, lt, ch])
c_scpVal = input.float( 0.0, "SCP Value", group = cs_g05, minval = 0.0)
cs_g06 = "Average Size"
c_avgCalc = input.string( ch, "Averaging Quantity", group = cs_g06, options = [tck, pts, ch])
c_avgDef = input.string( ch, 'Averaging Method', group = cs_g06, options = [sd, avg, ch])
c_ovrUndr = input.string( ch, "> Avg or < Avg", group = cs_g06, options = [gt, lt, ch])
c_HLorOC = input.string( ch, "High/Lo or Open/Close", group = cs_g06, options = [hl, oc, ch], tooltip="Benchmark for Averaging")
i_mult = input.float( 1.0, 'Avg Size Multiplier', group = cs_g06, minval = 0, step = 0.1, tooltip = 'Average Multiplier\n1.0 = the average. +/- 1.0 = % increase/decrease of average\n\n Standard Deviation:\n1.0 = 1 stdev. It is the number of standard devations added to average. (0.0 would = The Average)')
cs_g07 = "Search Within Price Range"
rangeH = input.float(100000, 'Top of Price Range', group = cs_g07, minval = 0)
rangeL = input.float( 1, 'Bottom of Price Range', group = cs_g07, minval = 0)
rangeOn = s_rng ? high <= rangeH and low >= rangeL : close > 0
bt_g1 = "Search Within Time Range"
c_start = input.time( title='Start Date', group = bt_g1, defval=timestamp('18 May 2022 00:00 +0000'))
c_end = input.time( title='End Date', group = bt_g1, defval=timestamp('01 Jan 2023 00:00 +0000'))
s_useSess = input.bool(true, 'Use Session Constraint |', group = bt_g1, inline='i')
s_incWE = input.bool(true, 'Include Weekends', group = bt_g1, inline='i')
c_sessPd = input.session('1800-1500', 'Session Definition', group = bt_g1)
o_sessionActive = backtest(c_start, c_end, s_useSess, s_incWE, c_sessPd)
cs_g08 = "Line Settings"
selector2 = input.string( c, 'Strike Line From:', group = cs_g08, options = [o, h, l, c, z])
fewerLines = input.int( 50, 'Max Number of Lines', group = cs_g08, minval = 1, maxval = 500)
lineLookback = input.int( 4999, 'Max Bar Lookback', group = cs_g08, minval = 100, maxval = 4999)
s_debug = input.bool( false, "Show Debug Panel")
// //}
// Specify altCriteria. (Hard Coded Candle Type) ///////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// {
s_bos = input.bool(false, "Show Breakouts")
s_bosCt = input.bool(false, "Show Breakout Ct")
var breakoutLvl = float(na)
var breakoutArray = array.new_float(20, float(na)) // Short-Term Breakouts
breakout = close > high[1]
breakoutFrom = 0.0
if breakout
breakoutLvl := high
array.unshift(breakoutArray, breakoutLvl)
for i = 0 to 19
if breakoutLvl >= array.get(breakoutArray, i)
breakoutFrom := breakoutFrom + 1
if array.get(breakoutArray, i + 1) > array.get(breakoutArray, i)
break
else
breakoutLvl := breakoutLvl[1]
if array.size(breakoutArray) > 20
array.pop(breakoutArray)
var breakdownLvl = float(na)
var breakdownArray = array.new_float(20, float(na)) // Short-Term Breakdowns
breakdown = close < low[1]
breakdownFrom = 0.0
if breakdown
breakdownLvl := low
array.unshift(breakdownArray, breakdownLvl)
for i = 0 to 19
if breakdownLvl <= array.get(breakdownArray, i)
breakdownFrom := breakdownFrom + 1
if array.get(breakdownArray, i + 1) < array.get(breakdownArray, i)
break
else
breakdownLvl := breakdownLvl[1]
if array.size(breakdownArray) > 20
array.pop(breakdownArray)
plotshape(s_bos ? breakoutFrom > breakoutFrom[1] : na, "Breakout", style=shape.triangleup, location=location.abovebar, color=color.new(color.green,50), size=size.tiny)
plotshape(s_bos ? breakdownFrom > breakdownFrom[1] : na, "Breakdown", style=shape.triangledown, location=location.belowbar, color=color.new(color.red,50), size=size.tiny)
if s_bosCt and breakoutFrom > breakoutFrom[1] and c_type != bear
label.new(bar_index, low, text=str.tostring(breakoutFrom), xloc=xloc.bar_index, yloc=yloc.belowbar, style=label.style_label_up, color=color.rgb(255, 255, 255, 100), textcolor=color.black, size=size.small)
if s_bosCt and breakdownFrom > breakdownFrom[1] and c_type != bull
label.new(bar_index, low, text=str.tostring(breakdownFrom), xloc=xloc.bar_index, yloc=yloc.abovebar, style=label.style_label_down, color=color.rgb(255, 255, 255, 100), textcolor=color.black, size=size.small)
// }
// -- Calculations {
o_hlc3Comp = c_hlc3Comp == o ? open : c_hlc3Comp == c ? close : c_hlc3Comp == scp ? pd.pct('scp') : na
// --- Override Calculation Type When Attribute Isn't Selected
if (c_bodyCalc == ch or c_uwCalc == ch or c_lwCalc == ch) and (c_bodyCalc != ch or c_uwCalc != ch or c_lwCalc != ch)
if c_bodyCalc != ch
c_uwCalc := c_uwCalc == ch ? c_bodyCalc : c_uwCalc
c_lwCalc := c_lwCalc == ch ? c_bodyCalc : c_uwCalc
else if c_uwCalc != ch
c_bodyCalc := c_bodyCalc == ch ? c_uwCalc : c_bodyCalc
c_lwCalc := c_lwCalc == ch ? c_uwCalc : c_lwCalc
else if c_lwCalc != ch
c_uwCalc := c_uwCalc == ch ? c_lwCalc : c_uwCalc
c_bodyCalc := c_bodyCalc == ch ? c_lwCalc : c_bodyCalc
p_range = c_bodyCalc == tck ? pd.tick("rg") : (c_bodyCalc == pts ? pd.pt('rg') : 100)
p_body = bodyRng == rg ? (c_bodyCalc == tck ? pd.tick("rg") : c_bodyCalc == pct ? pd.pct('rg', 2) * 100 : pd.pt('rg')) : (c_bodyCalc == tck ? pd.tick("oc") : c_bodyCalc == pct ? pd.pct('bd', 2) * 100 : pd.pt('oc'))
p_upper = c_uwCalc == tck ? pd.tick("uw") : (c_uwCalc == pct ? pd.pct("uw", 2) * 100 : pd.pt('uw'))
p_lower = c_lwCalc == tck ? pd.tick("lw") : (c_lwCalc == pct ? pd.pct('lw', 2) * 100 : pd.pt('lw'))
p_avg = s_avg ? (c_avgCalc == tck ? pd.tick('rg') : (c_avgCalc == pts ? pd.pt('rg') : na)) : pd.tick('rg')
var bullCummArray = array.new_float()
var bearCummArray = array.new_float()
if close > open and (s_time ? o_sessionActive : true) and (s_rng ? rangeOn : true)
array.push(bullCummArray, c_bodyCalc == pct ? (s_rng ? p_range : pd.tick('rg')) : (bodyRng == bd ? (c_bodyCalc == tck ? pd.tick('bd') : pd.pt('bd')) : (c_bodyCalc == tck ? pd.tick('rg') : pd.pt('rg'))))
avgBullDisp = math.round_to_mintick(array.avg(bullCummArray))
sdBullDisp = math.round_to_mintick(array.stdev(bullCummArray))
if close < open and (s_time ? o_sessionActive : true) and (s_rng ? rangeOn : true)
array.push(bearCummArray, c_bodyCalc == pct ? (s_rng ? p_range : pd.tick('rg')) : (bodyRng == bd ? (c_bodyCalc == tck ? pd.tick('bd') : pd.pt('bd')) : (c_bodyCalc == tck ? pd.tick('rg') : pd.pt('rg'))))
avgBearlDisp = math.round_to_mintick(array.avg(bearCummArray))
sdBearlDisp = math.round_to_mintick(array.stdev(bearCummArray))
altCriteriaBull = breakoutFrom > breakoutFrom[1] // true (if altCriteria not in use)
altCriteriaBear = breakdownFrom > breakdownFrom[1] // true (if altCriteria not in use)
// //}
// -- Conditions/Criteria {
// logic -> Check for altCriteria (coded criteria)
// If Alternative Criteria switch is on, then check altCriteriaBull, altCriteriaBear, or Both. if altCriteria is off, result is false
altCriteria = s_alt ? (c_type == bull ? altCriteriaBull :
(c_type == bear ? altCriteriaBear :
altCriteriaBull or altCriteriaBear)) :
false
// logic -> If using alternatvie criteria and c_src == 1 then criteria = true, otherwise ignore.
// Default of c_src is open price. It is rare that open price would be 1.
altCriteria := s_alt and c_src == 1 ? true : altCriteria
va.debug(1,0, console, str.tostring(altCriteria), 'altCriteria')
// logic -> Validate against c_type:
// When s_alt (using altCriteria), you need to test the candle for direction with (and) altCriteria.
// When not s_alt, you need to test for candle direction alone. Both is default. So false can never never triggers if s_alt is not switched on
// False only occurs when s_alt is on and altCriteria is not met
candleType = s_alt ? (c_type == bull ? altCriteria and close > open : (c_type == bear ? altCriteria and close < open : altCriteria)) :
(c_type == bull ? close > open : (c_type == bear ? close < open : c_type == both ? true : false ))
va.debug(1,1, console, str.tostring(candleType), 'candleType')
// The output of candleType (true or false) is derived by giving priority to altCriteria over candle direction
// That is to say if only altCriteria switch is on, you will get the output of altCriteria even when a direction is not chosen. It will test the bull and bear altcritieria...
// Effectively creating the same output as if the candleType is being disregared when altCriteria is being used.
// logic -> If none of the the candle attributes switches are on, these variables are bypassed and CandleType is used as the bool.
// The reason is that this allows for true/false of criteria to be defined only by candleType (and thus altCriteria).
// That is to say the result of candleType is passed through to be the result of o_body, o_uWick and o_lWick. Also otherwise stated these variables are bypassed, ignoring gt/lt/th inputs.
// However is one or more switches is on, THEN Else:
// Check CandleType for true/false. If false result of variable is false.
// If candleType is true, then check the ___Oper inputs
// If none of them are true, it will result in true. This means the switch is on, the candleType is found, but no operator has been definied. Its still meets the criteria because the criteria is candleType, not the operators.
// if any Operators are selected, the comparison will be made and true/false will reflect that result.
bool o_body = s_body ? candleType ? (bodyOper == lt ? p_body < bodyLtGt : (bodyOper == gt ? p_body > bodyLtGt : (bodyOper == th ? p_body < bodyLtGt and p_body > bodyLth : true))) : false : candleType
bool o_uWick = s_uWick ? candleType ? (upperOper == lt ? p_upper < upperLtGt : (upperOper == gt ? p_upper > upperLtGt : (upperOper == th ? p_upper < upperLtGt and p_upper > upperLth : true))) : false : candleType
bool o_lWick = s_lWick ? candleType ? (lowerOper == lt ? p_lower < lowerLtGt : (lowerOper == gt ? p_lower > lowerLtGt : (lowerOper == th ? p_lower < lowerLtGt and p_lower > lowerLth : true))) : false : candleType
va.debug(1,2, console, str.tostring(o_body), 'o_body')
va.debug(1,3, console, str.tostring(o_uWick), 'o_uWick')
va.debug(1,4, console, str.tostring(o_lWick), 'o_lWick')
// logic -> if the switch is off for body, uppwr wick and lower wick OR
// if the switch for time is on and its not in session OR
// if the switch for price range is on and its not in range... you get false. Criteria is not met on that bar
// otherwise, output for (body, uppwer wick and lower wick) all have to be true.
// They will be true when
// (a) altCriteria is selected alone and altCriteria = true,
// (b) candle attribute switch is on and Candle meets criteria but no ___oper's are selected (regardless of altCriteria, but subject to it if selected),
// (c) candle attribute switch is on and oper's are selected. Still subjected to altCriteria if on
criteria = (not s_body and not s_uWick and not s_lWick and not s_alt) or (s_time and not o_sessionActive) or (s_rng and not rangeOn) ? false : (o_body and o_uWick and o_lWick)
va.debug(1,5, console, str.tostring(criteria), 'criteria')
if criteria
va.debug(0,1, console, str.tostring(criteria), "Qualifying Candle Found")
if s_hlc3 and criteria and (s_time ? o_sessionActive : true) and (s_rng ? rangeOn : true)
if c_hlc3Oper == gt
criteria := (c_hlc3Comp == o ? hlc3 > open : (c_hlc3Comp == c ? hlc3 > close : (c_hlc3Comp == scp ? hlc3 > pd.pct('scp') : criteria)))
if c_hlc3Oper == lt
criteria := (c_hlc3Comp == o ? hlc3 < open : (c_hlc3Comp == c ? hlc3 < close : (c_hlc3Comp == scp ? hlc3 < pd.pct('scp') : criteria)))
va.debug(1,5, console, str.tostring(criteria), 'criteria + HLC3')
if s_scp and criteria and (s_time ? o_sessionActive : true) and (s_rng ? rangeOn : true)
if c_scpOper == gt
criteria := (c_scpComp == val ? pd.pct('scp') * 100 > c_scpVal : (c_scpComp == hlc ? pd.pct('scp') > (hlc3 - low) / (high - low) : criteria))
if c_scpOper == lt
criteria := (c_scpComp == val ? pd.pct('scp') * 100 < c_scpVal : (c_scpComp == hlc ? pd.pct('scp') < (hlc3 - low) / (high - low) : criteria))
va.debug(1,6, console, str.tostring(criteria), 'criteria + HLC3 + SCP')
if s_avg and criteria and (s_time ? o_sessionActive : true) and (s_rng ? rangeOn : true)
if c_avgDef == sd
if c_ovrUndr == gt
if c_type == bull
criteria := p_avg > math.round_to_mintick(avgBullDisp + (sdBullDisp * i_mult)) // sd, Greater than, bull candles
va.debug(0,2, console, str.tostring(criteria), "Found Using Stdev, >, Bull Bar")
else if c_type == bear
criteria := p_avg > math.round_to_mintick(avgBearlDisp + (sdBearlDisp * i_mult)) // sd, Greater than, bear candles
va.debug(0,3, console, str.tostring(criteria), "Found Using Stdev, >, Bear Bar")
else
criteria := p_avg > math.round_to_mintick(((avgBullDisp + avgBearlDisp)/2) + (((sdBullDisp + sdBearlDisp)/2) * i_mult)) // sd, Greater Than, bull and bear candles
va.debug(0,4, console, str.tostring(criteria), "Found Using StDev, >, Any Direction")
else if c_ovrUndr == lt
if c_type == bull
criteria := p_avg < math.round_to_mintick(avgBullDisp + (sdBullDisp * i_mult)) // sd, Less Than, bull candles
va.debug(0,5, console, str.tostring(criteria), "Found Using Stdev, <, Bull Bar")
else if c_type == bear
criteria := p_avg < math.round_to_mintick(avgBearlDisp + (sdBearlDisp * i_mult)) // sd, Less Than, bear candles
va.debug(0,6, console, str.tostring(criteria), "Found Using StDev, <, Bear Bar")
else
criteria := p_avg < math.round_to_mintick(((avgBullDisp + avgBearlDisp)/2) + (((sdBullDisp + sdBearlDisp)/2) * i_mult)) // sd, less than, bull and bear candles
va.debug(0,7, console, str.tostring(criteria), "Found Using Stdev. <, Any Direction")
if c_avgDef == avg
if c_ovrUndr == gt
if c_type == bull
criteria := p_avg > math.round_to_mintick(avgBullDisp * i_mult) // avg, Greater Than, Bull candles
va.debug(0,8, console, str.tostring(criteria), "Found Using Avg, >, Bull Bars")
else if c_type == bear
criteria := p_avg > math.round_to_mintick(avgBearlDisp * i_mult) // avg, Greater Than, Bear candles
va.debug(0,9, console, str.tostring(criteria), "Found Using Avg, >, Bear Bars")
else
criteria := p_avg > math.round_to_mintick(((avgBullDisp + avgBearlDisp)/2) * i_mult) // avg, Greater Than, Bull and Bear candles
va.debug(0,10, console, str.tostring(criteria), "Found Using Avg, >, Any Direction")
else if c_ovrUndr == lt
if c_type == bull
criteria := p_avg < math.round_to_mintick(avgBullDisp * i_mult) // avg, Less Than, Bull candles
va.debug(0,11, console, str.tostring(criteria), "Found Using Avg, <, Bull Bars")
else if c_type == bear
criteria := p_avg < math.round_to_mintick(avgBearlDisp * i_mult) // avg, Less Than, Bear candles
va.debug(0,12, console, str.tostring(criteria), "Found Using Avg, <, Bear Bars")
else
criteria := p_avg < math.round_to_mintick(((avgBullDisp + avgBearlDisp)/2) * i_mult) // avg, Less Than, Bull and Bear candles
va.debug(0,13, console, str.tostring(criteria), "Found Using Avg, <, Any Direction")
va.debug(1,6, console, str.tostring(criteria), 'Criteria + HLC3 + SCP + Avg')
var criteriaCt = 0
if criteria
criteriaCt += 1
if barstate.islast and criteriaCt == 0
if s_debug
va.debug(0,0, console, "", "NO CANDLE TYPE SELECTED\n OR NO CANDLES FIT CRITERIA\n--- Edit Selections in Settings Menu! ---")
else
runtime.error("No Candles Found Using the Current Criteria Or No Criteria Chosen. Change Settings to find candles matching your criteria.")
else
va.debug(0,0, console, "Debug Window", "")
// //}
// -- Plots - Displayed In Data Window {
plot(p_body, "Current Body Size", display = display.data_window, color=color.red)
plot(p_range, "Current Range", display = display.data_window, color=color.red)
plot(p_upper, "Current Upper Wick Size", display = display.data_window, color=color.red)
plot(p_lower, "Current Lower Wick Size", display = display.data_window, color=color.red)
plot(avgBullDisp, "Avg Size of Bull Bar in Test Range", display = display.data_window, color=color.orange)
plot(sdBullDisp, "Stdev of Bull Bar in Test Range", display = display.data_window, color=color.orange)
plot(avgBearlDisp, "Overall Avg Bear Bar", display = display.data_window, color=color.orange)
plot(sdBearlDisp, "Overall SD Bear Bar", display = display.data_window, color=color.orange)
plot(((avgBullDisp + avgBearlDisp)/2) * i_mult,
"Avg * Mult Candle Size (Avg Output)", display = display.data_window, color=color.orange)
plot(((avgBullDisp + avgBearlDisp)/2) + (((sdBullDisp + sdBearlDisp)/2) * i_mult),
"Avg + SD Candle Size (Stdev Output)", display = display.data_window, color=color.orange)
barcolor(criteria ? c_barCol : na)
bgcolor(s_time and s_bg ? (o_sessionActive ? s_bgCol : na) : na)
barcolor(criteria[1] and barstate.isconfirmed and close > open and high > high[1] and low >= low[1] ? color.green : na)
barcolor(criteria[1] and barstate.isconfirmed and close < open and high <= high[1] and low < low[1] ? color.red : na)
barcolor(criteria[1] and barstate.isconfirmed and not (close > open and high > high[1] and low > low[1]) and not (close < open and high < high[1] and low < low[1]) ? color.gray : na)
// -- Statistics -- //
var criteriaArray = array.new_float()
var bullArray = array.new_float()
var bearArray = array.new_float()
var otherBullArray = array.new_float()
var otherBearArray = array.new_float()
var totalCandles = 0
displacement = s_body and bodyRng == bd ? (c_bodyCalc == tck ? pd.tick("oc") : (c_bodyCalc == pct ? pd.pct('oc') : pd.pt('oc'))) :
(s_body and bodyRng == rg) or
(s_body and s_uWick and s_lWick) ? (c_bodyCalc == tck ? pd.tick('rg') : (c_bodyCalc == pct ? pd.pct('rg') : pd.pt('rg'))) :
s_uWick ? (c_uwCalc == tck ? pd.tick('uw') : (c_uwCalc == pct ? pd.pct('uw') : pd.pt('uw'))) :
s_lWick ? (c_lwCalc == tck ? pd.tick('lw') : (c_lwCalc == pct ? pd.pct('lw') : pd.pt('lw'))) :
s_uWick and s_lWick ? (c_uwCalc == tck ? pd.tick('uw') + pd.tick('lw') : (c_uwCalc == pct ? pd.pct('uw') + pd.pct('lw') : pd.pt('uw') + pd.pt('lw'))) : 0
if criteria
array.unshift(criteriaArray, displacement)
avgCriteria = array.avg(criteriaArray)
stdCriteria = array.stdev(criteriaArray)
maxCriteria = array.max(criteriaArray)
minCriteria = array.min(criteriaArray)
// -- You would edit these condtions to change the readouts in the Data Window
if criteria[1] and barstate.isconfirmed
if close > open
if high > high[1] and low >= low[1]
array.unshift(bullArray, displacement)
else
array.unshift(otherBullArray, displacement)
if close < open
if high <= high[1] and low < low[1]
array.unshift(bearArray, displacement)
else
array.unshift(otherBearArray, displacement)
total = array.size(bullArray) + array.size(bearArray) + array.size(otherBullArray) + array.size(otherBearArray)
totalCandles := (s_rng ? (rangeOn ? (s_time ? (o_sessionActive ? totalCandles + 1 : totalCandles) : totalCandles + 1) : totalCandles + 1) :
(s_time ? (o_sessionActive ? totalCandles + 1 : totalCandles) :
totalCandles + 1))
pctSignal = total / totalCandles
bullFollowed = array.size(bullArray)
notBullFollow = array.size(otherBullArray)
avgBullFollow = array.avg(bullArray)
bearFollowed = array.size(bearArray)
notBearFollow = array.size(otherBearArray)
avgBearFollow = array.avg(bearArray)
bullBreakout = math.round((bullFollowed / total), 2)
pctBullBar = math.round(((bullFollowed + notBullFollow) / total),2)
bearBreakout = math.round((bearFollowed / total), 2)
pctBearBar = math.round(((bearFollowed + notBearFollow) / total), 2)
plot(0, "--- Signal Freq. Analysis --", display = display.data_window)
plot(criteriaCt, "Instances Criteria = True", display = display.data_window)
plot(criteriaCt - total, "Number of Follow Up Doji's", display = display.data_window)
plot(total, "Total Useful Signals", display = display.data_window)
plot(pctSignal, "Pct of Time Useful Signal Occurence", display = display.data_window)
plot(0, "-- Signal Size Analysis --", display = display.data_window, color=color.green)
plot(avgCriteria, "Avg Size of Matching Candles", display = display.data_window, color=color.green)
plot(stdCriteria, "Stdev of Matching Candles", display = display.data_window, color=color.green)
plot(maxCriteria, "Size of Largest of Matching Candle", display = display.data_window, color=color.green)
plot(minCriteria, "Size of Smallest of Matching Candle", display = display.data_window, color=color.green)
plot(0, '-- Bar After Criteria is Met Bull or Bear --', display = display.data_window, color=color.black)
plot(bullFollowed + notBullFollow, "Total Follow Up Bars (FUB) where close>open", display = display.data_window, color=color.purple)
plot(bearFollowed + notBearFollow, "Total Follow Up Bars (FUB) where close<open", display = display.data_window, color=color.fuchsia)
plot(0, "-- Occurence Rate for Follow Up Bull Bars --", display = display.data_window, color=color.black)
plot(bullFollowed, "FUB Bull Breakout (High>High[1] and Low>=Low[1])(ct)", display = display.data_window, color=color.purple)
plot(avgBullFollow, "Avg Size of FUB Bull Breakout", display = display.data_window, color=color.purple)
plot(notBullFollow, "All Other Follow Up Bars Where close > open (ct)", display = display.data_window, color=color.purple)
plot(0, "-- Occurence Rate for Follow Up Bear Bars --", display = display.data_window, color=color.black)
plot(bearFollowed, "FUB Bear Breakout (High<=High[1] and Low<Low[1])(ct)", display = display.data_window, color=color.fuchsia)
plot(avgBearFollow, "Avg Size of FUB Bear Breakout", display = display.data_window, color=color.fuchsia)
plot(notBearFollow, "All Other Follow Up Bars Where close < open (ct)", display = display.data_window, color=color.fuchsia)
plot(0, "-- Pct Occurence Compared to Total Signals --", display = display.data_window, color=color.black)
plot(bullBreakout, "Pct of Time Bull Breakout Followed", display = display.data_window, color=color.lime)
plot(bearBreakout, "Pct of Time Bear Breakdown Followed", display = display.data_window, color=color.lime)
plot(pctBullBar, "Pct of Time Bull Bar Followed", display = display.data_window, color=color.lime)
plot(pctBearBar, "Pct of Time Bear Bar Followed", display = display.data_window, color=color.lime)
// //}
// -- Lines {
yloc = switch selector2
o => open
h => high
l => low
c => close
z => ohlc4
var lineArray = array.new_line()
if s_lines and criteria
array.unshift(lineArray, line.new(bar_index[1], yloc, bar_index, yloc, extend=extend.right, color=s_lCol, width=1))
if array.size(lineArray) > fewerLines
line.delete(array.get(lineArray, fewerLines))
array.remove(lineArray, fewerLines)
if s_debug
va.viewMatrix(console, position.bottom_right, size.normal, bar_index > 1)
// Edit to be able to update thumbnail
// //} |
RTI Pivot Points Standard | https://www.tradingview.com/script/FPZxmDfP-RTI-Pivot-Points-Standard/ | superkumar2020 | https://www.tradingview.com/u/superkumar2020/ | 34 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © superkumar2020
//@version=4
study("Pivot Points Standard", overlay=true)
WchosenColor(c_)=> c_ == "aqua" ? color.aqua : c_ == "black" ? color.black : c_ == "blue" ? color.blue : c_ == "fuchsia" ? color.fuchsia : c_ == "gray" ? color.gray : c_ == "green" ? color.green : c_ == "lime" ? color.lime : c_ == "maroon" ? color.maroon : c_ == "navy" ? color.navy : c_ == "olive" ? color.olive : c_ == "orange" ? color.orange : c_ == "purple" ? color.purple : c_ == "red" ? color.red : c_ == "silver" ? color.silver : c_ == "teal" ? color.teal : c_ == "white" ? color.white : c_ == "yellow" ? color.yellow : color.black
WhigherTF = "W"
Wmy_color = input(title="Weekly Color", defval="black", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])
WprevCloseHTF = security(syminfo.tickerid, WhigherTF, close[1], lookahead=true)
WprevOpenHTF = security(syminfo.tickerid, WhigherTF, open[1], lookahead=true)
WprevHighHTF = security(syminfo.tickerid, WhigherTF, high[1], lookahead=true)
WprevLowHTF = security(syminfo.tickerid, WhigherTF, low[1], lookahead=true)
WpLevel = (WprevHighHTF + WprevLowHTF + WprevCloseHTF) / 3
Wr1Level = WpLevel * 2 - WprevLowHTF
Ws1Level = WpLevel * 2 - WprevHighHTF
Wr2Level = WpLevel + (WprevHighHTF - WprevLowHTF)
Ws2Level = WpLevel - (WprevHighHTF - WprevLowHTF)
Wr3Level = WpLevel + 2*(WprevHighHTF - WprevLowHTF)
Ws3Level = WpLevel - 2*(WprevHighHTF - WprevLowHTF)
var line Wr1Line = na
var line WpLine = na
var line Ws1Line = na
var line Wr2Line = na
var line Ws2Line = na
var line Wr3Line = na
var line Ws3Line = na
var line Wm3Line = na
var label Wr3L = na
var label Wr1L = na
var label WpL = na
var label Ws1L = na
var label Ws2L = na
var label Ws3L = na
var label Wr2L = na
if WpLevel[1] != WpLevel
line.set_x2(Wr1Line, bar_index)
line.set_x2(WpLine, bar_index)
line.set_x2(Ws1Line, bar_index)
line.set_x2(Wr2Line, bar_index)
line.set_x2(Ws2Line, bar_index)
line.set_x2(Wr3Line, bar_index)
line.set_x2(Ws3Line, bar_index)
line.set_extend(Wr1Line, extend.none)
line.set_extend(WpLine, extend.none)
line.set_extend(Ws1Line, extend.none)
line.set_extend(Wr2Line, extend.none)
line.set_extend(Ws2Line, extend.none)
line.set_extend(Wr3Line, extend.none)
line.set_extend(Ws3Line, extend.none)
Wr1Line := line.new(bar_index, Wr1Level, bar_index, Wr1Level, width=1, extend=extend.right, color=color.green)
WpLine := line.new(bar_index, WpLevel, bar_index, WpLevel, width=2, extend=extend.right, color=color.yellow)
Ws1Line := line.new(bar_index, Ws1Level, bar_index, Ws1Level, width=1,extend=extend.right, color=color.red)
Wr2Line := line.new(bar_index, Wr2Level, bar_index, Wr2Level, width=1, extend=extend.right,color=color.green)
Ws2Line := line.new(bar_index, Ws2Level, bar_index, Ws2Level, width=1,extend=extend.right,color=color.red)
Wr3Line := line.new(bar_index, Wr3Level, bar_index, Wr3Level, width=1, extend=extend.right,color=color.green)
Ws3Line := line.new(bar_index, Ws3Level, bar_index, Ws3Level, width=1,extend=extend.right,color=color.red)
Wr1L := label.new(bar_index, Wr1Level, WhigherTF+".R1", style=label.style_none)
var label label1 = na
WpL := label.new(bar_index, WpLevel, WhigherTF+".P", style=label.style_none)
label.set_textalign(label1, text.align_right)
Ws1L := label.new(bar_index, Ws1Level, WhigherTF+".S1", style=label.style_none)
Wr2L := label.new(bar_index, Wr2Level, WhigherTF+".R2", style=label.style_none)
Ws2L := label.new(bar_index, Ws2Level, WhigherTF+".S2", style=label.style_none)
Wr3L := label.new(bar_index, Wr3Level, WhigherTF+".R3", style=label.style_none)
Ws3L := label.new(bar_index, Ws3Level, WhigherTF+".S3", style=label.style_none)
label.delete(Wr3L[1])
label.delete(Ws3L[1])
label.delete(Wr2L[1])
label.delete(Wr1L[1])
label.delete(WpL[1])
label.delete(Ws1L[1])
label.delete(Ws2L[1])
line.delete(Wr2Line[1])
line.delete(Wr1Line[1])
line.delete(Wm3Line[1])
line.delete(WpLine[1])
line.delete(Ws1Line[1])
line.delete(Ws2Line[1])
line.delete(Wr3Line[1])
line.delete(Ws3Line[1])
if not na(WpLine) and line.get_x2(WpLine) != bar_index
line.set_x2(Wr1Line, bar_index)
line.set_x2(WpLine, bar_index)
line.set_x2(Ws1Line, bar_index)
line.set_x2(Wr2Line, bar_index)
line.set_x2(Ws2Line, bar_index)
line.set_x2(Wr3Line, bar_index)
line.set_x2(Ws3Line, bar_index)
MchosenColor(c_)=> c_ == "aqua" ? color.aqua : c_ == "black" ? color.black : c_ == "blue" ? color.blue : c_ == "fuchsia" ? color.fuchsia : c_ == "gray" ? color.gray : c_ == "green" ? color.green : c_ == "lime" ? color.lime : c_ == "maroon" ? color.maroon : c_ == "navy" ? color.navy : c_ == "olive" ? color.olive : c_ == "orange" ? color.orange : c_ == "purple" ? color.purple : c_ == "red" ? color.red : c_ == "silver" ? color.silver : c_ == "teal" ? color.teal : c_ == "white" ? color.white : c_ == "yellow" ? color.yellow : color.black
MhigherTF = "M"
Mmy_color = input(title="Monthly Color", defval="green", options=["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"])
MprevCloseHTF = security(syminfo.tickerid, MhigherTF, close[1], lookahead=true)
MprevOpenHTF = security(syminfo.tickerid, MhigherTF, open[1], lookahead=true)
MprevHighHTF = security(syminfo.tickerid, MhigherTF, high[1], lookahead=true)
MprevLowHTF = security(syminfo.tickerid, MhigherTF, low[1], lookahead=true)
MpLevel = (MprevHighHTF + MprevLowHTF + MprevCloseHTF) / 3
Mr1Level = MpLevel * 2 - MprevLowHTF
Ms1Level = MpLevel * 2 - MprevHighHTF
Mr2Level = MpLevel + (MprevHighHTF - MprevLowHTF)
Ms2Level = MpLevel - (MprevHighHTF - MprevLowHTF)
Mr3Level = MpLevel + 2*(MprevHighHTF - MprevLowHTF)
Ms3Level = MpLevel - 2*(MprevHighHTF - MprevLowHTF)
var line Mr1Line = na
var line MpLine = na
var line Ms1Line = na
var line Mr2Line = na
var line Ms2Line = na
var line Mr3Line = na
var line Ms3Line = na
var line Mm3Line = na
var label Mr3L = na
var label Mr1L = na
var label MpL = na
var label Ms1L = na
var label Ms2L = na
var label Ms3L = na
var label Mr2L = na
if MpLevel[1] != MpLevel
line.set_x2(Mr1Line, bar_index)
line.set_x2(MpLine, bar_index)
line.set_x2(Ms1Line, bar_index)
line.set_x2(Mr2Line, bar_index)
line.set_x2(Ms2Line, bar_index)
line.set_x2(Mr3Line, bar_index)
line.set_x2(Ms3Line, bar_index)
line.set_extend(Mr1Line, extend.none)
line.set_extend(MpLine, extend.none)
line.set_extend(Ms1Line, extend.none)
line.set_extend(Mr2Line, extend.none)
line.set_extend(Ms2Line, extend.none)
line.set_extend(Mr3Line, extend.none)
line.set_extend(Ms3Line, extend.none)
Mr1Line := line.new(bar_index, Mr1Level, bar_index, Mr1Level, width=1, extend=extend.right, color=color.green)
MpLine := line.new(bar_index, MpLevel, bar_index, MpLevel, width=3, extend=extend.right, color=MchosenColor(Mmy_color))
Ms1Line := line.new(bar_index, Ms1Level, bar_index, Ms1Level, width=1,extend=extend.right, color=#FF5252)
Mr2Line := line.new(bar_index, Mr2Level, bar_index, Mr2Level, width=1, extend=extend.right,style=line.style_dotted, color=color.green)
Ms2Line := line.new(bar_index, Ms2Level, bar_index, Ms2Level, width=1,extend=extend.right, color=#FF5252)
Mr3Line := line.new(bar_index, Mr3Level, bar_index, Mr3Level, width=1, extend=extend.right,style=line.style_dashed, color=color.green)
Ms3Line := line.new(bar_index, Ms3Level, bar_index, Ms3Level, width=1,extend=extend.right, color=#FF5252)
Mr1L := label.new(bar_index, Mr1Level, MhigherTF+".R1", style=label.style_none)
var label label1 = na
MpL := label.new(bar_index, MpLevel, MhigherTF+".P", style=label.style_none)
label.set_textalign(label1, text.align_right)
Ms1L := label.new(bar_index, Ms1Level, MhigherTF+".S1", style=label.style_none)
Mr2L := label.new(bar_index, Mr2Level, MhigherTF+".R2", style=label.style_none)
Ms2L := label.new(bar_index, Ms2Level, MhigherTF+".S2", style=label.style_none)
Mr3L := label.new(bar_index, Mr3Level, MhigherTF+".R3", style=label.style_none)
Ms3L := label.new(bar_index, Ms3Level, MhigherTF+".S3", style=label.style_none)
label.delete(Mr3L[1])
label.delete(Ms3L[1])
label.delete(Mr2L[1])
label.delete(Mr1L[1])
label.delete(MpL[1])
label.delete(Ms1L[1])
label.delete(Ms2L[1])
line.delete(Mr2Line[1])
line.delete(Mr1Line[1])
line.delete(Mm3Line[1])
line.delete(MpLine[1])
line.delete(Ms1Line[1])
line.delete(Ms2Line[1])
line.delete(Mr3Line[1])
line.delete(Ms3Line[1])
if not na(MpLine) and line.get_x2(MpLine) != bar_index
line.set_x2(Mr1Line, bar_index)
line.set_x2(MpLine, bar_index)
line.set_x2(Ms1Line, bar_index)
line.set_x2(Mr2Line, bar_index)
line.set_x2(Ms2Line, bar_index)
line.set_x2(Mr3Line, bar_index)
line.set_x2(Ms3Line, bar_index) |
Price action: candlestick trend painter | https://www.tradingview.com/script/v4iTwlBb-Price-action-candlestick-trend-painter/ | Drbondsbody | https://www.tradingview.com/u/Drbondsbody/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Drbondsbody
//@version=5
indicator("HH/HL",shorttitle='HH/HL', overlay=true)
CandleHH=high>high[1] and low>low[1]
CandleLL=low<low[1] and high<high[1]
barcolor(CandleHH? color.green : CandleLL? color.red : color.white)
|
Local Polynomial Regression | https://www.tradingview.com/script/Gt1znE6D/ | wzkkzw12345 | https://www.tradingview.com/u/wzkkzw12345/ | 66 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wzkkzw12345
//@version=5
indicator("Kernel Regression",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.int(500,'Look Back Length',maxval=500,minval=0)
kernel_size = input.int(45,'Kernel Size',maxval=150,minval=0)
h = input.float(8.5,'Bandwidth')
src = (close*2+high+low)/4//input.source(hlc3,'Estimation Source')
order = input.int(4, 'Order of Regression',maxval=10,minval=0)
x_scaling = input.int(10, 'Custom Scaling for Scalability (to compute (x/scaling)^i)',maxval=100,minval=1)
use_volume = input.bool(false, "To use volume as an additional weight (currently it seems impossible...)")
repaint = input.bool(true, "Repaint the curve when prices get known")
//var log_src = 0.
log_src = request.security(syminfo.tickerid, timeframe.period, math.log(src))
//max_bars_back(log_src, 1000)
up_col = input.color(#39ff14,'Colors',inline='col')
dn_col = input.color(#ff1100,'',inline='col')
//----
n = bar_index
var k = 2
var kernel = array.new_float(0)
var ln = array.new_line(0)
var labels = array.new_label(0)
var weight_matrix = array.new_float((kernel_size+1)*(order+1),0)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
labelset(l,x,y,text_,col,style,textcolor,textalign)=>
label.set_xy(l,x,y)
label.set_text(l,text_)
label.set_color(l,col)
label.set_style(l,style)
label.set_textcolor(l,textcolor)
label.set_textalign(l,textalign)
// ------------------------------------------------------------------------------------
// Helper functions for simulating global variables using arrays
// ------------------------------------------------------------------------------------
new_string(value) =>
//{
array.new_string(1, value)
//}
new_color(value) =>
//{
array.new_color(1, value)
//}
get(global_variable_id) =>
//{
if (array.size(global_variable_id) > 0)
array.get(global_variable_id, 0)
//}
set(global_variable_id, value) =>
//{
if (array.size(global_variable_id) > 0)
array.set(global_variable_id, 0, value)
//}
//} GlobalVariables
// ====================================================================================================================================================
//
// LIBRARY: OutputStreams
//
// ====================================================================================================================================================
//{
// ------------------------------------------------------------------------------------
// Standard output
// ------------------------------------------------------------------------------------
var color NO_COLOR = color.new(#000000, 100)
var string[] output_stream = new_string("")
var color[] output_color = new_color(color.white)
var label output_label = label.new(0, 0, style = label.style_label_left, color = NO_COLOR, textcolor = array.get(output_color, 0))
clear_output() =>
//{
array.clear(output_stream)
array.push(output_stream, "")
label.set_text(output_label, get(output_stream))
//}
set_output_visible(visible) =>
//{
if (not visible)
//{
label.set_style(output_label, label.style_none)
label.set_textcolor(output_label, NO_COLOR)
//}
else
//{
label.set_style(output_label, label.style_label_left)
label.set_textcolor(output_label, get(output_color))
//}
//}
set_output_color(clr) =>
//{
set(output_color, clr)
//}
set_output_location(max_y, min_y) =>
//{
label.set_y(output_label, (max_y + min_y) / 2)
//}
output(msg) =>
//{
set(output_stream, get(output_stream) + msg)
label.set_x(output_label, bar_index)
label.set_text(output_label, get(output_stream))
//}
reset_output() =>
//{
clear_output()
set_output_color(color.white)
set_output_location(0, 0)
//}
//} GlobalVariables
// ====================================================================================================================================================
//
// LIBRARY: ArrayLib
//
// ====================================================================================================================================================
//{
// ------------------------------------------------------------------------------------
// Create an array from a time series
// ------------------------------------------------------------------------------------
array_create_from_series(series, lookback) =>
//{
float[] new_array = array.copy(array.new_float(lookback, 0))
for i = 0 to lookback - 1
//{
if (i >= lookback)
break
array.set(new_array, i, nz(series[i]))
//}
new_array
//}
// ------------------------------------------------------------------------------------
// Euclidean 2-norm of an array
// ------------------------------------------------------------------------------------
array_2_norm(array) =>
//{
int size = array.size(array)
float result = 0
for i = 0 to size - 1
//{
if (i >= size)
break
result := result + math.pow(array.get(array, i), 2)
//}
math.sqrt(result)
//}
// ------------------------------------------------------------------------------------
// Dot product of two arrays (vectors)
// ------------------------------------------------------------------------------------
array_dot_product(a_vector, b_vector) =>
//{
int size_a = array.size(a_vector)
int size_b = array.size(b_vector)
float result = 0
if (size_b >= size_a)
//{
for i = 0 to size_a - 1
//{
if (i >= size_a)
break
result := result + array.get(a_vector, i) * array.get(b_vector, i)
//}
//}
result
//}
//} ArrayLib
// ====================================================================================================================================================
//
// LIBRARY: MatrixLib
//
// ====================================================================================================================================================
//{
// ------------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------------
//{
var bool MM_END_IF = false
var float MM_RANK_CUTOFF = 10E-12
var int MM_META_SIZE = 2
var int MM_ROWS_INDEX = 0
var int MM_COLUMNS_INDEX = 1
var int MM_OP_ADD = 100
var int MM_OP_SUBTRACT = 101
var int MM_OP_MULTIPLY = 102
var int MM_OP_DIVIDE = 103
var int MM_OP_MODULUS = 104
var int MM_OP_SIN = 200
var int MM_OP_ASIN = 201
var int MM_OP_COS = 202
var int MM_OP_ACOS = 203
var int MM_OP_TAN = 204
var int MM_OP_ATAN = 205
var int MM_OP_TANH = 206
var int MM_OP_ATANH = 207
var int MM_OP_LOG = 208
var int MM_OP_LOG10 = 209
var int MM_OP_SIGMOID = 210
var int MM_OP_SILU = 211
var int MM_OP_GELU = 212
var int MM_OP_RELU = 213
var int MM_OP_LEAKY_RELU = 214
var int MM_OP_SIGN = 215
var int MM_MLR_ESTIMATE = 0
var int MM_MLR_SE_ESTIMATE = 1
var int MM_MLR_F_VALUE = 2
var int MM_MLR_CI = 3
var int MM_MLR_P_VALUE = 4
var int MM_MLR_R2 = 5
var int MM_MLR_ADJ_R2 = 6
var int MM_MLR_SSR = 7
var int MM_MLR_SSE = 8
var int MM_MLR_SST = 9
var int MM_MLR_MSR = 10
var int MM_MLR_MSE = 11
var int MM_MLR_MST = 12
var int MM_MLR_DFR = 13
var int MM_MLR_DFE = 14
var int MM_MLR_DFT = 15
var int MM_MLR_NUM_OF_OBSERVATIONS = 16
var int MM_MLR_NUM_OF_X_VARS = 17
var int MM_MLR_HAS_CONSTANT = 18
//} Constants
// ------------------------------------------------------------------------------------
// Functions
// ------------------------------------------------------------------------------------
//{
// ------------------------------------------------------------------------------------
// Create and return a copy of the specified matrix
// ------------------------------------------------------------------------------------
matrix_copy(matrix_array) =>
//{
array.copy(matrix_array)
//}
// ------------------------------------------------------------------------------------
// Create and return a new matrix with the same shape as the specified matrix, but
// filled with 0's
// ------------------------------------------------------------------------------------
matrix_copy_shape(matrix_array) =>
//{
int size = array.size(matrix_array)
float[] result = array.copy(matrix_array)
if (size > MM_META_SIZE)
//{
for i = MM_META_SIZE to size - 1
array.set(result, i, 0)
//}
result
//}
// ------------------------------------------------------------------------------------
// Clear a matrix, removing all rows and columns, resulting in an empty matrix
// ------------------------------------------------------------------------------------
matrix_clear(matrix_array) =>
//{
array.clear(matrix_array)
for i = 1 to MM_META_SIZE
array.push(matrix_array, 0)
//}
// ------------------------------------------------------------------------------------
// Create an empty matrix
// ------------------------------------------------------------------------------------
matrix_create_empty() =>
//{
array.copy(array.new_float(MM_META_SIZE, 0))
//}
// ------------------------------------------------------------------------------------
// Create a 'rows' by 'columns' matrix
// ------------------------------------------------------------------------------------
matrix_create(rows, columns) =>
//{
float[] new_matrix = matrix_create_empty()
if (rows > 0 and columns > 0)
//{
for i = 0 to rows * columns - 1
array.push(new_matrix, 0)
array.set(new_matrix, MM_ROWS_INDEX, rows)
array.set(new_matrix, MM_COLUMNS_INDEX, columns)
//}
new_matrix
//}
// ------------------------------------------------------------------------------------
// Create an identity matrix
// ------------------------------------------------------------------------------------
matrix_create_identity(size) =>
//{
float[] new_matrix = matrix_create_empty()
if (size > 0)
//{
for column = 0 to size - 1
for row = 0 to size - 1
array.push(new_matrix, column == row ? 1 : 0)
array.set(new_matrix, MM_ROWS_INDEX, size)
array.set(new_matrix, MM_COLUMNS_INDEX, size)
//}
new_matrix
//}
// ------------------------------------------------------------------------------------
// Get the column count of a matrix
// ------------------------------------------------------------------------------------
matrix_get_column_count(matrix_array) =>
//{
int(array.get(matrix_array, MM_COLUMNS_INDEX))
//}
// ------------------------------------------------------------------------------------
// Get the row count of a matrix
// ------------------------------------------------------------------------------------
matrix_get_row_count(matrix_array) =>
//{
int(array.get(matrix_array, MM_ROWS_INDEX))
//}
// ------------------------------------------------------------------------------------
// Get the underlying array index of the start of the specified column
// ------------------------------------------------------------------------------------
matrix_get_column_index(matrix_array, column) =>
//{
int(MM_META_SIZE + matrix_get_row_count(matrix_array) * column)
//}
// ------------------------------------------------------------------------------------
// Get matrix order as a string in the format "ROWSxCOLUMNS"
// ------------------------------------------------------------------------------------
matrix_get_order(matrix_array) =>
//{
str.tostring(matrix_get_row_count(matrix_array), "0") + "x" + str.tostring(matrix_get_column_count(matrix_array), "0")
//}
// ------------------------------------------------------------------------------------
// Get the size of the matrix (row count multiplied by column count)
// ------------------------------------------------------------------------------------
matrix_get_size(matrix_array) =>
//{
matrix_get_row_count(matrix_array) * matrix_get_column_count(matrix_array)
//}
// ------------------------------------------------------------------------------------
// Returns true if the matrix is square (same number of rows as columns)
// ------------------------------------------------------------------------------------
matrix_is_square(matrix_array) =>
//{
matrix_get_row_count(matrix_array) == matrix_get_column_count(matrix_array)
//}
// ------------------------------------------------------------------------------------
// Get the value from a specific position in a matrix
// ------------------------------------------------------------------------------------
matrix_get(matrix_array, row, column) =>
//{
int row_count = matrix_get_row_count(matrix_array)
int column_count = matrix_get_column_count(matrix_array)
int value_index = matrix_get_column_index(matrix_array, column) + row
if (value_index <= array.size(matrix_array) - 1 and row < row_count and column < column_count and row >= 0 and column >= 0)
array.get(matrix_array, value_index)
//}
// ------------------------------------------------------------------------------------
// Set the value at a specific position in a matrix
// ------------------------------------------------------------------------------------
matrix_set(matrix_array, row, column, value) =>
//{
int row_count = matrix_get_row_count(matrix_array)
int column_count = matrix_get_column_count(matrix_array)
int value_index = matrix_get_column_index(matrix_array, column) + row
if (value_index <= array.size(matrix_array) - 1 and row < row_count and column < column_count and row >= 0 and column >= 0)
array.set(matrix_array, value_index, value)
//}
// ------------------------------------------------------------------------------------
// Transpose a matrix so that each row becomes a column and return the new matrix
// ------------------------------------------------------------------------------------
matrix_transpose(matrix_array) =>
//{
int row_count = matrix_get_row_count(matrix_array)
int column_count = matrix_get_column_count(matrix_array)
// Create the matrix that will store the result of the operation
float[] result_matrix = matrix_create_empty()
// Set the metadata of the transposed matrix
array.set(result_matrix, MM_ROWS_INDEX, column_count)
array.set(result_matrix, MM_COLUMNS_INDEX, row_count)
// Transpose the matrix
int value_index = na
if (row_count > 0 and column_count > 0)
//{
for row = 0 to row_count - 1
//{
for column = 0 to column_count - 1
//{
value_index := matrix_get_column_index(matrix_array, column) + row
array.push(result_matrix, array.get(matrix_array, value_index))
//}
//}
//}
result_matrix
//}
// ------------------------------------------------------------------------------------
// Perform a matrix multiplication and return the result in a new matrix
// ------------------------------------------------------------------------------------
matrix_multiply(matrix_a, matrix_b) =>
//{
int row_count_a = matrix_get_row_count(matrix_a)
int row_count_b = matrix_get_row_count(matrix_b)
int column_count_a = matrix_get_column_count(matrix_a)
int column_count_b = matrix_get_column_count(matrix_b)
// Create a new matrix to store the result of the operation in
float[] result_matrix = matrix_create(row_count_a, column_count_b)
if (row_count_a > 0 and column_count_a > 0 and column_count_b > 0 and column_count_a == row_count_b)
//{
float value_a = na
float value_b = na
float value_result = na
int result_index = na
// Perform the multiplication matrix operation and store this in the result matrix
for row_a = 0 to row_count_a - 1
//{
for column_b = 0 to column_count_b - 1
//{
for column_a = 0 to column_count_a - 1
//{
float temp = 0
for row_b = 0 to row_count_b - 1
//{
float element_a = matrix_get(matrix_a, row_a, row_b)
float element_b = matrix_get(matrix_b, row_b, column_b)
temp := temp + element_a * element_b
//}
matrix_set(result_matrix, row_a, column_b, temp)
//}
//}
//}
//}
result_matrix
//}
// ------------------------------------------------------------------------------------
// Decomposer the matrix into an orthogonal matrix and an upper triangular matrix,
// using QR decomposition
//
// Original code taken from here (with consent from the author, tbiktag):
// https://www.tradingview.com/script/0GhsW1KR-Moving-Regression/
// ------------------------------------------------------------------------------------
matrix_get_qr_decomposition(matrix_array) =>
//{
int row_count = matrix_get_row_count(matrix_array)
int column_count = matrix_get_column_count(matrix_array)
float[] q = matrix_create(row_count, column_count)
float[] r = matrix_create(column_count, column_count)
if (row_count > 0 and column_count > 0)
//{
float norm = 0
float value = 0
float[] a = array.new_float(row_count)
// Get the first column of 'matrix_array' and its 2-norm
for row = 0 to row_count - 1
//{
value := matrix_get(matrix_array, row, 0)
norm := norm + math.pow(value, 2)
array.set(a, row, value)
//}
norm := math.sqrt(norm)
// Assign first diagonal element of R and first column of Q
matrix_set(r, 0, 0, norm)
for row = 0 to row_count - 1
matrix_set(q, row, 0, array.get(a, row) / norm)
// Repeat for the rest of the columns
if (column_count > 1)
//{
for k = 1 to column_count - 1
//{
for row = 0 to row_count - 1
array.set(a, row, matrix_get(matrix_array, row, k))
for column = 0 to k - 1
//{
if (column >= k)
break
// Get R[column, k] as scalar product of Q[column] column an A[k] column
norm := 0
for row = 0 to row_count - 1
norm := norm + matrix_get(q, row, column) * array.get(a, row)
matrix_set(r, column, k, norm)
// Update vector A
for row = 0 to row_count - 1
//{
value := array.get(a, row) - norm * matrix_get(q, row, column)
array.set(a, row, value)
//}
//}
// Get diagonal R[k, k] and Q[k] column
norm := array_2_norm(a)
matrix_set(r, k, k, norm)
for row = 0 to row_count - 1
matrix_set(q, row, k, array.get(a, row) / norm)
//}
//}
[q, r]
//}
else
[matrix_create_empty(), matrix_create_empty()]
//}
// ------------------------------------------------------------------------------------
// Get the pseudo-inverse from QR
//
// Original code taken from here (with consent from the author, tbiktag):
// https://www.tradingview.com/script/0GhsW1KR-Moving-Regression/
// ------------------------------------------------------------------------------------
matrix_get_pseudo_inverse_from_qr(q, r) =>
//{
int column_count = matrix_get_column_count(q)
float[] q_transposed = matrix_transpose(q)
var r_inv = matrix_create(column_count, column_count)
float value = 0
matrix_set(r_inv, 0, 0, 1 / matrix_get(r, 0, 0))
if (column_count > 1)
//{
for column = 1 to column_count - 1
//{
for row = 0 to column - 1
//{
value := 0
for k = row to column - 1
//{
if (k >= column)
break
value := value + matrix_get(r_inv, row, k) * matrix_get(r, k, column)
//}
matrix_set(r_inv, row, column, value)
//}
for k = 0 to column - 1
matrix_set(r_inv, k, column, -matrix_get(r_inv, k, column) / matrix_get(r, column, column))
matrix_set(r_inv, column, column, 1 / matrix_get(r, column, column))
//}
//}
matrix_multiply(r_inv, q_transposed)
//}
matrix_get_pseudo_inverse(matrix_array) =>
//{
[q, r] = matrix_get_qr_decomposition(matrix_array)
matrix_get_pseudo_inverse_from_qr(q, r)
//}
set_output_location(ta.highest(close, 300), ta.lowest(close, 300))
var power_cache = array.new_float(0)
//var inverse_matrix = array.new_float(0)
//var x_data_matrix_to_solve = matrix_create(int(order)+1, int(order)+1)
// *********** Initialization **************
if barstate.isfirst
for i = 0 to length-1 // ***
array.push(ln,line.new(na,na,na,na))
for i = 0 to (length-1)/2
array.push(labels,label.new(na,na,na))
for dist = 0 to kernel_size
array.push(kernel,math.exp(-(math.pow(dist/h,2)/2)))
// prepare the inverse matrices for different points (from border to center) to solve for the constant factor in the polynomial regression
if order !=0
x_data_matrix_to_solve = matrix_create(int(order)+1, int(order)+1)
// add the data from the left-hand-side, i.e. negative x values
for o = 0 to 2*order
sum_x_moment = 0.
for x = - kernel_size to 0
sum_x_moment += array.get(kernel,math.abs(x)) * math.pow(x/x_scaling,o)
for index_on_row = 0 to order
index_on_column = o - index_on_row
if index_on_column >= 0 and index_on_column <= order
matrix_set(x_data_matrix_to_solve, index_on_row, index_on_column, sum_x_moment)
inverse_matrix = matrix_get_pseudo_inverse(x_data_matrix_to_solve)
for i = 0 to order
array.set(weight_matrix, i, matrix_get(inverse_matrix, i, 0))
//output( str.tostring(matrix_get(inverse_matrix, i, 0)))
for x = 1 to kernel_size
for o = 0 to 2*order
additional_moment_for_data_on_the_right = array.get(kernel,math.abs(x)) * math.pow(x/x_scaling,o)
for index_on_row = 0 to order
index_on_column = o - index_on_row
if index_on_column >= 0 and index_on_column <= order
matrix_set(x_data_matrix_to_solve, index_on_row, index_on_column, additional_moment_for_data_on_the_right + matrix_get(x_data_matrix_to_solve, index_on_row, index_on_column))
inverse_matrix := matrix_get_pseudo_inverse(x_data_matrix_to_solve)
for i = 0 to order
array.set(weight_matrix, (order+1)*x+i, matrix_get(inverse_matrix, i, 0))
for x = -kernel_size to kernel_size
for o = 0 to order
array.push(power_cache, math.pow(x/x_scaling, o))
//----
line l = na // ****
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
max_bars_back(src, 900)
max_bars_back(log_src, 900)
max_bars_back(time, 900)
//log_src = array.new_float(length)
y = array.new_float(0)
//for i = 0 to length-1
// array.set(log_src, i, math.log(src[i]))
for i = 0 to length-1
sum = 0.
sumw = 0.
prediction = 0.
start_index = repaint ? math.max(0, i-kernel_size) : i
if order == 0
for j = start_index to (i+kernel_size)
w = array.get(kernel, math.abs(i-j))
sum += log_src[j]*w //math.log(src[j])*w//array.get(log_src, j)*w//
sumw += w
prediction := math.exp(sum/sumw)
else
y_moments = array.new_float(order+1, 0) // including the zero moment
volume_weight_total = 0.
counts = 0
for j = start_index to (i+kernel_size) // *********** Although in our mathematical treatment, we have defined data on the right as having x>0, here, larger indices refer to data on the left, and should be treated as negative
weighted_y = log_src[j]*array.get(kernel, math.abs(i-j))
power_cache_index = (i-j+kernel_size)*(order+1)
for o = 0 to order
pow = array.get(power_cache, power_cache_index+o)
array.set(y_moments, o, array.get(y_moments, o) + weighted_y*pow)
weight_matrix_start_index = repaint ? math.min(i, kernel_size)*(order+1) : 0
for o = 0 to order
prediction += array.get(y_moments, o)*array.get(weight_matrix, weight_matrix_start_index+o)
prediction := math.exp(prediction)
array.push(y,prediction)
i_label = 0
trend_label = true
for i = 0 to length-2
y2 = array.get(y,i+1)
y1 = array.get(y,i)
if i <= length-1
l := array.get(ln,i)
lset(l ,n-i,y1 ,n-i-1,y2 ,y2 > y1 ? #ff1100 : #39ff14)
label_ = array.get(labels, i_label)
if i != length-2 and trend_label
label_ := array.get(labels, i_label)
y3 = array.get(y,i+2)
if y1 > y2 and y2 < y3
labelset(label_, n-i,y1,'▲',col=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
i_label += 1
trend_label:= false
if y1 < y2 and y2 > y3
labelset(label_, n-i,y1,'▼',col=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
i_label += 1
trend_label:= false |
Balgat Ekibi | https://www.tradingview.com/script/sAvrMklF-Balgat-Ekibi/ | absoylu | https://www.tradingview.com/u/absoylu/ | 47 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © absoylu
//@version=5
indicator("Balgat Ekibi",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.float(500,'Window Size',maxval=500,minval=0)
h = input.float(8.,'Bandwidth')
mult = input.float(2.)
src = input.source(close,'Source')
up_col = input.color(#39ff14,'Colors',inline='col')
dn_col = input.color(#ff1100,'',inline='col')
//----
n = bar_index
var k = 2
var upper = array.new_line(0)
var lower = array.new_line(0)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length/k-1
array.push(upper,line.new(na,na,na,na))
array.push(lower,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)
sum_e = 0.
for i = 0 to length-1
sum = 0.
sumw = 0.
for j = 0 to length-1
w = math.exp(-(math.pow(i-j,2)/(h*h*2)))
sum += src[j]*w
sumw += w
y2 = sum/sumw
sum_e += math.abs(src[i] - y2)
array.push(y,y2)
mae = sum_e/length*mult
for i = 1 to length-1
y2 = array.get(y,i)
y1 = array.get(y,i-1)
up := array.get(upper,i/k)
dn := array.get(lower,i/k)
lset(up,n-i+1,y1 + mae,n-i,y2 + mae,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)
if src[i] > y1 + mae and src[i+1] < y1 + mae
label.new(n-i,src[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
if src[i] < y1 - mae and src[i+1] > y1 - mae
label.new(n-i,src[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
cross_up := array.get(y,0) + mae
cross_dn := array.get(y,0) - mae
alertcondition(ta.crossover(src,cross_up),'Down','Down')
alertcondition(ta.crossunder(src,cross_dn),'Up','Up') |
Calculate target by Range [Wyckoff,PnF] | https://www.tradingview.com/script/LjvwCJk4-Calculate-target-by-Range-Wyckoff-PnF/ | meomeo105 | https://www.tradingview.com/u/meomeo105/ | 808 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © meomeo105
//@version=5
indicator(title = 'Calculate target by Range [Wyckoff,PnF]',shorttitle = "Target",overlay = true)
DefaultSetting = "DefaultSetting"
mode = input.string(title='Box Size Assingment Method', defval='ATR', options=['ATR','Traditional'],group = DefaultSetting)
_modevalue = input.float(title='Value ATR/Traditional', defval=14, minval=0.000000000000001,group = DefaultSetting)
modevalue = mode=='ATR' ? math.ceil(_modevalue) : _modevalue
reversal = input.int(1, title='Reversal', minval=1,group = DefaultSetting)
_source = input.string(defval='Close', title='Source', options=['Close', 'High/Low'],group = DefaultSetting)
source = _source == "High/Low" ? "hl" : "close"
time1 = input.time(defval=0, title='Time Start',confirm = true,group = DefaultSetting , inline = "time1")
time2 = input.time(defval=0, title='End of Range',confirm = true , inline = "time2",group = DefaultSetting)
// Input Table
group_table = 'Table Infomation'
string tableYpos = input.string('top', '↕', inline='01', group=group_table, options=['top', 'middle', 'bottom'])
string tableXpos = input.string('right', '↔', inline='01', group=group_table, options=['left', 'center', 'right'], tooltip='Position on the chart.')
string textSize_ = input.string('Auto', 'Table Text Size', options=['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], group=group_table)
string textSize = textSize_ == 'Auto' ? size.auto : textSize_ == 'Tiny' ? size.tiny : textSize_ == 'Small' ? size.small : textSize_ == 'Normal' ? size.normal : textSize_ == 'Large' ? size.large : size.huge
color cell_col = input.color(color.white, 'Color', group=group_table)
bgcolor(time == time1 or time == time2 ? color.blue : na)
pnfTicker = ticker.pointfigure(syminfo.tickerid, source, mode, modevalue, reversal)
_time = request.security(pnfTicker, timeframe.period, time, barmerge.gaps_on)
_box = request.security(pnfTicker, timeframe.period, close > open ? open - close[1] : close[1] - open, barmerge.gaps_on)
_box := na(_box) ? _box[1] : math.abs(_box)
box = mode == 'ATR' ? _box : modevalue
pnfcolumns = _time >= math.min(time1,time2) and _time <= math.max(time1,time2) ? 1 : 0
//----------Show infomation-----------
// Table (collumn,row)
var table tableInfo = table.new(tableYpos + '_' + tableXpos, 1, 1, border_width=1)
table.cell(tableInfo, 0, 0, str.tostring(ta.cum(pnfcolumns)) + " * " + str.tostring(box) + " * " + str.tostring(reversal) + " = " + str.tostring(ta.cum(pnfcolumns)*box*reversal) , text_color=cell_col, bgcolor=color.new(cell_col, 90), text_size=textSize)
|
TPO Market Profile [Kioseff Trading] | https://www.tradingview.com/script/P9aVc7vy-TPO-Market-Profile-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 1,466 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Realtime TPO Profile [Kioseff Trading]", shorttitle = "Realtime TPO Profile", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 2000)
ti = input.string(defval = "Regular", title = "Calculation Type", options = ["Regular", "Fixed Range", "Fixed Interval"], group = "Calculation Type")
auto = input.string(defval = "Custom", options = ["Auto", "Custom"], title = "Auto Calculate Tick Levels? Custom?", inline = "1", group = "Current Session Configurations")
tickzz = input.float(defval = 50 ,title = "Ticks", inline = "1", group = "Current Session Configurations")
tickLevels = input.bool(false, title = "Show Tick Levels?", group = "Current Session Configurations")
textSize = input.string(defval = "Small", options = ["Auto","Tiny", "Small", "Normal", "Large", "Huge"], group = "Current Session Configurations")
showIb = input.bool(defval = false, title = "Show Initial Balance Range?", group = "Current Session Configurations")
sess = input.string(defval = "D", title = "Recalculate After How Much Time?", tooltip = "from 1 to 1440 for minutes \nfrom 1D to 365D for days \nfrom 1W to 52W for weeks \nfrom 1M to 12M for months", group = 'If "Regular" is Selected')
st = input.time(defval = timestamp("19 Sep 2022 00:00 +0300"), title = "Fixed Range Start", group = 'If "Fixed Range" Is Selected')
timE = input.session(defval = "1300-1700", title = "Time Range", group = 'If "Fixed Interval" is Selected', tooltip = 'Select "Fixed Interval" For The "Calculation Type" Setting To Activate This Feature')
showPre = input.bool(defval = true, title = "Show Previous Sessions TPO?", group = "Previous Session Settings")
blackBox = input.bool(defval = false, title = "Segment Previous Sessions With Black Box?", group = "Previous Session Settings")
rang = input.bool(defval = true, title = "Show Previous Sessions Ranges?", group = "Previous Session Settings")
distCalc = input.float(defval = 5.0, title = "% Distance to Hide Old SP Lines", tooltip = "If Price Exceeds The % Threshold Defined For This
Setting (Price Distance From An Existing Sp Line - The Sp Line Will Dissapear Until Price Is Within Proximity Once More",
group = "Previous Session Settings")
distCalc2 = input.float(defval = 5.0, title = "% Distance to Hide Old VA Lines", tooltip = "If Price Exceeds The % Threshold Defined For This
Setting (Price Distance From An Existing Va Line - The Va Line Will Dissapear Until Price Is Within Proximity Once More",
group = "Previous Session Settings")
distCalc3 = input.float(defval = 5.0, title = "% Distance to Hide Old POC Lines", tooltip = "If Price Exceeds The % Threshold Defined For This
Setting (Price Distance From An Existing Poc Line - The Poc Line Will Dissapear Until Price Is Within Proximity Once More",
group = "Previous Session Settings")
spShw = input.bool(defval = true, title = "Show SP Lines and Labels", group = "Display Options", tooltip = "If Deselected, TPO Letters Will Only Turn Red When a SP Forms. No Other Identifying Features are Displayed")
fr = input.bool(defval = true, title = "Show Fixed Range Label and Line?" , group ="Display Options")
warn = input.bool(defval = true, title = "Show Warning", group = "Display Options")
col = input.color(defval = color.gray, title = "Main Character Color (Gray Default)", group = "Colors")
col1 = input.color(defval = color.red , title = "SP Character Color (Red Default)", group = "Colors")
col2 = input.color(defval = color.yellow, title = "POC Character Color (Yellow Default)", group = "Colors")
col3 = input.color(defval = color.blue, title = "IB Character Color (Blue Default)", group = "Colors")
col4 = input.color(defval = color.lime, title = "Value Area Color (Lime Default)", group = "Colors")
col5 = input.color(defval = color.white, title = "Value Area Letter Color (White Default)", group = "Colors")
fnt = input.string(defval = "Default", title = "Font Type", options = ["Default", "Monospace"], group = "Colors")
if timeframe.isdwm
ti := "Fixed Range"
if fr == true and barstate.islast
line.new(math.round(st), close, math.round(st), close + 0.001, extend = extend.both, color = color.white, width = 4, xloc = xloc.bar_time)
if ti != "Fixed Range"
var box frStart = box.new(math.round(st), high + ta.tr, math.round(st), low - ta.tr,
bgcolor = color.new(color.white, 100), border_color = na, text_size = size.normal, text_color = color.white, text_wrap = text.wrap_none, text = "If Selected in Settings, \nFixed Range Begins Here", xloc = xloc.bar_time)
fixTime = time(timeframe.period, timE)
fonT = switch fnt
"Default" => font.family_default
"Monospace" => font.family_monospace
finTim = switch ti
"Regular" => timeframe.change(sess)
"Fixed Range" => time[1] < st and time >= st
"Fixed Interval" => na(fixTime[1]) and not na(fixTime)
sz = switch textSize
"Auto" => size.auto
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
var string [] str = array.from(
" A",
" B",
" C",
" D",
" E",
" F",
" G",
" H",
" I",
" J",
" K",
" L",
" M",
" N",
" O",
" P",
" Q",
" R",
" S",
" T",
" U",
" V",
" W",
" X",
" Y",
" Z",
" a",
" b",
" c",
" d",
" e",
" f",
" g",
" h",
" i",
" j",
" k",
" l",
" m",
" n",
" o",
" p",
" q",
" r",
" s",
" t",
" u",
" v",
" w",
" x",
" y",
" z"
)
if barstate.isfirst
sX = ""
for i = 0 to 51
sX := array.get(str, i) + "1 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "2 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "3 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "4 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "5 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "6 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "7 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "8 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "9 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "10 " // => Loops are run sequentially, not simultaneously, so string characters populate in order
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "11 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "12 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "13 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "14 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "15 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "16 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "17 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "18 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "19 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "20 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "21 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "22 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "23 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "24 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "25 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "26 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "27 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "28 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "29 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "30 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "31 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "32 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "33 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "34 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "35 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "36 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "37 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "38 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "39 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "39 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "40 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "41 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "42 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "43 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "44 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "45 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "46 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "47 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "48 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "49 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "50 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "51 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "52 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "53 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "54 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "55 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "56 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "57 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "58 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "59 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "60 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "61 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "62 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "63 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "64 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "65 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "66 "
array.push(str, sX)
cond(y, x) =>
not na(str.match(label.get_text(array.get(y, x)), "[1-9]"))
cond2(y, x) =>
not na(str.match(label.get_text(array.get(y, x)), "[10-66]"))
atr = ta.atr(14)
var float tickz = 0.0
ticks2 = array.new_float()
if ti == "Regular" or ti == "Fixed Interval"
if last_bar_index - bar_index == 1601
if syminfo.mintick >= 0.01
tickz := auto == "Custom" ? tickzz :
auto == "Auto" and timeframe.period == "1" ? atr * 50 :
auto == "Auto" and timeframe.period == "5" ? atr * 40 :
atr * 30
else
tickz := auto == "Custom" ? tickzz : atr * 100000
else
if time < st
if syminfo.mintick >= 0.01
tickz := auto == "Custom" ? tickzz :
auto == "Auto" and timeframe.period == "1" ? atr * 50 :
auto == "Auto" and timeframe.period == "5" ? atr * 40 :
atr * 30
else
tickz := auto == "Custom" ? tickzz : atr * 100000
var line [] tpoLines = array.new_line()
ticks = array.new_float()
var float max = 0.0
var float min = 10000000
var float [] track = array.new_float()
var label [] pocL = array.new_label()
var float [] finChe = array.new_float()
var line j = line.new(time, high, time, low, color = color.aqua, width = 4, xloc = xloc.bar_time)
var int first = 0
var int firstBar = 0
max := math.max(high, max)
min := math.min(low, min)
var float ibF = 0.0
var line [] ib = array.new_line()
var label [] tpoLabels = array.new_label()
var label [] SP = array.new_label()
var line [] val = array.new_line()
var label [] VA = array.new_label()
var line ibBar = na
var linefill fil = na
var label op = label.new(time, open, xloc = xloc.bar_time, size = size.large, text_font_family = fonT, color = color.new(color.white, 100), text = "●", style = label.style_label_right, textcolor = color.blue)
var int timRound = 0
if session.isfirstbar_regular[4] and timRound == 0
timRound := math.round(time - time[4])
timeCond = switch ti
"Regular" => last_bar_index - bar_index <= 1600
"Fixed Range" => time >= st
"Fixed Interval" => last_bar_index - bar_index <= 1600
if timeCond
if showIb == true and ti == "Regular"
if time == ibF
array.push(ib, line.new(first, max, time, max, color = color.new(col3, 50), xloc = xloc.bar_time))
array.push(ib, line.new(first, min, time, min, color = color.new(col3, 50), xloc = xloc.bar_time))
if array.size(ib) > 1
linefill.new(array.get(ib, 0), array.get(ib, 1), color.new(col3, 95))
if time == ibF and ti == "Regular"
line.delete(ibBar)
ibBar := line.new(first, max, first, min, color = color.blue, xloc =xloc.bar_time, width = 4)
if finTim
if array.size(val) > 0
for i = 0 to array.size(val) - 1
line.delete(array.shift(val))
if array.size(VA) > 0
for i = 0 to array.size(VA) - 1
label.delete(array.shift(VA))
if array.size(track) > 0
array.clear(track)
if array.size(finChe) > 0
array.clear(finChe)
if array.size(ib) > 0
for i = 0 to array.size(ib) - 1
line.delete(array.shift(ib))
if array.size(tpoLines) > 0
for i = 0 to array.size(tpoLines) - 1
line.delete(array.shift(tpoLines))
if array.size(tpoLabels) > 0
for i = 0 to array.size(tpoLabels) - 1
label.delete(array.shift(tpoLabels))
if array.size(SP) > 0
for i = 0 to array.size(SP) - 1
label.delete(array.shift(SP))
if array.size(pocL) > 0
for i = 0 to array.size(pocL) - 1
label.delete(array.shift(pocL))
max := high
min := low
first := math.round(time)
ibF := math.round(timestamp(year, month, dayofmonth, hour + 1, minute, second))
label.set_x(op, first), label.set_y(op, open)
firstBar := bar_index
array.push(ticks, low)
array.push(track, low)
for i = 1 to 500
if array.get(ticks, i - 1) + (tickz * syminfo.mintick) <= high
array.push(ticks, array.get(ticks, i - 1) + (tickz * syminfo.mintick))
else
break
for i = 0 to array.size(ticks) - 1
array.push(tpoLines, line.new(bar_index, array.get(ticks, i) ,
bar_index + 1, array.get(ticks, i),
color = tickLevels == true ? color.new(color.lime, 75) : na, xloc = xloc.bar_index))
array.push(tpoLabels, label.new(first, array.get(ticks, i) , text = " A", xloc = xloc.bar_time,
color = color.new(col, 100), textcolor = col, text_font_family = fonT, style = label.style_label_left))
if timeCond and not finTim and ti == "Regular"
or barstate.islast and ti == "Fixed Range"
or timeCond and not finTim and ti == "Fixed Interval" and fixTime
calc = max - min
var label ibav = label.new(bar_index, close, color = na, style = label.style_label_left, text_font_family = fonT)
if array.size(ib) > 1
for i = 0 to array.size(ib) - 1
line.set_x2(array.get(ib, i), time)
label.set_y(ibav, math.avg(line.get_y1(array.get(ib, 0)), line.get_y1(array.get(ib, 1))))
label.set_x(ibav, bar_index + 2)
label.set_text(ibav, "Initial Balance Range")
label.set_textcolor(ibav, col3)
label.set_color(ibav,color.new(color.white, 100))
else
label.set_textcolor(ibav, na)
if array.size(VA) > 0
for i = 0 to array.size(VA) - 1
label.delete(array.shift(VA))
if array.size(val) > 0
for i = 0 to array.size(val) - 1
line.delete(array.shift(val))
if array.size(tpoLines) > 0
for i = 0 to array.size(tpoLines) - 1
line.delete(array.shift(tpoLines))
if array.size(tpoLabels) > 0
for i = 0 to array.size(tpoLabels) - 1
label.delete(array.shift(tpoLabels))
if array.size(SP) > 0
for i = 0 to array.size(SP) - 1
label.delete(array.shift(SP))
if array.size(pocL) > 0
for i = 0 to array.size(pocL) - 1
label.delete(array.shift(pocL))
if array.size(finChe) > 0
array.clear(finChe)
if array.size(track) > 0
array.push(ticks, array.get(track, array.size(track) - 1))
for i = 1 to 500
if array.get(ticks, i - 1) + (tickz * syminfo.mintick) <= max
array.push(ticks, array.get(ticks, i - 1) + (tickz * syminfo.mintick))
else
break
array.push(ticks2, array.get(track, array.size(track) - 1))
for i = 1 to 500
if array.get(ticks2, i - 1) - (tickz * syminfo.mintick) >= min
array.push(ticks2, array.get(ticks2, i - 1) - (tickz * syminfo.mintick))
else
break
for i = array.size(ticks2) - 1 to 0
array.push(tpoLines, line.new( first, array.get(ticks2, i),
last_bar_time,
array.get(ticks2, i),
color = tickLevels == true ? color.new(color.lime, 75) : na,
xloc = xloc.bar_time
))
array.push(tpoLabels, label.new( first, array.get(ticks2, i),
color = color.new(color.white, 100),
textcolor = col,
size = sz,
style = label.style_label_left,
xloc = xloc.bar_time ,
text_font_family = fonT
))
for i = 0 to array.size(ticks) - 1
array.push(tpoLines, line.new( first, array.get(ticks, i),
last_bar_time,
array.get(ticks, i),
color = tickLevels == true ? color.new(color.lime, 75) : na,
xloc = xloc.bar_time
))
array.push(tpoLabels, label.new( first, array.get(ticks, i),
color = color.new(color.white, 100),
textcolor = col,
size = sz,
style = label.style_label_left,
xloc = xloc.bar_time,
text_font_family = fonT
))
if array.size(tpoLines) > 1 and bar_index - firstBar < array.size(str)
levels = array.new_float()
che = array.new_float(array.size(tpoLines), 0)
for i = bar_index - firstBar to 0
for x = 0 to array.size(tpoLines) - 1
if line.get_y1(array.get(tpoLines, x)) <= high[i] and line.get_y1(array.get(tpoLines, x)) >= low[i]
label.set_text(array.get(tpoLabels, x),
text = label.get_text(array.get(tpoLabels, x)) + array.get(str, math.abs(bar_index - firstBar - i)))
array.set(che, x, array.get(che, x) + 1)
len = 0.0
for x = 0 to array.size(tpoLabels) - 1
len := math.max(len, array.get(che, x))
lenTrack = 0
for x = 0 to array.size(tpoLabels) - 1
if array.get(che, x) == len
label.set_textcolor(array.get(tpoLabels, x), col2)
lenTrack := x
if bar_index - firstBar >= 4
line.set_color(array.get(tpoLines, x), color.new(col2, 75))
line.set_width(array.get(tpoLines, x), 2)
array.push(finChe, line.get_y1(array.get(tpoLines, x)))
if array.size(finChe) == 1
array.push(pocL, label.new(first, line.get_y1(array.get(tpoLines, x)), xloc = xloc.bar_time,
color = color.new(col, 100), textcolor = col2, style = label.style_label_right, text_font_family = fonT, text = "POC", size = sz))
break
sum = array.new_float()
sum1 = array.new_float()
lin = array.new_float()
lin1 = array.new_float()
cheX = array.new_float()
cheX1 = array.new_float()
if lenTrack > 0
for x = lenTrack - 1 to 0
array.push(sum , array.size(sum) == 0 ? array.get(che, x) : array.get(sum, array.size(sum) - 1) + array.get(che, x))
array.push(lin, label.get_y(array.get(tpoLabels, x)))
array.push(cheX, array.get(che, x))
for x = lenTrack to array.size(che) - 1
array.push(sum1, array.size(sum1) == 0 ? array.get(che, x) : array.get(sum1, array.size(sum1) - 1) + array.get(che, x))
array.push(lin1, label.get_y(array.get(tpoLabels, x)))
array.push(cheX1, array.get(che, x))
miN = math.min(array.size(sum), array.size(sum1))
for n = 0 to miN - 1
if array.get(sum, n) + array.get(sum1, n) >= array.sum(che) * .7
array.push(val,line.new(first , array.get(lin, n), time,
array.get(lin, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(val,line.new(first, array.get(lin1, n), time,
array.get(lin1, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(VA, label.new(first, line.get_y1(array.get(val, 0)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAH" : "VAL",
textcolor = col4, size = sz, color = color.new(color.white, 100), style = label.style_label_right, text_font_family = fonT, xloc = xloc.bar_time))
array.push(VA, label.new(first, line.get_y1(array.get(val, 1)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAL" : "VAH",
textcolor = col4, size = sz, color = color.new(color.white, 100), style = label.style_label_right, text_font_family = fonT, xloc = xloc.bar_time))
break
if array.size(val) < 2
stop = 0
if miN == array.size(sum1)
for n = 0 to array.size(cheX1) - 1
if array.get(cheX1, n) >= math.round(len * .7)
stop := n
for n = 0 to array.size(sum) - 1
if array.get(sum, n) + array.get(sum1, stop) >= array.sum(che) * .7
array.push(val,line.new(first, array.get(lin, n), time,
array.get(lin, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(val,line.new(first, array.get(lin1, stop), time,
array.get(lin1, stop), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(VA, label.new(first, line.get_y1(array.get(val, 0)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAH" : "VAL",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
array.push(VA, label.new(first, line.get_y1(array.get(val, 1)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAL" : "VAH",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
break
else
for n = 0 to array.size(cheX) - 1
if array.get(cheX, n) >= math.round(len * .7)
stop := n
for n = 0 to array.size(sum1) - 1
if array.get(sum, stop) + array.get(sum1, n) >= array.sum(che) * .7
array.push(val,line.new(first, array.get(lin1, n), time,
array.get(lin1, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(val,line.new(first, array.get(lin, stop), time,
array.get(lin, stop), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(VA, label.new(first, line.get_y1(array.get(val, 0)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAH" : "VAL",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
array.push(VA, label.new(first, line.get_y1(array.get(val, 1)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAL" : "VAH",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
break
if array.size(val) == 2 and array.size(pocL) > 0 and array.size(tpoLabels) > 0
fil := linefill.new(array.get(val, 0), array.get(val, 1), color = color.new(col4, 90))
for i = 0 to array.size(tpoLabels) - 1
if line.get_y1(array.get(val, 0)) > line.get_y2(array.get(val, 1))
if label.get_y(array.get(tpoLabels, i)) <= line.get_y1(array.get(val, 0))
and label.get_y(array.get(tpoLabels, i)) >= line.get_y1(array.get(val, 1))
and label.get_y(array.get(tpoLabels, i)) != label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoLabels, i), col5)
else if label.get_y(array.get(tpoLabels, i)) == label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoLabels, i), col2)
else
if label.get_y(array.get(tpoLabels, i)) >= line.get_y1(array.get(val, 0) )
and label.get_y(array.get(tpoLabels, i)) <= line.get_y1(array.get(val, 1))
and label.get_y(array.get(tpoLabels, i)) != label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoLabels, i), col5)
else if label.get_y(array.get(tpoLabels, i)) == label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoLabels, i), col2)
for x = 0 to array.size(tpoLabels) - 1
if str.length(label.get_text(array.get(tpoLabels, x))) == 2
or str.length(label.get_text(array.get(tpoLabels, x))) == 5 and cond2(tpoLabels, x) == true
or str.length(label.get_text(array.get(tpoLabels, x))) == 4 and cond(tpoLabels, x) == true
label.set_textcolor(array.get(tpoLabels, x), col1)
if bar_index - firstBar >= 4 and spShw == true
line.set_color(array.get(tpoLines, x), color.new(col1, 75))
array.push(SP, label.new(time, line.get_y1(array.get(tpoLines, x)), xloc = xloc.bar_time, color = color.new(col, 100),
style = label.style_label_left, text = "SP", textcolor = col1, text_font_family = fonT))
if array.size(VA) == 2 and array.size(pocL) > 0
if label.get_y(array.get(VA, 0)) == label.get_y(array.get(pocL, 0))
label.set_x(array.get(VA, 0), first - timRound)
if label.get_y(array.get(VA, 1)) == label.get_y(array.get(pocL, 0))
label.set_x(array.get(VA, 1), first - timRound)
if ti == "Regular" or ti == "Fixed Range"
line.set_x1(j, first)
line.set_x2(j, first)
line.set_y1(j, max)
line.set_y2(j, min)
else
if fixTime
line.set_x1(j, first)
line.set_x2(j, first)
line.set_y1(j, max)
line.set_y2(j, min)
var line [] SPCopy = array.new_line()
var line [] valCopy = array.new_line()
var label [] tpoLabelsCopy = array.new_label()
var line [] pocCopy = array.new_line()
var line [] jCopy = array.new_line()
var line [] ibBarCopy = array.new_line()
var box [] bBox = array.new_box()
tCnd = hour == str.tonumber(str.substring(timE, str.pos(timE, "-") + 1, str.length(timE) - 2))
and minute == str.tonumber(str.substring(timE, str.pos(timE, "-") + 3))
if session.islastbar and barstate.isconfirmed
and timeCond and ti == "Regular" and array.size(tpoLabels) > 0
and showPre == true
or tCnd and barstate.isconfirmed and timeCond and ti == "Fixed Interval"
and array.size(tpoLabels) > 0 and showPre == true
if blackBox == true
array.push(bBox, box.new(first, max, time, min, xloc = xloc.bar_time, bgcolor = #000000, border_color = na))
if rang == true
array.push(jCopy, line.copy(j))
array.push(ibBarCopy, line.copy(ibBar))
if array.size(val) > 0 and distCalc2 != 0
for i = 0 to array.size(val) - 1
array.push(valCopy, line.copy(array.get(val, i)))
if array.size(tpoLabels) > 0
for i = 0 to array.size(tpoLabels) - 1
array.push(tpoLabelsCopy, label.copy(array.get(tpoLabels, i)))
if label.get_y(array.get(tpoLabels, i)) == label.get_y(array.get(pocL, 0))
array.push(pocCopy, line.copy(array.get(tpoLines, i)))
if array.size(SP) > 0 and distCalc != 0
for i = 0 to array.size(SP) - 1
array.push(SPCopy, line.new(first, label.get_y(array.get(SP, i)), time, label.get_y(array.get(SP, i)), xloc = xloc.bar_time, color = color.new(col1, 80)))
if array.size(SPCopy) > 0
for i = 0 to array.size(SPCopy) - 1
if line.get_y1(array.get(SPCopy, i)) <= high and line.get_y1(array.get(SPCopy, i)) >= low
line.delete(array.get(SPCopy, i))
else
if math.abs((close / line.get_y1(array.get(SPCopy, i))- 1)* 100) <= distCalc
line.set_x2(array.get(SPCopy, i), time)
else if math.abs((close / line.get_y1(array.get(SPCopy, i)) - 1)* 100) >= distCalc
line.set_x2(array.get(SPCopy, i), line.get_x1(array.get(SPCopy, i)))
if array.size(valCopy) > 0
for i = 0 to array.size(valCopy) - 1
if line.get_y1(array.get(valCopy, i)) <= high and line.get_y1(array.get(valCopy, i)) >= low
line.delete(array.get(valCopy, i))
else if math.abs((close / line.get_y1(array.get(valCopy, i))- 1)* 100) <= distCalc2
line.set_x2(array.get(valCopy, i), time)
else if math.abs((close / line.get_y1(array.get(valCopy, i)) - 1)* 100) >= distCalc2
line.set_x2(array.get(valCopy, i), line.get_x1(array.get(valCopy, i)))
if array.size(pocCopy) > 0
for i = 0 to array.size(pocCopy) - 1
if line.get_y1(array.get(pocCopy, i)) <= high and line.get_y1(array.get(pocCopy, i)) >= low
line.delete(array.get(pocCopy, i))
else if math.abs((close / line.get_y1(array.get(pocCopy, i))- 1)* 100) <= distCalc3
line.set_x2(array.get(pocCopy, i), time)
else if math.abs((close / line.get_y1(array.get(pocCopy, i)) - 1)* 100) >= distCalc3
line.set_x2(array.get(pocCopy, i), line.get_x1(array.get(pocCopy, i)))
if array.size(tpoLabelsCopy) > 500
for i = 0 to array.size(tpoLabelsCopy) - 500
label.delete(array.shift(tpoLabelsCopy))
if array.size(ibBarCopy) > 1
line.delete(array.shift(ibBarCopy))
line.delete(array.shift(jCopy))
if array.size(bBox) > 1
box.delete(array.shift(bBox))
if warn == true
var table tab = table.new(position.top_right, 1, 1, frame_color = color.white, frame_width = 1)
table.cell(tab, 0, 0, text_size = size.small,
text = "If Letters Aren't Appearing: Decrease the 'Ticks' Setting. \nIf Letters are Cluttered: Increase the 'Ticks' Setting\nFor Your Changes to Take Effect: Change the 'Auto Calculate Tick Levels? Custom?' Setting to 'Custom'",
text_color = color.white, bgcolor = color.new(col3, 75))
|
Dollar Cost Averaging (Portfolio) | https://www.tradingview.com/script/JsEqD2C8/ | miraalgo | https://www.tradingview.com/u/miraalgo/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © miraalgo
//@version=5
indicator("Dollar Cost Averaging (Portfolio)",shorttitle="DCAP",precision=4)
var invest=0.0
var qty1=0.0,var qty2=0.0,var qty3=0.0,var qty4=0.0,var qty5=0.0,var qty6=0.0,var qty7=0.0,var qty8=0.0,var qty9=0.0,var qty10=0.0
var counter=0.0
var value=0.0
var yearly=1.0
t1=input.time(defval=timestamp("14 May 2010"),title="start")
t2=input.time(defval=timestamp("14 May 2030"),title="finish")
saving1=input.int(10,step=1,title="Invest 1",inline="1")
symbol1 = input.source(close, "Source",inline="1")
saving2=input.int(0,step=1,title="Invest 2",inline="2")
symbol2 = input.symbol("NYSE:IBM", "Symbol",inline="2" )
saving3=input.int(0,step=1,title="Invest 3",inline="3")
symbol3 = input.symbol("NYSE:IBM", "Symbol",inline="3" )
saving4=input.int(0,step=1,title="Invest 4",inline="4")
symbol4 = input.symbol("NYSE:IBM", "Symbol",inline="4" )
saving5=input.int(0,step=1,title="Invest 5",inline="5")
symbol5 = input.symbol("NYSE:IBM", "Symbol",inline="5" )
saving6=input.int(0,step=1,title="Invest 6",inline="6")
symbol6 = input.symbol("NYSE:IBM", "Symbol",inline="6" )
saving7=input.int(0,step=1,title="Invest 7",inline="7")
symbol7 = input.symbol("NYSE:IBM", "Symbol",inline="7" )
saving8=input.int(0,step=1,title="Invest 8",inline="8")
symbol8 = input.symbol("NYSE:IBM", "Symbol",inline="8" )
saving9=input.int(0,step=1,title="Invest 9",inline="9")
symbol9 = input.symbol("NYSE:IBM", "Symbol",inline="9" )
saving10=input.int(0,step=1,title="Invest 10",inline="10")
symbol10 = input.symbol("NYSE:IBM", "Symbol",inline="10" )
c1 = symbol1
c2 = request.security(symbol2, timeframe.period, close)
c3 = request.security(symbol3, timeframe.period, close)
c4 = request.security(symbol4, timeframe.period, close)
c5 = request.security(symbol5, timeframe.period, close)
c6 = request.security(symbol6, timeframe.period, close)
c7 = request.security(symbol7, timeframe.period, close)
c8 = request.security(symbol8, timeframe.period, close)
c9 = request.security(symbol9, timeframe.period, close)
c10 = request.security(symbol10, timeframe.period, close)
if time>t1 and time<t2 and timeframe.isdwm==true
counter:=counter+1
if na(c1) == false
qty1:= qty1 + (saving1/c1)
else
saving1:=0
if na(c2) == false
qty2:= qty2 + (saving2/c2)
else
saving2:=0
if na(c3) == false
qty3:= qty3 + (saving3/c3)
else
saving3:=0
if na(c4) ==false
qty4:= qty4 + (saving4/c4)
else
saving4:=0
if na(c5) ==false
qty5:= qty5 + (saving5/c5)
else
saving5:=0
if na(c6) ==false
qty6:= qty6 + (saving6/c6)
else
saving6:=0
if na(c7) ==false
qty7:= qty7 + (saving7/c7)
else
saving7:=0
if na(c8) ==false
qty8:= qty8 + (saving8/c8)
else
saving8:=0
if na(c9) ==false
qty9:= qty9 + (saving9/c9)
else
saving9:=0
if na(c10) ==false
qty10:= qty10 + (saving10/c10)
else
saving10:=0
invest:=invest + (saving1+saving2+saving3+saving4+saving5+saving6+saving7+saving8+saving9+saving10)
value1 = na(c1) ==false ? (qty1*c1) : 0
value2 = na(c2) ==false ? (qty2*c2) : 0
value3 = na(c3) ==false ? (qty3*c3) : 0
value4 = na(c4) ==false ? (qty4*c4) : 0
value5 = na(c5) ==false ? (qty5*c5) : 0
value6 = na(c6) ==false ? (qty6*c6) : 0
value7 = na(c7) ==false ? (qty7*c7) : 0
value8 = na(c8) ==false ? (qty8*c8) : 0
value9 = na(c9) ==false ? (qty9*c9) : 0
value10 = na(c10) ==false ? (qty10*c10) : 0
value :=value1 + value2 + value3 + value4 +value5 +value6 +value7 +value8 +value9 +value10
vi=value/invest
if timeframe.ismonthly
barly=math.pow(vi,(1/counter))
yearly:=math.pow(barly,12/timeframe.multiplier)
if timeframe.isweekly
barly=math.pow(vi,(1/counter))
yearly:=math.pow(barly,52/timeframe.multiplier)
if timeframe.isdaily
barly=math.pow(vi,(1/counter))
yearly:=math.pow(barly,365/timeframe.multiplier)
yearly:=(yearly-1)
savingperbar=saving1+saving2+saving3+saving4+saving5+saving6+saving7+saving8+saving9+saving10
plot(savingperbar,color=color.white,title="Investment")
plot(invest,color=color.white,title="Total Investment")
plot(value,color=value>invest ? color.green:color.red,title="Value")
plot(vi,color=color.yellow,title="Value/Investment")
plot(yearly,color=color.yellow,title="Yearly Profit/Loss (approx)")
plot((qty1*c1),title="asset 1",color= #7fb3d5,display=display.none)
plot((qty2*c2),title="asset 2",color=#2980b9,display=display.none)
plot((qty3*c3),title="asset 3",color=#1f618d ,display=display.none)
plot((qty4*c4),title="asset 4",color=color.blue,display=display.none)
plot((qty5*c5),title="asset 5",color=#d2b4de,display=display.none)
plot((qty6*c6),title="asset 6",color=#bb8fce,display=display.none)
plot((qty7*c7),title="asset 7",color=#a569bd,display=display.none)
plot((qty8*c8),title="asset 8",color=#f5cba7,display=display.none)
plot((qty9*c9),title="asset 9",color=#f0b27a,display=display.none)
plot((qty10*c10),title="asset 10",color=#eb984e,display=display.none)
|
Implied Volatility Estimator using Black Scholes [Loxx] | https://www.tradingview.com/script/xT4abuhx-Implied-Volatility-Estimator-using-Black-Scholes-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Implied Volatility Estimator using Black Scholes [Loxx]",
shorttitle ="IVEBS",
overlay = true,
max_lines_count = 500)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
//imports
import loxx/loxxexpandedsourcetypes/4
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
color darkGreenColor = #1B7E02
string rogersatch = "Roger-Satchell"
string c2c = "Close-to-Close"
string parkinson = "Parkinson"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
f_tickFormat() =>
_s = str.tostring(syminfo.mintick)
_s := str.replace_all(_s, '25', '00')
_s := str.replace_all(_s, '5', '0')
_s := str.replace_all(_s, '1', '0')
_s
// N(0,1) density
f(float x)=>
math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi)
// Boole's Rule
Boole(float StartPoint, float EndPoint, int n)=>
float[] X = array.new<float>(n + 1 , 0)
float[] Y = array.new<float>(n + 1 , 0)
float delta_x = (EndPoint - StartPoint) / n
for i = 0 to n
array.set(X, i, StartPoint + i * delta_x)
array.set(Y, i, f(array.get(X, i)))
float sum = 0
for t = 0 to (n - 1) / 4
int ind = 4 * t
sum += (1 / 45.0) *
(14 * array.get(Y, ind)
+ 64 * array.get(Y, ind + 1)
+ 24 * array.get(Y, ind + 2)
+ 64 * array.get(Y, ind + 3)
+ 14 * array.get(Y, ind + 4))
* delta_x
sum
// N(0,1) cdf by Boole's Rule
N(float x)=>
Boole(-10.0, x, 240)
// Black-Scholes Call Price
BSPrice(float S, float K, float r, float T, float q, float v, string PutCall)=>
float d = (math.log(S / K) + T * (r - q + 0.5 * v * v)) / (v * math.sqrt(T))
float call = S * math.exp(-q * T) * N(d) - math.exp(-r * T) * K * N(d - v * math.sqrt(T))
float out = 0
if (PutCall == "Call")
out := call
else
out := call - S * math.exp(-q * T) + K * math.exp(-r * T)
out
// Bisection Algorithm
BisecBSV(float S, float K, float r, float T, float q, float a, float b, float MktPrice, string PutCall)=>
int MaxIter = 50000
float Tol = 0.0000001
float midP = 0
float midCdif = 0
float out = 0
float lowCdif = MktPrice - BSPrice(S, K, r, T, q, a, PutCall)
float highCdif = MktPrice - BSPrice(S, K, r, T, q, b, PutCall)
float a1 = a
float b1 = b
if lowCdif * highCdif > 0
out := -1
else
for i = 0 to MaxIter
midP := (a1 + b1) / 2.0
midCdif := MktPrice - BSPrice(S, K, r, T, q, midP, PutCall)
if (math.abs(midCdif) < Tol)
break
else
if midCdif > 0
a1 := midP
else
b1 := midP
midP
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
float[] sarr = array.new_float(per, 0)
for i = 0 to per - 1
array.set(sarr, i, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Spot Price", group= "Basic Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
float K = input.float(160, "Strike Price", group = "Basic Settings")
float MktPrice = input.float(194.82, "Option Market Price", group = "Basic Settings")
string PutCall = input.string("Call", "Option type", options = ["Call", "Put"], group = "Basic Settings")
string rfrtype = input.string("USD", "Option Base Currency", options = ['USD', 'GBP', 'JPY', 'CAD', 'CNH', 'SGD', 'INR', 'AUD', 'SEK', 'NOK', 'DKK'], group = "Risk-free Rate Settings", tooltip = "Automatically pulls 10-year bond yield from corresponding currency")
float rfrman = input.float(3.97, "% Manual Risk-free Rate", group = "Risk-free Rate Settings") / 100
bool usdrsrman = input.bool(false, "Use manual input for Risk-free Rate?", group = "Risk-free Rate Settings")
float divsman = input.float(7.5, "% Manual Yearly Dividend Yield", group = "Dividend Settings") / 100
bool usediv = input.bool(true, "Adjust for Dividends?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
bool autodiv = input.bool(true, "Automatically Calculate Yearly Dividend Yield?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
int histvolper = input.int(22, "Historical Volatility Period", group = "Volatility Settings", tooltip = "This is here to use for volatility input.")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Volatility Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
float a = input.float(0.00000000001, "Bisection Algo starting value for lower volatility", group = "Bisection Algo Settings")
float b = input.float(7.0, "Bisection Algo starting value for higher volatility", group = "Bisection Algo Settings")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
float q = usediv ? (autodiv ? request.dividends(syminfo.tickerid) / close * 4 : divsman) : 0
string byield = switch rfrtype
"USD"=> 'US10Y'
"GBP"=> 'GB10Y'
"JPY"=> 'US10Y'
"CAD"=> 'CA10Y'
"CNH"=> 'CN10Y'
"SGD"=> 'SG10Y'
"INR"=> 'IN10Y'
"AUD"=> 'AU10Y'
"USEKSD"=> 'SE10Y'
"NOK"=> 'NO10Y'
"DKK"=> 'DK10Y'
=> 'US10Y'
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
float r = usdrsrman ? rfrman : request.security(byield, timeframe.period, spot) / 100
if barstate.islast
IV = BisecBSV(spot, K, r, T, q, a, b, MktPrice, PutCall)
var testTable = table.new(position = position.middle_right, columns = 1, rows = 16, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = " Inputs ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 1, text = " Spot Price: " + str.tostring(spot, f_tickFormat()) , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 2, text = " Strike Price: " + str.tostring(K, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 3, text = " Risk-free Rate Type: " + rfrtype , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 4, text = " Risk-free Rate: " + str.tostring(r * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 5, text = " Dividend Yield (annual): " + str.tostring(q * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 6, text = " Option Type: " + PutCall, bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 7, text = " Market Price: " + str.tostring(MktPrice, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 8, text = " Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 9, text = " Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 10, text = " Output ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 11, text = " Implied Volatility: " + str.tostring(IV * 100, "##.###") + "%", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 12, text = " Calculated Values ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 13, text = " Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 14, text = " Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 15, text = " Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "% ", bgcolor = darkGreenColor, text_color = color.white)
|
Boyle Trinomial Options Pricing Model [Loxx] | https://www.tradingview.com/script/IgEbTjmh-Boyle-Trinomial-Options-Pricing-Model-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 42 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Boyle Trinomial Options Pricing Model [Loxx]",
shorttitle ="BTOPM",
overlay = true,
max_lines_count = 500)
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
import loxx/loxxexpandedsourcetypes/4
//constants
color darkGreenColor = #1B7E02
string callString = "C"
string putString = "P"
string euroString = "E"
string amerString = "A"
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
float[] sarr = array.new_float(per, 0)
for i = 0 to per - 1
array.set(sarr, i, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
f_tickFormat() =>
_s = str.tostring(syminfo.mintick)
_s := str.replace_all(_s, '25', '00')
_s := str.replace_all(_s, '5', '0')
_s := str.replace_all(_s, '1', '0')
_s
trinomialOptionsPricingModel(float spot, float K, float r, float q, float v, float T, string PutCall, string EuroAmer, int n)=>
float b = r - q
float dt = T / n
float u = math.exp(v * math.sqrt(2.0 * dt))
float d = 1.0 / u
float pu = math.pow((math.exp(0.5 * b * dt) - math.exp(-v * math.sqrt(0.5 * dt))) / (math.exp(v * math.sqrt(0.5 * dt)) - math.exp(-v * math.sqrt(0.5 * dt))), 2)
float pd = math.pow((math.exp(v * math.sqrt(0.5 * dt)) - math.exp(0.5 * b * dt)) / (math.exp(v * math.sqrt(0.5 * dt)) - math.exp(-v * math.sqrt(0.5 * dt))), 2)
float pm = 1.0 - pu - pd
matrix<float> S = matrix.new<float>(2 * n + 1, n + 1, 0)
matrix<float> V = matrix.new<float>(2 * n + 1, n + 1, 0)
// Build the trinomial tree for the stock price evolution
for j = 0 to n
for i = 0 to 2 * j
matrix.set(S, i, j, spot * math.pow(u, float(j - i)))
// Compute terminal payoffs
for i = 0 to 2 * n
if PutCall == callString
matrix.set(V, i, n, math.max(matrix.get(S, i, n) - K, 0.0))
else if PutCall == putString
matrix.set(V, i, n, math.max(K - matrix.get(S, i, n), 0.0))
// Backward recursion through the tree
for j = n - 1 to 0
for i = 0 to 2 * j
if EuroAmer == euroString
matrix.set(V, i, j, math.exp(-r * dt) * (pu * matrix.get(V, i, j + 1) + pm * matrix.get(V, i + 1, j + 1) + pd * matrix.get(V, i + 2, j + 1)))
else if EuroAmer == amerString
if PutCall == callString
matrix.set(V, i, j, math.max(matrix.get(S, i, j) - K, math.exp(-r * dt) * (pu * matrix.get(V, i, j + 1) + pm * matrix.get(V, i + 1, j + 1) + pd * matrix.get(V, i + 2, j + 1))))
else if PutCall == putString
matrix.set(V, i, j, math.max(K - matrix.get(S, i, j), math.exp(-r * dt) * (pu * matrix.get(V, i, j + 1) + pm * matrix.get(V, i + 1, j + 1) + pd * matrix.get(V, i + 2, j + 1))))
matrix.get(V, 0, 0)
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Spot Price", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
int n = input.int(100, "Calculation Steps", maxval = 220, group = "Basic Settings")
float K = input.float(270, "Strike Price", group = "Basic Settings")
float v = input.float(90.14, "% Volatility", group = "Volatility Settings") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Volatility Settings", tooltip = "Not used in calculation. This is here for comparison to implied volatility")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Volatility Settings")
string rfrtype = input.string("USD", "Option Base Currency", options = ['USD', 'GBP', 'JPY', 'CAD', 'CNH', 'SGD', 'INR', 'AUD', 'SEK', 'NOK', 'DKK'], group = "Risk-free Rate Settings", tooltip = "Automatically pulls 10-year bond yield from corresponding currency")
float rfrman = input.float(3.97, "% Manual Risk-free Rate", group = "Risk-free Rate Settings") / 100
bool usdrsrman = input.bool(false, "Use manual input for Risk-free Rate?", group = "Risk-free Rate Settings")
float divsman = input.float(7.5, "% Manual Yearly Dividend Yield", group = "Dividend Settings") / 100
bool usediv = input.bool(true, "Adjust for Dividends?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
bool autodiv = input.bool(true, "Automatically Calculate Yearly Dividend Yield?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
float q = usediv ? (autodiv ? request.dividends(syminfo.tickerid) / close * 4 : divsman) : 0
string byield = switch rfrtype
"USD"=> 'US10Y'
"GBP"=> 'GB10Y'
"JPY"=> 'US10Y'
"CAD"=> 'CA10Y'
"CNH"=> 'CN10Y'
"SGD"=> 'SG10Y'
"INR"=> 'IN10Y'
"AUD"=> 'AU10Y'
"USEKSD"=> 'SE10Y'
"NOK"=> 'NO10Y'
"DKK"=> 'DK10Y'
=> 'US10Y'
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float r = usdrsrman ? rfrman : request.security(byield, timeframe.period, spot) / 100
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
var testTable = table.new(position = position.middle_right, columns = 1, rows = 19, bgcolor = color.yellow, border_width = 1)
ecout = trinomialOptionsPricingModel(spot, K, r, q, v, T, callString, euroString, n)
epout = trinomialOptionsPricingModel(spot, K, r, q, v, T, putString, euroString, n)
acout = trinomialOptionsPricingModel(spot, K, r, q, v, T, callString, amerString, n)
apout = trinomialOptionsPricingModel(spot, K, r, q, v, T, putString, amerString, n)
float tempr = syminfo.type == "futures" ? 0 : r
table.cell(table_id = testTable, column = 0, row = 0, text = " Inputs ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 1, text = " Calculation Steps: " + str.tostring(n, "##.##") , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 2, text = " Spot Price: " + str.tostring(spot, f_tickFormat()) , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 3, text = " Strike Price: " + str.tostring(K, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 4, text = " Volatility (annual): " + str.tostring(v * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 5, text = " Risk-free Rate Type: " + rfrtype , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 6, text = " Risk-free Rate: " + str.tostring(tempr * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 7, text = " Dividend Yield (annual): " + str.tostring(q * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 8, text = " Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 9, text = " Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 10, text = " Output ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 11, text = " European Call: " + str.tostring(ecout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 12, text = " European Put: " + str.tostring(epout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 13, text = " American Call: " + str.tostring(acout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 14, text = " American Put: " + str.tostring(apout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 15, text = " Calculated Values ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 16, text = " Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 17, text = " Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 18, text = " Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
|
Volume Weighted Reversal Bands | https://www.tradingview.com/script/f2JLT1wp-Volume-Weighted-Reversal-Bands/ | FriendOfTheTrend | https://www.tradingview.com/u/FriendOfTheTrend/ | 260 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FriendOfTheTrend
//@version=5
indicator("Volume Weighted Reversal Bands", overlay=true)
//Percent Deviation Amount
percentDeviation = input.float(.5, title="Percentage Deviation Per Channel")/100
//Turn Short Moving Average Off
shortMaOff = input.bool(false, title="Turn Short MA Off")
vwapOff = input.bool(false, title="Turn VWAP Off")
//Styling
mainLineSupportColor = input.color(color.lime, title="Main Line Support Color")
mainLineResistanceColor = input.color(color.red, title="Main Line Resistance Color")
mainLinewidth = input.int(4, title="Main Linewidth")
deviationLineSupportColor = input.color(color.lime, title="Deviation Lines Support Color")
deviationLineResistanceColor = input.color(color.red, title="Deviation Lines Resistance Color")
deviationLinewidth = input.int(2, title="Deviation Linewidth")
vwapColor = input.color(color.white, title="VWAP Color")
vwapLinewidth = input.int(1, title="VWAP Linewidth")
shortMaSupportColor = input.color(color.lime, title="Short Line Support Color")
shortMaResistanceColor = input.color(color.red, title="Short Line Resistance Color")
shortMaLinewidth = input.int(1, title="Short MA Linewidth")
//Moving Averages
vwma100 = ta.vwma(close, 100)
vwma500 = ta.vwma(close, 500)
vwma1000 = ta.vwma(close, 1000)
vwap = ta.vwap(close)
//Combined Moving Average Logic
combinedMa = (vwma100 + vwma500 + vwma1000 + vwap) / 4
shortMa = (ta.vwma(close, 5) + ta.vwma(close, 10) + ta.vwma(close, 20) + ta.vwma(close, 50) + ta.wma(close, 5) + ta.wma(close, 10) + ta.wma(close, 20) + ta.wma(close, 50)) / 8
//Percentage Deviation Calculations
combinedMa1Up = combinedMa * (1 + percentDeviation)
combinedMa2Up = combinedMa * (1 + (percentDeviation*2))
combinedMa3Up = combinedMa * (1 + (percentDeviation*3))
combinedMa4Up = combinedMa * (1 + (percentDeviation*4))
combinedMa5Up = combinedMa * (1 + (percentDeviation*5))
combinedMa6Up = combinedMa * (1 + (percentDeviation*6))
combinedMa7Up = combinedMa * (1 + (percentDeviation*7))
combinedMa8Up = combinedMa * (1 + (percentDeviation*8))
combinedMa9Up = combinedMa * (1 + (percentDeviation*9))
combinedMa10Up = combinedMa * (1 + (percentDeviation*10))
combinedMa1Down = combinedMa * (1 - percentDeviation)
combinedMa2Down = combinedMa * (1 - (percentDeviation*2))
combinedMa3Down = combinedMa * (1 - (percentDeviation*3))
combinedMa4Down = combinedMa * (1 - (percentDeviation*4))
combinedMa5Down = combinedMa * (1 - (percentDeviation*5))
combinedMa6Down = combinedMa * (1 - (percentDeviation*6))
combinedMa7Down = combinedMa * (1 - (percentDeviation*7))
combinedMa8Down = combinedMa * (1 - (percentDeviation*8))
combinedMa9Down = combinedMa * (1 - (percentDeviation*9))
combinedMa10Down = combinedMa * (1 - (percentDeviation*10))
// Plot Lines
plot(combinedMa, title="Start Line", color=close > combinedMa ? mainLineSupportColor : mainLineResistanceColor, linewidth=mainLinewidth)
plot(combinedMa1Up, title="Up 1 Deviation Line", color=close > combinedMa1Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa2Up, title="Up 2 Deviation Line", color=close > combinedMa2Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa3Up, title="Up 3 Deviation Line", color=close > combinedMa3Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa4Up, title="Up 4 Deviation Line", color=close > combinedMa4Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa5Up, title="Up 5 Deviation Line", color=close > combinedMa5Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa6Up, title="Up 6 Deviation Line", color=close > combinedMa6Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa7Up, title="Up 7 Deviation Line", color=close > combinedMa7Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa8Up, title="Up 8 Deviation Line", color=close > combinedMa8Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa9Up, title="Up 9 Deviation Line", color=close > combinedMa9Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa10Up, title="Up 10 Deviation Line", color=close > combinedMa10Up ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa1Down, title="Down 1 Deviation Line", color=close > combinedMa1Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa2Down, title="Down 2 Deviation Line", color=close > combinedMa2Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa3Down, title="Down 3 Deviation Line", color=close > combinedMa3Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa4Down, title="Down 4 Deviation Line", color=close > combinedMa4Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa5Down, title="Down 5 Deviation Line", color=close > combinedMa5Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa6Down, title="Down 6 Deviation Line", color=close > combinedMa6Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa7Down, title="Down 7 Deviation Line", color=close > combinedMa7Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa8Down, title="Down 8 Deviation Line", color=close > combinedMa8Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa9Down, title="Down 9 Deviation Line", color=close > combinedMa9Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(combinedMa10Down, title="Down 10 Deviation Line", color=close > combinedMa10Down ? deviationLineSupportColor : deviationLineResistanceColor, linewidth=deviationLinewidth)
plot(vwapOff ? na : ta.vwap(close), color=vwapColor, linewidth=vwapLinewidth)
plot(shortMaOff ? na : shortMa, color=close > shortMa ? shortMaSupportColor : shortMaResistanceColor, linewidth=shortMaLinewidth)
|
Volume Spikes | https://www.tradingview.com/script/6wUMpFxu-Volume-Spikes/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,620 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeforopp
//@version=5
indicator("Volume Spikes [TFO]", "Volume Spikes [TFO]", overlay=true)
// Variables and constants
vol_x = input.float(1.5, step=0.1, title="Volume Multiplier", tooltip="This multiplier will act as a threshold to determine which volume spikes are shown. A volume multiplier of 2 will only show volume spikes that are 2x the value of the volume SMA")
vol_ma = input(100, "Volume SMA Length")
only_valid_hl = input(true, "Only Use Valid Highs & Lows", tooltip="Only show long signals when the candle in question forms a local low, and vice versa")
only_hammers_shooters = input(true, "Only Use Hammers & Shooters")
only_same_color = input(false, "Only Use Same-Close Volume Spikes", tooltip="Only show long signals when the volume spike appears on an up-close candle, and vice versa")
session = input.session("0000-0000", "Session Time")
bull_color = input.color(color.green)
bear_color = input.color(color.red)
t = not na(time(timeframe.period, session))
// Candle calculations
valid_high = only_valid_hl ? high[1] > high[2] and high[1] > high[0] : true
valid_low = only_valid_hl ? low[1] < low[2] and low[1] < low[0] : true
distance_hl = high - low
valid_hammer = open > low + distance_hl / 2 and close > low + distance_hl / 2
valid_shooter = open < low + distance_hl / 2 and close < low + distance_hl / 2
if only_hammers_shooters
valid_high := valid_high and valid_shooter[1]
valid_low := valid_low and valid_hammer[1]
if only_same_color
valid_high := valid_high and close[1] < open[1]
valid_low := valid_low and close[1] > open[1]
// Volume check
// Is volume sufficiently greater than its MA?
vol_check = volume > ta.sma(volume, vol_ma) * vol_x and t
result_bearish = valid_high and vol_check[1]
result_bullish = valid_low and vol_check[1]
alertcondition(result_bearish, "Bearish Volume Spike", "Bearish Volume Spike")
alertcondition(result_bullish, "Bullish Volume Spike", "Bullish Volume Spike")
plotshape(result_bearish, color=bear_color, style=shape.circle, location=location.abovebar, size=size.tiny, offset = -1)
plotshape(result_bullish, color=bull_color, style=shape.circle, location=location.belowbar, size=size.tiny, offset = -1) |
Variance | https://www.tradingview.com/script/0DXMrmQL-Variance/ | gulls | https://www.tradingview.com/u/gulls/ | 1 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gulls
//@version=5
indicator("Variance")
plot(ta.ema((close-close[1]),60))
hline(0, color=color.new(color.red,50))
hline(1)
hline(2)
hline(3)
hline(-1)
hline(-2) |
Percent Range | https://www.tradingview.com/script/tGrbgzTp-Percent-Range/ | gulls | https://www.tradingview.com/u/gulls/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gulls
//@version=5
indicator("Percent Range",timeframe = '')
length = input.int(5, minval=1, title = 'EMA')
PercentB = ((close-open)/(high[1]-low[1]))*(close/low)
BEMA = ta.ema(PercentB,5)
ema12 = ta.ema(BEMA, length)
ema22 = ta.ema(ema12, length)
ema32 = ta.ema(ema22, length)
out2 = 3 * (ema12 - ema22) + ema32
plot(out2, "Range", color=color.green)
A = ta.highest(high,5)
B = ta.lowest(low,5)
C = (close-B)/(A-B)
plot(ta.vwma(C,5)-0.50,color=color.yellow)
hline(0)
hline(0,color=color.white)
hline(0.1,color=color.white)
hline(-0.1,color=color.white)
hline(0.2,color=color.green)
hline(-0.2,color=color.red)
hline(0.3,color=color.green)
hline(-0.3,color=color.red)
hline(.6,color=color.blue)
hline(.5,color=color.blue)
hline(.4,color=color.blue)
hline(-.6,color=color.blue)
hline(-.5,color=color.blue)
hline(-.4,color=color.blue) |
Cutlers RSI | https://www.tradingview.com/script/J2ongRdA-Cutlers-RSI/ | TanHef | https://www.tradingview.com/u/TanHef/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TanHef
//Cutlers' RSI is a variation of the original RSI Developed by Welles Wilder.
//This variation uses a simple moving average instead of an exponetial average.
//Since a simple moving average is used by this variation, a longer length tends to give better results.
//CALCULATION
//Step1: Calculating the Gains and Losses within the chosen period.
//Step2: Calculating the simple moving averages of gains and losses.
//Step3: Calculating Cutler’s Relative Strength (RS). Calculated using the following:
// Cutler’s RS = SMA(gains,length) / SMA(losses,length)
//Step 4: Calculating the Cutler’s Relative Strength Index (RSI). Calculated used the following:
// RSI = 100 — [100/(1 + RS)]
//@version=5
indicator("Cutlers RSI")
//RSI
length = input(14,title="Length",inline="LenSRC",group='RSI Settings',tooltip="It is suggested to use higher lengths rather than lower lengths due to the Simple Moving Average being used in the Cutler's RSI calculation and not the Exponential")
src = input.source(close,title="Source",inline="LenSRC",group='RSI Settings')
//MA
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => 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)
displayMA = input(false,title="Display MA",inline="MADisplay",group="MA Settings")
displayMACrossFill = input(false,title="Fill",inline="MADisplay",group="MA Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings",inline="MA")
maLengthInput = input.int(14, title="MA Length", group="MA Settings",inline="MA")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")
//Signals
tt_TRENDobos = "Trend OB/OS: Uptrend after above Overbought Level. Downtrend after below Oversold Level\n(For the traditional RSI OB=60 and OS=40 is used)"
tt_OBOS = "OB/OS: When above Overbought, or below oversold"
tt_50Cross = '50-Cross: Above 50 line is uptrend, below is downtrend.'
tt_Direction = "Direction: moving up or down"
tt_RSIvsMA = "RSI vs MA: RSI above is uptrend, RSI below is downtrend"
tt_signals = tt_TRENDobos +'\n\n' + tt_OBOS + '\n\n' + tt_50Cross + "\n\n" + tt_Direction +"\n\n" + tt_RSIvsMA
displaySignal = input(false,title="Display Signal",group="Signals",inline="Signal")
displaySignalVal = input.string("OB/OS (RSI)",title="",options=["Trend OB/OS(RSI)","OB/OS (RSI)","50-Cross (RSI)","Direction (RSI)","Trend OB/OS(MA)","OB/OS (MA)","50-Cross (MA)","Direction (MA)","RSI vs MA"],group="Signals",inline="Signal",tooltip=tt_signals)
//Colors
upCol = input(color.new(color.lime,70),title='', inline="Signal", group='Signals')
downCol = input(color.new(color.red,70),title='', inline="Signal", group='Signals')
//Oversold / Overbought
osLevel = input.float(30.0, minval=1, maxval=99, title='Oversold ', inline="os", group='Oversold/Overbought')
obLevel = input.float(70.0, minval=1, maxval=99, title='Overbought', inline="ob", group='Oversold/Overbought')
//Calculate Cuttlers RSI
float gains = 0.0
float losses = 0.0
for k = 0 to length - 1
float difference = nz(src[k]) - nz(src[k+1])
gains := difference > 0.0 ? gains + difference : gains
losses := difference < 0.0 ? losses - difference : losses
rsi = losses > 0.0 ? 100. - 100. / (1.0 + gains / losses) : 50.0
//Calculate MA
rsiMA = ma(rsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"
//Calculate Signals
sigCol = color(na)
if displaySignalVal == "Trend OB/OS(RSI)"
sigCol := rsi < osLevel ? downCol : (rsi > obLevel ? upCol : sigCol[1])
else if displaySignalVal == "OB/OS (RSI)"
sigCol := rsi < osLevel ? upCol : (rsi > obLevel ? downCol : na)
else if displaySignalVal == "50-Cross (RSI)"
sigCol := rsi >= 50 ? upCol : downCol
else if displaySignalVal == "Direction (RSI)"
sigCol := rsi == rsi[1] ? sigCol[1] : (rsi > rsi[1] ? upCol : downCol)
else if displaySignalVal == "Trend OB/OS(MA)"
sigCol := rsiMA < osLevel ? downCol : (rsiMA > obLevel ? upCol : sigCol[1])
else if displaySignalVal == "OB/OS (MA)"
sigCol := rsiMA < osLevel ? upCol : (rsiMA > obLevel ? downCol : na)
else if displaySignalVal == "50-Cross (MA)"
sigCol := rsiMA >= 50 ? upCol : downCol
else if displaySignalVal == "Direction (MA)"
sigCol := rsiMA == rsiMA[1] ? sigCol[1] : (rsiMA > rsiMA[1] ? upCol : downCol)
else if displaySignalVal == "RSI vs MA"
sigCol := rsi == rsiMA ? sigCol[1] : (rsi > rsiMA ? upCol : downCol)
//Plot Overbought/Oversold
rsiUpperBand = hline(obLevel, "Upper Band", color=#787B86, linewidth=1)
hline(50, "Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(osLevel, "Lower Band", color=#787B86, linewidth=1)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
//Plot Signal
bgcolor(displaySignal ? sigCol : na)
//Plot MA
rsiMAPlot = plot(displayMA ? rsiMA : na, title="RSI-based MA", color=displayMACrossFill == false ? color.yellow : (rsi > rsiMA ? color.lime : color.red))
rsiForMAPlot = plot(displayMA ? rsi : na, title="RSI for MA (invisible placeholder)",color=color.new(color.blue,100))
//BB
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill")
//Plot MA Fill
fill(rsiMAPlot,rsiForMAPlot, color = rsi > rsiMA ? color.lime : color.red, display = displayMACrossFill and isBB == false ? display.all : display.none) //Normal MA Fill
fill(bbUpperBand,rsiForMAPlot, color = rsi > (rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput) ? color.red : na, display = displayMACrossFill and isBB ? display.all : display.none) //Above BB Fill
fill(bbLowerBand,rsiForMAPlot, color = rsi < rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput ? color.lime : na, display = displayMACrossFill and isBB ? display.all : display.none) //Below BB Fill
//Plot RSI
plot(rsi,title="Harris RSI")
//Alerts
tt_alert = "Check off each piece of criteria you want for the alerts, then select Okay. Then go to 'Create Alert' and set the condition to 'Harris RSI', select create."
alertBuySignal = input(false,title="🟢Buy Signal Alert",group="Alerts",tooltip=tt_alert)
alertSellSignal = input(false,title="🔴Sell Signal Alert",group="Alerts")
if alertBuySignal and sigCol[1] == color.lime and sigCol[2] != color.lime
alert(timeframe.period + "🟢Harris RSI Alert - RSI: " + str.tostring(rsi,'#.#') + "\n" + displaySignalVal, alert.freq_once_per_bar)
if alertSellSignal and sigCol[1] == color.red and sigCol[2] != color.red
alert(timeframe.period + "🔴Harris RSI Alert - RSI: " + str.tostring(rsi,'#.#') + "\n" + displaySignalVal, alert.freq_once_per_bar)
|
Harris RSI | https://www.tradingview.com/script/QY5IsV2P-Harris-RSI/ | TanHef | https://www.tradingview.com/u/TanHef/ | 62 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TanHef
//This is a variation of Wilder's RSI created by Michael Harris.
//CALCULATION
//The average change of each of the length's source value is compared to the more recent source value
//The average difference of both positive or negative changes is found
//The range of 100 is divided by the divided result of the average incremented and decremented ratio plus one
//This result of the above is subracted from the range value of 100
//@version=5
indicator("Harris RSI")
length = input(14,title="Length",inline="LenSRC",group='RSI Settings')
src = input.source(close,title="Source",inline="LenSRC",group='RSI Settings')
//MA
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => 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)
displayMA = input(false,title="Display MA",inline="MADisplay",group="MA Settings")
displayMACrossFill = input(false,title="Fill",inline="MADisplay",group="MA Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings",inline="MA")
maLengthInput = input.int(14, title="MA Length", group="MA Settings",inline="MA")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")
//Signals
tt_TRENDobos = "Trend OB/OS: Uptrend after above Overbought Level. Downtrend after below Oversold Level\n(For the traditional RSI OB=60 and OS=40 is used)"
tt_OBOS = "OB/OS: When above Overbought, or below oversold"
tt_50Cross = '50-Cross: Above 50 line is uptrend, below is downtrend.'
tt_Direction = "Direction: moving up or down"
tt_RSIvsMA = "RSI vs MA: RSI above is uptrend, RSI below is downtrend"
tt_signals = tt_TRENDobos +'\n\n' + tt_OBOS + '\n\n' + tt_50Cross + "\n\n" + tt_Direction +"\n\n" + tt_RSIvsMA
displaySignal = input(false,title="Display Signal",group="Signals",inline="Signal")
displaySignalVal = input.string("OB/OS (RSI)",title="",options=["Trend OB/OS(RSI)","OB/OS (RSI)","50-Cross (RSI)","Direction (RSI)","Trend OB/OS(MA)","OB/OS (MA)","50-Cross (MA)","Direction (MA)","RSI vs MA"],group="Signals",inline="Signal",tooltip=tt_signals)
//"Trend OB/OS(RSI)","OB/OS (RSI)","50-Cross (RSI)","Direction (RSI)","OB/OS (MA)","50-Cross (MA)","Direction (MA)","RSI vs MA"
upCol = input(color.new(color.lime,70),title='', inline="Signal", group='Signals')
downCol = input(color.new(color.red,70),title='', inline="Signal", group='Signals')
//Oversold / Overbought
osLevel = input.float(30.0, minval=1, maxval=99, title='Oversold ', inline="os", group='Oversold/Overbought')
obLevel = input.float(70.0, minval=1, maxval=99, title='Overbought', inline="ob", group='Oversold/Overbought')
//Calculate Harris RSI
float up = 0.0
float down = 0.0
float avgerageUp = 0.0
float avgerageDown = 0.0
for k = 0 to length - 1
float difference = nz(src[k]) - nz(src[k+1])
if(difference > 0.)
avgerageUp += difference
up += 1
else
avgerageDown -= difference
down += 1
avgerageUp := up != 0.0 ? avgerageUp/up : avgerageUp
avgerageDown := down != 0.0 ? avgerageDown/down : avgerageDown
float RS = 1
RS := avgerageDown != 0. ? avgerageUp / avgerageDown : RS
rsi = 100-100 / (1.0 + RS)
//Calculate MA
rsiMA = ma(rsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"
//Calculate Signals
sigCol = color(na)
if displaySignalVal == "Trend OB/OS(RSI)"
sigCol := rsi < osLevel ? downCol : (rsi > obLevel ? upCol : sigCol[1])
else if displaySignalVal == "OB/OS (RSI)"
sigCol := rsi < osLevel ? upCol : (rsi > obLevel ? downCol : na)
else if displaySignalVal == "50-Cross (RSI)"
sigCol := rsi >= 50 ? upCol : downCol
else if displaySignalVal == "Direction (RSI)"
sigCol := rsi == rsi[1] ? sigCol[1] : (rsi > rsi[1] ? upCol : downCol)
else if displaySignalVal == "Trend OB/OS(MA)"
sigCol := rsiMA < osLevel ? downCol : (rsiMA > obLevel ? upCol : sigCol[1])
else if displaySignalVal == "OB/OS (MA)"
sigCol := rsiMA < osLevel ? upCol : (rsiMA > obLevel ? downCol : na)
else if displaySignalVal == "50-Cross (MA)"
sigCol := rsiMA >= 50 ? upCol : downCol
else if displaySignalVal == "Direction (MA)"
sigCol := rsiMA == rsiMA[1] ? sigCol[1] : (rsiMA > rsiMA[1] ? upCol : downCol)
else if displaySignalVal == "RSI vs MA"
sigCol := rsi == rsiMA ? sigCol[1] : (rsi > rsiMA ? upCol : downCol)
//Plot Overbought/Oversold
rsiUpperBand = hline(obLevel, "Upper Band", color=#787B86, linewidth=1)
hline(50, "Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(osLevel, "Lower Band", color=#787B86, linewidth=1)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
//Plot Signal
bgcolor(displaySignal ? sigCol : na)
//Plot MA
rsiMAPlot = plot(displayMA ? rsiMA : na, title="RSI-based MA", color=displayMACrossFill == false ? color.yellow : (rsi > rsiMA ? color.lime : color.red))
rsiForMAPlot = plot(displayMA ? rsi : na, title="RSI for MA (invisible placeholder)",color=color.new(color.blue,100))
//BB
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill")
//Plot MA Fill
fill(rsiMAPlot,rsiForMAPlot, color = rsi > rsiMA ? color.lime : color.red, display = displayMACrossFill and isBB == false ? display.all : display.none) //Normal MA Fill
fill(bbUpperBand,rsiForMAPlot, color = rsi > (rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput) ? color.red : na, display = displayMACrossFill and isBB ? display.all : display.none) //Above BB Fill
fill(bbLowerBand,rsiForMAPlot, color = rsi < rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput ? color.lime : na, display = displayMACrossFill and isBB ? display.all : display.none) //Below BB Fill
//Plot RSI
plot(rsi,title="Harris RSI")
//Alerts
tt_alert = "Check off each piece of criteria you want for the alerts, then select Okay. Then go to 'Create Alert' and set the condition to 'Harris RSI', select create."
alertBuySignal = input(false,title="🟢Buy Signal Alert",group="Alerts",tooltip=tt_alert)
alertSellSignal = input(false,title="🔴Sell Signal Alert",group="Alerts")
if alertBuySignal and sigCol[1] == color.lime and sigCol[2] != color.lime
alert(timeframe.period + "🟢Harris RSI Alert - RSI: " + str.tostring(rsi,'#.#') + "\n" + displaySignalVal, alert.freq_once_per_bar)
if alertSellSignal and sigCol[1] == color.red and sigCol[2] != color.red
alert(timeframe.period + "🔴Harris RSI Alert - RSI: " + str.tostring(rsi,'#.#') + "\n" + displaySignalVal, alert.freq_once_per_bar)
|
Supply and Demand Zones | https://www.tradingview.com/script/yvnrFXP4-Supply-and-Demand-Zones/ | funguru58 | https://www.tradingview.com/u/funguru58/ | 96 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © funguru58
//@version=4
study(title="Supply and Demand Zones",shorttitle="Supply / Demand",overlay=true)
//Daily zones
daily = input(title = "Daily",type = input.bool,defval=true)
dopen = security(syminfo.tickerid,'D',open,barmerge.gaps_off,barmerge.lookahead_on)
dayrange=(high-low)
dcol = color.red
r1 = security(syminfo.tickerid,'D',dayrange)
r2 = security(syminfo.tickerid, 'D', dayrange[1])
r3 = security(syminfo.tickerid, 'D', dayrange[2])
r4= security(syminfo.tickerid, 'D', dayrange[3])
r5= security(syminfo.tickerid, 'D', dayrange[4])
r6 = security(syminfo.tickerid, 'D', dayrange[5])
r7 = security(syminfo.tickerid, 'D', dayrange[6])
r8 = security(syminfo.tickerid, 'D', dayrange[7])
r9= security(syminfo.tickerid, 'D', dayrange[8])
r10= security(syminfo.tickerid, 'D', dayrange[9])
adr_10 = (r1+r2+r3+r4+r5+r6+r7+r8+r9+r10) /10
adr_9 = (r1+r2+r3+r4+r5+r6+r7+r8+r9) /9
adr_8 = (r1+r2+r3+r4+r5+r6+r7+r8) /8
adr_7 = (r1+r2+r3+r4+r5+r6+r7) /7
adr_6 = (r1+r2+r3+r4+r5+r6) /6
adr_5 = (r1+r2+r3+r4+r5) /5
adr_4 = (r1+r2+r3+r4) /4
adr_3 = (r1+r2+r3) /3
adr_2= (r1+r2)/2
adr_1 = r1
adrhigh10 = dopen+(adr_10/2)
adrhigh5 = dopen+(adr_5/2)
adrlow5 = dopen-(adr_5/2)
adrlow10 = dopen-(adr_10/2)
dayh5 = plot( daily? adrhigh5 : na, color = dcol)
dayh10 = plot( daily? adrhigh10 : na, color = dcol)
dayl5 = plot( daily? adrlow5 : na, color = dcol)
dayl10 = plot( daily? adrlow10 : na, color = dcol)
fill(dayh5,dayh10 , color=dcol)
fill(dayl5,dayl10,color=dcol)
//Weekly zones
weekly = input(title = "Weekly",type = input.bool,defval=true)
wopen = security(syminfo.tickerid,'W',open,barmerge.gaps_off,barmerge.lookahead_on)
weekrange=(high-low)
wcol = color.blue
wr1 = security(syminfo.tickerid,'W',weekrange)
wr2 = security(syminfo.tickerid, 'W', weekrange[1])
wr3 = security(syminfo.tickerid, 'W', weekrange[2])
wr4= security(syminfo.tickerid, 'W', weekrange[3])
wr5= security(syminfo.tickerid, 'W', weekrange[4])
wr6 = security(syminfo.tickerid, 'W', weekrange[5])
wr7 = security(syminfo.tickerid, 'W', weekrange[6])
wr8 = security(syminfo.tickerid, 'W', weekrange[7])
wr9= security(syminfo.tickerid, 'W', weekrange[8])
wr10= security(syminfo.tickerid, 'W', weekrange[9])
awr_10 = (wr1+wr2+wr3+wr4+wr5+wr6+wr7+wr8+wr9+wr10) /10
awr_9 = (wr1+wr2+wr3+wr4+wr5+wr6+wr7+wr8+wr9) /9
awr_8 = (wr1+wr2+wr3+wr4+wr5+wr6+wr7+wr8) /8
awr_7 = (wr1+wr2+wr3+wr4+wr5+wr6+wr7) /7
awr_6 = (wr1+wr2+wr3+wr4+wr5+wr6) /6
awr_5 = (wr1+wr2+wr3+wr4+wr5) /5
awr_4 = (wr1+wr2+wr3+wr4) /4
awr_3 = (wr1+wr2+wr3) /3
awr_2= (wr1+wr2)/2
awr_1 = wr1
awrhigh10 = wopen+(awr_10/2)
awrhigh5 = wopen+(awr_5/2)
awrlow5 = wopen-(awr_5/2)
awrlow10 = wopen-(awr_10/2)
weekh5 = plot( weekly? awrhigh5 : na, color = wcol)
weekh10 = plot( weekly? awrhigh10 : na, color = wcol)
weekl5 = plot( weekly? awrlow5 : na, color = wcol)
weekl10 = plot( weekly? awrlow10 : na, color = wcol)
fill(weekh5,weekh10,color=wcol)
fill(weekl5,weekl10,color=wcol)
//Monthly zones
monthly = input(title = "Monthly",type = input.bool,defval=true)
mopen = security(syminfo.tickerid,'M',open,barmerge.gaps_off,barmerge.lookahead_on)
monthrange=(high-low)
mcol = color.green
mr1 = security(syminfo.tickerid,'M',monthrange)
mr2 = security(syminfo.tickerid, 'M', monthrange[1])
mr3 = security(syminfo.tickerid, 'M', monthrange[2])
mr4= security(syminfo.tickerid, 'M', monthrange[3])
mr5= security(syminfo.tickerid, 'M', monthrange[4])
mr6 = security(syminfo.tickerid, 'M', monthrange[5])
mr7 = security(syminfo.tickerid, 'M', monthrange[6])
mr8 = security(syminfo.tickerid, 'M', monthrange[7])
mr9= security(syminfo.tickerid, 'M', monthrange[8])
mr10= security(syminfo.tickerid, 'M', monthrange[9])
amr_10 = (mr1+mr2+mr3+mr4+mr5+mr6+mr7+mr8+mr9+mr10) /10
amr_9 = (mr1+mr2+mr3+mr4+mr5+mr6+mr7+mr8+mr9) /9
amr_8 = (mr1+mr2+mr3+mr4+mr5+mr6+mr7+mr8) /8
amr_7 = (mr1+mr2+mr3+mr4+mr5+mr6+mr7) /7
amr_6 = (mr1+mr2+mr3+mr4+mr5+mr6) /6
amr_5 = (mr1+mr2+mr3+mr4+mr5) /5
amr_4 = (mr1+mr2+mr3+mr4) /4
amr_3 = (mr1+mr2+mr3) /3
amr_2= (mr1+mr2)/2
amr_1 = mr1
amrhigh10 = mopen+(amr_10/2)
amrhigh5 = mopen+(amr_5/2)
amrlom5 = mopen-(amr_5/2)
amrlom10 = mopen-(amr_10/2)
monthh5 = plot( monthly? amrhigh5 : na, color = mcol)
monthh10 = plot( monthly? amrhigh10 : na, color = mcol)
monthl5 = plot( monthly? amrlom5 : na, color = mcol)
monthl10 = plot( monthly? amrlom10 : na, color = mcol)
fill(monthh5,monthh10,color=mcol)
fill(monthl5,monthl10,color=mcol) |
TPO Letters [Kioseff Trading] | https://www.tradingview.com/script/llVldJto-TPO-Letters-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 404 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("TPO Letters [Kioseff Trading]", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 500)
lettersOnly = input.string(defval = "Letters", title = "Letters | Circles | Boxes", options = ["Letters", "Circles", "Boxes"])
ti = input.string(defval = "Regular", title = "Use Fixed Range to Calculate?", options = ["Regular", "Fixed Range"])
sess = input.string(defval = "D", title = "Recalculate After How Much Time?", tooltip = "from 1 to 1440 for minutes \nfrom 1D to 365D for days \nfrom 1W to 52W for weeks \nfrom 1M to 12M for months")
auto = input.string(defval = "Custom", options = ["Auto", "Custom"], title = "Auto Calculate Tick Levels? Custom?", inline = "1")
tickzz = input.float(defval = 100 ,title = "Ticks", inline = "1")
textSize = input.string(defval = "Small", options = ["Tiny", "Small", "Normal", "Large", "Huge"])
resCount = input.string(defval = "No", options = ["Yes", "No"], title = "Reset Characters After Exhuasting Alphabet? (Remove Numbers from TPO Letters)")
fr = input.bool(defval = true, title = "Show Fixed Range Label and Line?")
warn = input.bool(defval = true, title = "Show Warning")
tickLevels = input.bool(false, title = "Show Tick Levels?")
showCount = input.bool(defval = true, title = "Show Letter Count?")
showCol = input.bool(defval = true, title = "Color Letters in Value Area Only?")
ibFill = input.bool(defval = false, title = "Show IB Lines/Fill?")
showIb = input.bool(defval = false, title = "Color Initial Balance Characters?")
chrC = input.bool(defval = true, title = "Show Bottom Right Table?")
st = input.time(defval = timestamp("19 Sep 2022 00:00 +0300"), title = "Fixed Range Start", group = "Fixed Range")
sCol = input.color(title = "Start Color", group = "Gradient Color" ,defval = color.lime, tooltip = "Coloring of TPO Characters Operates on a Gradient. Consequently, the
Selected Start Color Ascribes the Initial Coloring of Letters. The Selected End Color Dictates the Final Coloring of Characters.")
eCol = input.color(title = "End Color", group = "Gradient Color", defval = color.red)
col = input.color(defval = color.gray, title = "Main Character Color (Gray Default)", group = "Colors")
col1 = input.color(defval = color.red , title = "SP Character Color (Red Default)")
col2 = input.color(defval = color.yellow, title = "POC Character Color (Yellow Default)")
col3 = input.color(defval = color.blue, title = "IB Character Color (Blue Default)")
col4 = input.color(defval = color.lime, title = "Value Area Color (Lime Default)")
col6 = input.color(defval = #a5d6a7, title = "Tick Level Value Area Color")
fnt = input.string(defval = "Default", title = "Font Type", options = ["Default", "Monospace"])
if fr == true and barstate.islast
line.new(math.round(st), close, math.round(st), close + 0.001, extend = extend.both, color = color.white, width = 4, xloc = xloc.bar_time)
if ti != "Fixed Range"
var box frStart = box.new(math.round(st), high + ta.tr, math.round(st), low - ta.tr,
bgcolor = color.new(color.white, 100), border_color = na, text_size = size.normal, text_color = color.white, text_wrap = text.wrap_none, text = "If Selected in Settings, \nFixed Range Begins Here", xloc = xloc.bar_time)
fonT = switch fnt
"Default" => font.family_default
"Monospace" => font.family_monospace
finTim = switch ti
"Regular" => timeframe.change(sess)
"Fixed Range" => time[1] < st and time >= st
sz = switch textSize
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
var int count = 0
var int firs = 0
var int ibB = 0
var float ibTime = 0.0
if session.isfirstbar_regular and count == 0
count := 1
firs := bar_index
ibTime := math.round(timestamp(year, month, dayofmonth, hour + 1, minute, second))
if time == ibTime and count == 1
ibB := bar_index
if session.isfirstbar_regular and count[1] == 1
firs := bar_index - firs
count := 2
var string [] str = switch lettersOnly
"Letters" => array.from(
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z"
)
"Boxes" => array.from("■")
"Circles" => array.from("◉")
if barstate.isfirst
if lettersOnly == "Boxes"
for i = 0 to 50
array.push(str, "■")
if lettersOnly == "Circles"
for i = 0 to 50
array.push(str, "◉")
sX = ""
if resCount == "No"
for i = 0 to 51
sX := array.get(str, i) + "1 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "2 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "3 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "4 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "5 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "6 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "7 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "8 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "9 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "10 " // => Loops are run sequentially, not simultaneously, so string characters populate in order
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "11 "
array.push(str, sX)
for i = 0 to 51
sX := array.get(str, i) + "12 "
array.push(str, sX)
else
for i = 0 to array.size(str) - 1
array.push(str, array.get(str, i))
for i = 0 to array.size(str) - 1
array.push(str, array.get(str, i))
for i = 0 to array.size(str) - 1
array.push(str, array.get(str, i))
for i = 0 to array.size(str) - 1
array.push(str, array.get(str, i))
import kaigouthro/hsvColor/1 as col // Great Library -> Check it out (CTRL + CLICK)
var color [] tpoLetCol = array.new_color()
if ti == "Regular"
if count[1] == 1 and count == 2
for i = 0 to firs
array.push(tpoLetCol, col.hsv_gradient(i , 0 , firs , eCol, sCol))
cond(y, x) =>
str.contains(label.get_text (array.get(y, x)),"1" ) or
str.contains(label.get_text(array.get(y, x)),"2" ) or
str.contains(label.get_text(array.get(y, x)),"3" ) or
str.contains(label.get_text(array.get(y, x)),"4" ) or
str.contains(label.get_text(array.get(y, x)),"5" ) or
str.contains(label.get_text(array.get(y, x)),"6" ) or
str.contains(label.get_text(array.get(y, x)),"7" ) or
str.contains(label.get_text(array.get(y, x)),"8" ) or
str.contains(label.get_text(array.get(y, x)),"9" ) or
str.contains(label.get_text(array.get(y, x)),"9" )
cond2(y, x) =>
str.contains(label.get_text(array.get(y, x)),"10" ) or
str.contains(label.get_text(array.get(y, x)),"11" ) or
str.contains(label.get_text(array.get(y, x)),"12" ) or
str.contains(label.get_text(array.get(y, x)),"13" ) or
str.contains(label.get_text(array.get(y, x)),"14" ) or
str.contains(label.get_text(array.get(y, x)),"15" ) or
str.contains(label.get_text(array.get(y, x)),"16" ) or
str.contains(label.get_text(array.get(y, x)),"17" ) or
str.contains(label.get_text(array.get(y, x)),"18" ) or
str.contains(label.get_text(array.get(y, x)),"19" ) or
str.contains(label.get_text(array.get(y, x)),"20" ) or
str.contains(label.get_text(array.get(y, x)),"21" ) or
str.contains(label.get_text(array.get(y, x)),"22" ) or
str.contains(label.get_text(array.get(y, x)),"23" ) or
str.contains(label.get_text(array.get(y, x)),"24" ) or
str.contains(label.get_text(array.get(y, x)),"25" ) or
str.contains(label.get_text(array.get(y, x)),"26" ) or
str.contains(label.get_text(array.get(y, x)),"27" ) or
str.contains(label.get_text(array.get(y, x)),"28" ) or
str.contains(label.get_text(array.get(y, x)),"29" ) or
str.contains(label.get_text(array.get(y, x)),"30" ) or
str.contains(label.get_text(array.get(y, x)),"31" ) or
str.contains(label.get_text(array.get(y, x)),"32" ) or
str.contains(label.get_text(array.get(y, x)),"33" ) or
str.contains(label.get_text(array.get(y, x)),"34" ) or
str.contains(label.get_text(array.get(y, x)),"35" ) or
str.contains(label.get_text(array.get(y, x)),"36" ) or
str.contains(label.get_text(array.get(y, x)),"37" ) or
str.contains(label.get_text(array.get(y, x)),"38" ) or
str.contains(label.get_text(array.get(y, x)),"39" ) or
str.contains(label.get_text(array.get(y, x)),"40" ) or
str.contains(label.get_text(array.get(y, x)),"41" ) or
str.contains(label.get_text(array.get(y, x)),"42" ) or
str.contains(label.get_text(array.get(y, x)),"43" ) or
str.contains(label.get_text(array.get(y, x)),"44" ) or
str.contains(label.get_text(array.get(y, x)),"45" ) or
str.contains(label.get_text(array.get(y, x)),"46" ) or
str.contains(label.get_text(array.get(y, x)),"47" ) or
str.contains(label.get_text(array.get(y, x)),"48" ) or
str.contains(label.get_text(array.get(y, x)),"49" ) or
str.contains(label.get_text(array.get(y, x)),"50" ) or
str.contains(label.get_text(array.get(y, x)),"51" ) or
str.contains(label.get_text(array.get(y, x)),"52" ) or
str.contains(label.get_text(array.get(y, x)),"53" ) or
str.contains(label.get_text(array.get(y, x)),"54" ) or
str.contains(label.get_text(array.get(y, x)),"55" ) or
str.contains(label.get_text(array.get(y, x)),"56" ) or
str.contains(label.get_text(array.get(y, x)),"57" ) or
str.contains(label.get_text(array.get(y, x)),"58" ) or
str.contains(label.get_text(array.get(y, x)),"59" ) or
str.contains(label.get_text(array.get(y, x)),"60" ) or
str.contains(label.get_text(array.get(y, x)),"61" ) or
str.contains(label.get_text(array.get(y, x)),"62" ) or
str.contains(label.get_text(array.get(y, x)),"63" ) or
str.contains(label.get_text(array.get(y, x)),"64" ) or
str.contains(label.get_text(array.get(y, x)),"65" ) or
str.contains(label.get_text(array.get(y, x)),"66" )
atr = ta.atr(14)
var float tickz = 0.0
ticks2 = array.new_float()
if ti == "Regular"
if last_bar_index - bar_index == 1601
if syminfo.mintick >= 0.01
tickz := auto == "Custom" ? tickzz :
auto == "Auto" and timeframe.period == "1" ? atr * 50 :
auto == "Auto" and timeframe.period == "5" ? atr * 40 :
atr * 30
else
tickz := auto == "Custom" ? tickzz : atr * 100000
else
if time < st
if syminfo.mintick >= 0.01
tickz := auto == "Custom" ? tickzz :
auto == "Auto" and timeframe.period == "1" ? atr * 50 :
auto == "Auto" and timeframe.period == "5" ? atr * 40 :
atr * 30
else
tickz := auto == "Custom" ? tickzz : atr * 100000
var line [] tpoLines = array.new_line()
ticks = array.new_float()
var float max = 0.0
var float min = 10000000
var float [] track = array.new_float()
var label [] pocL = array.new_label()
var float [] finChe = array.new_float()
var label [] letters = array.new_label()
var box [] lettersBox = array.new_box()
index = array.new_int()
var int timRound = 0
var int finB = 0
var float l = 0.0
if session.isfirstbar_regular
finB := bar_index + ibB
l := low
if session.isfirstbar_regular[4] and timRound == 0
timRound := math.round(time - time[4])
timeCond = switch ti
"Regular" => last_bar_index - bar_index <= 1600
"Fixed Range" => time >= st
var line [] ib = array.new_line()
var label [] SP = array.new_label()
var line [] val = array.new_line()
var label [] VA = array.new_label()
var int first = 0
var int firstBar = 0
var linefill fil = na
var float ibF = 0.0
var label [] tpoCount = array.new_label()
var line ibOpen = na
var line j = na
var label o = na
if timeCond
if timeCond[1] == false
j := line.new(bar_index, high, bar_index, low, color = color.aqua, width = 4, xloc = xloc.bar_index)
o := label.new(bar_index, open, xloc = xloc.bar_index, size = size.large, text_font_family = fonT, color = color.new(color.white, 100), text = "●", style = label.style_label_right, textcolor = color.blue)
if firstBar != 0
line.set_x1(j, firstBar - 1)
line.set_x2(j, firstBar - 1)
line.set_y1(j, max)
line.set_y2(j, min)
if time == ibF
if ibFill == true
array.push(ib, line.new(first, max, time, max, color = color.new(col3, 50), xloc = xloc.bar_time))
array.push(ib, line.new(first, min, time, min, color = color.new(col3, 50), xloc = xloc.bar_time))
if array.size(ib) > 1
linefill.new(array.get(ib, 0), array.get(ib, 1), color.new(col3, 95))
ibOpen := line.new(firstBar - 1, max, firstBar - 1, min, color = color.blue, width = 4)
max := math.max(high, max)
min := math.min(low, min)
if finTim
line.delete(ibOpen)
if array.size(tpoLetCol) == 0
for i = 0 to 1200
array.push(tpoLetCol, col.hsv_gradient(i , 0 , firs , eCol, sCol))
if array.size(val) > 0
for i = 0 to array.size(val) - 1
line.delete(array.shift(val))
if array.size(VA) > 0
for i = 0 to array.size(VA) - 1
label.delete(array.shift(VA))
if array.size(track) > 0
array.clear(track)
if array.size(finChe) > 0
array.clear(finChe)
if array.size(ib) > 0
for i = 0 to array.size(ib) - 1
line.delete(array.shift(ib))
if array.size(tpoLines) > 0
for i = 0 to array.size(tpoLines) - 1
line.delete(array.shift(tpoLines))
if array.size(SP) > 0
for i = 0 to array.size(SP) - 1
label.delete(array.shift(SP))
if array.size(pocL) > 0
for i = 0 to array.size(pocL) - 1
label.delete(array.shift(pocL))
if array.size(lettersBox) > 0
for i = 0 to array.size(lettersBox) - 1
box.delete(array.shift(lettersBox))
max := high
min := low
first := math.round(time)
ibF := math.round(timestamp(year, month, dayofmonth, hour + 1, minute, second))
label.set_x(o, bar_index)
label.set_y(o, open)
firstBar := bar_index
array.push(ticks, low)
array.push(track, low)
for i = 1 to 500
if array.get(ticks, i - 1) + (tickz * syminfo.mintick) <= high
array.push(ticks, array.get(ticks, i - 1) + (tickz * syminfo.mintick))
else
break
for i = 0 to array.size(ticks) - 1
array.push(tpoLines, line.new(bar_index, array.get(ticks, i) ,
bar_index + 1, array.get(ticks, i),
color = tickLevels == true ? color.new(color.lime, 75) : na, xloc = xloc.bar_index))
if barstate.islast
if array.size(VA) > 0
for i = 0 to array.size(VA) - 1
label.delete(array.shift(VA))
if array.size(val) > 0
for i = 0 to array.size(val) - 1
line.delete(array.shift(val))
if array.size(tpoLines) > 0
for i = 0 to array.size(tpoLines) - 1
line.delete(array.shift(tpoLines))
if array.size(SP) > 0
for i = 0 to array.size(SP) - 1
label.delete(array.shift(SP))
if array.size(pocL) > 0
for i = 0 to array.size(pocL) - 1
label.delete(array.shift(pocL))
if array.size(finChe) > 0
array.clear(finChe)
if array.size(letters) > 0
for i = 0 to array.size(letters) - 1
label.delete(array.shift(letters))
if array.size(lettersBox) > 0
for i = 0 to array.size(lettersBox) - 1
box.delete(array.shift(lettersBox))
if array.size(tpoCount) > 0
for i = 0 to array.size(tpoCount) - 1
label.delete(array.shift(tpoCount))
array.push(ticks, array.get(track, array.size(track) - 1))
for i = 1 to 500
if array.get(ticks, i - 1) + (tickz * syminfo.mintick) <= max
array.push(ticks, array.get(ticks, i - 1) + (tickz * syminfo.mintick))
else
break
array.push(ticks2, array.get(track, array.size(track) - 1))
for i = 1 to 500
if array.get(ticks2, i - 1) - (tickz * syminfo.mintick) >= min
array.push(ticks2, array.get(ticks2, i - 1) - (tickz * syminfo.mintick))
else
break
for i = array.size(ticks2) - 1 to 0
array.push(tpoLines, line.new( first, array.get(ticks2, i),
last_bar_time,
array.get(ticks2, i),
color = tickLevels == true ? color.new(color.lime, 75) : na,
xloc = xloc.bar_time
))
for i = 1 to array.size(ticks) - 1
array.push(tpoLines, line.new( first, array.get(ticks, i),
last_bar_time,
array.get(ticks, i),
color = tickLevels == true ? color.new(color.lime, 75) : na,
xloc = xloc.bar_time
))
if array.size(tpoLines) > 1 and bar_index - firstBar < array.size(str)
levels = array.new_float()
levels2 = array.new_float()
che = array.new_float(array.size(tpoLines), 0)
for i = bar_index - firstBar to 0
grad = col.hsv_gradient(bar_index[i], firstBar, last_bar_index, sCol, eCol)
for x = 0 to array.size(tpoLines) - 1
if line.get_y1(array.get(tpoLines, x)) <= high[i] and line.get_y1(array.get(tpoLines, x)) >= low[i]
if array.size(lettersBox) < 500
array.push(lettersBox, box.new(bar_index[i], line.get_y1(array.get(tpoLines,x)), bar_index[i], line.get_y1(array.get(tpoLines,x)),
bgcolor = color.new(color.white, 100), border_color = color.new(color.white, 100), text = array.get(str, bar_index - firstBar - i), text_size = sz,
text_color = ti == "Regular" ? array.get(tpoLetCol, i) : grad, text_font_family = fonT))
array.push(levels, line.get_y1(array.get(tpoLines,x)))
else
array.push(letters, label.new(bar_index[i], line.get_y1(array.get(tpoLines, x)),
array.get(str, bar_index - firstBar - i), style = label.style_label_left, color = color.new(color.white, 100), size = sz,
textcolor = ti == "Regular" ? array.get(tpoLetCol, i) : grad, text_font_family = fonT))
array.push(levels2, line.get_y1(array.get(tpoLines,x)))
for i = 0 to array.size(tpoLines) - 1
if array.size(lettersBox) > 0
for x = 0 to array.size(levels) - 1
if line.get_y1(array.get(tpoLines, i)) == array.get(levels, x)
array.set(che, i, array.get(che, i) + 1)
if array.size(letters) > 0
for x = 0 to array.size(levels2) - 1
if line.get_y1(array.get(tpoLines, i)) == array.get(levels2, x)
array.set(che, i, array.get(che, i) + 1)
if showCount == true
if array.size(tpoCount) > 0
for i = 0 to array.size(tpoCount) - 1
label.delete(array.shift(tpoCount))
for i = 0 to array.size(che) - 1
array.push(tpoCount, label.new(bar_index + 5, line.get_y1(array.get(tpoLines, i)),
text = str.tostring(array.get(che, i)) + " (" + str.tostring(line.get_y1(array.get(tpoLines, i)), format.mintick) + ")",
color = color.new(color.white, 100), textcolor = color.white, style = label.style_label_left))
len = 0.0
for x = 0 to array.size(che) - 1
len := math.max(len, array.get(che, x))
lenTrack = 0
for x = 0 to array.size(tpoLines) - 1
if array.get(che, x) == len
lenTrack := x
if bar_index - firstBar >= 4
line.set_color(array.get(tpoLines, x), color.new(col2, 75))
line.set_width(array.get(tpoLines, x), 2)
if showCount == true
label.set_textcolor(array.get(tpoCount, x), col2)
array.push(finChe, line.get_y1(array.get(tpoLines, x)))
if array.size(finChe) == 1
array.push(pocL, label.new(first, line.get_y1(array.get(tpoLines, x)), xloc = xloc.bar_time,
color = color.new(col, 100), textcolor = col2, style = label.style_label_right, text_font_family = fonT, text = "POC", size = sz))
break
sum = array.new_float()
sum1 = array.new_float()
lin = array.new_float()
lin1 = array.new_float()
cheX = array.new_float()
cheX1 = array.new_float()
if lenTrack > 0
for x = lenTrack - 1 to 0
array.push(sum , array.size(sum) == 0 ? array.get(che, x) : array.get(sum, array.size(sum) - 1) + array.get(che, x))
array.push(lin, line.get_y1(array.get(tpoLines, x)))
array.push(cheX, array.get(che, x))
for x = lenTrack to array.size(che) - 1
array.push(sum1, array.size(sum1) == 0 ? array.get(che, x) : array.get(sum1, array.size(sum1) - 1) + array.get(che, x))
array.push(lin1, line.get_y1(array.get(tpoLines, x)))
array.push(cheX1, array.get(che, x))
miN = math.min(array.size(sum), array.size(sum1))
for n = 0 to miN - 1
if array.get(sum, n) + array.get(sum1, n) >= array.sum(che) * .7
array.push(val,line.new(first , array.get(lin, n), time,
array.get(lin, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(val,line.new(first, array.get(lin1, n), time,
array.get(lin1, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(VA, label.new(first, line.get_y1(array.get(val, 0)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAH" : "VAL",
textcolor = col4, size = sz, color = color.new(color.white, 100), style = label.style_label_right, text_font_family = fonT, xloc = xloc.bar_time))
array.push(VA, label.new(first, line.get_y1(array.get(val, 1)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAL" : "VAH",
textcolor = col4, size = sz, color = color.new(color.white, 100), style = label.style_label_right, text_font_family = fonT, xloc = xloc.bar_time))
break
if array.size(val) < 2
stop = 0
if miN == array.size(sum1)
for n = 0 to array.size(cheX1) - 1
if array.get(cheX1, n) >= math.round(len * .7)
stop := n
for n = 0 to array.size(sum) - 1
if array.get(sum, n) + array.get(sum1, stop) >= array.sum(che) * .7
array.push(val,line.new(first, array.get(lin, n), time,
array.get(lin, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(val,line.new(first, array.get(lin1, stop), time,
array.get(lin1, stop), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(VA, label.new(first, line.get_y1(array.get(val, 0)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAH" : "VAL",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
array.push(VA, label.new(first, line.get_y1(array.get(val, 1)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAL" : "VAH",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
break
else
for n = 0 to array.size(cheX) - 1
if array.get(cheX, n) >= math.round(len * .7)
stop := n
for n = 0 to array.size(sum1) - 1
if array.get(sum, stop) + array.get(sum1, n) >= array.sum(che) * .7
array.push(val,line.new(first, array.get(lin1, n), time,
array.get(lin1, n), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(val,line.new(first, array.get(lin, stop), time,
array.get(lin, stop), xloc = xloc.bar_time, color = color.new(col4, 75)))
array.push(VA, label.new(first, line.get_y1(array.get(val, 0)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAH" : "VAL",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
array.push(VA, label.new(first, line.get_y1(array.get(val, 1)), text = line.get_y1(array.get(val, 0)) > line.get_y1(array.get(val, 1)) ? "VAL" : "VAH",
textcolor = col4, size = sz, color = color.new(color.white, 100), text_font_family = fonT, style = label.style_label_right, xloc = xloc.bar_time))
break
if array.size(val) == 2 and array.size(pocL) > 0 and array.size(tpoLines) > 0
fil := linefill.new(array.get(val, 0), array.get(val, 1), color = color.new(col4, 90))
if showCol == true
if array.size(lettersBox) > 0
for i = 0 to array.size(lettersBox) - 1
if line.get_y1(array.get(val, 0)) > line.get_y2(array.get(val, 1))
if box.get_top(array.get(lettersBox, i)) > line.get_y1(array.get(val, 0))
or box.get_top(array.get(lettersBox, i)) < line.get_y1(array.get(val, 1))
box.set_text_color(array.get(lettersBox, i), col)
else
if box.get_top(array.get(lettersBox, i)) < line.get_y1(array.get(val, 0))
or box.get_top(array.get(lettersBox, i)) > line.get_y1(array.get(val, 1))
box.set_text_color(array.get(lettersBox, i), col)
if array.size(letters) > 0
for i = 0 to array.size(letters) - 1
if line.get_y1(array.get(val, 0)) > line.get_y2(array.get(val, 1))
if label.get_y(array.get(letters, i)) > line.get_y1(array.get(val, 0))
or label.get_y(array.get(letters, i)) < line.get_y1(array.get(val, 1))
label.set_textcolor(array.get(letters, i), col)
else
if label.get_y(array.get(letters, i)) < line.get_y1(array.get(val, 0))
or label.get_y(array.get(letters, i)) > line.get_y1(array.get(val, 1))
label.set_textcolor(array.get(letters, i), col)
if showCount == true
for i = 0 to array.size(tpoLines) - 1
if array.get(che, i) == 1
label.set_textcolor(array.get(tpoCount, i), col1)
if line.get_y1(array.get(tpoLines, i)) == label.get_y(array.get(VA, 0))
or line.get_y1(array.get(tpoLines, i)) == label.get_y(array.get(VA, 1))
label.set_textcolor(array.get(tpoCount, i), col4)
if label.get_y(array.get(VA, 0)) > label.get_y(array.get(VA, 1))
if line.get_y1(array.get(tpoLines, i)) < label.get_y(array.get(VA, 0))
and line.get_y1(array.get(tpoLines, i)) > label.get_y(array.get(VA, 1))
and line.get_y1(array.get(tpoLines, i)) != label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoCount, i), col6)
if line.get_y1(array.get(tpoLines, i)) > label.get_y(array.get(VA, 0))
or line.get_y1(array.get(tpoLines, i)) < label.get_y(array.get(VA, 1))
if array.get(che, i) > 1 and line.get_y1(array.get(tpoLines, i)) !=
label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoCount, i), col)
else if label.get_y(array.get(VA, 0)) < label.get_y(array.get(VA, 1))
if line.get_y1(array.get(tpoLines, i)) > label.get_y(array.get(VA, 0))
and line.get_y1(array.get(tpoLines, i)) < label.get_y(array.get(VA, 1))
and line.get_y1(array.get(tpoLines, i)) != label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoCount, i), col6)
if line.get_y1(array.get(tpoLines, i)) > label.get_y(array.get(VA, 1))
or line.get_y1(array.get(tpoLines, i)) < label.get_y(array.get(VA, 0))
if array.get(che, i) > 1 and line.get_y1(array.get(tpoLines, i)) !=
label.get_y(array.get(pocL, 0))
label.set_textcolor(array.get(tpoCount, i), col)
if showIb == true
if array.size(lettersBox) > 0
for i = 0 to array.size(lettersBox) - 1
if box.get_left(array.get(lettersBox, i)) < finB
box.set_text_color(array.get(lettersBox, i), col3)
if array.size(letters) > 0
for i = 0 to array.size(letters) - 1
if label.get_x(array.get(letters, i)) < finB
label.set_textcolor(array.get(letters, i), col3)
if array.size(tpoCount) > 0
var label lab = na
label.delete(lab)
lab := label.new(bar_index + 5, label.get_y(array.get(tpoCount, 0)) - (tickz * syminfo.mintick), text = "Total TPO: " + str.tostring(array.sum(che)),
style = label.style_label_left, color = color.new(color.white, 100), textcolor = color.teal)
if warn == true
var table tab = table.new(position.top_right, 2, 2, frame_color = color.white, frame_width = 1)
table.cell(tab, 0, 0, text_size = size.small,
text = "If Letters Aren't Appearing: Decrease the 'Ticks' Setting. \nIf Letters are Cluttered: Increase the 'Ticks' Setting\nFor Your Changes to Take Effect: Change the 'Auto Calculate Tick Levels? Custom?' Setting to 'Custom'",
text_color = color.white, bgcolor = color.new(col3, 75))
if chrC == true
var table tab1 = table.new(position.bottom_right, 2, 2)
table.cell(tab1, 0, 0,
text_color = color.white, text_size = size.small, text = str.tostring(array.size(lettersBox)) + " Boxes Used (500 Max)\nIf The Number of Labels is Greater Than 500 - Early Session TPO Letters Will Delete." )
table.cell(tab1, 0, 1,
text_color = color.white, text_size = size.small, text = str.tostring(array.size(letters) + array.size(tpoCount) + 1) + " Labels Used (500 Max)\nIf The Number of Labels is Greater Than 500 - Later Session TPO Letters Will Delete." )
|
Auto Fibonacci [Misu] | https://www.tradingview.com/script/J3pAXcYv-Auto-Fibonacci-Misu/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 645 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©Misu
//@version=5
indicator("Auto Fibonacci [Misu]", overlay = true, shorttitle="Auto Fibo [Misu]", max_lines_count = 500, max_labels_count = 500)
import Fontiramisu/fontilab/12 as fontilab
// import Fontiramisu/fontLib/87 as fontilab
// ] —————— Input Vars —————— [
// Get user input
var devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot."
var depthTooltip = "The minimum number of bars that will be taken into account when analyzing pivots."
src = input.source(close, "Source", group="Settings")
thresholdMultiplier = input.float(title="Deviation", defval=2.5, minval=0, tooltip=devTooltip, group="Pivot Settings")
depth = input.int(title="Depth", defval=50, minval=1, tooltip=depthTooltip, group="Pivot Settings")
isColorAll = input.bool(true, "", group="UI Settings", inline="color")
colorAll = input.color(color.white, "Color All Lines ----", group="UI Settings", inline="color")
rightOffset = input.int(25, "Line Offset Right", group="UI Settings", inline="offset")
leftOffset = input.int(20, "Left", group="UI Settings", inline="offset")
isfib0000 = input.bool(true, "", group="UI Settings", inline="0")
nFib0000 = input.float(0, "", step=0.01, group="UI Settings", inline="0")
colorFib0000 = input.color(color.white, "", group="UI Settings", inline="0")
isfib0206 = input.bool(false, "", group="UI Settings", inline="0")
nFib0206 = input.float(0.206, "", step=0.01, group="UI Settings", inline="0")
colorFib0206 = input.color(color.white, "", group="UI Settings", inline="0")
isfib0382 = input.bool(true, "", group="UI Settings", inline="0.382")
nFib0382 = input.float(0.382, "", step=0.01, group="UI Settings", inline="0.382")
colorFib0382 = input.color(color.white, "", group="UI Settings", inline="0.382")
isfib0500 = input.bool(false, "", group="UI Settings", inline="0.382")
nFib0500 = input.float(0.5, "", step=0.01, group="UI Settings", inline="0.382")
colorFib0500 = input.color(color.white, "", group="UI Settings", inline="0.382")
isfib0618 = input.bool(true, "", group="UI Settings", inline="0.618")
nFib0618 = input.float(0.618, "", step=0.01, group="UI Settings", inline="0.618")
colorFib0618 = input.color(color.white, "", group="UI Settings", inline="0.618")
isfib0786 = input.bool(true, "", group="UI Settings", inline="0.618")
nFib0786 = input.float(0.718, "", step=0.01, group="UI Settings", inline="0.618")
colorFib0786 = input.color(color.white, "", group="UI Settings", inline="0.618")
isfib1000 = input.bool(true, "", group="UI Settings", inline="1")
nFib1000 = input.float(1, "", step=0.01, group="UI Settings", inline="1")
colorFib1000 = input.color(color.white, "", group="UI Settings", inline="1")
isfib1414 = input.bool(false, "", group="UI Settings", inline="1")
nFib1414 = input.float(1.414, "", step=0.01, group="UI Settings", inline="1")
colorFib1414 = input.color(color.white, "", group="UI Settings", inline="1")
isfib1618 = input.bool(false, "", group="UI Settings", inline="1.618")
nFib1618 = input.float(1.618, "", step=0.01, group="UI Settings", inline="1.618")
colorFib1618 = input.color(color.white, "", group="UI Settings", inline="1.618")
isfib2000 = input.bool(false, "", group="UI Settings", inline="1.618")
nFib2000 = input.float(2, "", step=0.01, group="UI Settings", inline="1.618")
colorFib2000 = input.color(color.white, "", group="UI Settings", inline="1.618")
isfib2618 = input.bool(false, "", group="UI Settings", inline="2.618")
nFib2618 = input.float(2.618, "", step=0.01, group="UI Settings", inline="2.618")
colorFib2618 = input.color(color.white, "", group="UI Settings", inline="2.618")
// ] —————— Find Dev Pivots —————— [
// Prepare pivot variables
var line lineLast = na
var int iLast = 0 // Index last
var int iPrev = 0 // Index previous
var float pLast = 0 // Price last
var float pLastHigh = 0 // Price last
var float pLastLow = 0 // Price last
var isHighLast = false // If false then the last pivot was a pivot low
isPivotFound = false
// Get pivot information from dev pivot finding function
[dupLineLast, dupIsHighLast, dupIPrev, dupILast, dupPLast, dupPLastHigh, dupPLastLow] =
fontilab.getDeviationPivots(thresholdMultiplier, depth, lineLast, isHighLast, iLast, pLast, true, close, high, low)
if not na(dupIsHighLast)
lineLast := dupLineLast
isHighLast := dupIsHighLast
iPrev := dupIPrev
iLast := dupILast
pLast := dupPLast
pLastHigh := dupPLastHigh
pLastLow := dupPLastLow
isPivotFound := true
// ] —————— Find Trend —————— [
var tDirUp = true
var pDirStrike = 0
var upB = close
var lowB = close
var midB = close
var nStrike = 2
var fib0000 = close
var fib0206 = close
var fib0382 = close
var fib0500 = close
var fib0618 = close
var fib0786 = close
var fib1000 = close
var fib1414 = close
var fib1618 = close
var fib2000 = close
var fib2618 = close
// Get trend and up/low Bands.
[midBDup, upBDup, lowBDup, pDirStrikeDup, tDirUpDup] = fontilab.getInterTrend(src, upB, lowB, pLast, tDirUp, pDirStrike, isPivotFound, isHighLast, 2, 0.5, depth)
pDirStrike := nz(pDirStrikeDup)
tDirUp := nz(tDirUpDup)
upB := nz(upBDup)
lowB := nz(lowBDup)
midB := nz(midBDup)
// Logic fibo direction.
var state = 1
var fiboDirUp = true
var lastState = 1
state := pDirStrike < nStrike ? 0 : not tDirUp ? -1 : tDirUp == 1 ? 1 : nz(state[1])
lastState := state != state[1] ? state[1] : lastState
fiboDirUp := state == 0 ? lastState == 1 : state == 1
// Calculate fibs levels.
rangeD = upB - lowB
fib0000 := fiboDirUp ? upB - nFib0000 * rangeD : lowB + nFib0000 * rangeD
fib0206 := fiboDirUp ? upB - nFib0206 * rangeD : lowB + nFib0206 * rangeD
fib0382 := fiboDirUp ? upB - nFib0382 * rangeD : lowB + nFib0382 * rangeD
fib0500 := fiboDirUp ? upB - nFib0500 * rangeD : lowB + nFib0500 * rangeD
fib0618 := fiboDirUp ? upB - nFib0618 * rangeD : lowB + nFib0618 * rangeD
fib0786 := fiboDirUp ? upB - nFib0786 * rangeD : lowB + nFib0786 * rangeD
fib1000 := fiboDirUp ? upB - nFib1000 * rangeD : lowB + nFib1000 * rangeD
fib1414 := fiboDirUp ? upB - nFib1414 * rangeD : lowB + nFib1414 * rangeD
fib1618 := fiboDirUp ? upB - nFib1618 * rangeD : lowB + nFib1618 * rangeD
fib2000 := fiboDirUp ? upB - nFib2000 * rangeD : lowB + nFib2000 * rangeD
fib2618 := fiboDirUp ? upB - nFib2618 * rangeD : lowB + nFib2618 * rangeD
// Last Update Barindex.
var barLastUpdate = 0
barLastUpdate := midB != midB[1] ? bar_index : barLastUpdate
// ] —————— Plot —————— [
var fib0000Line = line.new(0, low, bar_index, high)
var fib0000Label = label.new(bar_index, low, text="Init")
var fib0206Line = line.new(0, low, bar_index, high)
var fib0206Label = label.new(bar_index, low, text="Init")
var fib0382Line = line.new(0, low, bar_index, high)
var fib0382Label = label.new(bar_index, low, text="Init")
var fib0500Line = line.new(0, low, bar_index, high)
var fib0500Label = label.new(bar_index, low, text="Init")
var fib0618Line = line.new(0, low, bar_index, high)
var fib0618Label = label.new(bar_index, low, text="Init")
var fib0786Line = line.new(0, low, bar_index, high)
var fib0786Label = label.new(bar_index, low, text="Init")
var fib1000Line = line.new(0, low, bar_index, high)
var fib1000Label = label.new(bar_index, low, text="Init")
var fib1414Line = line.new(0, low, bar_index, high)
var fib1414Label = label.new(bar_index, low, text="Init")
var fib1618Line = line.new(0, low, bar_index, high)
var fib1618Label = label.new(bar_index, low, text="Init")
var fib2000Line = line.new(0, low, bar_index, high)
var fib2000Label = label.new(bar_index, low, text="Init")
var fib2618Line = line.new(0, low, bar_index, high)
var fib2618Label = label.new(bar_index, low, text="Init")
labelOffset = rightOffset - 5
if isfib0000
line.delete(fib0000Line)
label.delete(fib0000Label)
fib0000Line := line.new(barLastUpdate - leftOffset, fib0000, bar_index + rightOffset, fib0000, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib0000, width=1)
fib0000Label := label.new(x=bar_index + labelOffset, y = fib0000, xloc=xloc.bar_index, text=str.tostring(nFib0000), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0000, textalign=text.align_center)
if isfib0206
line.delete(fib0206Line)
label.delete(fib0206Label)
fib0206Line := line.new(barLastUpdate - leftOffset, fib0206, bar_index + rightOffset, fib0206, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib0206, width=1)
fib0206Label := label.new(x=bar_index + labelOffset, y = fib0206, xloc=xloc.bar_index, text=str.tostring(nFib0206), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0206, textalign=text.align_center)
if isfib0382
line.delete(fib0382Line)
label.delete(fib0382Label)
fib0382Line := line.new(barLastUpdate - leftOffset, fib0382, bar_index + rightOffset, fib0382, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib0382, width=1)
fib0382Label := label.new(x=bar_index + labelOffset, y = fib0382, xloc=xloc.bar_index, text=str.tostring(nFib0382), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0382, textalign=text.align_center)
if isfib0500
line.delete(fib0500Line)
label.delete(fib0500Label)
fib0500Line := line.new(barLastUpdate - leftOffset, fib0500, bar_index + rightOffset, fib0500, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib0500, width=1)
fib0500Label := label.new(x=bar_index + labelOffset, y = fib0500, xloc=xloc.bar_index, text=str.tostring(nFib0500), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0500, textalign=text.align_center)
if isfib0618
line.delete(fib0618Line)
label.delete(fib0618Label)
fib0618Line := line.new(barLastUpdate - leftOffset, fib0618, bar_index + rightOffset, fib0618, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib0618, width=1)
fib0618Label := label.new(x=bar_index + labelOffset, y = fib0618, xloc=xloc.bar_index, text=str.tostring(nFib0618), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0618, textalign=text.align_center)
if isfib0786
line.delete(fib0786Line)
label.delete(fib0786Label)
fib0786Line := line.new(barLastUpdate - leftOffset, fib0786, bar_index + rightOffset, fib0786, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib0786, width=1)
fib0786Label := label.new(x=bar_index + labelOffset, y = fib0786, xloc=xloc.bar_index, text=str.tostring(nFib0786), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0786, textalign=text.align_center)
if isfib1000
line.delete(fib1000Line)
label.delete(fib1000Label)
fib1000Line := line.new(barLastUpdate - leftOffset, fib1000, bar_index + rightOffset, fib1000, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib1000, width=1)
fib1000Label := label.new(x=bar_index + labelOffset, y = fib1000, xloc=xloc.bar_index, text=str.tostring(nFib1000), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib1000, textalign=text.align_center)
if isfib1414
line.delete(fib1414Line)
label.delete(fib1414Label)
fib1414Line := line.new(barLastUpdate - leftOffset, fib1414, bar_index + rightOffset, fib1414, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib1414, width=1)
fib1414Label := label.new(x=bar_index + labelOffset, y = fib1414, xloc=xloc.bar_index, text=str.tostring(nFib1414), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib1414, textalign=text.align_center)
if isfib1618
line.delete(fib1618Line)
label.delete(fib1618Label)
fib1618Line := line.new(barLastUpdate - leftOffset, fib1618, bar_index + rightOffset, fib1618, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib1618, width=1)
fib1618Label := label.new(x=bar_index + labelOffset, y = fib1618, xloc=xloc.bar_index, text=str.tostring(nFib1618), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib1618, textalign=text.align_center)
if isfib2000
line.delete(fib2000Line)
label.delete(fib2000Label)
fib2000Line := line.new(barLastUpdate - leftOffset, fib2000, bar_index + rightOffset, fib2000, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib2000, width=1)
fib2000Label := label.new(x=bar_index + labelOffset, y = fib2000, xloc=xloc.bar_index, text=str.tostring(nFib2000), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib2000, textalign=text.align_center)
if isfib2618
line.delete(fib2618Line)
label.delete(fib2618Label)
fib2618Line := line.new(barLastUpdate - leftOffset, fib2618, bar_index + rightOffset, fib2618, xloc=xloc.bar_index, color=isColorAll ? colorAll : colorFib2618, width=1)
fib2618Label := label.new(x=bar_index + labelOffset, y = fib2618, xloc=xloc.bar_index, text=str.tostring(nFib2618), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib2618, textalign=text.align_center)
// linefill.new(fib0786Line, fib1000Line, color.blue)
// ] |
MTF TMO | https://www.tradingview.com/script/nU0kaCxC-MTF-TMO/ | lnlcapital | https://www.tradingview.com/u/lnlcapital/ | 207 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// @version=5
//
// TMO (T)rue (M)omentum (O)scillator) MTF (Higher Aggregation) Version
//
// TMO calculates momentum using the DELTA of price. Giving a much better picture of trend, reversals and divergences than momentum oscillators using price.
//
// There are 3 additional TMOs for an even better picture of the trend. (Higher aggregation TMO dictates the lower aggregation TMO)
//
// Created by L&L Capital
//
indicator("MTF TMO", shorttitle="MTF TMO", overlay=false)
// Inputs
tmolength = input.int(14,title="Length")
calcLength = input(5, title="Calc Length")
smoothLength = input(3, title="Smooth Length")
// TMO 1 Calculations
TimeFrame1 = input.timeframe('D', "TMO 1", options=['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'])
srcc1 = request.security(syminfo.tickerid, TimeFrame1, close)
srco1 = request.security(syminfo.tickerid, TimeFrame1, open)
o1 = srco1
c1 = srcc1
data1 = 0
for i1 = 1 to tmolength -1
if c1 > o1[i1]
data1 := data1 + 1
if c1 < o1[i1]
data1 := data1 - 1
EMA1 = ta.ema(data1,calcLength)
Main1 = request.security(syminfo.tickerid, TimeFrame1, ta.ema(EMA1, smoothLength))
Signal1 = request.security(syminfo.tickerid, TimeFrame1, ta.ema(Main1, smoothLength))
// TMO 1 Plots
color1 = Main1 > Signal1 ? #27c22e : #ff0000
mainLine1 = plot(15*Main1/tmolength, title="TMO 1 Main", color=color1)
signalLine1 = plot(15*Signal1/tmolength, title="TMO 1 Signal", color=color1)
fill(mainLine1, signalLine1, title="TMO 1 Fill", color=color1, transp=75)
// TMO 2 Calculations
TimeFrame2 = input.timeframe('2D', "TMO 2", options=['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'])
srcc2 = request.security(syminfo.tickerid, TimeFrame2, close)
srco2 = request.security(syminfo.tickerid, TimeFrame2, open)
o2 = srco2
c2 = srcc2
data2 = 0
for i2 = 1 to tmolength -1
if c2 > o2[i2]
data2 := data2 + 1
if c2 < o2[i2]
data2 := data2 - 1
EMA2 = ta.ema(data2,calcLength)
Main2 = request.security(syminfo.tickerid, TimeFrame2, ta.ema(EMA2, smoothLength))
Signal2 = request.security(syminfo.tickerid, TimeFrame2, ta.ema(Main2, smoothLength))
// TMO 2 Plots
color2 = Main2 > Signal2 ? #27c22e : #ff0000
mainLine2 = plot(15*Main2/tmolength, title="TMO 2 Main", color=color2)
signalLine2 = plot(15*Signal2/tmolength, title="TMO 2 Signal", color=color2)
fill(mainLine2, signalLine2, title="TMO 2 Fill", color=color2, transp=75)
// TMO 3 Calculations
TimeFrame3 = input.timeframe('W', "TMO 3", options=['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'])
srcc3 = request.security(syminfo.tickerid, TimeFrame3, close)
srco3 = request.security(syminfo.tickerid, TimeFrame3, open)
o3 = srco3
c3 = srcc3
data3 = 0
for i3 = 1 to tmolength -1
if c3 > o3[i3]
data3 := data3 + 1
if c3 < o3[i3]
data3 := data3 - 1
EMA3 = ta.ema(data3,calcLength)
Main3 = request.security(syminfo.tickerid, TimeFrame3, ta.ema(EMA3, smoothLength))
Signal3 = request.security(syminfo.tickerid, TimeFrame3, ta.ema(Main3, smoothLength))
// TMO 3 Plots
color3 = Main3 > Signal3 ? #27c22e : #ff0000
mainLine3 = plot(15*Main3/tmolength, title="TMO 3 Main", color=color3)
signalLine3 = plot(15*Signal3/tmolength, title="TMO 3 Signal", color=color3)
fill(mainLine3, signalLine3, title="TMO 3 Fill", color=color3, transp=75)
// TMO 4 Calculations
TimeFrame4 = input.timeframe('M', "TMO 4", options=['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'])
srcc4 = request.security(syminfo.tickerid, TimeFrame4, close)
srco4 = request.security(syminfo.tickerid, TimeFrame4, open)
o4 = srco4
c4 = srcc4
data4 = 0
for i4 = 1 to tmolength -1
if c4 > o4[i4]
data4 := data4 + 1
if c4 < o4[i4]
data4 := data4 - 1
EMA4 = ta.ema(data4,calcLength)
Main4 = request.security(syminfo.tickerid, TimeFrame4, ta.ema(EMA4, smoothLength))
Signal4 = request.security(syminfo.tickerid, TimeFrame4, ta.ema(Main4, smoothLength))
// TMO 4 Plots
color4 = Main4 > Signal4 ? #27c22e : #ff0000
mainLine4 = plot(15*Main4/tmolength, title="TMO 4 Main", color=color4,display=display.none)
signalLine4 = plot(15*Signal4/tmolength, title="TMO 4 Signal", color=color4,display=display.none)
fill(mainLine4, signalLine4, title="TMO 4 Fill", color=color4, transp=75,display=display.none)
// Background & Colors
upper = hline(10, title="OB Line", color=#ff0000, linestyle=hline.style_solid,display=display.none)
lower = hline(-10, title="OS Line", color=#27c22e, linestyle=hline.style_solid,display=display.none)
ob = hline(math.round(15), title="OB Cutoff Line", color=#ff0000, linestyle=hline.style_solid)
os = hline(-math.round(15), title="OS Cutoff Line", color=#27c22e, linestyle=hline.style_solid)
zero = hline(0, title="Zero Line", color=#2a2e39, linestyle=hline.style_solid)
fill(ob, upper, title="OB Fill", color= #ff0000, transp = 75)
fill(os, lower, title="OS Fill", color= #27c22e, transp = 75)
|
YOY[TV1] | https://www.tradingview.com/script/CItBmXcl-yoy-tv1/ | TV-1ndicators | https://www.tradingview.com/u/TV-1ndicators/ | 17 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TV-1ndicators
//@version=5
indicator("YOY[TV1]")
manual_offset = input.int(0 ,'Offset' ,minval=0 ,tooltip=' Offset - отступ, время в барах. данные которых сравниваются. 0 - автоматическое определения для дневного(365),недельного(52), месячного(12) графиков.')
yoy(offset)=>
nz((close-close[offset])/close[offset]) *100
yoy = manual_offset? yoy(manual_offset):timeframe.ismonthly?yoy(12): timeframe.isweekly? yoy(52):timeframe.isdaily?yoy(365): na
if na(yoy)
runtime.error('Timeframe must be monthly or weekly or daily for auto offset. Usu manual offset for other timeframes. ')
plot(yoy)
|
Interactive Lot/Position Calculator FTX/OKX DCA [RDM13-NOSTRA] | https://www.tradingview.com/script/hGauHrrp/ | RDM13 | https://www.tradingview.com/u/RDM13/ | 110 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RDM13 / NOSTRA
//@version=5
indicator("Lot Calculator FTX/OKX DCA [NOSTRA] ", overlay=true)
// CELL DISPLAY
show_lotsize = input.bool(title="Use Lot Size ?", defval=false, inline="1", group = "Cell Display")
show_target = input.bool(title="Use Target ? " , defval=true, inline= "1", group = "Cell Display")
show_stop = input.bool(title="Use Stop ? " , defval=false, inline= "1", group = "Cell Display")
show_ratio = input.bool(title="R ? " , defval=false, inline= "1", group = "Cell Display")
show_p2 = input.bool(title="p2 ? " , defval=true, inline= "2", group = "Cell Display")
show_p3 = input.bool(title="p3 ? " , defval=false, inline= "2", group = "Cell Display")
show_p4 = input.bool(title="p4 ? " , defval=false, inline= "2", group = "Cell Display")
// CHART DISPLAY
show_line = input.bool(title="Show Lines ? " , defval=true, inline="1", group = "Chart Display")
show_line_target = input.bool(title="Show Target Line ? " , defval=false, inline="1", group = "Chart Display")
show_line_stop = input.bool(title="Show Stop Line ? " , defval=false, inline="1", group = "Chart Display")
tst(x)=> str.tostring(x)
var int dec = str.length(str.tostring(syminfo.mintick))-2
trc(number) =>
factor = math.pow(10, dec)
int(number * factor) / factor
trc_(number) =>
factor = math.pow(10, 2) // base = 0
int(number * factor) / factor
// -------------------------
// PRICE
gr1 = 'Entry & SL Price'
eP = input.price(10, 'Entry Price' , confirm=true, group=gr1, inline="1")
sl = input.price(15, 'Target Price' , confirm=true, group=gr1, inline="1")
eP2 = input.price(8, 'P2' , confirm=true, group = gr1)
eP3 = input.price(7, 'P3' , confirm=true, group = gr1 )
eP4 = input.price(6, 'P4' , group = gr1 )
stop = input.price(90, 'Stop Loss' , group = gr1)
// RISK MANAGER
gr11 = 'MONEY MANAGEMENT'
equity = input(100000, 'Account Size', inline="1", group=gr11)
equity_devise = input.string(defval="USD", title="", options=["USD", "USDT", "USDC", "BUSD", "DAI","EUR", "BTC", "ETH"] , inline="1", group=gr11)
riskmode = input.string(defval="USD", title="Risk Mode", options=["%", "USD"], group=gr11) //== "%"
riskInp = input(10000, title='Risk ' , group=gr11)
perLotSize = input.float(10 , title='LotSize' , group=gr11, tooltip = " (ex: 1 lot = 10 USD). Unit per lot = 10")
risk = riskInp
balance = equity
riskCurrUSD = risk
riskCurrPerc = risk*balance/100
int riskCurr = (na)
if riskmode == "%"
riskCurr := riskCurrPerc
else if riskmode == "USD"
riskCurr := riskCurrUSD
// stop & target
slRangeL = eP>sl? eP-sl : sl-eP
st = slRangeL/syminfo.mintick
slRangeL2 = eP>stop? stop-eP : eP-stop
st2 = math.abs(slRangeL2)/syminfo.mintick // math.abs ?
pz = riskCurr/eP
lz = pz/perLotSize
risk2USD = risk*balance/100
risk2Perc = riskCurr*100 / balance
int risk2 = (na)
if riskmode == "%"
risk2 := risk2USD
else if riskmode == "USD"
risk2 := risk2Perc
//target
targetlong = ((sl-eP)/eP)*100 // long
targetshort = ((eP-sl)/sl)*100 // short
target_perc = sl > eP ? targetlong : targetshort
//stoploss
stoplong = ((stop - eP) / eP)*100
stopshort = ((eP-stop)/stop)*100
stop_perc = stop < eP ? stoplong : stopshort
//ratio
ratio = (target_perc / math.abs(stop_perc))
//************************//
int risk_label = na
if riskmode =="%"
risk_label := risk*balance/100
else if riskmode == "USD"
risk_label := risk
riskp2 = risk_label
pz2 = riskp2/eP2
riskp3 = risk_label * 4
pz3 = riskp3/eP3
riskp4 = risk_label * 8
pz4 = riskp4/eP4
// ----------------
// Smart Table
// --------
gr10 = 'TABLE DISPLAY'
tabPosI = input.string('Top', 'Table Position', ['Top', 'Middle', 'Bot'], group=gr10)
tabCol = input.color(color.new(#673ab7, 35), 'Table Color', inline='1', group=gr10)
textCol = input.color(color.white, 'Text', inline='1', group=gr10)
textSizeI = input.string('Small', 'Text Size', ['Small', 'Tiny', 'Normal'], group=gr10)
textSize = textSizeI=='Small'? size.small : textSizeI=='Tiny'? size.tiny : size.normal
size_label_Inp = input.string('Small', 'Label Size', ['Small', 'Tiny', 'Normal'], group=gr10)
size_label = size_label_Inp=='Small'? size.small : size_label_Inp=='Tiny'? size.tiny : size.normal
tabPos = tabPosI=='Top'? position.top_center : tabPosI=='Bot'? position.bottom_right : position.middle_right
var smartTable = table.new(tabPos, 50, 50, color.new(color.black,100), color.new(color.black,100), 2, border_color= color.new(color.black,100) ,border_width=3)
gr13 = "STYLE SETTINGS"
long_col = input.color(color.new(color.blue, 70), 'Long Color', inline='2', group=gr13)
short_col = input.color(color.new(color.red, 70), 'Long Color', inline='2', group=gr13)
line_style = input.string(line.style_dotted, title="Line Style", options=[line.style_dotted, line.style_solid, line.style_dashed], inline='2', group=gr13)
sCol = input.color(color.green , "Target Color", inline='2', group=gr13)
stopCol = input.color(color.orange , "Stop Color", inline='2', group=gr13)
extline = input.string(extend.none, "Line Extended", options=[extend.none,extend.left, extend.right], inline="2", group=gr13)
table.cell( smartTable , 1, 0, 'Risk' + " " + equity_devise , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_lotsize
table.cell(smartTable, 2, 0, 'Unit/Lot' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
table.cell( smartTable, 5, 0, 'Position Size' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_lotsize
table.cell(smartTable, 6, 0, 'Lot Size' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_target
table.cell(smartTable, 7, 0, 'Target Tick' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_stop
table.cell(smartTable, 8, 0, 'Stop Tick' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_ratio
table.cell(smartTable, 9, 0, 'Ratio' , text_color=textCol, text_size=textSize, bgcolor=tabCol)
select_usd_1 = tst(risk) + " (" + tst(trc(risk2)) + "%)"
select_perc_1 = tst(risk)+ "%" + " (" + tst(trc(risk2)) + ")"
table.cell(smartTable , 1, 1, riskmode=="%" ? select_perc_1 : select_usd_1 , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_lotsize
table.cell(smartTable, 2, 1, tst(perLotSize), text_color=textCol, text_size=textSize, bgcolor=tabCol) // add
table.cell(smartTable, 5, 1, tst(trc_(pz))+ " " + syminfo.basecurrency, text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_lotsize
table.cell(smartTable, 6, 1, tst(trc_(lz))+" lots", text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_target
table.cell(smartTable, 7, 1, tst(trc_(st)) + " (" + tst(trc_(target_perc)) + "%)" , text_color=textCol, text_size=textSize, bgcolor=tabCol)
//table.cell(smartTable, 8, 1, tst(trc(target_perc)) + " %", text_color=textCol, text_size=textSize, bgcolor=tabCol) // ad
if show_stop
table.cell(smartTable, 8, 1, tst(trc_(st2)) + " (" + tst(trc_(stoplong)) + "%)" , text_color=textCol, text_size=textSize, bgcolor=tabCol)
if show_ratio
table.cell(smartTable, 9, 1, "R " + tst(trc_(ratio)) , text_color=textCol, text_size=textSize, bgcolor=tabCol)
var color entry_col = na
if show_line == true
entry_col := sl > eP ? long_col : short_col
else if show_line == false
entry_col := color.gray
transCol = entry_col
l_col = color.new(entry_col,5)
// entry
eL = line.new (bar_index[1], eP, bar_index+40, eP, color=l_col, style=line_style, extend=extline)
eL1 = label.new(bar_index+40, eP, 'P1 : ' + tst(eP) + " (" + tst(risk_label) + " " + equity_devise + " = " + tst(trc_(pz)) + " " + syminfo.basecurrency + ") ", textcolor=color.white, color=transCol, style=label.style_label_left, size=size_label)
line.delete (eL[1])
label.delete(eL1[1])
//*****************************//
if show_p2
eL_2 = line.new (bar_index[1], eP2, bar_index+40, eP2, color=l_col, style=line_style, extend=extline)
eL2 = label.new(bar_index+40, eP2, 'P2 : ' + tst(eP2) + " (" + tst(riskp2) + " " + equity_devise + " = " + tst(trc_(pz2)) + " " + syminfo.basecurrency + ") " , textcolor=color.white, color=transCol, style=label.style_label_left , size=size_label)
line.delete (eL_2[1])
label.delete(eL2[1])
if show_p3
eL_3 = line.new (bar_index[1], eP3, bar_index+40, eP3, color=l_col, style=line_style, extend=extline)
eL3 = label.new(bar_index+40, eP3, 'P3 : ' + tst(eP3) + " (" + tst(riskp3) + " " + equity_devise + " = " + tst(trc_(pz3)) + " " + syminfo.basecurrency + ") ", textcolor=color.white, color=transCol, style=label.style_label_left, size=size_label)
line.delete (eL_3[1])
label.delete(eL3[1])
if show_p4
eL_4 = line.new (bar_index[1], eP4, bar_index+40, eP4, color=l_col, style=line_style, extend=extline)
eL4 = label.new(bar_index+40, eP4, 'P4 : ' + tst(eP4) + " (" + tst(riskp4) + " " + equity_devise + " = " + tst(trc_(pz4)) + " " + syminfo.basecurrency + ") ", textcolor=color.white, color=transCol, style=label.style_label_left, size=size_label)
line.delete (eL_4[1])
label.delete(eL4[1])
if show_line_target
sL = line.new (bar_index[1], sl, bar_index+40, sl , color=color.new(sCol,5) , style=line_style, extend=extline)
sL1 = label.new(bar_index+40, sl, 'Target : ' + tst(sl) + " (" + tst(trc_(target_perc)) + " %) " , textcolor=color.white, color=sCol, style=label.style_label_left, size=size_label)
line.delete (sL[1])
label.delete(sL1[1])
if show_line_stop
stopL = line.new (bar_index[1], stop, bar_index+40, stop , color=color.new(stopCol,5), style=line_style, extend=extline)
stopL1 = label.new(bar_index+40, stop, 'Stop Loss : ' + tst(stop) + " (" + tst(trc_(stoplong)) + "%)" , textcolor=color.white, color=stopCol, style=label.style_label_left, size=size_label)
line.delete (stopL[1])
label.delete(stopL1[1])
|
EMA x5 | https://www.tradingview.com/script/2jBbFFyE-EMA-x5/ | Gabriel-Tan | https://www.tradingview.com/u/Gabriel-Tan/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Gabriel-Tan
//Edited to 3 EMAs
//@version=5
indicator(title='EMA x5', shorttitle='EMA x5', overlay=true)
shownormalEMA = input.bool(title="Show normal EMA's?", defval=false)
showHTFEMA = input.bool(title="Show HTF EMA's?", defval=true)
var reso = "Higher Timeframe Resolutions"
reso1 = input.timeframe(title='Trend Condiiton Timeframe 1 (Base Timeframe)', defval='240', group=reso)
reso2 = input.timeframe(title='Trend Condiiton Timeframe 2 (Comparing Timeframe)', defval='480', group=reso)
reso3 = input.timeframe(title='Trend Condiiton Timeframe 3 (Optional Timeframe)', defval ='720', group=reso)
reso4 = input.timeframe(title='Trend Condiiton Timeframe 4 (Optional Timeframe)', defval ='D', group=reso)
EMA1 = ta.ema(close, input(title='EMA1:', defval=5))
EMA2 = ta.ema(close, input(title='EMA2:', defval=20))
EMA3 = ta.ema(close, input(title='EMA3:', defval=50))
EMA4 = ta.ema(close, input(title="EMA4:", defval=100))
EMA5 = ta.ema(close, input(title="EMA5:", defval=200))
ema50Smooth4hours = request.security(syminfo.tickerid, reso1, EMA3, gaps=barmerge.gaps_on)
ema50Smooth8hours = request.security(syminfo.tickerid, reso2, EMA3, gaps=barmerge.gaps_on)
ema50Smooth12hours = request.security(syminfo.tickerid, reso3, EMA3, gaps=barmerge.gaps_on)
plot(shownormalEMA ? EMA1 : na, color=color.new(color.red, 0), title='EMA 1')
plot(shownormalEMA ? EMA2 : na, color=color.new(color.green, 0), title='EMA2')
plot(shownormalEMA ? EMA3 : na, color=color.new(color.orange, 0), title='EMA3')
plot(shownormalEMA ? EMA4 : na, color=color.new(color.aqua, 0), title="EMA4")
plot(shownormalEMA ? EMA5 : na, color=color.new(color.fuchsia, 0), title="EMA5")
plot(showHTFEMA ? EMA3 : na, color=color.new(color.red, 0), title="Current EMA 50", linewidth=2)
plot(showHTFEMA ? ema50Smooth8hours : na, color=color.new(color.aqua, 0), title="Resolution 2 EMA 50")
plot(showHTFEMA ? ema50Smooth12hours : na, color=color.new(color.fuchsia, 0), title="Resolution 3 EMA 50")
|
Probability Cloud BASIC [@AndorraInvestor] | https://www.tradingview.com/script/11Nbv8Sw-Probability-Cloud-BASIC-AndorraInvestor/ | AndorraInvestor | https://www.tradingview.com/u/AndorraInvestor/ | 37 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ©AndorraInvestor
// On Twitter: _ _____ _
// ____ /\ | | |_ _| | |
// / __ \ / \ _ __ __| | ___ _ __ _ __ __ _ | | _ ____ _____ ___| |_ ___ _ __
// / / _` | / /\ \ | '_ \ / _` |/ _ \| '__| '__/ _` | | | | '_ \ \ / / _ \/ __| __/ _ \| '__|
// | | (_| |/ ____ \| | | | (_| | (_) | | | | | (_| |_| |_| | | \ V / __/\__ \ || (_) | |
// \ \__,_/_/ \_\_| |_|\__,_|\___/|_| |_| \__,_|_____|_| |_|\_/ \___||___/\__\___/|_|
// \____/
//
//@version=5
indicator("🔮☁️ Probability Cloud BASIC [@AndorraInvestor]", overlay=true)
//==================================================================================================
// Thanks to u/Electrified for letting me use some of his work as starting point for my first script
//==================================================================================================
import Electrified/MovingAverages/10 as MA
import Electrified/DataCleaner/7 as Data
SMA = 'SMA', EMA = 'EMA', WMA = 'WMA', VWMA = 'VWMA', VAWMA = 'VAWMA'
cloudcol = input(color.new(color.blue,98), "Cloud Color")
var type = input.string(WMA, "Mode", options=[SMA,EMA,WMA,VWMA,VAWMA])
src = input.source(hl2, "Source")
var len1 = 5
var len2 = 10
var len3 = 15
var len4 = 20
var len5 = 25
var len6 = 30
var len7 = 35
var len8 = 40
var len9 = 45
var len10 = 50
var len11 = 55
var len12 = 60
var len13 = 65
var len14 = 70
var len15 = 75
var len16 = 80
var len17 = 85
var len18 = 90
var len19 = 95
var len20 = 100
ma1 = MA.get(type, len1, src)
ma2 = MA.get(type, len2, src)
ma3 = MA.get(type, len3, src)
ma4 = MA.get(type, len4, src)
ma5 = MA.get(type, len5, src)
ma6 = MA.get(type, len6, src)
ma7 = MA.get(type, len7, src)
ma8 = MA.get(type, len8, src)
ma9 = MA.get(type, len9, src)
ma10 = MA.get(type, len10, src)
ma11 = MA.get(type, len11, src)
ma12 = MA.get(type, len12, src)
ma13 = MA.get(type, len13, src)
ma14 = MA.get(type, len14, src)
ma15 = MA.get(type, len15, src)
ma16 = MA.get(type, len16, src)
ma17 = MA.get(type, len17, src)
ma18 = MA.get(type, len18, src)
ma19 = MA.get(type, len19, src)
ma20 = MA.get(type, len20, src)
ma_d1 = (src - ma1)/ma1
ma_d2 = (src - ma2)/ma2
ma_d3 = (src - ma3)/ma3
ma_d4 = (src - ma4)/ma4
ma_d5 = (src - ma5)/ma5
ma_d6 = (src - ma6)/ma6
ma_d7 = (src - ma7)/ma7
ma_d8 = (src - ma8)/ma8
ma_d9 = (src - ma9)/ma9
ma_d10 = (src - ma10)/ma10
ma_d11 = (src - ma11)/ma11
ma_d12 = (src - ma12)/ma12
ma_d13 = (src - ma13)/ma13
ma_d14 = (src - ma14)/ma14
ma_d15 = (src - ma15)/ma15
ma_d16 = (src - ma16)/ma16
ma_d17 = (src - ma17)/ma17
ma_d18 = (src - ma18)/ma18
ma_d19 = (src - ma19)/ma19
ma_d20 = (src - ma20)/ma20
//In this BASIC version number of outliers is fixed to 4
cleaned1 = Data.naOutliers(ma_d1, len1, 4)
cleaned2 = Data.naOutliers(ma_d2, len2, 4)
cleaned3 = Data.naOutliers(ma_d3, len3, 4)
cleaned4 = Data.naOutliers(ma_d4, len4, 4)
cleaned5 = Data.naOutliers(ma_d5, len5, 4)
cleaned6 = Data.naOutliers(ma_d6, len6, 4)
cleaned7 = Data.naOutliers(ma_d7, len7, 4)
cleaned8 = Data.naOutliers(ma_d8, len8, 4)
cleaned9 = Data.naOutliers(ma_d9, len9, 4)
cleaned10 = Data.naOutliers(ma_d10, len10, 4)
cleaned11 = Data.naOutliers(ma_d11, len11, 4)
cleaned12 = Data.naOutliers(ma_d12, len12, 4)
cleaned13 = Data.naOutliers(ma_d13, len13, 4)
cleaned14 = Data.naOutliers(ma_d14, len14, 4)
cleaned15 = Data.naOutliers(ma_d15, len15, 4)
cleaned16 = Data.naOutliers(ma_d16, len16, 4)
cleaned17 = Data.naOutliers(ma_d17, len17, 4)
cleaned18 = Data.naOutliers(ma_d18, len18, 4)
cleaned19 = Data.naOutliers(ma_d19, len19, 4)
cleaned20 = Data.naOutliers(ma_d20, len20, 4)
avg1 = ta.sma(cleaned1, len1) * ma1
stdev1 = ta.stdev(cleaned1, len1) * ma1
avg2 = ta.sma(cleaned2, len2) * ma2
stdev2 = ta.stdev(cleaned2, len2) * ma2
avg3 = ta.sma(cleaned3, len3) * ma3
stdev3 = ta.stdev(cleaned3, len3) * ma3
avg4 = ta.sma(cleaned4, len4) * ma4
stdev4 = ta.stdev(cleaned4, len4) * ma4
avg5 = ta.sma(cleaned5, len5) * ma5
stdev5 = ta.stdev(cleaned5, len5) * ma5
avg6 = ta.sma(cleaned6, len6) * ma6
stdev6 = ta.stdev(cleaned6, len6) * ma6
avg7 = ta.sma(cleaned7, len7) * ma7
stdev7 = ta.stdev(cleaned7, len7) * ma7
avg8 = ta.sma(cleaned8, len8) * ma8
stdev8 = ta.stdev(cleaned8, len8) * ma8
avg9 = ta.sma(cleaned9, len9) * ma9
stdev9 = ta.stdev(cleaned9, len9) * ma9
avg10 = ta.sma(cleaned10, len10) * ma10
stdev10 = ta.stdev(cleaned10, len10) * ma10
avg11 = ta.sma(cleaned11, len11) * ma11
stdev11 = ta.stdev(cleaned11, len11) * ma11
avg12 = ta.sma(cleaned12, len12) * ma12
stdev12 = ta.stdev(cleaned12, len12) * ma12
avg13 = ta.sma(cleaned13, len13) * ma13
stdev13 = ta.stdev(cleaned13, len13) * ma13
avg14 = ta.sma(cleaned14, len14) * ma14
stdev14 = ta.stdev(cleaned14, len14) * ma14
avg15 = ta.sma(cleaned15, len15) * ma15
stdev15 = ta.stdev(cleaned15, len15) * ma15
avg16 = ta.sma(cleaned16, len16) * ma16
stdev16 = ta.stdev(cleaned16, len16) * ma16
avg17 = ta.sma(cleaned17, len17) * ma17
stdev17 = ta.stdev(cleaned17, len17) * ma17
avg18 = ta.sma(cleaned18, len18) * ma18
stdev18 = ta.stdev(cleaned18, len18) * ma18
avg19 = ta.sma(cleaned19, len19) * ma19
stdev19 = ta.stdev(cleaned19, len19) * ma19
avg20 = ta.sma(cleaned20, len20) * ma20
stdev20 = ta.stdev(cleaned20, len20) * ma20
upper1 = ma1 + avg1 + stdev1
lower1 = ma1 + avg1 - stdev1
upper2 = ma2 + avg2 + stdev2
lower2 = ma2 + avg2 - stdev2
upper3 = ma3 + avg3 + stdev3
lower3 = ma3 + avg3 - stdev3
upper4 = ma4 + avg4 + stdev4
lower4 = ma4 + avg4 - stdev4
upper5 = ma5 + avg5 + stdev5
lower5 = ma5 + avg5 - stdev5
upper6 = ma6 + avg6 + stdev6
lower6 = ma6 + avg6 - stdev6
upper7 = ma7 + avg7 + stdev7
lower7 = ma7 + avg7 - stdev7
upper8 = ma8 + avg8 + stdev8
lower8 = ma8 + avg8 - stdev8
upper9 = ma9 + avg9 + stdev9
lower9 = ma9 + avg9 - stdev9
upper10 = ma10 + avg10 + stdev10
lower10 = ma10 + avg10 - stdev10
upper11 = ma11 + avg11 + stdev11
lower11 = ma11 + avg11 - stdev11
upper12 = ma12 + avg12 + stdev12
lower12 = ma12 + avg12 - stdev12
upper13 = ma13 + avg13 + stdev13
lower13 = ma13 + avg13 - stdev13
upper14 = ma14 + avg14 + stdev14
lower14 = ma14 + avg14 - stdev14
upper15 = ma15 + avg15 + stdev15
lower15 = ma15 + avg15 - stdev15
upper16 = ma16 + avg16 + stdev16
lower16 = ma16 + avg16 - stdev16
upper17 = ma17 + avg17 + stdev17
lower17 = ma17 + avg17 - stdev17
upper18 = ma18 + avg18 + stdev18
lower18 = ma18 + avg18 - stdev18
upper19 = ma19 + avg19 + stdev19
lower19 = ma19 + avg19 - stdev19
upper20 = ma20 + avg20 + stdev20
lower20 = ma20 + avg20 - stdev20
//The "display=dispplay.none" is the best solution to the "Maximum number of output series" error, which was reached once color was an added input variable.
pUpper1 = plot(upper1 + stdev1, display=display.none)
pLower1 = plot(lower1 - stdev1, display=display.none)
pUpper2 = plot(upper2 + stdev2, display=display.none)
pLower2 = plot(lower2 - stdev2, display=display.none)
pUpper3 = plot(upper3 + stdev3, display=display.none)
pLower3 = plot(lower3 - stdev3, display=display.none)
pUpper4 = plot(upper4 + stdev4, display=display.none)
pLower4 = plot(lower4 - stdev4, display=display.none)
pUpper5 = plot(upper5 + stdev5, display=display.none)
pLower5 = plot(lower5 - stdev5, display=display.none)
pUpper6 = plot(upper6 + stdev6, display=display.none)
pLower6 = plot(lower6 - stdev6, display=display.none)
pUpper7 = plot(upper7 + stdev7, display=display.none)
pLower7 = plot(lower7 - stdev7, display=display.none)
pUpper8 = plot(upper8 + stdev8, display=display.none)
pLower8 = plot(lower8 - stdev8, display=display.none)
pUpper9 = plot(upper9 + stdev9, display=display.none)
pLower9 = plot(lower9 - stdev9, display=display.none)
pUpper10 = plot(upper10 + stdev10, display=display.none)
pLower10 = plot(lower10 - stdev10, display=display.none)
pUpper11 = plot(upper11 + stdev11, display=display.none)
pLower11 = plot(lower11 - stdev11, display=display.none)
pUpper12 = plot(upper12 + stdev12, display=display.none)
pLower12 = plot(lower12 - stdev12, display=display.none)
pUpper13 = plot(upper13 + stdev13, display=display.none)
pLower13 = plot(lower13 - stdev13, display=display.none)
pUpper14 = plot(upper14 + stdev14, display=display.none)
pLower14 = plot(lower14 - stdev14, display=display.none)
pUpper15 = plot(upper15 + stdev15, display=display.none)
pLower15 = plot(lower15 - stdev15, display=display.none)
pUpper16 = plot(upper16 + stdev16, display=display.none)
pLower16 = plot(lower16 - stdev16, display=display.none)
pUpper17 = plot(upper17 + stdev17, display=display.none)
pLower17 = plot(lower17 - stdev17, display=display.none)
pUpper18 = plot(upper18 + stdev18, display=display.none)
pLower18 = plot(lower18 - stdev18, display=display.none)
pUpper19 = plot(upper19 + stdev19, display=display.none)
pLower19 = plot(lower19 - stdev19, display=display.none)
pUpper20 = plot(upper20 + stdev20, display=display.none)
pLower20 = plot(lower20 - stdev20, display=display.none)
fill(pUpper1, pLower1, cloudcol)
fill(pUpper2, pLower2, cloudcol)
fill(pUpper3, pLower3, cloudcol)
fill(pUpper4, pLower4, cloudcol)
fill(pUpper5, pLower5, cloudcol)
fill(pUpper6, pLower6, cloudcol)
fill(pUpper7, pLower7, cloudcol)
fill(pUpper8, pLower8, cloudcol)
fill(pUpper9, pLower9, cloudcol)
fill(pUpper10, pLower10, cloudcol)
fill(pUpper11, pLower11, cloudcol)
fill(pUpper12, pLower12, cloudcol)
fill(pUpper13, pLower13, cloudcol)
fill(pUpper14, pLower14, cloudcol)
fill(pUpper15, pLower15, cloudcol)
fill(pUpper16, pLower16, cloudcol)
fill(pUpper17, pLower17, cloudcol)
fill(pUpper18, pLower18, cloudcol)
fill(pUpper19, pLower19, cloudcol)
fill(pUpper20, pLower20, cloudcol)
fill(pUpper17, pLower17, cloudcol)
fill(pUpper18, pLower18, cloudcol)
fill(pUpper19, pLower19, cloudcol)
fill(pUpper20, pLower20, cloudcol)
|
RF+ Divergence Scalping System | https://www.tradingview.com/script/lKhzrLPA-RF-Divergence-Scalping-System/ | tvenn | https://www.tradingview.com/u/tvenn/ | 399 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tvenn
//@version=5
indicator(title="RF+ Divergence Scalping System", shorttitle="RF+", overlay = true, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400)
// strategy(title="RF+ strategies", max_bars_back = 1000, max_labels_count = 400, max_lines_count = 400, initial_capital = 10000, default_qty_value = 10, slippage = 5 )
//=Constants
green = #95BD5F
red = #EA1889
mocha = #C0A392
//=Range Filters
//==================================================================================================================================
showDashboard = input(false, title="Show Dashboard", inline='1')
dashboardPosition = input.string(title='', defval='Top Right', options=['Top Right', 'Bottom Right', 'Top Left', 'Bottom Left'], inline='1')
dashboardSize = input.string(title='', defval='Mobile', options=['Mobile', 'Desktop'], inline='1')
showRangeFilters = input(true, title="Show Range Filters", tooltip="The 2x Range Filters can be used to help indicate short term trend direction. When both Range Filters change colour can help to determine when price is ready to reverse, especially helpful in timing entries for regular divergences and avoiding entering too early, where price can often take some time before it actually begins to reverse. A common mistake in trading divergences is to enter too early.")
showMTFSignals = input(true, title="Show MTF Signals")
showRealPriceLine = input(false, title="Show Real Price Line", tooltip="This will show a real price line for use with Heikin Ashi candles.\n\nNOTE: this feature may lag slightly due to the large number of features. Consider using a standalone indicator such as 'Real Price Line + Dots (for Heikin Ashi), linked in my Tradingview profile.")
showRealCloseDots = input(false, title="Show Real Price Close Dots", tooltip="This will show real price close dots on each candle, for use with Heikin Ashi candles.\n\nNOTE: this feature may lag slightly due to the large number of features. Consider using a standalone indicator such as 'Real Price Line + Dots (for Heikin Ashi), linked in my Tradingview profile")
enableMA = input(true, title="Show Moving Averages")
enableMTFMA = input(true, title="Show MTF Moving Averages", tooltip="Enabling this will show the various levels of the selected moving average for each of the selected timeframes below on a single chart, shown as a horizontal line on the right of the chart.\n\nThis can help identify levels at which price may react to the moving average (which may occur on multiple timeframes) without having to monitor those additional chart timeframes directly.")
showVWAP = input(false, title="Show VWAP", inline="vwap")
showpivot = input(false, title="Show Pivot Points")
showWatermark = input(true, title="Show Watermark")
//=Divergence settings
//==================================================================================================================================
grp_div = "Divergence settings"
showlines = input(defval = true, title = "Show Divergence Lines", group=grp_div)
showlast = input(defval = true, title = "Show Only Last Divergence", group=grp_div)
shownum = input(defval = false, title = "Show Divergence Number", group=grp_div)
dontconfirm = input(defval = false, title = "Don't Wait for Confirmation", group=grp_div)
showConfirmlines= input(defval = false, title = "Show Regular Divergence Confirm Lines", group=grp_div, tooltip="This will place a horizontal line extending right from the startpoint of regular divergences, these lines can be used as a confirmation entry level into some regular divergence reversal trades, if and when price reverses, and pushes past this level.\n\nThey will not be shown for hidden divergences.")
confirmLineLen = input.int(20, title="Extend Regular Divergence Confirm Line", group=grp_div)
showindis = input.string(defval = "Don't Show", title = "Show Indicator Names", options = ["Full", "First Letter", "Don't Show"], group=grp_div)
searchdiv = input.string(defval = "Regular/Hidden", title = "Show Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group=grp_div)
showlimit = input.int(1, title="Minimum Number of Divergence", minval = 1, maxval = 11, group=grp_div)
//=Custom confluence signals
//==================================================================================================================================
grp_SIGNALS = "Custom signals"
MTFOBOSDivSignal = input(true, title="Show MTF CCI/Stoch RSI OB/OS + Div", group=grp_SIGNALS, tooltip="Places label to indicate where MTF Stoch RSI / MTF CCI oversold AND recent bullish divergence, and where MTF Stoch RSI / MTF CCI overbought AND recent bearish divergence.\n\nYou can alert these using the alert called 'MTF OB/OS + Div on RF+'")
showpullbackdivergence = input(false, title="Show RF Pullbacks with Divergences", group=grp_SIGNALS, tooltip="Icons will show signals for long entries:\n\n1) Price closes beneath 2x uptrending Range Filters and\n2) That candle also forms a bullish divergence that supports the direction of the Range Filters\n\nAnd for short entries:\n\n1) Price closes above 2x downtrending Range Filters and\n2) That candle also forms a bearish divergence that supports the direction of the Range Filters.\n\nThese signals represent a possible entry into a trend continuation trade in the direction indicated by the 2xRFs and the suppporting divergence.\n\nDesigned primarily for the 2-3m timeframes, but also work on higher timeframes.")
showFilteredDivEntryCriteria= input(false, title="Show Divs Filtered by 21sma + RSI MA (for 15m)", group=grp_SIGNALS, tooltip="Show divergence signals that are filtered by\n\nFor buy signals\n1) Price above the 21sma and\n2) Has a recent bullish divergence and\n3) RSI above the RSI moving average\n\n Or\n\nFor sell signals\n1)Price is below 21sma and\n2) Has recent bearish divergence and\n3) RSI is below the RSI moving average.\n\nThe RSI moving average trend filter settings are found under the section in this settings menu called RSI trend filter. This signal is designed for the 15 minute timeframe.\n\nSignals print gold triangle")
//=Select divergence indicators
//==================================================================================================================================
grp_DIVINDI = "Use divergences from indicators"
calcuo = input(defval = true, title = "UO", group=grp_DIVINDI)
calctsi = input(defval = true, title = "TSI", group=grp_DIVINDI)
calcufo = input(defval = true, title = "UFO", group=grp_DIVINDI, tooltip="This is a hybrid of the UO x MFI, the oscillator is calculated by taking an average of the two values.\n\UFO = (UO_Value + MFI_Value) / 2")
calcrsi = input(defval = true, title = "RSI", group=grp_DIVINDI)
calcmfi = input(defval = true, title = "MFI", group=grp_DIVINDI)
calccci = input(defval = false, title = "CCI", group=grp_DIVINDI)
calccdv = input(defval = false, title = "CDV", group=grp_DIVINDI)
calcstoc = input(defval = false, title = "Stochastic", group=grp_DIVINDI)
//=Real price line & real price close dots
//==================================================================================================================================
//Real price line and dot settings
grp_HA = "Real price for Heikin Ashi candles"
realclosedotscolor = input(color.new(color.aqua, 50), title="Real Price Close Dot Color", group=grp_HA)
showRealPriceLinelinecolor = input(color.new(color.aqua, 0), title="Real Price Line Color", group=grp_HA)
realpricewidth = input.int(1, options=[1, 2], title="Real Price Line Width", group=grp_HA)
real_price = ticker.new(prefix=syminfo.prefix, ticker=syminfo.ticker)
real_close = request.security(symbol=real_price, timeframe='', expression=close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
if(showRealPriceLine)
real_price_line = line.new(bar_index[1], real_close, bar_index, real_close, xloc.bar_index, extend.both, showRealPriceLinelinecolor, line.style_dotted, realpricewidth)
line.delete(real_price_line[1])
//Show real price close dots
plotshape(series=real_close, title="Real price close dots", location=location.absolute, color=realclosedotscolor, editable=false, style=shape.circle, size=size.auto, display=(showRealCloseDots ? display.all : display.none))
// =MTF Stoch
//==================================================================================================================================
grp_MTFSRSI = "MTF Stoch RSI"
smoothK = input.int(3, "K", minval=1, group=grp_MTFSRSI)
smoothD = input.int(3, "D", minval=1, group=grp_MTFSRSI)
lengthRSI = input.int(14, "RSI Length", minval=1, group=grp_MTFSRSI)
lengthStoch = input.int(14, "Stochastic Length", minval=1, group=grp_MTFSRSI)
rsi1 = ta.rsi(close, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
grp_CTFSRSI1 = "Show Current Timeframe OB/OS in Ribbon"
includeCurrentTFOBOS = input(true, title="Show Current Timeframe OB/OS Ribbon", group=grp_CTFSRSI1, tooltip="this will include in the ribbon indications where the Stoch RSI is overbought or oversold on the current timeframe")
CTF_1 = input.string("Chart", title="CTF", options=["Chart"], group=grp_CTFSRSI1, inline="tf1")
CTF_OSTHRESH_1 = input(20, title="", group=grp_CTFSRSI1, inline="tf1")
CTF_OBTHRESH_1 = input(80, title="", group=grp_CTFSRSI1, inline="tf1")
//Primary MTF Stoch RSI confluences
grp_MTFSRSI1 = "MTF Stoch RSI"
stochRSIRibbonPosition = input.string('Bottom', title="Stoch RSI Ribbon Position", options=['Top', 'Bottom'], group=grp_MTFSRSI1)
overboughtColor_1 = input.color(red, title="Stoch Overbought Color", group=grp_MTFSRSI1)
oversoldColor_1 = input.color(green, title="Stoch Oversold Color", group=grp_MTFSRSI1)
enableOBOS_1 = input(true, title="Show MTF Stoch RSI OB/OS in ribbon", group=grp_MTFSRSI1, tooltip="This will show a ribbon to indicate the MTF Stoch RSI overbought and oversold confuences")
useBgColorMTFStochOBOS_1 = input(false, title="Color Background where MTF Stoch RSI OB/OS", group=grp_MTFSRSI1, tooltip="his will color the background of the chart to indicate the MTF Stoch RSI overbought and oversold confuences")
useBarColorMTFStochOBOS_1= input(false, title="Color Candles where MTF Stoch RSI OB/OS", group=grp_MTFSRSI1, tooltip="his will color the candles on the chart to indicate the MTF Stoch RSI overbought and oversold confuences")
grp_MTFSRSI1_ = "Stoch RSI MTF [Timeframe] [OS level] [OB level]"
TF_1 = input.string("1", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1_, inline="mtf1")
TF_2 = input.string("5", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1_, inline="mtf2")
TF_3 = input.string("15", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1_, inline="mtf3")
MTF_OSTHRESH_1 = input(20, title="", group=grp_MTFSRSI1_, inline="mtf1")
MTF_OSTHRESH_2 = input(20, title="", group=grp_MTFSRSI1_, inline="mtf2")
MTF_OSTHRESH_3 = input(20, title="", group=grp_MTFSRSI1_, inline="mtf3")
MTF_OBTHRESH_1 = input(80, title="", group=grp_MTFSRSI1_, inline="mtf1")
MTF_OBTHRESH_2 = input(80, title="", group=grp_MTFSRSI1_, inline="mtf2")
MTF_OBTHRESH_3 = input(80, title="", group=grp_MTFSRSI1_, inline="mtf3")
MTF1 = request.security(syminfo.tickerid, TF_1 == "Chart" ? "" : TF_1, k, barmerge.gaps_off)
MTF2 = request.security(syminfo.tickerid, TF_2 == "Chart" ? "" : TF_2, k, barmerge.gaps_off)
MTF3 = request.security(syminfo.tickerid, TF_3 == "Chart" ? "" : TF_3, k, barmerge.gaps_off)
allMTFStochOB_1 = (MTF1 > MTF_OBTHRESH_1 and MTF2 > MTF_OBTHRESH_2 and MTF3 > MTF_OBTHRESH_3)
allMTFStochOS_1 = (MTF1 < MTF_OSTHRESH_1 and MTF2 < MTF_OSTHRESH_2 and MTF3 < MTF_OSTHRESH_3)
obColor_1 = (k > CTF_OBTHRESH_1+10 ? color.new(overboughtColor_1, 50) : enableOBOS_1 and k > CTF_OBTHRESH_1+10 ? color.new(overboughtColor_1, 70) : na)
osColor_1 = (k < CTF_OSTHRESH_1-10 ? color.new(oversoldColor_1, 50) : enableOBOS_1 and k < CTF_OSTHRESH_1 ? color.new(oversoldColor_1, 70) : na)
allOBColor_1 = (allMTFStochOB_1 ? overboughtColor_1 : na)
allOSColor_1 = (allMTFStochOS_1 ? oversoldColor_1 : na)
_stochRSIRibbonPosition = switch stochRSIRibbonPosition
"Top" => location.top
"Bottom" => location.bottom
plotchar(k, title="Current TF SRSI overbought", color=(includeCurrentTFOBOS ? obColor_1 : na), char="■", location=_stochRSIRibbonPosition)
plotchar(k, title="Current TF SRSI oversold", color=(includeCurrentTFOBOS ? osColor_1 : na), char="■", location=_stochRSIRibbonPosition)
plotchar(k, title="All overbought/oversold", color=(enableOBOS_1 and showMTFSignals and allMTFStochOB_1 ? allOBColor_1 : (enableOBOS_1 and showMTFSignals and allMTFStochOS_1 ? allOSColor_1 : na)), char="■", location=_stochRSIRibbonPosition)
// plotchar(k, title="3x TF all oversold", color=(enableOBOS_1 ? allOSColor_1 : na), char="■", location=_stochRSIRibbonPosition)
//bgcolor
bgcolor((useBgColorMTFStochOBOS_1 and allMTFStochOB_1 and showMTFSignals ? color.new(allOBColor_1, 90) : (useBgColorMTFStochOBOS_1 and allMTFStochOS_1 and showMTFSignals ? color.new(allOSColor_1, 90) : na)), title='Stoch RSI OB/OS background colour')
barcolor(useBarColorMTFStochOBOS_1 and allMTFStochOB_1 and showMTFSignals ? allOBColor_1 : (useBarColorMTFStochOBOS_1 and allMTFStochOS_1 and showMTFSignals ? allOSColor_1 : na))
// =MTF CCI
//==================================================================================================================================
grp_CCI = "MTF CCI settings"
ccisrc = input(hlc3, title="CCI Source", group=grp_CCI)
ccilen = input(20, title="CCI Length", group=grp_CCI)
cci_val = ta.cci(ccisrc, ccilen) // CCI
cciRibbonPosition = input.string('Top', title="CCI Ribbon Position", options=['Top', 'Bottom'], group=grp_CCI)
overboughtColorCCI = input(color.rgb(175, 49, 49), title="CCI Overbought Color", group=grp_CCI)
oversoldColorCCI = input(color.rgb(49, 117, 51), title="CCI Oversold Color", group=grp_CCI)
enableOBOSCCI = input(true, title="Enable MTF CCI OB/OS Ribbon", group=grp_CCI)
useBgColorMTFCCIOBOS = input(false, title="Color Background where MTF CCI OB/OS", group=grp_CCI, tooltip="his will color the background of the chart to indicate the MTF CCI overbought and oversold confuences")
useBarColorMTFCCIOBOS = input(false, title="Color Candles where MTF CCI OB/OS", group=grp_CCI, tooltip="his will color the candles on the chart to indicate the MTF CCI overbought and oversold confuences")
includeCurrentTFOBOSCCI = input(true, title="Show Current Timeframe OB/OS in Ribbon", group="Current timeframe [Timeframe] [OS level] [OB level]", tooltip="this will include in the ribbon indications where the CCI is overbought or oversold on the current timeframe")
CCICTF_1 = input.string("Chart", title="CTF", options=["Chart"], group="Current timeframe [Timeframe] [OS level] [OB level]", inline="tf1")
CCICTF_OSTHRESH_1 = input(-150, title="", group="Current timeframe [Timeframe] [OS level] [OB level]", inline="tf1")
CCICTF_OBTHRESH_1 = input(150, title="", group="Current timeframe [Timeframe] [OS level] [OB level]", inline="tf1")
//MTF CCI confluences
CCITF_1 = input.string("1", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf1")
CCITF_2 = input.string("5", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf2")
CCITF_3 = input.string("15", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf3")
CCIMTF_OSTHRESH_1 = input(-150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf1")
CCIMTF_OSTHRESH_2 = input(-150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf2")
CCIMTF_OSTHRESH_3 = input(-150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf3")
CCIMTF_OBTHRESH_1 = input(150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf1")
CCIMTF_OBTHRESH_2 = input(150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf2")
CCIMTF_OBTHRESH_3 = input(150, title="", group="CCI MTF confluences [Timeframe] [OS level] [OB level]", inline="mtf3")
CCIMTF1 = request.security(syminfo.tickerid, CCITF_1 == "Chart" ? "" : CCITF_1, cci_val, barmerge.gaps_off)
CCIMTF2 = request.security(syminfo.tickerid, CCITF_2 == "Chart" ? "" : CCITF_2, cci_val, barmerge.gaps_off)
CCIMTF3 = request.security(syminfo.tickerid, CCITF_3 == "Chart" ? "" : CCITF_3, cci_val, barmerge.gaps_off)
allMTFCCIOB = (CCIMTF1 > CCIMTF_OBTHRESH_1 and CCIMTF2 > CCIMTF_OBTHRESH_2 and CCIMTF3 > CCIMTF_OBTHRESH_3)
allMTFCCIOS = (CCIMTF1 < CCIMTF_OSTHRESH_1 and CCIMTF2 < CCIMTF_OSTHRESH_2 and CCIMTF3 < CCIMTF_OSTHRESH_3)
obColorCCI = (cci_val > CCICTF_OBTHRESH_1+20 ? color.new(overboughtColorCCI, 50) : cci_val > CCICTF_OBTHRESH_1 ? color.new(overboughtColorCCI, 70) : na)
osColorCCI = (cci_val < CCICTF_OSTHRESH_1-20 ? color.new(oversoldColorCCI, 50) : cci_val < CCICTF_OSTHRESH_1 ? color.new(oversoldColorCCI, 70) : na)
allOBColorCCI = (allMTFCCIOB ? overboughtColorCCI : na)
allOSColorCCI = (allMTFCCIOS ? oversoldColorCCI : na)
_cciRibbonPosition = switch cciRibbonPosition
"Top" => location.top
"Bottom" => location.bottom
plotchar(cci_val, title="Current TF overbought", color=(enableOBOSCCI and includeCurrentTFOBOSCCI ? obColorCCI : na), char="■", location=_cciRibbonPosition, size=size.auto)
plotchar(cci_val, title="Current TF oversold", color=(enableOBOSCCI and includeCurrentTFOBOSCCI ? osColorCCI : na), char="■", location=_cciRibbonPosition, size=size.auto)
plotchar(cci_val, title="All overbought/oversold", color=(enableOBOSCCI and showMTFSignals and allMTFCCIOB ? allOBColorCCI : (enableOBOSCCI and showMTFSignals and allMTFCCIOS ? allOSColorCCI : na)), char="■", location=_cciRibbonPosition, size=size.auto)
// plotchar(cci_val, title="All oversold", color=(enableOBOSCCI ? allOSColorCCI : na), char="■", location=_cciRibbonPosition, size=size.auto)
bgcolor((useBgColorMTFCCIOBOS and allMTFCCIOB and showMTFSignals ? color.new(allOBColorCCI, 80) : (useBgColorMTFCCIOBOS and allMTFCCIOS and showMTFSignals ? color.new(allOSColorCCI, 80) : na)), title='CCI OB/OS background colour')
barcolor(useBarColorMTFCCIOBOS and allMTFCCIOB and showMTFSignals ? allOBColorCCI : (useBarColorMTFCCIOBOS and allMTFCCIOS and showMTFSignals ? allOSColorCCI : na))
grp_CombiMTF = "Combi MTF signals"
showCombiMTF = input.bool(true, title="Show combi MTF CCI and Stoch RSI signals", group=grp_CombiMTF, tooltip="This will show where both the MTF CCI and MTF Stoch RSI overbought and oversold occur together")
showCombiMTFOBColor = input.color(color.new(red, 75), title="Combi MTF Overbought Color", group=grp_CombiMTF)
showCombiMTFOSColor = input.color(color.new(green, 75), title="Combi MTF Oversold Color", group=grp_CombiMTF)
//MTF CCI AND StochRSI BOTH overbought / oversold
bgcolor(showCombiMTF and allMTFCCIOB and allMTFStochOB_1 and showMTFSignals ? showCombiMTFOBColor : (showCombiMTF and allMTFCCIOS and allMTFStochOS_1 and showMTFSignals ? showCombiMTFOSColor : na), title="MTF CCI AND MTF StochRSI Both OB/OS")
//=Moving averages
//==================================================================================================================================
ma(length, type) =>
switch type
"SMA" => ta.sma(close, length)
"EMA" => ta.ema(close, length)
"SMMA (RMA)" => ta.rma(close, length)
"WMA" => ta.wma(close, length)
"VWMA" => ta.vwma(close, length)
"HULLMA" => ta.wma(2*ta.wma(close, length/2)-ta.wma(close, length), math.floor(math.sqrt(length)))
grp_MA = "Moving averages"
ma1color = input(color.new(color.orange, 40), title="", group=grp_MA, inline="1")
lenMA1 = input(144, title="", group=grp_MA, inline="1")
typeMA1 = input.string(title = "", defval = "EMA", options=["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA", "HULLMA"], group=grp_MA, inline="1")
showma1 = input(true, title="Enable", group=grp_MA, inline="1")
ma2color = input(color.new(color.white, 40), title="", group=grp_MA, inline="2")
lenMA2 = input(50, title="", group=grp_MA, inline="2")
typeMA2 = input.string(title = "", defval = "EMA", options=["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA", "HULLMA"], group=grp_MA, inline="2")
showma2 = input(false, title="Enable", group=grp_MA, inline="2")
ma3color = input(color.new(red, 40), title="", group=grp_MA, inline="3")
lenMA3 = input(21, title="", group=grp_MA, inline="3")
typeMA3 = input.string(title = "", defval = "EMA", options=["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA", "HULLMA"], group=grp_MA, inline="3")
showma3 = input(false, title="Enable", group=grp_MA, inline="3")
plot(showma1 and enableMA ? ma(lenMA1, typeMA1) : na, title="MA 1", color = ma1color, linewidth=1, display = display.pane)
plot(showma2 and enableMA ? ma(lenMA2, typeMA2) : na, title="MA 2", color = ma2color, linewidth=1, display = display.pane)
plot(showma3 and enableMA ? ma(lenMA3, typeMA3) : na, title="MA 3", color = ma3color, linewidth=1, display = display.pane)
//=VWAP Settings
//==================================================================================================================================
grp_VWAP = "Anchored VWAP Settings"
vwapColor = input.color(color.new(color.aqua, 0), title="", group=grp_VWAP, inline="vwap")
anchor = input.string("2 Day", title="", options=["1 Day", "2 Day", "Week", "Month"], group=grp_VWAP, inline="vwap")
src = input(hlc3, title="", group=grp_VWAP, inline="vwap")
stdevMult = input(1.0, title="", group=grp_VWAP, inline="vwapdev")
showVWAPBand= input(true, title="Show Deviation Band Multiplier", group=grp_VWAP, inline="vwapdev")
if barstate.islast and ta.cum(volume) == 0
runtime.error("No volume is provided by the data vendor.")
isNewPeriod = switch anchor
"1 Day" => timeframe.change("D")
"2 Day" => timeframe.change("2D")
"Week" => timeframe.change("W")
"Month" => timeframe.change("M")
=> false
if na(src[1])
isNewPeriod := true
float vwapValue = na
float upperBandValue1 = na
float lowerBandValue1 = na
if not (timeframe.isdwm) //Hide VWAP on charts 1D or Above
[_vwap, _stdevUpper, _] = ta.vwap(src, isNewPeriod, 1)
vwapValue := _vwap
stdevAbs = _stdevUpper - _vwap
upperBandValue1 := showVWAP ? (_vwap + stdevAbs * stdevMult) : na
lowerBandValue1 := showVWAP ? (_vwap - stdevAbs * stdevMult) : na
plot((showVWAP ? vwapValue : na), title="VWAP", color=vwapColor)
fill(plot(upperBandValue1, title="Upper Band #1", color=color.new(vwapColor, 70), display = showVWAPBand ? display.all : display.none), plot(lowerBandValue1, title="Lower Band #1", color=color.new(vwapColor, 70), display = showVWAPBand ? display.all : display.none), title="Bands Fill #1", color= color.new(vwapColor, 97), display = showVWAPBand ? display.all : display.none)
//=MTF MA settings
//==================================================================================================================================
grp_MTFMA = "MTF MA Settings"
MTFMALen = input.int(144, title="", minval=2, maxval=200, step=1, group=grp_MTFMA, inline="0")
MTFMAType = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HULLMA"], group=grp_MTFMA, inline="0")
realPriceTicker = ticker.new(prefix=syminfo.prefix, ticker=syminfo.ticker)
getTimeframe(timeframe) =>
switch timeframe
"1m" => "1"
"2m" => "2"
"3m" => "3"
"5m" => "5"
"10m" => "10"
"15m" => "15"
// MTF MA #1
tf1LineColor = input.color(color.new(color.orange, 40), title="", group=grp_MTFMA, inline='1')
tf1 = input.string("3m", title="", options=["1m", "2m", "3m", "5m", "10m", "15m"], group=grp_MTFMA, inline='1')
enableTF1 = input.bool(true, title='Show Level', group=grp_MTFMA, inline='1', tooltip="")
// MTF MA #2
tf2LineColor = input.color(color.new(color.orange, 40), title="", group=grp_MTFMA, inline='2')
tf2 = input.string("5m", title="", options=["1m", "2m", "3m", "5m", "10m", "15m"], group=grp_MTFMA, inline='2')
enableTF2 = input.bool(true, title='Show Level', group=grp_MTFMA, inline='2')
// MTF MA #3
tf3LineColor = input.color(color.new(color.orange, 40), title='', group=grp_MTFMA, inline='3')
tf3 = input.string("15m", title='', options=["1m", "2m", "3m", "5m", "10m", "15m"], group=grp_MTFMA, inline='3')
enableTF3 = input.bool(true, title='Show Level', group=grp_MTFMA, inline='3')
mtf1MA = request.security(symbol=realPriceTicker, timeframe=getTimeframe(tf1), expression=ma(MTFMALen, MTFMAType), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
mtf2MA = request.security(symbol=realPriceTicker, timeframe=getTimeframe(tf2), expression=ma(MTFMALen, MTFMAType), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
mtf3MA = request.security(symbol=realPriceTicker, timeframe=getTimeframe(tf3), expression=ma(MTFMALen, MTFMAType), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
mtfMATextColor = input.color(color.new(color.orange, 70), title="", group=grp_MTFMA, inline="4")
showTFLabel = input.bool(true, title='Show Timeframe Labels', group=grp_MTFMA, inline="4")
if (enableMTFMA and enableTF1)
mtf1MALine = line.new(x1=bar_index, x2=bar_index + 10, y1=mtf1MA, y2=mtf1MA, extend=extend.right, style=line.style_dotted, color=tf1LineColor)
line.delete(mtf1MALine[1])
if(showTFLabel)
mtf1MALabel = label.new(x=(bar_index + 20), y=mtf1MA, style=label.style_label_down, text=tf1, color=na, textcolor=mtfMATextColor)
label.delete(mtf1MALabel[1])
if(enableMTFMA and enableTF2)
mtf2MALine = line.new(x1=bar_index, x2=bar_index + 10, y1=mtf2MA, y2=mtf2MA, extend=extend.right, style=line.style_dotted, color=tf2LineColor)
line.delete(mtf2MALine[1])
if(showTFLabel)
mtf2MALabel = label.new(x=(bar_index + 20), y=mtf2MA, style=label.style_label_down, text=tf2, color=na, textcolor=mtfMATextColor)
label.delete(mtf2MALabel[1])
if(enableMTFMA and enableTF3)
mtf3MALine = line.new(x1=bar_index, x2=bar_index + 10, y1=mtf3MA, y2=mtf3MA, extend=extend.right, style=line.style_dotted, color=tf3LineColor)
line.delete(mtf3MALine[1])
if(showTFLabel)
mtf3MALabel = label.new(x=(bar_index + 20), y=mtf3MA, style=label.style_label_down, text=tf3, color=na, textcolor=mtfMATextColor)
label.delete(mtf3MALabel[1])
//=Range Filter settings
//==================================================================================================================================
grp_RF = "Range Filters"
//Range Filter #1 Settings
grp_RF1 = "Range Filter #1 settings"
rf1UpColor = input.color(color.new(#CCCCCC, 50), title="Range Filter 1 Bullish Color", group=grp_RF1)
rf1DownColor = input.color(color.new(color.blue, 50), title="Range Filter 1 Bearish Color", group=grp_RF1)
rf1LineWidth = input.int(1, minval=1, maxval=3, title="Range Filter 1 Line Width", group=grp_RF1)
src1 = input(defval=hl2, title="Source", group=grp_RF1)
per1 = input(defval=30, title="Sampling Period", group=grp_RF1)
mult1 = input(defval=2.6, title="Range Multiplier", group=grp_RF1)
//Range Filter #2 Settings
grp_RF2 = "Range Filter #2 settings"
rf2UpColor = input.color(color.new(#CCCCCC, 0), title="Range Filter 2 Bullish Color", group=grp_RF2)
rf2DownColor = input.color(color.new(color.blue, 0), title="Range Filter 2 Bearish Color", group=grp_RF2)
rf2LineWidth = input.int(2, minval=1, maxval=3, title="Range Filter 2 Line Width", group=grp_RF2)
src2 = input(defval=ohlc4, title="Source", group=grp_RF2)
per2 = input(defval=48, title="Sampling Period", group=grp_RF2)
mult2 = input(defval=3.4, title="Range Multiplier", group=grp_RF2)
// Smooth average
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng1 = smoothrng(src1, per1, mult1)
smrng2 = smoothrng(src2, per2, mult2)
// Range Filter calculation
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt1 = rngfilt(src1, smrng1)
filt2 = rngfilt(src2, smrng2)
//RF Filter direction
upward1 = 0.0
downward1 = 0.0
upward2 = 0.0
downward2 = 0.0
upward1 := filt1 > filt1[1] ? nz(upward1[1]) + 1 : filt1 < filt1[1] ? 0 : nz(upward1[1])
downward1 := filt1 < filt1[1] ? nz(downward1[1]) + 1 : filt1 > filt1[1] ? 0 : nz(downward1[1])
upward2 := filt2 > filt2[1] ? nz(upward2[1]) + 1 : filt2 < filt2[1] ? 0 : nz(upward2[1])
downward2 := filt2 < filt2[1] ? nz(downward2[1]) + 1 : filt2 > filt2[1] ? 0 : nz(downward2[1])
//RF Target bands
hband1 = filt1 + smrng1
lband1 = filt1 - smrng1
hband2 = filt2 + smrng2
lband2 = filt2 - smrng2
//RF Colors
filtcolor1 = upward1 > 0 ? rf1UpColor : rf1DownColor
filtcolor2 = upward2 > 0 ? rf2UpColor : rf2DownColor
filtplot1 = plot((showRangeFilters ? filt1 : na), color=filtcolor1, linewidth=rf1LineWidth, title="Range Filter #1", display=display.pane)
filtplot2 = plot((showRangeFilters ? filt2 : na), color=filtcolor2, linewidth=rf2LineWidth, title="Range Filter #2", display=display.pane)
// Break Outs
longCond = bool(na)
shortCond = bool(na)
longCond := src1 > filt1 and src1 > src1[1] and upward1 > 0 or
src1 > filt1 and src1 < src1[1] and upward1 > 0
shortCond := src1 < filt1 and src1 < src1[1] and downward1 > 0 or
src1 < filt1 and src1 > src1[1] and downward1 > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1
alertcondition(longCondition, title="Range Filter 1 Buy in RF+", message="Range Filter 1 Buy in RF+")
alertcondition(shortCondition, title="Range Filter 1 Sell in RF+", message="Range Filter 1 Sell in RF+")
//=Imported indicator code for divergence detection
//==================================================================================================================================
//UO code
grp_UO = "UO Settings"
length1 = input.int(7, minval=1, title = "Fast Length", group=grp_UO)
length2 = input.int(14, minval=1, title = "Middle Length", group=grp_UO)
length3 = input.int(28, minval=1, title = "Slow Length", group=grp_UO)
average(bp, tr_, length) => math.sum(bp, length) / math.sum(tr_, length)
high_ = math.max(high, close[1])
low_ = math.min(low, close[1])
bp = close - low_
tr_ = high_ - low_
avg7 = average(bp, tr_, length1)
avg14 = average(bp, tr_, length2)
avg28 = average(bp, tr_, length3)
ultimate_value = 100 * (4*avg7 + 2*avg14 + avg28)/7
//UO code end
//TSI
grp_TSI = "TSI settings"
long = input(title="Long Length", defval=6, group=grp_TSI)
short = input(title="Short Length", defval=13, group=grp_TSI)
tsisignal = input(title="Signal Length", defval=4, group=grp_TSI)
price = close[0]
double_smooth(src, long, short) =>
fist_smooth = ta.ema(src, long)
ta.ema(fist_smooth, short)
pc = ta.change(price)
double_smoothed_pc = double_smooth(pc, long, short)
double_smoothed_abs_pc=double_smooth(math.abs(pc), long, short)
tsi_val = (double_smoothed_pc / double_smoothed_abs_pc)
tsi_value = (double_smoothed_pc / double_smoothed_abs_pc)
lagline = int(ta.ema(tsi_value, tsisignal))
tsi_lagline_value = (ta.ema(tsi_value, tsisignal))
tsi_bands_crossed_up= (tsi_value > tsi_lagline_value) ? 1 : 0
//TSI code end
// Cumulative delta code
tw = high - math.max(open, close)
bw = math.min(open, close) - low
body = math.abs(close - open)
_rate(cond) =>
ret = 0.5 * (tw + bw + (cond ? 2 * body : 0)) / (tw + bw + body)
ret := nz(ret) == 0 ? 0.5 : ret
ret
deltaup = volume * _rate(open <= close)
deltadown = volume * _rate(open > close)
delta = close >= open ? deltaup : -deltadown
cdv = ta.cum(delta)
// End of Cumulative delta code
//=MFI length setting
mfilen = input(14, title="MFI Length", group="MFI settings")
//end of Imported indicator code
//=Trend filter
//==================================================================================================================================
rsiLengthInput = input.int(150, minval=1, title="RSI Length", group="RSI Trend Filter")
rsiSourceInput = input.source(close, "Source", group="RSI Trend Filter")
maLengthInput = input.int(35, title="MA Length", group="RSI Trend Filter")
//=Watermark
//==================================================================================================================================
textVPosition = input.string("top", "", options = ["top", "middle", "bottom"], group = "Watermark text", inline="w0")
showText = input(true, title="Show Text", group = "Watermark text", inline="w0")
s_title = input.string("small", "", options = ["small", "normal", "large", "huge", "auto"], group = "Watermark text", inline="w1")
c_title = input.color(color.new(color.gray, 0), "", group = "Watermark text", inline="w1")
title = input("RF+", "", group = "Watermark text", inline="w1")
s_subtitle = input.string("normal", "", options = ["small", "normal", "large", "huge", "auto"], group = "Watermark text", inline="w2")
c_subtitle = input(color.new(color.gray, 0), "", group = "Watermark text", inline="w2")
subtitle = input("Divergence Scalping System", "", group = "Watermark text", inline="w2")
symVPosition = input.string("bottom", "", options = ["top", "middle", "bottom"], group = "Watermark symbol", inline="w3")
showSymText = input(true, title="Show Symbol", group = "Watermark symbol", inline="w3")
symInfo = syminfo.ticker + " | " + timeframe.period + (timeframe.isminutes ? "M" : na)
date = str.tostring(dayofmonth(time_close)) + "/" + str.tostring(month(time_close)) + "/" + str.tostring(year(time_close))
s_symInfo = input.string("normal", "", options = ["small", "normal", "large", "huge", "auto"], group = "Watermark symbol", inline="w4")
c_symInfo = input(color.new(color.gray, 30), "", group = "Watermark symbol", inline="w4")
c_bg = color.new(color.blue, 100)
//text watermark creation
textWatermark = table.new(textVPosition + "_" + "center", 1, 3)
if showText == true and showWatermark
table.cell(textWatermark, 0, 0, title, 0, 0, c_title, "center", text_size = s_title, bgcolor = c_bg)
table.cell(textWatermark, 0, 1, subtitle, 0, 0, c_subtitle, "center", text_size = s_subtitle, bgcolor = c_bg)
//symbol info watermark creation
symWatermark = table.new(symVPosition + "_" + "center", 5, 5)
if showSymText == true and showWatermark
table.cell(symWatermark, 0, 1, symInfo, 0, 0, c_symInfo, "center", text_size = s_symInfo, bgcolor = c_bg)
//=Styles
//==================================================================================================================================
grp_STYLES = "Styles"
MTFTableColor = input.color(color.new(color.white, 100), title="Dashboard Color", group=grp_STYLES)
confirmLineColor = input.color(color.orange, title="Confirm Line Color", group=grp_STYLES)
reg_div_l_style_ = input.string(defval = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STYLES)
hid_div_l_style_ = input.string(defval = "Dotted", title = "Hdden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STYLES)
reg_div_l_width = input.int(defval = 2, title = "Regular Divergence Line Width", minval = 1, maxval = 5, group=grp_STYLES)
hid_div_l_width = input.int(defval = 2, title = "Hidden Divergence Line Width", minval = 1, maxval = 5, group=grp_STYLES)
pos_reg_div_col = input(defval = color.new(green, 40), title = "Bullish Regular Divergence", group=grp_STYLES)
neg_reg_div_col = input(defval = color.new(red, 40), title = "Bearish Regular Divergence", group=grp_STYLES)
pos_hid_div_col = input(defval = color.new(green, 40), title = "Bullish Hidden Divergence", group=grp_STYLES)
neg_hid_div_col = input(defval = color.new(red, 40), title = "Bearish Hidden Divergence", group=grp_STYLES)
pos_div_text_col = input(defval = color.new(color.white, 10), title = "Bullish Divergence Text Color", group=grp_STYLES)
neg_div_text_col = input(defval = color.new(color.white, 10), title = "Bearish Divergence Text Color", group=grp_STYLES)
//=Pivot point settings
//==================================================================================================================================
grp_PP = "Pivot point settings"
pp = input.int(defval = 12, title = "Pivot period", minval = 1, maxval = 50, group=grp_PP)
maxpp = input.int(defval = 5, title = "Maximum Pivot periods to check for divs", minval = 1, maxval = 100, group=grp_PP)
maxbars = input.int(defval = 100, title = "Maximum Bars to Check", minval = 1, maxval = 200, group=grp_PP)
source = input.string(defval = "Close", title = "Source for Pivot points", options = ["Close", "High/Low"], group=grp_PP)
prd = pp
//=Divergence logic
//==================================================================================================================================
// set line styles
var reg_div_l_style = reg_div_l_style_ == "Solid" ? line.style_solid :
reg_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
var hid_div_l_style = hid_div_l_style_ == "Solid" ? line.style_solid :
hid_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
// get indicators
uo = ultimate_value
tsi = tsi_value
rsi = ta.rsi(close, 14) // RSI
Mfi = ta.mfi(hlc3, mfilen) // Money Flow Index
ufo = (ultimate_value + Mfi) / 2 // UFO
cci = ta.cci(ccisrc, ccilen) // CCI
stk = ta.sma(ta.stoch(close, high, low, lengthStoch), smoothD) // Stoch
// keep indicators names and colors in arrays
var indicators_name = array.new_string(14)
var div_colors = array.new_color(4)
if barstate.isfirst
// names
array.set(indicators_name, 0, showindis == "Full" ? "UO" : "U")
array.set(indicators_name, 1, showindis == "Full" ? "TSI" : "T")
array.set(indicators_name, 2, showindis == "Full" ? "UFO" : "U")
array.set(indicators_name, 3, showindis == "Full" ? "RSI" : "R")
array.set(indicators_name, 4, showindis == "Full" ? "MFI" : "M")
array.set(indicators_name, 5, showindis == "Full" ? "CCI" : "C")
array.set(indicators_name, 6, showindis == "Full" ? "CDV" : "C")
array.set(indicators_name, 7, showindis == "Full" ? "Stoch" : "S")
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)
// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh((source == "Close" ? close : high), prd, prd)
float pl = ta.pivotlow((source == "Close" ? close : low), prd, prd)
plotshape(ph and showpivot, text = "", style = shape.circle, color = color.new(color.orange, 70), textcolor = color.new(#FFFFFF, 80), location = location.abovebar, offset = -prd, size=size.tiny)
plotshape(pl and showpivot, text = "", style = shape.circle, color = color.new(color.orange, 70), textcolor = color.new(#FFFFFF, 80), location = location.belowbar, offset = -prd, size=size.tiny)
// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 22
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
// add PHs to the array
if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)
// add PLs to the array
if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)
// functions to check Regular Divergences and Hidden Divergences
// function to check positive regular or negative hidden divergence
// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond)=>
divlen = 0
prsc = source == "Close" ? close : low
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src > src[1] or close > close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x))) or
(cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - close[len]) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// function to check negative regular or positive hidden divergence
// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond)=>
divlen = 0
prsc = source == "Close" ? close : high
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src < src[1] or close < close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x))) or
(cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// calculate 4 types of divergence if enabled in the options and return divergences in an array
calculate_divs(cond, indicator)=>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 1) : 0)
array.set(divs, 1, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 1) : 0)
array.set(divs, 2, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 2) : 0)
array.set(divs, 3, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 2) : 0)
divs
// array to keep all divergences
var all_divergences = array.new_int(44) // 11 indicators * 4 divergence = 44 elements
// set related array elements
array_set_divs(div_pointer, index)=>
for x = 0 to 3
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// set divergences array
array_set_divs(calculate_divs(calcuo, uo), 0)
array_set_divs(calculate_divs(calctsi, tsi), 1)
array_set_divs(calculate_divs(calcufo, ufo), 2)
array_set_divs(calculate_divs(calcrsi, rsi), 3)
array_set_divs(calculate_divs(calcmfi, Mfi), 4)
array_set_divs(calculate_divs(calccci, cci), 5)
array_set_divs(calculate_divs(calccdv, cdv), 6)
array_set_divs(calculate_divs(calcstoc, stk), 7)
// check minimum number of divergence, if less than showlimit then delete all divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1
total_div := total_div + math.round(math.sign(array.get(all_divergences, x)))
if total_div < showlimit
array.fill(all_divergences, 0)
// keep line in an array
var pos_div_lines = array.new_line(0)
var pos_div_confirm_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var neg_div_confirm_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines()=>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1
line.delete(array.get(pos_div_lines, j))
array.clear(pos_div_lines)
delete_old_pos_div_confirm_lines()=>
if array.size(pos_div_confirm_lines) > 0
for j = 0 to array.size(pos_div_confirm_lines) - 1
line.delete(array.get(pos_div_confirm_lines, j))
array.clear(pos_div_confirm_lines)
delete_old_neg_div_lines()=>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1
line.delete(array.get(neg_div_lines, j))
array.clear(neg_div_lines)
delete_old_neg_div_confirm_lines()=>
if array.size(neg_div_confirm_lines) > 0
for j = 0 to array.size(neg_div_confirm_lines) - 1
line.delete(array.get(neg_div_confirm_lines, j))
array.clear(neg_div_confirm_lines)
delete_old_pos_div_labels()=>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)
delete_old_neg_div_labels()=>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)
// delete last created lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n)=>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n)=>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false
// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
// draw divergences lines and labels
divergence_text_top = ""
divergence_text_bottom = ""
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option
for x = 0 to 10
div_type = -1
for y = 0 to 3
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if (y % 2) == 1
dnumdiv_top := dnumdiv_top + 1
top_label_col := array.get(div_colors, y)
if (y % 2) == 0
dnumdiv_bottom := dnumdiv_bottom + 1
bottom_label_col := array.get(div_colors, y)
if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = showlines ? line.new(x1 = bar_index - array.get(all_divergences, x * 4 + y),
y1 = (source == "Close" ? close[array.get(all_divergences, x * 4 + y)] :
(y % 2) == 0 ? low[array.get(all_divergences, x * 4 + y)] :
high[array.get(all_divergences, x * 4 + y)]),
x2 = bar_index - startpoint,
y2 = (source == "Close" ? close[startpoint] :
(y % 2) == 0 ? low[startpoint] :
high[startpoint]),
color = array.get(div_colors, y),
style = y < 2 ? reg_div_l_style : hid_div_l_style,
width = y < 2 ? reg_div_l_width : hid_div_l_width
)
: na
new_confirm_line = showlines ? line.new(x1 = bar_index - array.get(all_divergences, x * 4 + y),
y1 = (source == "Close" ? close[array.get(all_divergences, x * 4 + y)] :
(y % 2) == 0 ? low[array.get(all_divergences, x * 4 + y)] :
high[array.get(all_divergences, x * 4 + y)]),
x2 = bar_index - startpoint + confirmLineLen,
y2 = (source == "Close" ? close[array.get(all_divergences, x * 4 + y)] :
(y % 2) == 0 ? low[array.get(all_divergences, x * 4 + y)] :
high[array.get(all_divergences, x * 4 + y)]),
color = y < 2 and showConfirmlines ? confirmLineColor : na,
style = line.style_solid,
width = 1
)
: na
if (y % 2) == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
last_pos_div_lines := 0
if showlast
delete_old_pos_div_lines()
delete_old_pos_div_confirm_lines()
array.push(pos_div_lines, new_line)
array.push(pos_div_confirm_lines, new_confirm_line)
last_pos_div_lines := last_pos_div_lines + 1
remove_last_pos_divs := true
if (y % 2) == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
last_neg_div_lines := 0
if showlast
delete_old_neg_div_lines()
delete_old_neg_div_confirm_lines()
array.push(neg_div_lines, new_line)
array.push(neg_div_confirm_lines, new_confirm_line)
last_neg_div_lines := last_neg_div_lines + 1
remove_last_neg_divs := true
// set variables for alerts
if y == 0
pos_reg_div_detected := true
if y == 1
neg_reg_div_detected := true
if y == 2
pos_hid_div_detected := true
if y == 3
neg_hid_div_detected := true
// get text for labels
if div_type >= 0
divergence_text_top := divergence_text_top + ((div_type % 2) == 1 ? (showindis != "Don't Show" ? array.get(indicators_name, x) + "\n" : "") : "")
if div_type >= 0
divergence_text_bottom := divergence_text_bottom + ((div_type % 2) == 0 ? (showindis != "Don't Show" ? array.get(indicators_name, x) + "\n" : "") : "")
// draw labels
if showindis != "Don't Show" or shownum
if shownum and dnumdiv_top > 0
divergence_text_top := divergence_text_top + str.tostring(dnumdiv_top)
if shownum and dnumdiv_bottom > 0
divergence_text_bottom := divergence_text_bottom + str.tostring(dnumdiv_bottom)
if divergence_text_top != ""
if showlast
delete_old_neg_div_labels()
array.push(neg_div_labels,
label.new( x = bar_index,
y = math.max(high, high[1]),
text = divergence_text_top,
color = top_label_col,
textcolor = neg_div_text_col,
style = label.style_label_down,
size=size.tiny
))
if divergence_text_bottom != ""
if showlast
delete_old_pos_div_labels()
array.push(pos_div_labels,
label.new( x = bar_index,
y = math.min(low, low[1]),
text = divergence_text_bottom,
color = bottom_label_col,
textcolor = pos_div_text_col,
style = label.style_label_up,
size=size.tiny
))
alertcondition((pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]) or (neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]), title='Divergence Detected in RF+', message='Divergence Detected in RF+')
// //MTF Stoch RSI / MTF CCI alert when all overbought or oversold
alertcondition((allMTFStochOB_1 and not allMTFStochOB_1[1]) or (allMTFStochOS_1 and not allMTFStochOS_1[1]) or (allMTFCCIOB and not allMTFCCIOB[1]) or (allMTFCCIOS and not allMTFCCIOS[1]), title="MTF OB/OS on RF+", message="MTF OB/OS on RF+")
//=Confluences are met signals // see allconfluencesmet setting at top of file for details in tooltip
//==================================================================================================================================
var recentBarsWithPosDivConfluences = false
var recentBarsWithNegDivConfluences = false
recentBarsWithMTFOB = 0
for obi = 0 to 4
if allMTFStochOB_1[obi] or allMTFCCIOB[obi]
recentBarsWithMTFOB := recentBarsWithMTFOB + 1
break
recentBarsWithMTFOS = 0
for osi = 0 to 4
if allMTFStochOS_1[osi] or allMTFCCIOS[osi]
recentBarsWithMTFOS := recentBarsWithMTFOS + 1
break
noWickBull = (open == low)
noWickBear = (open == high)
pullbackWithBullishDivCondition = showpullbackdivergence and (upward1 and upward2) and (pos_hid_div_detected or pos_reg_div_detected) and (close < filt1 and close < filt2) ? 1.0 : 0.0
pullbackWithBearishDivCondition = showpullbackdivergence and (downward1 and downward2) and (neg_hid_div_detected or neg_reg_div_detected) and (close > filt1 and close > filt2) ? 1.0 : 0.0
//Pullbacks - trend continuation confleunce signal
plotchar(pullbackWithBullishDivCondition, char="◡", color=green, title="Pullback with Bullish div", location=location.belowbar, size=size.tiny, offset=0)
plotchar(pullbackWithBearishDivCondition, char="◠", color=red, title="Pullback with Bearish div", location=location.abovebar, size=size.tiny, offset=0)
alertcondition(pullbackWithBullishDivCondition or pullbackWithBearishDivCondition, title="Pullback with divergence in RF+", message="Pullback with divergence in RF+")
// =Dashboard table
//==================================================================================================================================
//Trend filter
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
trsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
trsiMA = ta.sma(rsi, maLengthInput)
//Stats
rangeFilterTrendingUp = upward1 and upward2 ? true : false
rangeFilterTrendingDown = downward1 and downward2 ? true : false
ema144TrendingUp = close > ta.ema(close, 144) ? true : false
priceAbove21SMA = close > ta.sma(close, 21) ? true : false
tsiBandsCrossingUp = tsi_bands_crossed_up ? true : false
mfiAbove50 = Mfi > 50 ? true : false
uoAbove50 = ultimate_value > 50 ? true : false
tsiAbove0 = tsi_value > 0 ? true : false
//Entry criteria
shortPullbackEntryCriteriaMet() =>
showpullbackdivergence and (downward1 and downward2) and (neg_hid_div_detected or neg_reg_div_detected) and (close > filt1 and close > filt2) ? true : false
longPullbackEntryCriteriaMet() =>
showpullbackdivergence and (upward1 and upward2) and (pos_hid_div_detected or pos_reg_div_detected) and (close < filt1 and close < filt2) ? true : false
shortDivEntryCriteriaMet() =>
showFilteredDivEntryCriteria and (neg_hid_div_detected or neg_reg_div_detected) and (close < filt1 and close < filt2) and not priceAbove21SMA and trsi < trsiMA ? true : false
longDivEntryCriteriaMet() =>
showFilteredDivEntryCriteria and (pos_hid_div_detected or pos_reg_div_detected) and (close > filt1 and close > filt2) and priceAbove21SMA and trsi > trsiMA ? true : false
recentBarsWithPosDiv = 0
for pdi = 0 to 4
if pos_hid_div_detected[pdi] or pos_reg_div_detected[pdi]
recentBarsWithPosDiv := recentBarsWithPosDiv + 1
break
recentBarsWithNegDiv = 0
for ndi = 0 to 4
if neg_hid_div_detected[ndi] or neg_reg_div_detected[ndi]
recentBarsWithNegDiv := recentBarsWithNegDiv + 1
break
plotchar(shortDivEntryCriteriaMet(), char="🢓", color=color.orange, title="short entry", location=location.abovebar, size=size.small, offset=0)
plotchar(longDivEntryCriteriaMet(), char="🢑", color=color.orange, title="long entry", location=location.belowbar, size=size.small, offset=0)
alertcondition(shortDivEntryCriteriaMet() or longDivEntryCriteriaMet(), title="Div filtered by 21sma & RSI MA in RF+", message="Div filtered by 21sma & RSI MA in RF+")
plotshape(MTFOBOSDivSignal and recentBarsWithMTFOB and recentBarsWithNegDiv and not (recentBarsWithMTFOB[1] and recentBarsWithNegDiv[1]), text = "", style = shape.labeldown, color = color.new(red, 70), textcolor = color.new(#FFFFFF, 50), location = location.abovebar, size=size.small)
plotshape(MTFOBOSDivSignal and recentBarsWithMTFOS and recentBarsWithPosDiv and not (recentBarsWithMTFOS[1] and recentBarsWithPosDiv[1]), text = "", style = shape.labelup, color = color.new(green, 70), textcolor = color.new(#FFFFFF, 50), location = location.belowbar, size=size.small)
alertcondition(MTFOBOSDivSignal and ((recentBarsWithMTFOB and recentBarsWithNegDiv and not (recentBarsWithMTFOB[1] and recentBarsWithNegDiv[1])) or (recentBarsWithMTFOS and recentBarsWithPosDiv) and not (recentBarsWithMTFOS[1] and recentBarsWithPosDiv[1])), title="MTF OB/OS + Div on RF+", message="MTF OB/OS + Div on RF+")
_position = switch dashboardPosition
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
=> position.bottom_right
_size = switch dashboardSize
"Mobile" => size.small
"Desktop" => size.normal
// We use `var` to only initialize the table on the first bar.
var table dashboard = table.new(_position, 4, 4, bgcolor = MTFTableColor, frame_width = 0, frame_color = na)
LabelColor = color.new(color.white, 70)
ValueColor = color.new(color.white, 20)
_CCIlabelColor(val, ob, os) =>
val > ob ? overboughtColorCCI : (val < os ? oversoldColorCCI : ValueColor)
_SRSIlabelColor(val, ob, os) =>
val > ob ? overboughtColor_1 : (val < os ? oversoldColor_1 : ValueColor)
// We call functions like `ta.atr()` outside the `if` block so it executes on each bar.
if barstate.islast and showDashboard
// We only populate the table on the last bar.
table.cell(dashboard, 0, 0, text="CCI", text_color=LabelColor, text_halign=text.align_left, text_size=size.small, width=2)
table.cell(dashboard, 0, 1, text=CCITF_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny)
table.cell(dashboard, 0, 2, text=CCITF_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny)
table.cell(dashboard, 0, 3, text=CCITF_3+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny)
table.cell(dashboard, 1, 0, text="", width=3, text_color=LabelColor, text_halign=text.align_left, text_size=size.small)
table.cell(dashboard, 1, 1, text=str.tostring(math.round(CCIMTF1, 0)) , text_color=_CCIlabelColor(CCIMTF1, CCIMTF_OBTHRESH_1, CCIMTF_OSTHRESH_1), text_halign=text.align_right, text_size=_size)
table.cell(dashboard, 1, 2, text=str.tostring(math.round(CCIMTF2, 0)) , text_color=_CCIlabelColor(CCIMTF2, CCIMTF_OBTHRESH_2, CCIMTF_OSTHRESH_2), text_halign=text.align_right, text_size=_size)
table.cell(dashboard, 1, 3, text=str.tostring(math.round(CCIMTF3, 0)), text_color=_CCIlabelColor(CCIMTF3, CCIMTF_OBTHRESH_3, CCIMTF_OSTHRESH_3), text_halign=text.align_right, text_size=_size)
table.cell(dashboard, 2, 0, text="STOCH", text_color=LabelColor, text_halign=text.align_left, text_size=size.small, width=2)
table.cell(dashboard, 2, 1, text=TF_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny)
table.cell(dashboard, 2, 2, text=TF_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny)
table.cell(dashboard, 2, 3, text=TF_3+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny)
table.cell(dashboard, 3, 0, text="", width=3, text_color=LabelColor, text_halign=text.align_left, text_size=size.small)
table.cell(dashboard, 3, 1, text=str.tostring(math.round(MTF1, 0)) , text_color=_SRSIlabelColor(MTF1, MTF_OBTHRESH_1, MTF_OSTHRESH_1), text_halign=text.align_right, text_size=_size)
table.cell(dashboard, 3, 2, text=str.tostring(math.round(MTF2, 0)) , text_color=_SRSIlabelColor(MTF2, MTF_OBTHRESH_2, MTF_OSTHRESH_2), text_halign=text.align_right, text_size=_size)
table.cell(dashboard, 3, 3, text=str.tostring(math.round(MTF3, 0)) , text_color=_SRSIlabelColor(MTF3, MTF_OBTHRESH_3, MTF_OSTHRESH_3), text_halign=text.align_right, text_size=_size)
plot(bar_index, title="bar index", display=display.data_window)
// grp_STRAT = "Strategy settings"
// timeInput = input.time(timestamp("1 Nov 2022 00:00 +0000"), title="Start date", group=grp_STRAT)
// tpInPips = input.int(220, title="TP (in pips)", group=grp_STRAT)
// slInPips = input.int(20, title="SL (in pips)", group=grp_STRAT)
// timePeriod = time >= timeInput
// longSignal = MTFOBOSDivSignal and (recentBarsWithMTFOS and recentBarsWithPosDiv) and tsi_bands_crossed_up and longCondition
// shortSignal = MTFOBOSDivSignal and (recentBarsWithMTFOB and recentBarsWithNegDiv) and not tsi_bands_crossed_up and shortCondition
// // longSignal = ta.crossunder(vwapValue, close)
// // shortSignal = ta.crossover(vwapValue, close)
// if(longSignal and timePeriod)
// strategy.entry("Long", strategy.long)
// strategy.exit("Exit long", "Long", loss=slInPips, profit=tpInPips)
// if(shortSignal and timePeriod)
// strategy.entry("Short", strategy.short)
// strategy.exit("Exit short", "Short", loss=slInPips, profit=tpInPips) |
sohail Anjum EMA buy sell | https://www.tradingview.com/script/35BKChlR-sohail-Anjum-EMA-buy-sell/ | specialabbasi | https://www.tradingview.com/u/specialabbasi/ | 68 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0
//@version=5
indicator('sohail Anjum EMA buy sell', shorttitle = 'SA Ema', overlay=true)
fema = input(12, title='12 Ema')
sema = input(26, title='26 Ema')
fastEma = ta.ema(close, fema)
slowEma = ta.ema(close, sema)
ema200 = ta.ema(close, 200)
plot(fastEma, color=color.new(color.green, 0),linewidth=2)
plot(slowEma, color=color.new(color.red, 0),linewidth=2)
plot(ema200, color=color.new(color.yellow, 22),linewidth=3)
//rsi
rsivalue = ta.rsi(close, 14)
Buy=ta.crossover(fastEma, slowEma) and (rsivalue > 50)
Sell=ta.crossunder(fastEma, slowEma) and (rsivalue < 35) //and (close < ema200) and (rsivalue < 35)
plotshape(Buy, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), size=size.small)
plotshape(Sell, title='Sell', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), size=size.small)
alertcondition(Buy, 'ema Long', 'ema Long')
alertcondition(Sell, 'ema Short', 'ema Short') |
MFI + Realtime Divergences | https://www.tradingview.com/script/us72MGfI-MFI-Realtime-Divergences/ | tvenn | https://www.tradingview.com/u/tvenn/ | 176 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tvenn
//@version=5
indicator("MFI + Realtime Divergences", shorttitle="MFI+", overlay=false, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400, precision=3)
pulldatafromtimeframe = input.string("Chart", title="Select alternate timeframe in mins", options=["Chart", "1", "2", "3", "4", "5", "10", "15", "30", "45", "60", "120", "240"])
green = color.new(#95BD5F, 30)
red = color.new(#EA1889, 30)
transp = color.new(#FFFFFF, 100)
//MFI
grp_MFIS = "MFI Settings"
mfilength1 = input(14, title="MFI Length", group=grp_MFIS)
mfisrc = input(hlc3, title="MFI Source", group=grp_MFIS)
mfi = ta.mfi(mfisrc, mfilength1)
//MFI end
mfi_raw = mfi
//Divergence Settings
grp_DivS = "Divergence Settings"
showlines = input(defval = true, title = "Show Divergence Lines", group=grp_DivS)
showlast = input(defval = true, title = "Show Only Last Divergence", group=grp_DivS)
dontconfirm = input(defval = true, title = "Don't Wait for Confirmation", group=grp_DivS)
//Detail
grp_Detail = "Details"
showBands = input(false, title="Range bands", group=grp_Detail, inline="0")
obosHighlightEnabled= input.bool(false, title="Highlight overbought & oversold", group=grp_Detail, inline="1")
backgroundSignalOn = input(false, title="Centerline cross background color", group=grp_Detail, tooltip="This will colour the background according to whether the RSI is above or below the 50 level.", inline="2")
oscSignalOn = input(false, title="Centerline cross oscillator color", group=grp_Detail, tooltip="This will colour the oscillator according to whether the RSI is above or below the 50 level.", inline="3")
fadeOutOsc = input(false, title="Fade out oscillator", group=grp_Detail, tooltip="Fade out the oscillator leaving only the most recent periods prominent for a clearer chart.")
flipOsc = input.bool(false, title="Flip Oscillator", group=grp_Detail, tooltip="This will flip the oscillator upside down. The purpose is for use with the flip chart feature of Tradingview (Alt+i), which does not also flip the oscillator. This may help those with a particular long/short bias to see the other side of things. Divergence lines will not be drawn.")
distanceTransparency = (bar_index > (last_bar_index - 30) ? 10 : (bar_index > last_bar_index - 60 ? 20 : (bar_index > last_bar_index - 80 ? 30 : (bar_index > last_bar_index - 100 ? 40 : (bar_index > last_bar_index - 120 ? 50 : (bar_index > last_bar_index - 140 ? 60 : (bar_index > last_bar_index - 160 ? 70 : 80)))))))
//Plot oscillator
osc_raw = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, mfi_raw, barmerge.gaps_off)
osc = (flipOsc ? 100-osc_raw : osc_raw)
oscColor = ((obosHighlightEnabled and osc > 80) ? red : ((obosHighlightEnabled and osc < 20) ? red : (oscSignalOn and osc > 50 ? green : (oscSignalOn and osc < 50 ? red : (fadeOutOsc ? color.new(color.blue, distanceTransparency) : color.blue)))))
plot(osc, color=oscColor, linewidth=2, title="MFI")
//MTF confluences
//===============================================================================================================================
grp_SRSI = "MTF Stoch RSI settings for ribbon"
ribbonPos = input.string(title="MTF Stoch ribbon position", defval='Top', options=['Top', 'Bottom', 'Absolute'], group=grp_SRSI)
smoothK = input.int(3, "K line", minval=1, group=grp_SRSI)
smoothD = input.int(3, "D line", minval=1, group=grp_SRSI)
lengthRSI = input.int(14, "RSI Length", minval=1, group=grp_SRSI)
lengthStoch = input.int(14, "Stochastic Length", minval=1, group=grp_SRSI)
src = close
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
k1 = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, k, barmerge.gaps_off)
d1 = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, d, barmerge.gaps_off)
//Bands
bandColor = showBands ? color.new(#777777, 0) : color.new(#777777, 100)
band1 = hline(80, color=bandColor, linestyle=hline.style_dotted, linewidth=1)
band2 = hline(50, color=color.new(#777777, 0), linestyle=hline.style_dotted, linewidth=1)
band0 = hline(20, color=bandColor, linestyle=hline.style_dotted, linewidth=1)
//Primary timeframes confluences
grp_MTFSRSI1 = "MTF Stoch RSI #1 for ribbon"
overboughtColor_1 = input.color(color.new(red, 20), title="MTF #1 OB color", group=grp_MTFSRSI1)
oversoldColor_1 = input.color(color.new(green, 20), title="MTF #1 OS color", group=grp_MTFSRSI1)
useBgColorMTFStochOBOS_1 = input(false, title="Color ribbon where MTF #1 OB/OS", group=grp_MTFSRSI1, tooltip="This will color the top of the panel to indicate the overbought / oversold state of the Stochastic RSI on all 3x selected timeframes together at the same time. These multi-timeframe overbought and oversold signals can be used as a confluence for regular divergence entries, indicating possible nearterm price reversal.")
grp_MTFSRSI1Conf = "Stoch RSI MTF confluences 1 [Timeframe] [OS level] [OB level]"
MTF_1_1 = input.string("1", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1Conf, inline="mtf1")
MTF_2_1 = input.string("5", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1Conf, inline="mtf2")
MTF_3_1 = input.string("15", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1Conf, inline="mtf3")
MTF_OSTHRESH_1_1 = input(20, title="", group=grp_MTFSRSI1Conf, inline="mtf1")
MTF_OSTHRESH_2_1 = input(20, title="", group=grp_MTFSRSI1Conf, inline="mtf2")
MTF_OSTHRESH_3_1 = input(20, title="", group=grp_MTFSRSI1Conf, inline="mtf3")
MTF_OBTHRESH_1_1 = input(80, title="", group=grp_MTFSRSI1Conf, inline="mtf1")
MTF_OBTHRESH_2_1 = input(80, title="", group=grp_MTFSRSI1Conf, inline="mtf2")
MTF_OBTHRESH_3_1 = input(80, title="", group=grp_MTFSRSI1Conf, inline="mtf3")
MTF1_1 = request.security(syminfo.tickerid, MTF_1_1 == "Chart" ? "" : MTF_1_1, k, barmerge.gaps_off)
MTF2_1 = request.security(syminfo.tickerid, MTF_2_1 == "Chart" ? "" : MTF_2_1, k, barmerge.gaps_off)
MTF3_1 = request.security(syminfo.tickerid, MTF_3_1 == "Chart" ? "" : MTF_3_1, k, barmerge.gaps_off)
allMTFStochOB_1 = (MTF1_1 > MTF_OBTHRESH_1_1 and MTF2_1 > MTF_OBTHRESH_2_1 and MTF3_1 > MTF_OBTHRESH_3_1)
allMTFStochOS_1 = (MTF1_1 < MTF_OSTHRESH_1_1 and MTF2_1 < MTF_OSTHRESH_2_1 and MTF3_1 < MTF_OSTHRESH_3_1)
obColor_1 = (k > 80 ? overboughtColor_1 : transp)
osColor_1 = (k < 20 ? oversoldColor_1 : transp)
allOBColor_1 = (allMTFStochOB_1 ? overboughtColor_1 : transp)
allOSColor_1 = (allMTFStochOS_1 ? oversoldColor_1 : transp)
//Secondary timeframes confluences
grp_MTFSRSI2 = "MTF Stoch RSI #2 for ribbon"
overboughtColor_2 = input.color(color.new(color.red, 50), title="MTF #2 OB color", group=grp_MTFSRSI2)
oversoldColor_2 = input.color(color.new(color.green, 50), title="MTF #2 OS color", group=grp_MTFSRSI2)
useBgColorMTFStochOBOS_2 = input(false, title="Color ribbon where MTF #2 OB/OS", group=grp_MTFSRSI2, tooltip="This will colour the background of the chart to indicate the overbought / oversold state of the Stochastic RSI on all 3x selected timeframes together at the same time. These multi-timeframe overbought and oversold signals can be used as a confluence for entries.")
grp_MTFSRSI2Conf = "Stoch RSI MTF confluences 2 [Timeframe] [OS level] [OB level]"
MTF_1_2 = input.string("15", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2Conf, inline="mtf1")
MTF_2_2 = input.string("30", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2Conf, inline="mtf2")
MTF_3_2 = input.string("60", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2Conf, inline="mtf3")
MTF_OSTHRESH_1_2 = input(20, title="", group=grp_MTFSRSI2Conf, inline="mtf1")
MTF_OSTHRESH_2_2 = input(20, title="", group=grp_MTFSRSI2Conf, inline="mtf2")
MTF_OSTHRESH_3_2 = input(20, title="", group=grp_MTFSRSI2Conf, inline="mtf3")
MTF_OBTHRESH_1_2 = input(80, title="", group=grp_MTFSRSI2Conf, inline="mtf1")
MTF_OBTHRESH_2_2 = input(80, title="", group=grp_MTFSRSI2Conf, inline="mtf2")
MTF_OBTHRESH_3_2 = input(80, title="", group=grp_MTFSRSI2Conf, inline="mtf3")
MTF1_2 = request.security(syminfo.tickerid, MTF_1_2 == "Chart" ? "" : MTF_1_2, k, barmerge.gaps_off)
MTF2_2 = request.security(syminfo.tickerid, MTF_2_2 == "Chart" ? "" : MTF_2_2, k, barmerge.gaps_off)
MTF3_2 = request.security(syminfo.tickerid, MTF_3_2 == "Chart" ? "" : MTF_3_2, k, barmerge.gaps_off)
allMTFStochOB_2 = (MTF1_2 > MTF_OBTHRESH_1_2 and MTF2_2 > MTF_OBTHRESH_2_2 and MTF3_2 > MTF_OBTHRESH_3_2)
allMTFStochOS_2 = (MTF1_2 < MTF_OSTHRESH_1_2 and MTF2_2 < MTF_OSTHRESH_2_2 and MTF3_2 < MTF_OSTHRESH_3_2)
obColor_2 = (k > 80 ? overboughtColor_2 : transp)
osColor_2 = (k < 20 ? oversoldColor_2 : transp)
allOBColor_2 = (allMTFStochOB_2 ? overboughtColor_2 : transp)
allOSColor_2 = (allMTFStochOS_2 ? oversoldColor_2 : transp)
_ribbonLocation = switch ribbonPos
"Absolute" => location.absolute
"Top" => location.top
"Bottom" => location.bottom
//MTF signal ribbon
plotshape(useBgColorMTFStochOBOS_1 and allMTFStochOB_1, title="OB/OS", location=_ribbonLocation, color=allOBColor_1, style=shape.circle, size=size.auto)
plotshape(useBgColorMTFStochOBOS_1 and allMTFStochOS_1, title="OB/OS", location=_ribbonLocation, color=allOSColor_1, style=shape.circle, size=size.auto)
plotshape(useBgColorMTFStochOBOS_2 and allMTFStochOB_2, title="OB/OS", location=_ribbonLocation, color=allOBColor_2, style=shape.circle, size=size.auto)
plotshape(useBgColorMTFStochOBOS_2 and allMTFStochOS_2, title="OB/OS", location=_ribbonLocation, color=allOSColor_2, style=shape.circle, size=size.auto)
//background fill options
fill(band0, band1, backgroundSignalOn and osc > 50 ? red : backgroundSignalOn and osc < 50 ? green : color.new(#AAAAAA, 100), editable=1)
//Pivot settings
grp_PPS = "Pivot Point Settings"
pp = input.int(defval = 12, title = "Pivot period", minval = 1, maxval = 50, group=grp_PPS)
maxpp = input.int(defval = 5, title = "Maximum Pivot periods to check for divs", minval = 1, maxval = 100, group=grp_PPS)
maxbars = input.int(defval = 100, title = "Maximum Bars to Check", minval = 1, maxval = 300, group=grp_PPS)
source = "Close"
searchdiv = input.string(defval = "Regular/Hidden", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group=grp_DivS)
//Update Pivot Period based on Timeframe logic
enableAutoAdjustPivot = input(true, title="Auto adjust Pivot period for below timeframes", group=grp_PPS, tooltip="This will update the 'Pivot Period' based upon the values selected below when you switch to that chart timeframe.")
TF1 = input.string("5", title="On", inline="1", options=["1", "2", "3", "5", "15", "30", "45", "60", "120", "240"], group=grp_PPS)
TF2 = input.string("15", title="On", inline="2", options=["1", "2", "3", "5", "15", "30", "45", "60", "120", "240"], group=grp_PPS)
TF3 = input.string("60", title="On", inline="3", options=["1", "2", "3", "5", "15", "30", "45", "60", "120", "240"], group=grp_PPS)
TF4 = input.string("240", title="On", inline="4", options=["1", "2", "3", "5", "15", "30", "45", "60", "120", "240"], group=grp_PPS)
TFP1 = input(12, title="min chart use Pivot", inline="1", group=grp_PPS)
TFP2 = input(7, title="min chart use Pivot", inline="2", group=grp_PPS)
TFP3 = input(5, title="min chart use Pivot", inline="3", group=grp_PPS)
TFP4 = input(1, title="min chart use Pivot", inline="4", group=grp_PPS)
int usePivot = na
for x = 0 to 3 - 1
if timeframe.period == str.tostring(TF1) and enableAutoAdjustPivot
usePivot:= int(TFP1)
else if timeframe.period == str.tostring(TF2) and enableAutoAdjustPivot
usePivot:= int(TFP2)
else if timeframe.period == str.tostring(TF3) and enableAutoAdjustPivot
usePivot:= int(TFP3)
else if timeframe.period == str.tostring(TF4) and enableAutoAdjustPivot
usePivot:= int(TFP4)
else
usePivot:= pp
prd = usePivot
//Styles
grp_STY = "Styles"
pos_reg_div_col = input(defval = green, title = "Positive Regular Divergence", group=grp_STY)
neg_reg_div_col = input(defval = red, title = "Negative Regular Divergence", group=grp_STY)
pos_hid_div_col = input(defval = green, title = "Positive Hidden Divergence", group=grp_STY)
neg_hid_div_col = input(defval = red, title = "Negative Hidden Divergence", group=grp_STY)
reg_div_l_style_= input.string(defval = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STY)
hid_div_l_style_= input.string(defval = "Dotted", title = "Hdden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STY)
reg_div_l_width = input.int(defval = 2, title = "Regular Divergence Line Width", minval = 1, maxval = 2, group=grp_STY)
hid_div_l_width = input.int(defval = 2, title = "Hidden Divergence Line Width", minval = 1, maxval = 2, group=grp_STY)
// set line styles
var reg_div_l_style = reg_div_l_style_ == "Solid" ? line.style_solid :
reg_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
var hid_div_l_style = hid_div_l_style_ == "Solid" ? line.style_solid :
hid_div_l_style_ == "Dashed" ? line.style_dashed :
line.style_dotted
// get indicators
uo = osc
// keep indicator colors in arrays
var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)
// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh(close, prd, prd)
float pl = ta.pivotlow(close, prd, prd)
// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
// add PHs to the array
if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)
// add PLs to the array
if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)
// functions to check Regular Divergences and Hidden Divergences
// function to check positive regular or negative hidden divergence
// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond)=>
divlen = 0
prsc = close
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src > src[1] or close > close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x))) or
(cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - close[len]) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// function to check negative regular or positive hidden divergence
// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond)=>
divlen = 0
prsc = close
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src < src[1] or close < close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x))) or
(cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// calculate 4 types of divergence if enabled in the options and return divergences in an array
calculate_divs(cond, indicator)=>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 1) : 0)
array.set(divs, 1, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 1) : 0)
array.set(divs, 2, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 2) : 0)
array.set(divs, 3, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 2) : 0)
divs
// array to keep all divergences
var all_divergences = array.new_int(4) // 1 indicator * 4 divergence = 4 elements
// set related array elements
array_set_divs(div_pointer, index)=>
for x = 0 to 3
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// set divergences array
array_set_divs(calculate_divs(true, uo), 0)
// keep line in an array
var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines()=>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1
line.delete(array.get(pos_div_lines, j))
array.clear(pos_div_lines)
delete_old_neg_div_lines()=>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1
line.delete(array.get(neg_div_lines, j))
array.clear(neg_div_lines)
delete_old_pos_div_labels()=>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)
delete_old_neg_div_labels()=>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)
// delete last creted lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n)=>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n)=>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false
// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
// draw divergences lines and labels
divergence_text_top = ""
divergence_text_bottom = ""
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option
for x = 0 to 0
div_type = -1
for y = 0 to 3
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if (y % 2) == 1
dnumdiv_top := dnumdiv_top + 1
top_label_col := array.get(div_colors, y)
if (y % 2) == 0
dnumdiv_bottom := dnumdiv_bottom + 1
bottom_label_col := array.get(div_colors, y)
if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = (showlines and not flipOsc) ? line.new(x1 = bar_index - array.get(all_divergences, x * 4 + y),
y1 = (source == "Close" ? uo[array.get(all_divergences, x * 4 + y)] :
(y % 2) == 0 ? low[array.get(all_divergences, x * 4 + y)] :
high[array.get(all_divergences, x * 4 + y)]),
x2 = bar_index - startpoint,
y2 = (source == "Close" ? uo[startpoint] :
(y % 2) == 0 ? low[startpoint] :
high[startpoint]),
color = array.get(div_colors, y),
style = y < 2 ? reg_div_l_style : hid_div_l_style,
width = y < 2 ? reg_div_l_width : hid_div_l_width
)
: na
if (y % 2) == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
last_pos_div_lines := 0
if showlast
delete_old_pos_div_lines()
array.push(pos_div_lines, new_line)
last_pos_div_lines := last_pos_div_lines + 1
remove_last_pos_divs := true
if (y % 2) == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
last_neg_div_lines := 0
if showlast
delete_old_neg_div_lines()
array.push(neg_div_lines, new_line)
last_neg_div_lines := last_neg_div_lines + 1
remove_last_neg_divs := true
// set variables for alerts
if y == 0
pos_reg_div_detected := true
if y == 1
neg_reg_div_detected := true
if y == 2
pos_hid_div_detected := true
if y == 3
neg_hid_div_detected := true
alertcondition(pos_reg_div_detected and not pos_reg_div_detected[1], title='Regular Bullish Divergence in MFI', message='Regular Bullish Divergence in MFI')
alertcondition(neg_reg_div_detected and not neg_reg_div_detected[1], title='Regular Bearish Divergence in MFI', message='Regular Bearish Divergence in MFI')
alertcondition(pos_hid_div_detected and not pos_hid_div_detected[1], title='Hidden Bullish Divergence in MFI', message='Hidden Bullish Divergence in MFI')
alertcondition(neg_hid_div_detected and not neg_hid_div_detected[1], title='Hidden Bearish Divergence in MFI', message='Hidden Bearish Divergence in MFI')
alertcondition((pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]), title='Bullish Divergence Detected in MFI', message='Bullish Divergence Detected in MFI')
alertcondition((neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]), title='Bearish Divergence Detected in MFI', message='Bearish Divergence Detected in MFI')
alertcondition((pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]) and (neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]), title='Divergence Detected in MFI', message='Divergence Detected in MFI')
//Oscillator label
var table isFlippedLabel = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.black, 100), frame_width = 0, frame_color = color.new(#000000, 100))
if barstate.islast and flipOsc
// We only populate the table on the last bar.
table.cell(isFlippedLabel, 0, 0, text="Flipped", text_color=color.gray, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) |
Smoothed RSI w/ VWAP & Moving Average | https://www.tradingview.com/script/AnavLcea-Smoothed-RSI-w-VWAP-Moving-Average/ | DDMyke | https://www.tradingview.com/u/DDMyke/ | 85 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DDMyke
//@version=5
indicator(title="Smoothed RSI w/ VWAP & Moving Average", shorttitle="RSIv", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
showRSI = input.bool(true, 'RSI', inline='rv', group="RSI Settings")
showRSIvwap = input.bool(true, 'VWAP', inline='rv', group="RSI Settings")
showbarcolor = input.bool(false, 'Barcolor', inline='rv', group="RSI Settings")
rsiLengthInput = input.int(14, minval=1, title="Length", group="RSI Settings")
rsiSmoothing = input.int(2,'smoothing', group="RSI Settings")
rsiWidth = input.int(1, 'Width', group="RSI Settings")
showMA = input.bool(true, 'Moving Average', group="MA Settings")
maTypeInput = input.string("WMA", title="Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA", "VWAP"], group="MA Settings")
maLengthInput = input.int(34, title="Length", group="MA Settings")
maWidth = input.int(1, 'Width', group="MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, step=0.25, title="BB StdDev", group="MA Settings")
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))
smoorsi = ta.rma(rsi,rsiSmoothing)
ma(smoorsi, maLengthInput, maTypeInput) =>
switch maTypeInput
"SMA" => ta.sma(smoorsi, maLengthInput)
"Bollinger Bands" => ta.sma(smoorsi, maLengthInput)
"EMA" => ta.ema(smoorsi, maLengthInput)
"SMMA (RMA)" => ta.rma(smoorsi, maLengthInput)
"WMA" => ta.wma(smoorsi, maLengthInput)
"VWMA" => ta.vwma(smoorsi, maLengthInput)
"VWAP" => ta.vwap(smoorsi)
rsiMA = ma(smoorsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"
//-------------------------------------------------------------- VWAP
RSIvwap = ta.vwap(smoorsi)
//-------------------------------------------------------------- Plots
StrongBull = smoorsi > 55 and smoorsi > rsiMA and smoorsi > RSIvwap
Bullish = smoorsi > 55 and smoorsi < rsiMA and smoorsi > RSIvwap
StrongBear = smoorsi < 45 and smoorsi < rsiMA and smoorsi < RSIvwap
Bearish = smoorsi > 45 and smoorsi < rsiMA and smoorsi < RSIvwap
Neutral = smoorsi > 45 or smoorsi < 55
colorchange = StrongBull ? color.new(#00ff00,0) : Bullish ? color.new(#1b5e20,0) : Bearish ? color.new(#801922,0) : StrongBear ? color.new(#ff0000,0) : Neutral ? color.new(#ffffff,0) : na
plot(showRSI ? smoorsi : na, "Smoothed RSI", color=colorchange, linewidth=rsiWidth)
plot(showRSIvwap ? RSIvwap : na, "RSI-based VWAP", color=color.new(#5b9cf6,50), linewidth=rsiWidth)
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.new(#b2b5be,65), style=plot.style_line)
plot(showMA ? rsiMA : na, "RSI-based MA", color=color.new(#b2b5be,65), linewidth=maWidth, style=plot.style_line)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.new(#b2b5be,65), style=plot.style_line)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(#0000ff,95) : na, title="Bollinger Bands Background")
barcolor = StrongBull ? color.new(#00ff00,20) : Bullish ? color.new(#1b5e20,20) : Bearish ? color.new(#801922,20) : StrongBear ? color.new(#ff0000,20) : color.new(#ffffff,20)
barcolor(showbarcolor ? barcolor : na)
//-------------------------------------------------------------- Hlines
rsiUpperBand = hline(75, "RSI Upper Band", color=color.new(#131722,0), linestyle=hline.style_dotted)
midBand = hline(50, "RSI Middle Band", color=color.new(#2a2e39,0), linestyle=hline.style_dotted)
rsiLowerBand = hline(25, "RSI Lower Band", color=color.new(#131722,0), linestyle=hline.style_dotted)
fill(rsiUpperBand, midBand, color=color.new(#00ff00,98), title="Upper Fill")
fill(midBand, rsiLowerBand, color=color.new(#ff0000,98), title="Lower Fill")
|
TMO Arrows | https://www.tradingview.com/script/JjO6E4lI-TMO-Arrows/ | lnlcapital | https://www.tradingview.com/u/lnlcapital/ | 378 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// @version=5
//
// TMO (T)rue (M)omentum (O)scillator) Arrows
//
// TMO calculates momentum using the DELTA of price. Giving a much better picture of trend, reversals and divergences than momentum oscillators using price.
//
// TMO Arrows are working on the same principle as the TMO oscillator, but they are ploted directly on the chart. Advantageos especially for those who want
// to combine TMO with other studies but have no space on the chart.
//
// Created by L&L Capital
//
indicator("TMO Arrows", shorttitle="TMO Arrows", overlay=true)
// Inputs
TimeFrame = input.timeframe('D', "TimeFrame", options=['1','2','3','5','10','15','20','30','45',"60","120","180","240",'D','2D','3D','4D','W','2W','3W','M','2M','3M'])
tmolength = input.int(14,title="Length")
calcLength = input(5, title="Calc Length")
smoothLength = input(3, title="Smooth Length")
// TMO Calculations
srcc = request.security(syminfo.tickerid, TimeFrame, close)
srco = request.security(syminfo.tickerid, TimeFrame, open)
o = srco
c = srcc
data = 0
for i = 1 to tmolength -1
if c > o[i]
data := data + 1
if c < o[i]
data := data - 1
EMA5 = ta.ema(data,calcLength)
Main = request.security(syminfo.tickerid, TimeFrame, ta.ema(EMA5, smoothLength))
Signal = request.security(syminfo.tickerid, TimeFrame, ta.ema(Main, smoothLength))
mainLine = (15*Main/tmolength)
signalLine = (15*Signal/tmolength)
// TMO Arrow Up
TMOArrowUp = ta.crossover(mainLine,signalLine)
plotshape(TMOArrowUp,title='TMO Up',style=shape.triangleup,location=location.belowbar,color=(#009900),size=size.small)
//TMO Arrow Dn
TMOArrowDn = ta.crossover(signalLine, mainLine)
plotshape(TMOArrowDn,title='TMO Down',style=shape.triangledown,location=location.abovebar,color=(#cc0000),size=size.small)
// TMO Arrow Up (Oversold Extremes Only)
TMOArrowUpEx = (mainLine < -9) and ta.crossover(mainLine,signalLine)
plotshape(TMOArrowUpEx,title='TMO Up (Oversolds Only)',style=shape.triangleup,location=location.belowbar,color=(#27c22e),size=size.small,display=display.none)
// TMO Arrow Dn (Overbought Extremes Only)
TMOArrowDnEx = (mainLine > 9) and ta.crossover(signalLine, mainLine)
plotshape(TMOArrowDnEx,title='TMO Down (Overboughts Only)',style=shape.triangledown,location=location.abovebar,color=(#ff0000),size=size.small,display=display.none)
|
Cox-Ross-Rubinstein Binomial Tree Options Pricing Model [Loxx] | https://www.tradingview.com/script/hw252XKE-Cox-Ross-Rubinstein-Binomial-Tree-Options-Pricing-Model-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 72 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//
// Cox-Ross-Rubinstein Binomial Tree Options Pricing Model adjusted to take account of dividend yield
//
//@version=5
indicator("Cox-Ross-Rubinstein Binomial Tree Options Pricing Model [Loxx]",
shorttitle ="CRRBTOPM",
overlay = true,
max_lines_count = 500)
//imports
import loxx/loxxexpandedsourcetypes/4
//constants
string rogersatch = "Roger-Satchell"
string parkinson = "Parkinson"
string c2c = "Close-to-Close"
string gkvol = "Garman-Klass"
string gkzhvol = "Garman-Klass-Yang-Zhang"
string ewmavolstr = "Exponential Weighted Moving Average"
string timtoolbar= "Time Now = Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970."
string timtoolnow = "Time Bar = The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session."
string timetooltrade = "Trading Day = The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970)."
ewmavol(float src, int per) =>
float lambda = (per - 1) / (per + 1)
float temp = na
temp := lambda * nz(temp[1], math.pow(src, 2)) + (1.0 - lambda) * math.pow(src, 2)
out = math.sqrt(temp)
out
rogerssatchel(int per) =>
float sum = math.sum(math.log(high/ close) * math.log(high / open)
+ math.log(low / close) * math.log(low / open), per) / per
float out = math.sqrt(sum)
out
closetoclose(float src, int per) =>
float avg = ta.sma(src, per)
float[] sarr = array.new_float(0)
for i = 0 to per - 1
array.push(sarr, math.pow(nz(src[i]) - avg, 2))
float out = math.sqrt(array.sum(sarr) / (per - 1))
out
parkinsonvol(int per)=>
float volConst = 1.0 / (4.0 * per * math.log(2))
float sum = volConst * math.sum(math.pow(math.log(high / low), 2), per)
float out = math.sqrt(sum)
out
garmanKlass(int per)=>
float hllog = math.log(high / low)
float oplog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(hllog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(oplog, 2), per)
float sum = parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
f_tickFormat() =>
_s = str.tostring(syminfo.mintick)
_s := str.replace_all(_s, '25', '00')
_s := str.replace_all(_s, '5', '0')
_s := str.replace_all(_s, '1', '0')
_s
if not timeframe.isdaily
runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.")
darkGreenColor = #1B7E02
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Spot Price", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
int n = input.int(100, "Calculation Steps", maxval = 300, group = "Basic Settings")
float K = input.float(3500, "Strike Price", group = "Basic Settings")
float v = input.float(25.6, "% Volatility", group = "Volatility Settings", tooltip = "Enter this number based on some calculateion you make yourself or use the historical volatility below.") / 100
int histvolper = input.int(22, "Historical Volatility Period", group = "Volatility Settings", tooltip = "This is here to use for volatility input.")
string hvoltype = input.string(c2c, "Historical Volatility Type", options = [c2c, gkvol, gkzhvol, rogersatch, ewmavolstr, parkinson], group = "Volatility Settings")
string rfrtype = input.string("USD", "Option Base Currency", options = ['USD', 'GBP', 'JPY', 'CAD', 'CNH', 'SGD', 'INR', 'AUD', 'SEK', 'NOK', 'DKK'], group = "Risk-free Rate Settings", tooltip = "Automatically pulls 10-year bond yield from corresponding currency")
float rfrman = input.float(3.97, "% Manual Risk-free Rate", group = "Risk-free Rate Settings") / 100
bool usdrsrman = input.bool(false, "Use manual input for Risk-free Rate?", group = "Risk-free Rate Settings")
float divsman = input.float(7.5, "% Manual Yearly Dividend Yield", group = "Dividend Settings") / 100
bool usediv = input.bool(true, "Adjust for Dividends?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
bool autodiv = input.bool(true, "Automatically Calculate Yearly Dividend Yield?", tooltip = "Only works if divdends exist for the current ticker", group = "Dividend Settings")
string timein = input.string("Time Now", title = "Time Now Type", options = ["Time Now", "Time Bar", "Trading Day"], group = "Time Intrevals", tooltip = timtoolnow + "; " + timtoolbar + "; " + timetooltrade)
int daysinyear = input.int(252, title = "Days in Year", minval = 1, maxval = 365, group = "Time Intrevals", tooltip = "Typically 252 or 365")
float hoursinday = input.float(24, title = "Hours Per Day", minval = 1, maxval = 24, group = "Time Intrevals", tooltip = "Typically 6.5, 8, or 24")
int thruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time")
int thruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time")
int thruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time")
int mins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time")
int hours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time")
int secs = input.int(0, title = "Expiry Second", minval = 0, maxval = 60, group = "Expiry Date/Time")
// seconds per year given inputs above
int spyr = math.round(daysinyear * hoursinday * 60 * 60)
// precision calculation miliseconds in time intreval from time equals now
start = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday
finish = timestamp(thruYear, thruMonth, thruDay, hours, mins, secs)
temp = (finish - start)
float T = (finish - start) / spyr / 1000
float q = usediv ? (autodiv ? request.dividends(syminfo.tickerid) / close * 4 : divsman) : 0
string byield = switch rfrtype
"USD"=> 'US10Y'
"GBP"=> 'GB10Y'
"JPY"=> 'US10Y'
"CAD"=> 'CA10Y'
"CNH"=> 'CN10Y'
"SGD"=> 'SG10Y'
"INR"=> 'IN10Y'
"AUD"=> 'AU10Y'
"USEKSD"=> 'SE10Y'
"NOK"=> 'NO10Y'
"DKK"=> 'DK10Y'
=> 'US10Y'
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float spot = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float r = usdrsrman ? rfrman : request.security(byield, timeframe.period, spot) / 100
float hvolout = switch hvoltype
parkinson => parkinsonvol(histvolper)
rogersatch => rogerssatchel(histvolper)
c2c => closetoclose(math.log(spot / nz(spot[1])), histvolper)
gkvol => garmanKlass(histvolper)
gkzhvol => gkyzvol(histvolper)
ewmavolstr => ewmavol(math.log(spot / nz(spot[1])), histvolper)
if barstate.islast
var matrix<float> S = matrix.new<float>(n + 1, n + 1, 0)
var matrix<float> EC = matrix.new<float>(n + 1, n + 1, 0)
var matrix<float> EP = matrix.new<float>(n + 1, n + 1, 0)
var matrix<float> AC = matrix.new<float>(n + 1, n + 1, 0)
var matrix<float> AP = matrix.new<float>(n + 1, n + 1, 0)
float dt = T / n
float u = math.exp(v * math.sqrt(dt))
float d = math.exp(-v * math.sqrt(dt))
float tmpr = syminfo.type == "futures" ? 1 - d : math.exp((r - q) * dt) - d
float p = tmpr / (u - d)
for j = 0 to n
for i = 0 to j
matrix.set(S, i, j, spot * math.pow(u, j - i) * math.pow(d, i))
for i = 0 to n
matrix.set(EC, i, n, math.max(matrix.get(S, i, n) - K, 0))
matrix.set(AC, i, n, math.max(matrix.get(S, i, n) - K, 0))
matrix.set(EP, i, n, math.max(K - matrix.get(S, i, n), 0))
matrix.set(AP, i, n, math.max(K - matrix.get(S, i, n), 0))
for j = n - 1 to 0
for i = 0 to j
matrix.set(EC, i, j, math.exp(-r * dt) * (p * matrix.get(EC, i, j + 1) + (1 - p) * matrix.get(EC, i + 1, j + 1)))
matrix.set(EP, i, j, math.exp(-r * dt) * (p * matrix.get(EP, i, j + 1) + (1 - p) * matrix.get(EP, i + 1, j + 1)))
matrix.set(AC, i, j, math.max(matrix.get(S, i, j) - K, math.exp(-r * dt) * (p * matrix.get(AC, i, j + 1)) + (1 - p) * matrix.get(AC, i + 1, j + 1)))
matrix.set(AP, i, j, math.max(K - matrix.get(S, i, j), math.exp(-r * dt) * (p * matrix.get(AP, i, j + 1)) + (1 - p) * matrix.get(AP, i + 1, j + 1)))
var testTable = table.new(position = position.middle_right, columns = 1, rows = 19, bgcolor = color.yellow, border_width = 1)
ecout = matrix.get(EC, 0, 0)
epout = matrix.get(EP, 0, 0)
acout = matrix.get(AC, 0, 0)
apout = matrix.get(AP, 0, 0)
float tempr = syminfo.type == "futures" ? 0 : r
table.cell(table_id = testTable, column = 0, row = 0, text = " Inputs ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 1, text = " Calculation Steps: " + str.tostring(n, "##.##") , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 2, text = " Spot Price: " + str.tostring(spot, f_tickFormat()) , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 3, text = " Strike Price: " + str.tostring(K, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 4, text = " Volatility (annual): " + str.tostring(v * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 5, text = " Risk-free Rate Type: " + rfrtype , bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 6, text = " Risk-free Rate: " + str.tostring(tempr * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 7, text = " Dividend Yield (annual): " + str.tostring(q * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 8, text = " Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 9, text = " Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 10, text = " Output ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 11, text = " European Call: " + str.tostring(ecout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 12, text = " European Put: " + str.tostring(epout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 13, text = " American Call: " + str.tostring(acout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 14, text = " American Put: " + str.tostring(apout, f_tickFormat()), bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 15, text = " Calculated Values ", bgcolor=color.yellow, text_color = color.black)
table.cell(table_id = testTable, column = 0, row = 16, text = " Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 17, text = " Hist. Daily Volatility: " + str.tostring(hvolout * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 18, text = " Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white)
|
Annualizer: New Indicator + CPI Analysis | https://www.tradingview.com/script/tdzctFnb-Annualizer-New-Indicator-CPI-Analysis/ | Skipper86 | https://www.tradingview.com/u/Skipper86/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Skipper86
//Date created: 9/25/2022
//Purpose of indicator: To analyze month-over-month (MoM) and year-over-year (YoY) changes in cumulative indexes such as CPI and M2
//Calculates:
//1. year-over-year % change
//2. annualized % change based on MoM % change (extrapolates MoM % change for comparison to YoY by multiplying by 12)
//notes:
//1. This indicator will not work on percent change ticker symbols such as YoY CPI percentage ("USCCPI"),
// it must be used on cumulative ticker symbols such as "CPIAUCSL" or "M2SL"
//2. This indicator will work on any timeframe but it will always show data based on monthly chart data.
//@version=5
indicator(title="Annualizer", shorttitle="Annualized", format=format.percent)
//designates script as an indicator script, assigns titles, and sets y-axis format to percent
TickerSymbol = input.symbol("CPIAUCSL","Symbol")
//Creates user input in settings menu for changing ticker symbol, defaults to CPIAUCSL
//CPIAUCSL = Consumer Price Index for All Urban Consumers: All Items in U.S. City Average
//TickerSymbol = syminfo.tickerid
//In order to link the ticker symbol to the chart's symbol, use the alternate TickerSymbol formula above (ref.)
//note: the 2 formulas below are referenced by the formula below them which runs monthly chart data (monthly closes) through
//them regardless of the current timeframe of the chart. This allows the indicator to be used on any timeframe while
//still properly referencing monthly data for annualization
//This limits the script to only capturing monthly data, even if weekly data or data reported more often is available.
//This limitation should be suitable for macroeconomic data such as cpi and M2 money supply which are usually analyzed
//on a monthly basis. In order to work with lower timeframes, the "M" in the 3rd formula below needs to be changed to
//reflect a lower timeframe such as "W", "D", or "60" (1hr). Multipliers and lookbacks will also need to be adjusted.
pctchangeYoY = 100*(close-close[12])/close[12]
//pct change YoY = 100*(current value - value from 12 months ago)/value from 12 months ago
pctchangeAnn = 100*(close - close[1])/close[1]*12
//MoM pct change annualized = MoM pct change multipled by number of months in a year (12)
//MoM pct change = 100*(current value - previous month's value)/previous month's value
[YoYx, Annx] = request.security(TickerSymbol, "M", [pctchangeYoY, pctchangeAnn], lookahead=barmerge.lookahead_on)
//calculates YoY and Annualized MoM pct changes by running monthly data of TickerSymbol through formulas above
plot(YoYx, color=#FF0000, title="YoY % Change")
plot(Annx, color=TickerSymbol == "FRED:M2SL" ? #006600:#2962FF, title="Annualized % Change")
//plots calculated pct changes below main chart
//if Ticker symbol is "FRED:M2SL" which is M2 money supply, plots annualized pct change in green, otherwise, plots it in blue
hline(0, color=#787B8650)
//plots horizontal line at zero pct for reference
//End of Script |
[FrizLabz]FVG Bar | https://www.tradingview.com/script/k4zMdmSj-FrizLabz-FVG-Bar/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 180 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FFriZz
//@version=5
indicator('[FrizLabz]FVG Bar',overlay = true,max_lines_count = 500,max_labels_count = 500,max_boxes_count = 500,max_bars_back = 5000,explicit_plot_zorder = true)
import FFriZz/BoxLine_Lib/1 as obj
//Inputs
fvg_i = input.bool(true,'FVG | On/Off?',group = 'FVG')
cross_i = input.bool(true,'Delete FVG when Completely filled',group = 'FVG')
crossAdj_i = input.bool(true,'Adjust FVG when Filled/Mitigated[Delete Must be',group = 'FVG')
fvg_w = input.int(2,'FVG Width',group = 'FVG')
count_i = input.int(100,'Display Count',group = 'FVG')
bullFvg_c = input.color(#00ff00,'Bull',group='FVG Colors',inline='C')
bearFvg_c = input.color(#ff0000,'Bear',group='FVG Colors',inline='C')
//Variables
var line[] aBull = array.new<line>()
var line[] aBear = array.new<line>()
bearFvg = high < low[2] and fvg_i
bullFvg = low > high[2] and fvg_i
fvgC = bullFvg ? bullFvg_c : bearFvg_c
//FVG Edit Function
fvgEdit(aBull,aBear,count) =>
for s = 0 to 1
line[] aLine = aBull
int aSize = array.size(aBull)
switch s
1 => aSize := array.size(aBear), aLine := aBear
if aSize > 0
for i = aSize - 1 to 0
getLine = array.get(aLine,i)
y1 = line.get_y1(getLine)
y2 = line.get_y2(getLine)
cross = low < y2
crossAdj = low < y1
switch s
1 => cross := high > y2, crossAdj := high > y1
if crossAdj_i and crossAdj and cross_i
switch s
0 => line.set_y1(getLine,low)
1 => line.set_y1(getLine,high)
if cross_i and cross
line.delete(array.remove(aLine,i))
if barstate.islast
if aSize > count
line.delete(array.pop(aLine))
//ifs and make FVG
if bullFvg
array.unshift(aBull,
line.new(
bar_index - 1,
low,
bar_index - 1,
high[2],
width = fvg_w,
color = fvgC))
if bearFvg
array.unshift(aBear,
line.new(
bar_index - 1,
high,
bar_index - 1,
low[2],
width = fvg_w,
color = fvgC))
//Fun Call
fvgEdit(aBull,aBear,count_i)
|
RSI Influenced Average | https://www.tradingview.com/script/NZ2EupFI-RSI-Influenced-Average/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 32 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EsIstTurnt
//@version=5
indicator("RSI Influenced Average",overlay=true)
//Inputs
option = input.bool(false,'Alternative Calculation Method',group='Calculate')
invert = input.bool(false,'Invert RSI Values',group='Calculate')
colorize = input.bool(true,'Show Alternating Colors',group='Appearance')
length = input.int(64,'MA Length',group='Calculate')
rsiscale = input.string('900',title='Alternate Calculation Scaling',options=['100','333','666','900'],group='Calculate')
rsi_isr = input.string(title="RSI/ISR/AVG", defval="AVG", options=["RSI","ISR","AVG"],group='Calculate')
maInput = input.string(title="MA", defval="LRC", options=["EMA", "SMA", "VWMA", "WMA","LRC"],group='Calculate')
width = input.string('2',title='Line Width',options=['1','2','3','4'],group='Appearance')
upcol = input.color(#acfb00,'Up Color',group='Appearance')
dncol = input.color(#ff0000,'Down Color',group='Appearance')
////////////////Calculate/////////////////
//RSI
rsi = ta.rsi(input.source(close,'RSI Source'),input.int(32,'RSI Length'))
isr = 100-rsi
rsilen1 = rsi>80?64:rsi>70?56:rsi>60?48:rsi>50?40:rsi>40?32:rsi>30?24:rsi>20?16:8
//Alternate Calculation Scaling
scale1 = rsiscale=='100'?100:rsiscale=='333'?333:rsiscale=='666'?666 :rsiscale=='900'?900:na
scale2 = rsiscale=='100'?.5 :rsiscale=='333'?.85:rsiscale=='666'?.925:rsiscale=='900'?.945:na
dif1 = (rsi/scale1)+scale2
dif2 = (isr/scale1)+scale2
//Center
h1 = ta.highest(high,input.int(48,'Upper Lookback'))
h2 = ta.highest(high,rsilen1)
l1 = ta.lowest (low ,input.int(48,'Lower Lookback'))
l2 = ta.lowest (low ,rsilen1)
hl_1 = math.avg(h1,l1) //Centerpoint 1
hl_2 = math.avg(h2,l2) //Centerpoint 2
//Difference
hl_1_dif = h1-l1
hl_2_dif = h2-l2
difscale1 = (rsi/100)*hl_1_dif
difscale2 = (isr/100)*hl_2_dif
//Apply RSI
rsiscale1 = ta.swma(l1+difscale1)
rsiscale2 = ta.swma(l2+difscale2)
isrscale1 = ta.swma(h1-difscale1)
isrscale2 = ta.swma(h2-difscale2)
rsima = dif1*hl_1
isrma = dif2*hl_2
rsiisr1 = rsi_isr == "RSI" ? rsiscale1 : rsi_isr == "AVG" ? math.avg(rsima,isrma) : isrma
rsiisr2 = rsi_isr == "RSI" ? rsiscale2 : rsi_isr == "AVG" ? math.avg(rsima,isrma) : isrma
rsiisr3 = rsi_isr == "RSI" ? rsiscale1 : rsi_isr == "AVG" ? math.avg(rsiscale1,isrscale1) : isrscale1
rsiisr4 = rsi_isr == "RSI" ? rsiscale2 : rsi_isr == "AVG" ? math.avg(rsiscale2,isrscale2) : isrscale2
basis1 = maInput == "EMA" ? ta.ema(rsima, length) :maInput == "SMA"? ta.sma(rsima , length):maInput == "VWMA"? ta.vwma(rsima , length):maInput == "WMA"? ta.wma(rsima , length):maInput == "LRC"?ta.linreg(rsima ,length,0):rsima
basis2 = maInput == "EMA" ? ta.ema(isrma, length) :maInput == "SMA"? ta.sma(isrma , length):maInput == "VWMA"? ta.vwma(isrma , length):maInput == "WMA"? ta.wma(isrma , length):maInput == "LRC"?ta.linreg(isrma ,length,0):isrma
basis3 = maInput == "EMA" ? ta.ema(rsiisr3, length):maInput == "SMA"? ta.sma(rsiisr3, length):maInput == "VWMA"? ta.vwma(rsiisr3, length):maInput == "WMA"? ta.wma(rsiisr3, length):maInput == "LRC"?ta.linreg(rsiisr3,length,0):rsiisr1
basis4 = maInput == "EMA" ? ta.ema(rsiisr4, length):maInput == "SMA"? ta.sma(rsiisr4, length):maInput == "VWMA"? ta.vwma(rsiisr4, length):maInput == "WMA"? ta.wma(rsiisr4, length):maInput == "LRC"?ta.linreg(rsiisr4,length,0):rsiisr2
rsi_ma = option?invert?basis2:basis1:invert?basis4:basis3
////////////////Appearance/////////////////
//Colors
color = colorize?color.new(rsi_ma<ta.sma(close,8)?upcol:dncol,input.int(50,'Transparency')):input.color(color.gray,'Static Color')
//Thickness
linewidth = width=='1'?1:width=='2'?2:width=='3'?3:4
//Plot
plot(rsi_ma,linewidth=linewidth,color=color)
|
SPY Offset | https://www.tradingview.com/script/nr8Xdclr-SPY-Offset/ | Grynn | https://www.tradingview.com/u/Grynn/ | 2 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Grynn ([email protected])
//@version=5
indicator("SPY Diff", "Fair Value (lime)", overlay = true)
//spy = request.security("SP500", timeframe.period, ta.sma(close, 7)) //timeframe.period - use chart's timeframe
netliq = request.security("FRED:WALCL-(FRED:RRPONTSYD+FRED:WTREGEN)", timeframe.period, ta.sma(close, 7)/1000/1000/1000/1.1 - 1625)
upperBand = netliq + 350
lowerBand = netliq - 150
plot(netliq, title = "Net Liq", color= color.lime, linewidth = 4)
plot(upperBand, color= color.red, linewidth = 4)
plot(lowerBand, color= color.green, linewidth = 4)
//diff = spy - netliq
//plot(spy, title = "SPY", color= color.blue, linewidth = 4)
|
COT Report Indicator | https://www.tradingview.com/script/B6J550VX-COT-Report-Indicator/ | Trading_Nerd | https://www.tradingview.com/u/Trading_Nerd/ | 606 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingNerd
//@version=5
indicator('COT Report Indicator', format=format.volume, precision=0)
// Variables {
i_tableAlign = input.string(position.middle_right, 'Align Table', [position.middle_right, position.middle_left])
table t = table.new(i_tableAlign, 7, 6, color.rgb(19, 23, 34), color.white, 2, color.white, 2)
color textCl = color.white
color clCom = color.gray
color clNoncom = color.blue
color clSpec = color.orange
// }
// INPUTS {
i_dataSource = input.string('Futures Only', 'Data', ['Futures Only', 'Futures and Options'])
i_showCom = input.bool(true, 'Show Commercials')
// }
// Functions {
f_getCl(value) =>
if value > 0
color.lime
else if value < 0
color.red
else
color.white
// }
// Request {
sHead = 'QUANDL:CFTC/'
sData = i_dataSource == 'Futures Only' ? '_F_L_ALL|' : '_FO_L_ALL|'
// Financial Markets (Commercial)
comColumnLong = '4'
comColumnShort = '5'
// Non-Commercials (large Speculators)
noncomColumnLong = '1'
noncomColumnShort = '2'
// Non-Reportable (small Speculators)
specColumnLong = '8'
specColumnShort = '9'
// CFTC Market Codes
// Codes from https://data.nasdaq.com/data/CFTC-commodity-futures-trading-commission-reports
f_getCode(pair) =>
string code = switch pair
'USD' => '098662' // USD Index
'EUR' => '099741'
'AUD' => '232741'
'GBP' => '096742'
'CAD' => '090741'
'JPY' => '097741'
'CHF' => '092741'
'NZD' => '112741'
'BTC' => '133741'
'GOLD' => '088691'
'SILVER' => '084691'
'PLATINUM' => '076651'
'PALLADIUM' => '075651'
'ALUMINUM' => '191651'
'COPPER' => '085692'
'CRUDE OIL' => 'T'
'SOYBEAN OIL' => '007601'
'S&P 500' => '13874P'
'S&P 500 Mini' => '13874A'
'Dow Jones' => '12460P'
'NIKKEI' => '240741'
'NASDAQ' => '20974P'
'RUSSELL 2000' => '239777'
'Volatility S&P 500' => '1170E1'
=> ''
code
f_getTicker() =>
switch syminfo.ticker
'GOLD' => 'GOLD'
'GOLD1!' => 'GOLD'
'XAU' => 'GOLD'
'XAUUSD' => 'GOLD'
'SILVER' => 'SILVER'
'SILVER1!' => 'SILVER'
'PLATINUM' => 'PLATINUM'
'PALLADIUM' => 'PALLADIUM'
'COPPER' => 'COPPER'
'ALUMINUM' => 'ALUMINUM'
'OIL' => 'CRUDE OIL'
'CL1!' => 'CRUDE OIL'
'SOYUSD' => 'SOYBEAN OIL'
'ZL1!' => 'SOYBEAN OIL'
'SPX' => 'S&P 500'
'ES1!' => 'S&P 500'
'XSP' => 'S&P 500 Mini'
'NKD' => 'NIKKEI'
'NKD1!' => 'NIKKEI'
'NK225' => 'NIKKEI'
'NK2251!' => 'NIKKEI'
'DJI' => 'Dow Jones'
'US30' => 'Dow Jones'
'NASDAQ' => 'NASDAQ'
'US100' => 'NASDAQ'
'NDX' => 'NASDAQ'
'RUT' => 'RUSSELL 2000'
'RTY' => 'RUSSELL 2000'
'VIX' => 'Volatility S&P 500'
=> ''
f_getCurrency(curr) =>
if curr == ''
f_getTicker()
else
curr
f_getCurrencyAB(base, quote) =>
retBase = f_getCurrency(base)
retQuote = f_getCurrency(quote)
// find a correlating currency for that ticker
if retBase == retQuote or retQuote == ''
retQuote := switch retBase
'S&P 500' => 'USD'
'S&P 500 Mini' => 'USD'
=> quote
[retBase, retQuote]
// Data functions
// Commercials
dLong(asCode) =>
request.security(sHead + asCode + sData + comColumnLong, 'W', close, lookahead=barmerge.lookahead_on)
dShort(asCode) =>
request.security(sHead + asCode + sData + comColumnShort, 'W', close, lookahead=barmerge.lookahead_on)
// large - Non Commercials
dLong2(asCode2) =>
request.security(sHead + asCode2 + sData + noncomColumnLong, 'W', close, lookahead=barmerge.lookahead_on)
dShort2(asCode2) =>
request.security(sHead + asCode2 + sData + noncomColumnShort, 'W', close, lookahead=barmerge.lookahead_on)
// small - Non-Reportable
dLong3(asCode3) =>
request.security(sHead + asCode3 + sData + specColumnLong, 'W', close, lookahead=barmerge.lookahead_on)
dShort3(asCode3) =>
request.security(sHead + asCode3 + sData + specColumnShort, 'W', close, lookahead=barmerge.lookahead_on)
f_getData(code) =>
comLong = dLong(code)
comShort = dShort(code)
noncomLong = dLong2(code)
noncomShort = dShort2(code)
specLong = dLong3(code)
specShort = dShort3(code)
[comLong, comShort, noncomLong, noncomShort, specLong, specShort]
f_calcNet(comLong, comShort, noncomLong, noncomShort, specLong, specShort) =>
netCom = comLong - comShort
netNoncom = noncomLong - noncomShort
netSpec = specLong - specShort
[netCom, netNoncom, netSpec]
// }
// Calculations {
[currencyA, currencyB] = f_getCurrencyAB(syminfo.basecurrency, syminfo.currency)
codeA = f_getCode(currencyA)
codeB = f_getCode(currencyB)
[pairA_coms_long, pairA_coms_short, pairA_noncoms_long, pairA_noncoms_short, pairA_spec_long, pairA_spec_short] = f_getData(codeA)
[pairB_coms_long, pairB_coms_short, pairB_noncoms_long, pairB_noncoms_short, pairB_spec_long, pairB_spec_short] = f_getData(codeB)
// Calc net
[net_comA, net_noncomA, net_specA] = f_calcNet(pairA_coms_long, pairA_coms_short, pairA_noncoms_long, pairA_noncoms_short, pairA_spec_long, pairA_spec_short)
[net_comB, net_noncomB, net_specB] = f_calcNet(pairB_coms_long, pairB_coms_short, pairB_noncoms_long, pairB_noncoms_short, pairB_spec_long, pairB_spec_short)
net_comApercentLong = pairA_coms_long / (pairA_coms_long + pairA_coms_short) * 100
net_comBpercentLong = pairB_coms_long / (pairB_coms_long + pairB_coms_short) * 100
net_noncomApercentLong = pairA_noncoms_long / (pairA_noncoms_long + pairA_noncoms_short) * 100
net_noncomBpercentLong = pairB_noncoms_long / (pairB_noncoms_long + pairB_noncoms_short) * 100
net_specApercentLong = pairA_spec_long / (pairA_spec_long + pairA_spec_short) * 100
net_specBpercentLong = pairB_spec_long / (pairB_spec_long + pairB_spec_short) * 100
// --------------
// // percent calculation
symbol_com_sum = pairA_coms_long + pairA_coms_short + pairB_coms_long + pairB_coms_short
symbol_com_long = (pairA_coms_long + pairB_coms_short) / symbol_com_sum * 100
symbol_com_short = (pairA_coms_short + pairB_coms_long) / symbol_com_sum * 100
symbol_noncom_sum = pairA_noncoms_long + pairA_noncoms_short + pairB_noncoms_long + pairB_noncoms_short
symbol_noncom_long = (pairA_noncoms_long + pairB_noncoms_short) / symbol_noncom_sum * 100
symbol_noncom_short = (pairA_noncoms_short + pairB_noncoms_long) / symbol_noncom_sum * 100
symbol_spec_sum = pairA_spec_long + pairA_spec_short + pairB_spec_long + pairB_spec_short
symbol_spec_long = (pairA_spec_long + pairB_spec_short) / symbol_spec_sum * 100
symbol_spec_short = (pairA_spec_short + pairB_spec_long) / symbol_spec_sum * 100
// }
// Plots {
plot_com = i_showCom ? symbol_com_long : na
plotStyle = if (timeframe.isweekly or timeframe.ismonthly)
plot.style_line
else
plot.style_stepline
plot(plot_com, "Commercials", clCom, 3, plotStyle, histbase=0)
plot(symbol_noncom_long, "Non-Commercials", clNoncom, 3, plotStyle, histbase=0)
plot(symbol_spec_long, "Retail Traders", clSpec, 3, plotStyle, histbase=0)
// Labels
if i_showCom
label comLabel = label.new(bar_index+1, symbol_com_long, 'Commercials', xloc.bar_index, yloc.price, clCom, label.style_label_left)
label.delete(comLabel[1])
label noncomLabel = label.new(bar_index+1, symbol_noncom_long, 'Non-Commercials', xloc.bar_index, yloc.price, clNoncom, label.style_label_left)
label specLabel = label.new(bar_index+1, symbol_spec_long, 'Retail Traders', xloc.bar_index, yloc.price, clSpec, label.style_label_left)
label.delete(noncomLabel[1])
label.delete(specLabel[1])
// Table
f_textCell(col, row, txt) =>
table.cell(t, col, row, txt, text_color=textCl)
f_fillCell(col, row, value) =>
valueStr = str.tostring(value, format.volume)
cl = f_getCl(value)
table.cell(t, col, row, valueStr, text_color=cl)
f_fillPercent(col, row, value, isLong) =>
valueStr = str.tostring(value, format.volume) + '%'
cl = if isLong and value > 50
color.lime
else if not isLong and value > 50
color.red
else
color.white
table.cell(t, col, row, valueStr, text_color=cl)
// Merge cells
table.merge_cells(t, 1, 0, 3, 0)
table.merge_cells(t, 4, 0, 6, 0)
f_textCell(1, 0, currencyA)
f_textCell(4, 0, currencyB)
f_textCell(1, 1, 'Net Contracts')
f_textCell(2, 1, 'Long')
f_textCell(3, 1, 'Short')
f_textCell(4, 1, 'Net Contracts')
f_textCell(5, 1, 'Long')
f_textCell(6, 1, 'Short')
if i_showCom
table.cell(t, 0, 2, 'Commercials', text_color=textCl)
f_fillCell(1, 2, net_comA)
f_fillCell(4, 2, net_comB)
f_fillPercent(2, 2, net_comApercentLong, true)
f_fillPercent(3, 2, 100-net_comApercentLong, false)
f_fillPercent(5, 2, net_comBpercentLong, true)
f_fillPercent(6, 2, 100-net_comBpercentLong, false)
table.cell(t, 0, 3, 'Institutional', text_color=textCl)
f_fillCell(1, 3, net_noncomA)
f_fillCell(4, 3, net_noncomB)
f_fillPercent(2, 3, net_noncomApercentLong, true)
f_fillPercent(3, 3, 100-net_noncomApercentLong, false)
f_fillPercent(5, 3, net_noncomBpercentLong, true)
f_fillPercent(6, 3, 100-net_noncomBpercentLong, false)
table.cell(t, 0, 4, 'Retail Traders', text_color=textCl)
f_fillCell(1, 4, net_specA)
f_fillCell(4, 4, net_specB)
f_fillPercent(2, 4, net_specApercentLong, true)
f_fillPercent(3, 4, 100-net_specApercentLong, false)
f_fillPercent(5, 4, net_specBpercentLong, true)
f_fillPercent(6, 4, 100-net_specBpercentLong, false)
hplot0 = hline(0)
hplot50 = hline(50)
hplot100 = hline(100)
color clShort = color.new(color.red, 90)
color clLong = color.new(color.green, 90)
fill(hplot0, hplot50, clShort)
fill(hplot50, hplot100, clLong)
// }
|
Tick Statistics | https://www.tradingview.com/script/K9n3ueax-Tick-Statistics/ | Sharad_Gaikwad | https://www.tradingview.com/u/Sharad_Gaikwad/ | 269 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sharad_Gaikwad
//@version=5
indicator("Tick Statistics", overlay = true)
tab = table.new(position=position.top_right, columns=7, rows=200,frame_color = color.yellow, frame_width = 1)
msg(int row, int col, string msg_str, clr=color.blue) =>
table.cell(table_id=tab, column=col, row=row, text=msg_str, text_color=clr)
t(val) => str.tostring(val)
get_tick_summary(_tick_arr, _up_arr, _down_arr, _nc_arr, _cmp_arr, _vol_arr) =>
summary_ticks = '========== Ticks ==========\n'
summary_volume = '========== Volume ==========\n'
max_min = '========== Max-Min =========\n'
candle_summary = '====== Candle Summary ======\n'
upp = 0, dnp = 0, ncp = 0
upv = 0.0, dnv = 0.0, ncv = 0.0
max_vol = 0.0, min_vol = 99999999999999.99, max_vol_price =0.0, min_vol_price = 0.0
max_vol_tick = 0.0, min_vol_tick = 0.0
max_price = 0.0, min_price = 99999999999.99, max_price_vol = 0.0, min_price_vol = 0.0
max_price_tick = 0.0, min_price_tick = 0.0
max_tick = 0.0, min_tick = 999999999999.99
max_tick_tick_no = 0., min_tick_tick_no = 0.
up_counter = 0, down_counter = 0
succive_up = 0.0, succive_down = 0.0
last_tick_price = 0.0, first_tick_price = 0.0
up_str = ';', down_str = ';'
if(array.size(_tick_arr) > 1)
size = array.size(_tick_arr) - 1
size_cmp = array.size(_cmp_arr) - 1
vol_now = 0.0
// This identifies successive up and down tick but not working as expected
// for i1 = 0 to size_cmp
// if(i1 < size_cmp)
// // if(array.get(_cmp_arr, i) < array.get(_cmp_arr, i+1))
// // down_counter := down_counter + 1
// // down_str := down_str + t(down_counter) + ';'
// // else
// // down_counter := 0
// if(array.get(_cmp_arr, i1) > array.get(_cmp_arr, i1+1))
// up_counter := up_counter + 1
// up_str := up_str + t(up_counter) + ';'
// else
// up_counter := 0
// if(i1 < size_cmp)
// if(array.get(_cmp_arr, i1) < array.get(_cmp_arr, i1+1))
// down_counter := down_counter + 1
// down_str := down_str + t(down_counter) + ';'
// else
// down_counter := 0
for i = 0 to size
if(i == 0 )
last_tick_price := array.get(_cmp_arr, i)
first_tick_price := array.get(_cmp_arr, i)
if(i < size)
vol_now := array.get(_vol_arr, i) - array.get(_vol_arr, i+1)
else
vol_now := array.get(_vol_arr, i)
if(vol_now > max_vol)
max_vol := vol_now
max_vol_price := array.get(_cmp_arr, i)
max_vol_tick := array.get(_tick_arr, i)
if(vol_now < min_vol)
min_vol := vol_now
min_vol_price := array.get(_cmp_arr, i)
min_vol_tick := array.get(_tick_arr, i)
if(array.get(_cmp_arr, i) > max_price)
max_price := array.get(_cmp_arr, i)
max_price_vol := vol_now
max_price_tick := array.get(_tick_arr, i)
if(array.get(_cmp_arr, i) < min_price)
min_price := array.get(_cmp_arr, i)
min_price_vol := vol_now
min_price_tick := array.get(_tick_arr, i)
upp := upp + array.get(_up_arr, i)
dnp := dnp + array.get(_down_arr, i)
ncp := ncp + array.get(_nc_arr, i)
if(i != size)
upv := upv + (array.get(_up_arr, i) * (array.get(_vol_arr, i) - array.get(_vol_arr, i+1)))
dnv := dnv + (array.get(_down_arr, i) * (array.get(_vol_arr, i) - array.get(_vol_arr, i+1)))
ncv := ncv + (array.get(_nc_arr, i) * (array.get(_vol_arr, i) - array.get(_vol_arr, i+1)))
tick_size = array.get(_cmp_arr, i) - array.get(_cmp_arr, i+1)
max_tick_tick_no := math.abs(tick_size) > math.abs(max_tick) ? array.get(_tick_arr, i) : max_tick_tick_no
max_tick := math.abs(tick_size) > math.abs(max_tick) ? tick_size : max_tick
min_tick_tick_no := math.abs(tick_size) < math.abs(min_tick) ? array.get(_tick_arr, i) : min_tick_tick_no
min_tick := math.abs(tick_size) < math.abs(min_tick) ? tick_size : min_tick
if(i == size)
upv := upv + (array.get(_up_arr, i) * (array.get(_vol_arr, i) ))
dnv := dnv + (array.get(_down_arr, i) * (array.get(_vol_arr, i)))
ncv := ncv + (array.get(_nc_arr, i) * (array.get(_vol_arr, i) ))
up_arr = str.split(up_str, ';')
if(array.size(up_arr) > 1)
for x = 0 to array.size(up_arr) - 1
if(str.tonumber(array.get(up_arr, x)) > succive_up)
succive_up := str.tonumber(array.get(up_arr, x))
down_arr = str.split(down_str, ';')
if(array.size(down_arr) > 1)
for x1 = 0 to array.size(down_arr) - 1
if(str.tonumber(array.get(up_arr, x1)) > succive_up)
succive_up := str.tonumber(array.get(up_arr, x1))
summary_ticks := summary_ticks + 'Total ticks = '+ t(upp+dnp+ncp) + '\n' +
'Up ticks = '+t(upp)+'\n'+
'Down ticks = '+t(dnp)+'\n'+
'No chgang (NC) = '+t(ncp)+'\n' +
'Biggest tick = '+t(max_tick)+ ' @ Tick no = '+t(max_tick_tick_no) +'\n'+
'Smallest tick = '+t(min_tick)+ ' @ Tick no = '+t(min_tick_tick_no)
// 'Succive Up = '+t(succive_up)+'\n'+
// 'Succive Down = '+t(succive_down)
summary_volume := '\n' + summary_volume +
'Total = '+t(upv+dnv+ncv)+'\n'+
'Up = '+t(upv)+'\n'+
'Down = '+t(dnv)+'\n'+
'No Change = '+t(ncv)+'\n'+
'Candle Vol = '+t(volume)
vol_state = upv > dnv ? 'Up' : upv < dnv ? 'Down' : '---'
price_state = last_tick_price > first_tick_price ? 'Up' : last_tick_price < first_tick_price ? 'Down' : '---'
candle_summary := candle_summary +
'Price = '+ price_state +'\n' +
'Volume = '+ vol_state +'\n'
[summary_ticks + summary_volume+ '\n'+
max_min +
'Max Vol = ' + t(max_vol) + ' @ Price = ' + t(max_vol_price) + ' @ Tick no = ' + t(max_vol_tick) + '\n' +
'Min Vol = ' + t(min_vol) + ' @ Price = ' + t(min_vol_price) + ' @ Tick no = ' + t(min_vol_tick) + '\n' +
'Max Price = ' + t(max_price) + ' @ Vol = ' + t(max_price_vol) + ' @ Tick no = ' + t(max_price_tick) + '\n' +
'Min Price = ' + t(min_price) + ' @ Vol = ' + t(min_price_vol) + ' @ Tick no = ' + t(min_price_tick) + '\n' +
candle_summary, vol_state != price_state]
varip tick_arr = array.new<float>()
varip up_arr = array.new<int>()
varip down_arr = array.new<int>()
varip nc_arr = array.new<int>()
varip cmp_arr = array.new<float>()
varip vol_arr = array.new<float>()
varip prev_tick_price = float(na)
varip prev_tick_vol = float(na)
varip tick_no = int(na)
if(barstate.isnew)
tick_no := 0
array.clear(tick_arr), array.clear(up_arr), array.clear(down_arr)
array.clear(nc_arr), array.clear(cmp_arr), array.clear(vol_arr)
tick_no := tick_no + 1
upp = close > prev_tick_price ? 1 : 0
downp = close < prev_tick_price ? 1 : 0
ncp = close == prev_tick_price ? 1 : 0
array.unshift(tick_arr, tick_no)
array.unshift(up_arr, upp)
array.unshift(down_arr, downp)
array.unshift(nc_arr, ncp)
array.unshift(cmp_arr, close)
array.unshift(vol_arr, volume)
//text_str = ''
if(barstate.isconfirmed)
text_str = "Data displaying tick by tick changes in price and volume\n\n"+'Tick\t|Typ\t|CMP\t|Vol\t\t|PC\t\t|VC'
text_str1 = ''
if(array.size(tick_arr) > 1)
for i = 0 to array.size(tick_arr) - 1
price_change = 0.0
vol_change = 0.0
if(i < array.size(tick_arr) - 1)
price_change := array.get(cmp_arr, i) - array.get(cmp_arr, i+1)
vol_change := array.get(vol_arr, i) - array.get(vol_arr, i+1)
tick_type = array.get(up_arr, i) == 1 ? 'Up' : array.get(down_arr, i) == 1 ? 'Dn' : '--'
data = t(array.get(tick_arr, i)) + '\t|'
+ tick_type + '\t|'
+ t(math.round(array.get(cmp_arr, i), 2)) + '\t|'
+ t(math.round(array.get(vol_arr, i), 2)) + '\t|'
+ t(math.round(price_change, 2)) + '\t|'
+ t(math.round(vol_change, 2))
if(str.length(text_str) + str.length(data) <= 4000)
text_str := text_str + '\n' + data //text_str1 + '\n'+ data
// else
// text_str := text_str + '\n'+ data
str = text_str // +'\n'+text_str1
label.new(bar_index, low, yloc = yloc.belowbar, style = label.style_diamond, size = size.tiny, tooltip = str)
[tick_summary, divergence] = get_tick_summary(tick_arr, up_arr, down_arr, nc_arr, cmp_arr, vol_arr)
clr = divergence ? color.red : color.green
label.new(bar_index, low, yloc = yloc.abovebar, style = label.style_diamond, size = size.tiny, tooltip = tick_summary, color = clr)
prev_tick_price := close
prev_tick_vol := volume
|
Tradesharpe Session Bias | https://www.tradingview.com/script/AOZlwRHd-Tradesharpe-Session-Bias/ | TradeSharpe99 | https://www.tradingview.com/u/TradeSharpe99/ | 142 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradeSharpe99
//@version=5
indicator(title="Tradesharpe Session Bias", overlay=true)
loc = input.string("TOP RIGHT", title="TABLE LOCATION", options=['TOP RIGHT', 'TOP LEFT', 'BOTTOM RIGHT', 'BOTTOM LEFT'])
locc = loc == "TOP RIGHT" ? position.top_right :
loc == "TOP LEFT" ? position.top_left :
loc == "BOTTOM RIGHT" ? position.bottom_right : position.bottom_left
//HIGH TF DATA
[dclose, dopen] = request.security("", "D", [close[1], open[1]])
[cl, op] = request.security("", "240", [close[1], open[1]])
//HIGH TF DATA BREAKDOWN
dtype = dclose>dopen ? 1 : dclose<dopen ? 2 : 3
ftype = cl>op ? 11 : cl<op ? 22 : 33
//RESULT CALCULATIONS
textone = (dtype == 1 and ftype == 11) ? "BULLISH" :
(dtype == 1 and ftype != 11) ? "MIXED" :
(dtype == 2 and ftype == 22) ? "BEARISH" :
(dtype == 2 and ftype != 22) ? "MIXED" : "MIXED1"
//COLOR CONDITIONS
textcol = (dtype == 1 and ftype == 11) ? color.green :
(dtype == 1 and ftype != 11) ? color.gray :
(dtype == 2 and ftype == 22) ? color.red :
(dtype == 2 and ftype != 22) ? color.gray : color.gray
//TABLE IMPLEMENTATION
var testTable = table.new(position = locc, columns = 2, rows = 1, bgcolor = color.white, border_color=color.black, border_width = 1)
if barstate.islast
table.cell(table_id = testTable, column = 0, row = 0, text = "SESSION BIAS", bgcolor=color.white, text_color=color.black)
table.cell(table_id = testTable, column = 1, row = 0, text = textone, bgcolor=textcol)
"Update Existing Script" |
Gaussian Average Convergence Divergence | https://www.tradingview.com/script/nSxFhNAA-Gaussian-Average-Convergence-Divergence/ | themocrew | https://www.tradingview.com/u/themocrew/ | 31 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © themocrew
//@version=5
indicator(title="Gaussian Average Convergence Divergence", shorttitle="GACD", overlay=false)
// ===== INDICATOR SETTINGS ===== {
// LENGTH INPUT SETTINGS
int i_length = input.int(defval=21, minval=2, title="Length 1", group="GACD Settings")
int i_length2 = input.int(defval=34, minval=2, title="Length 2", group="GACD Settings")
int i_length3 = input.int(defval=21, minval=2,title="Length 3", group="GACD Settings")
// HISTOGRAM COLOR CUSTOMIZATION SETTINGS
color i_col_grow_above = input.color(defval=#26A69A, title="Above Grow", group="Histogram", inline="Above")
color i_col_fall_above = input.color(defval=#B2DFDB, title="Fall", group="Histogram", inline="Above")
color i_col_grow_below = input.color(defval=#FFCDD2, title="Below Grow", group="Histogram", inline="Below")
color i_col_fall_below = input.color(defval=#FF5252, title="Fall", group="Histogram", inline="Below")
// SIGNAL LINE COLOR CUSTOMIZATION SETTINGS
color i_signal_line_above = input.color(defval=color.green, title="Cross Above", group="Signal Lines", inline="Line")
color i_signal_line_below = input.color(defval=color.red, title="Cross Below", group="Signal Lines", inline="Line")
// BAND COLOR CUSTOMIZATION SETTINGS
bool i_show_fill = input.bool(defval=true, title="Display Fill", group="Band")
color i_band_above = input.color(defval=color.green, title="Band Above", group="Band", inline="Band")
color i_band_below = input.color(defval=color.red, title="Band Below", group="Band", inline="Band")
int i_band_opacity = 100 - input.int(defval=100, minval=0, maxval=100, title="Opacity (%)", group="Band")
// VERTICAL LINE CUSTOMIZATION SETTINGS
bool i_vert = input.bool(defval=true, title="Display Verticle Line", group="Verticle Line")
color i_vert_above = input.color(defval=color.green, title="Cross Above", group="Verticle Line", inline="Color")
color i_vert_below = input.color(defval=color.red, title="Cross Below", group="Verticle Line", inline="Color")
string i_vert_style = input.string(defval="Dashed", title="Line Style", options=["Solid", "Dashed", "Dotted"], group="Verticle Line")
int i_vert_thickness = input.int(defval=1, minval=1, maxval=5, title="Line Thickness", group="Verticle Line")
// TREND TABLE CUSTOMIZATION SETTINGS
bool i_display_trend = input.bool(defval=true, title="Display Trend Analysis", group="Trend Analysis")
color i_table_background_color = input.color(defval=color.black, title="Background Color", group="Trend Analysis")
color i_text_color_uptrend = input.color(defval=color.green, title="Up Trend Color", group="Trend Analysis")
color i_text_color_downtrend = input.color(defval=color.red, title="Down Trend Color", group="Trend Analysis")
color i_text_color_undetermined = input.color(defval=color.white, title="Undetermined Trend Color", group="Trend Analysis")
// }
// ===== CALCULATIONS ===== {
f_G(_data,_length) =>
var float g = 0.0
float betaDenom = 10 * (math.log(math.sum((math.max(high, close[1]) - math.min(low, close[1])), _length) / (ta.highest(high, _length) - ta.lowest(low, _length))) / math.log(_length))
float w = (2 * math.pi / _length)
float beta = (1 - math.cos(w)) / (math.pow(1.414, 2.0 / betaDenom) - 1 )
float alpha = (-beta + math.sqrt(beta * beta + 2 * beta))
g := math.pow(alpha, 4) * _data + 4 * (1 - alpha) * nz(g[1]) - 6 * math.pow(1 - alpha,2) * nz(g[2]) + 4 * math.pow(1 - alpha,3) * nz(g[3]) - math.pow( 1 - alpha,4) * nz(g[4])
float fgA = f_G(close,i_length) - f_G(close,i_length2)
float fgB = f_G(fgA,i_length3)
float fgD = fgA - fgB
// }
// ===== Plotting ===== {
// HISTOGRAM
plot(fgD, style = plot.style_columns, color = (fgD>=0 ? (fgD[1] < fgD ? i_col_grow_above : i_col_fall_above) : (fgD[1] < fgD ? i_col_grow_below : i_col_fall_below)))
// SIGANL LINES
fgAplot = plot(fgA,color = fgA > fgB ? i_signal_line_above : i_signal_line_below)
fgBplot = plot(fgB,color = fgA > fgB ? i_signal_line_above : i_signal_line_below)
// BAND
fill(fgAplot, fgBplot, color=fgA > fgB ? color.new(i_band_above, i_show_fill ? i_band_opacity : 100) : color.new(i_band_below, i_show_fill ? i_band_opacity : 100))
// VERTICLE LINE
if i_vert
if fgD > 0 and fgD[1] < 0
line.new(bar_index, fgD, bar_index, fgD * 1.01, extend = extend.both, color = i_vert_above, style = i_vert_style == "Dashed" ? line.style_dashed : i_vert_style == "Solid" ? line.style_solid : line.style_dotted, width = i_vert_thickness)
if fgD < 0 and fgD[1] > 0
line.new(bar_index, fgD, bar_index, fgD * 1.01, extend = extend.both, color = i_vert_below, style = i_vert_style == "Dashed" ? line.style_dashed : i_vert_style == "Solid" ? line.style_solid : line.style_dotted, width = i_vert_thickness)
// TREND TABLE
string trendText = ""
if math.max(fgA, fgB) < 0 and fgA < fgB
trendText := "Trend Down"
else if math.max(fgA, fgB) < 0 and fgA > fgB
trendText := "Trend Down Slowing"
else if (0 > fgA and 0 < fgB or 0 < fgA and 0 > fgB) and fgD > fgD[1]
trendText := "Trend Reversing"
else if math.min(fgA, fgB) > 0 and fgA > fgB
trendText := "Trend Up"
else if math.min(fgA, fgB) > 0 and fgA < fgB
trendText := "Trend Up Slowing"
else if math.min(fgA, fgB) > 0 and fgD > fgD[1]
trendText := "Trend Up Accelerating"
else if math.min(fgA, fgB) > 0 and fgA < fgB and fgD < fgD[1]
trendText := "Trend Up decelerating"
else
trendText := "Undetermined Trend"
var table trendDisplay = table.new(position=position.top_right, columns=1, rows=1, bgcolor=i_table_background_color)
if barstate.islast and i_display_trend
table.cell(table_id=trendDisplay, column=0, row=0, text=trendText, text_color=math.max(fgA, fgB) < 0 ? i_text_color_downtrend : math.min(fgA, fgB) > 0 ? i_text_color_uptrend : i_text_color_undetermined)
// } |
VPT Timeleft v.10 | https://www.tradingview.com/script/0YfGY6Rz-VPT-Timeleft-v-10/ | vptradingschool | https://www.tradingview.com/u/vptradingschool/ | 9 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vptradingschool
//@version=5
indicator("VPT Timeleft v1", overlay=true)
timeLeft = input(true, title ='Time Counter in Minutes')
// Counter in Minutes
secondsLeft = barstate.isrealtime ?
(time_close - timenow) / 1000 :
100
if (timeLeft == true)
liveGuide_label = label.new(x=bar_index, y=high, color=(secondsLeft < 59? #e60000: color.teal), textcolor=color.white, style=label.style_label_left)
label.set_text(id=liveGuide_label, text=(secondsLeft == 100? "❤": str.tostring ( int(secondsLeft/60) ) + "." + (math.round(secondsLeft % 60,0) < 10? "0" : "") + str.tostring( math.round(secondsLeft % 60,0) ) + " m"))
label.set_xy(liveGuide_label,bar_index[0] +3 ,close) // VPTDC instead of linePrice
label.delete(liveGuide_label[1])
|
GKYZ-Filtered, Non-Linear Regression MA [Loxx] | https://www.tradingview.com/script/OLXmph7m-GKYZ-Filtered-Non-Linear-Regression-MA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 640 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("GKYZ-Filtered, Non-Linear Regression MA [Loxx]",
shorttitle = "GKYZFNLRMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
nonLinearRegression(float src, int per)=>
float AvgX = 0
float AvgY = 0
float[] nlrXValue = array.new<float>(per, 0)
float[] nlrYValue = array.new<float>(per, 0)
for i = 0 to per - 1
array.set(nlrXValue, i, i)
array.set(nlrYValue, i, nz(src[i]))
AvgX += array.get(nlrXValue, i)
AvgY += array.get(nlrYValue, i)
AvgX /= per
AvgY /= per
float SXX = 0
float SXY = 0
float SYY = 0
float SXX2 = 0
float SX2X2 = 0
float SYX2 = 0
for i = 0 to per - 1
float XM = array.get(nlrXValue, i) - AvgX
float YM = array.get(nlrYValue, i) - AvgY
float XM2 = array.get(nlrXValue, i) * array.get(nlrXValue, i) - AvgX * AvgX
SXX += XM * XM
SXY += XM * YM
SYY += YM * YM
SXX2 += XM * XM2
SX2X2 += XM2 * XM2
SYX2 += YM * XM2
float tmp = 0
float ACoeff = 0
float BCoeff = 0
float CCoeff = 0
tmp := SXX * SX2X2 - SXX2 * SXX2
if tmp != 0
BCoeff := (SXY * SX2X2 - SYX2 * SXX2) / tmp
CCoeff := (SXX * SYX2 - SXX2 * SXY) / tmp
ACoeff := AvgY - BCoeff * AvgX - CCoeff * AvgX * AvgX
tmp := ACoeff + CCoeff
tmp
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * gkyzvol(len) * src
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(60, "Period", group = "Basic Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "GKYZFNLRMA", "Both", "None"], group= "Filter Settings")
filter = input.float(0.5, "Filter Multiple", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show Signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? gkyzFilter(src, filterperiod, filter) : src
out = nonLinearRegression(src, per)
out := filterop == "Both" or filterop == "GKYZFNLRMA" and filter > 0 ? gkyzFilter(out, filterperiod, filter) : out
sig = out[1]
goLong_pre = ta.crossover(out, sig)
goShort_pre = ta.crossunder(out, sig)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
colorout = contSwitch == 1 ? greencolor : redcolor
barcolor(colorbars ? colorout : na)
plot(out, "GKYZFNLRMA", color = colorout, linewidth = 3)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
Fourier Spectrometer of Price w/ Extrapolation Forecast [Loxx] | https://www.tradingview.com/script/Plhgucwi-Fourier-Spectrometer-of-Price-w-Extrapolation-Forecast-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 277 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("Fourier Spectrometer of Price w/ Extrapolation Forecast [Loxx]",
shorttitle = "FSPEF [Loxx]",
overlay = false,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
redcolor = #ff1100
orangecolor = #ff5d00
greencolor = #0cb51a
bluecolor = #2157f3
purplecolor = #673ab7
fuchsiacolor = #e91e63
yellowcolor = #ffdd00
specOpsLinearRegression(src, int i0, int i1, float[] aArr)=>
int aPeriod = 0
int rRetError = 0
float aVal_0 = 0
float aVal_1 = 0
float aB = 0
float aMaxDev = 0
float aStdError = 0
float aRSquared = 0
float x = 0
float y = 0
float y1 = 0
float y2 = 0
float sumy = 0
float sumx = 0
float sumxy = 0
float sumx2 = 0
float sumy2 = 0
float sumx22 = 0
float sumy22 = 0
float div1 = 0
float div2 = 0
aPeriod := i1 - i0 + 1
for int i = 0 to aPeriod - 1
y := nz(src[i0 + i])
x := i
sumy += y
sumxy += y * i
sumx += x
sumx2 += math.pow(x, 2)
sumy2 += math.pow(y, 2)
sumx22 := math.pow(sumx, 2)
sumy22 := math.pow(sumy, 2)
div1 := sumx2 * aPeriod - sumx22
div2 := math.sqrt((aPeriod * sumx2 - sumx22) * (aPeriod * sumy2 - sumy22))
//regression line
if div1 != 0.0
aB := (sumxy * aPeriod - sumx * sumy) / div1
aVal_0 := (sumy - sumx * aB) / aPeriod
aVal_1 := aVal_0 + aB * (aPeriod - 1)
rRetError += -1
else
rRetError += -1
//stderr & maxdev
aMaxDev := 0
aStdError := 0
for i = 0 to aPeriod - 1
y1 := nz(src[i0 + i])
y2 := aVal_0 + aB * i
aMaxDev := math.max(math.abs(y1 - y2), aMaxDev)
aStdError += math.pow(y1 - y2, 2)
aStdError := math.sqrt(aStdError / aPeriod)
//rsquared
if div2 != 0
aRSquared := math.pow((aPeriod * sumxy - sumx * sumy) / div2, 2)
else
rRetError += -2
for i = 0 to aPeriod - 1
y := nz(src[i0 + i])
x := aVal_0 + i * (aVal_1 - aVal_0) / aPeriod
array.set(aArr, i, y - x)
rRetError
specOpsArcTan(float aS, float aC)=>
float out = 0
while true
if not aS
out := 0
break
if not aC
if aS > 0
out := (math.atan(1) * 2)
break
else if (aS < 0)
out := (math.atan(1) * 6)
break
else
if aS > 0
if aC > 0
out := (math.atan(aS / aC))
break
else
out := (math.atan(aS / aC) + math.atan(1) * 4)
break
else
if aC > 0
out := (math.atan(aS / aC) + math.atan(1) * 8)
break
else
out := (math.atan(aS / aC) + math.atan(1) * 4)
break
out
specOpsFourier(float[] aArr)=>
int tN = array.size(aArr)
int tM = int(math.max(tN / 2, 1))
float[] aA = array.new<float>(tN, 0)
float[] aB = array.new<float>(tN, 0)
float[] aR = array.new<float>(tN, 0)
float[] aF = array.new<float>(tN, 0)
for ti = 1 to tM - 1
array.set(aA, ti, 0)
array.set(aB, ti, 0)
for tj = 0 to tN - 1
array.set(aA, ti, array.get(aA, ti) + array.get(aArr, tj) * math.sin(ti * 2 * math.pi * tj / tN))
array.set(aB, ti, array.get(aA, ti) + array.get(aArr, tj) * math.cos(ti * 2 * math.pi * tj / tN))
array.set(aA, ti, 2 * array.get(aA, ti) / tN)
array.set(aB, ti, 2 * array.get(aB, ti) / tN)
array.set(aR, ti, math.sqrt(math.pow(array.get(aA, ti), 2) + math.pow(array.get(aB, ti), 2)))
array.set(aF, ti, specOpsArcTan(array.get(aB, ti), array.get(aA, ti)))
[aA, aB, aR, aF]
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(500, "Period", maxval = 1000, minval = 64, group = "Basic Settings")
startFromBar = input.int(100, "Future Bars", maxval = 100, group = "Basic Settings")
freq1col = input.color(greencolor, "Frequency 1 Color", group = "UI Settings")
freq2col = input.color(redcolor, "Frequency 2 Color", group = "UI Settings")
freq3col = input.color(purplecolor, "Frequency 3 Color", group = "UI Settings")
freq4col = input.color(color.yellow, "Frequency 4 Color", group = "UI Settings")
freq5col = input.color(bluecolor, "Frequency 5 Color", group = "UI Settings")
freq6col = input.color(color.white, "Frequency 6 Color", group = "UI Settings")
freq7col = input.color(fuchsiacolor, "Frequency 7 Color", group = "UI Settings")
freq8col = input.color(color.aqua, "Frequency 8 Color", group = "UI Settings")
freq1width = input.int(4, "Frequency 1 Width", group = "UI Settings")
freq2width = input.int(3, "Frequency 2 Width", group = "UI Settings")
freq3width = input.int(2, "Frequency 3 Width", group = "UI Settings")
freq4width = input.int(1, "Frequency 4 Width", group = "UI Settings")
freq5width = input.int(1, "Frequency 5 Width", group = "UI Settings")
freq6width = input.int(1, "Frequency 6 Width", group = "UI Settings")
freq7width = input.int(1, "Frequency 7 Width", group = "UI Settings")
freq8width = input.int(1, "Frequency 8 Width", group = "UI Settings")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
float[] srcarr = array.new<float>(per + 1, 0)
float[] aArr = array.new<float>(per, 0)
var pvlines1 = array.new_line(0)
var pvlines2 = array.new_line(0)
var pvlines3 = array.new_line(0)
var pvlines4 = array.new_line(0)
var pvlines5 = array.new_line(0)
var pvlines6 = array.new_line(0)
var pvlines7 = array.new_line(0)
var pvlines8 = array.new_line(0)
if barstate.isfirst
for i = 0 to 61
array.push(pvlines1, line.new(na, na, na, na))
array.push(pvlines2, line.new(na, na, na, na))
array.push(pvlines3, line.new(na, na, na, na))
array.push(pvlines4, line.new(na, na, na, na))
array.push(pvlines5, line.new(na, na, na, na))
array.push(pvlines6, line.new(na, na, na, na))
array.push(pvlines7, line.new(na, na, na, na))
array.push(pvlines8, line.new(na, na, na, na))
drawlines(float[] arrin, array<line> linesarr, int startFromBar, color colorin, int linewidth)=>
skipperpv =
array.size(arrin) >= 1000 ? 11 :
array.size(arrin) >= 800 ? 10 :
array.size(arrin) >= 700 ? 9 :
array.size(arrin) >= 600 ? 8 :
array.size(arrin) >= 500 ? 7 :
array.size(arrin) >= 400 ? 6 :
array.size(arrin) >= 300 ? 5 :
array.size(arrin) >= 200 ? 4 :
array.size(arrin) >= 100 ? 2 : 1
i = 0
j = 0
while i < array.size(arrin) - skipperpv - 1 - startFromBar
if j > array.size(linesarr) - 1
break
pvline = array.get(linesarr, j)
line.set_xy1(pvline, bar_index - i - skipperpv + startFromBar, array.get(arrin, i + skipperpv + startFromBar))
line.set_xy2(pvline, bar_index - i + startFromBar, array.get(arrin, i+ startFromBar))
line.set_color(pvline, colorin)
if bar_index - i + startFromBar < last_bar_index
line.set_style(pvline, line.style_solid)
else
line.set_style(pvline, line.style_dotted)
line.set_width(pvline, linewidth)
i += skipperpv
j += 1
specOpsLinearRegression(src, startFromBar, startFromBar + per - 1, aArr)
if barstate.islast
temps = array.size(aArr)
[A, B, R, F] = specOpsFourier(aArr)
var float[] outbf1 = array.new<float>(temps + startFromBar + 1, 0)
var float[] outbf2 = array.new<float>(temps + startFromBar + 1, 0)
var float[] outbf3 = array.new<float>(temps + startFromBar + 1, 0)
var float[] outbf4 = array.new<float>(temps + startFromBar + 1, 0)
var float[] outbf5 = array.new<float>(temps + startFromBar + 1, 0)
var float[] outbf6 = array.new<float>(temps + startFromBar + 1, 0)
var float[] outbf7 = array.new<float>(temps + startFromBar + 1, 0)
var float[] outbf8 = array.new<float>(temps + startFromBar + 1, 0)
for i = 0 to temps - 1
int ii = i + startFromBar
float MA = src
array.set(outbf1, ii, nz(MA + (array.get(A, 1) * math.sin(1 * 2 * math.pi * i / (per - 1)) + array.get(B, 1) * math.cos(1 * 2 * math.pi * i /(per - 1)))))
array.set(outbf2, ii, nz(MA + (array.get(A, 2) * math.sin(2 * 2 * math.pi * i / (per - 1)) + array.get(B, 2) * math.cos(2 * 2 * math.pi * i /(per - 1)))))
array.set(outbf3, ii, nz(MA + (array.get(A, 3) * math.sin(3 * 2 * math.pi * i / (per - 1)) + array.get(B, 3) * math.cos(3 * 2 * math.pi * i /(per - 1)))))
array.set(outbf4, ii, nz(MA + (array.get(A, 4) * math.sin(4 * 2 * math.pi * i / (per - 1)) + array.get(B, 4) * math.cos(4 * 2 * math.pi * i /(per - 1)))))
array.set(outbf5, ii, nz(MA + (array.get(A, 5) * math.sin(5 * 2 * math.pi * i / (per - 1)) + array.get(B, 5) * math.cos(5 * 2 * math.pi * i /(per - 1)))))
array.set(outbf6, ii, nz(MA + (array.get(A, 6) * math.sin(6 * 2 * math.pi * i / (per - 1)) + array.get(B, 6) * math.cos(6 * 2 * math.pi * i /(per - 1)))))
array.set(outbf7, ii, nz(MA + (array.get(A, 7) * math.sin(7 * 2 * math.pi * i / (per - 1)) + array.get(B, 7) * math.cos(7 * 2 * math.pi * i /(per - 1)))))
array.set(outbf8, ii, nz(MA + (array.get(A, 8) * math.sin(8 * 2 * math.pi * i / (per - 1)) + array.get(B, 8) * math.cos(8 * 2 * math.pi * i /(per - 1)))))
drawlines(outbf1, pvlines1, startFromBar, freq1col, freq1width)
drawlines(outbf2, pvlines2, startFromBar, freq2col, freq2width)
drawlines(outbf3, pvlines3, startFromBar, freq3col, freq3width)
drawlines(outbf4, pvlines4, startFromBar, freq4col, freq4width)
drawlines(outbf5, pvlines5, startFromBar, freq5col, freq5width)
drawlines(outbf6, pvlines6, startFromBar, freq6col, freq6width)
drawlines(outbf7, pvlines7, startFromBar, freq7col, freq7width)
drawlines(outbf8, pvlines8, startFromBar, freq8col, freq8width)
|
Bollinger Bands | https://www.tradingview.com/script/1u5ufTRc-Bollinger-Bands/ | Amit_001 | https://www.tradingview.com/u/Amit_001/ | 110 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Amit_001
//@version=5
indicator(shorttitle="BB POS", title="Bollinger Band POS", overlay=true)
length = input.int(20, minval=1)
src = input(close, title="Source")
mult = input.float(1, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
aboveSDev = low[1] < (ta.sma(close[1], length) + (mult * ta.stdev(close[1], length))) and low > upper
belowSDev = high[1] > (ta.sma(close[1], length) - (mult * ta.stdev(close[1], length))) and high < lower
if (aboveSDev)
box.new(left=bar_index, top=high, right=bar_index+4, bottom=low, border_color=color.new(color.green,25), bgcolor=color.new(color.green,40))
if (belowSDev)
box.new(left=bar_index, top=high, right=bar_index+4, bottom=low, border_color=color.new(color.blue,45), bgcolor=color.new(color.blue,40)) |
Current Market Strength | https://www.tradingview.com/script/Y3m1h8QG-Current-Market-Strength/ | JaxonBest | https://www.tradingview.com/u/JaxonBest/ | 7 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JaxonBest
//@version=5
indicator("Current Market Strength", "CMS", false)
plcmt = 1
cv = open
tf = input.int(10, "Average", 2)
fhv = close
for i = 1 to tf
if close[i] < cv
cv := close[i]
plcmt += 1
if close[i] > fhv
fhv := close[i]
mrsi = ta.rsi(close, tf) / 10
psv = false
cms = plcmt + mrsi, style=plot.style_line
cms_med = ((cms - mrsi) / 2) + mrsi
sma_length = input.int(14, "SMA")
sma = ta.sma(cms_med, sma_length)
plot(cms_med, "CMS", color.orange)
plot(sma, "SCMS", color.blue) |
Indicateur C17V2 | https://www.tradingview.com/script/I5kxEYVg/ | W-Levrai | https://www.tradingview.com/u/W-Levrai/ | 14 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © W-Levrai
//@version=4
study("C17v2", overlay=true)
//voidlines=context
voidLines = input(true, "Context On/Off")
emaLines = input(true, "EMA (7, 8, 20, 21, 200, 800) On / Off")
//Color Gradient Code
//Shoutout to @LunaOwl for Making This!
//Red //Orange
Red_1 = color.new(#FF0000, 0), Orange_1 = color.new(#FF9800, 0)
Red_2 = color.new(#FF0000, 30), Orange_2 = color.new(#FF9800, 30)
Red_3 = color.new(#FF0000, 50), Orange_3 = color.new(#FF9800, 50)
Red_4 = color.new(#FF0000, 60), Orange_4 = color.new(#FF9800, 70)
Red_5 = color.new(#FF0000, 80), Orange_5 = color.new(#FF9800, 80)
//Yellow //Green
Yellow_1 = color.new(#FFE500, 0), Green_1 = color.new(#00FF00, 0)
Yellow_2 = color.new(#FFE500, 30), Green_2 = color.new(#00FF00, 30)
Yellow_3 = color.new(#FFE500, 50), Green_3 = color.new(#00FF00, 50)
Yellow_4 = color.new(#FFE500, 60), Green_4 = color.new(#00FF00, 70)
Yellow_5 = color.new(#FFE500, 80), Green_5 = color.new(#00FF00, 80)
//Blue //Indigo
Blue_1 = color.new(#4985E7, 0), Indigo_1 = color.new(#7A2BCE, 0)
Blue_2 = color.new(#4985E7, 30), Indigo_2 = color.new(#7A2BCE, 30)
Blue_3 = color.new(#4985E7, 50), Indigo_3 = color.new(#7A2BCE, 50)
Blue_4 = color.new(#4985E7, 60), Indigo_4 = color.new(#7A2BCE, 60)
Blue_5 = color.new(#4985E7, 80), Indigo_5 = color.new(#7A2BCE, 80)
//Purple
Purple_1 = color.new(#D12FAD, 0)
Purple_2 = color.new(#D12FAD, 30)
Purple_3 = color.new(#D12FAD, 50)
Purple_4 = color.new(#D12FAD, 60)
Purple_5 = color.new(#D12FAD, 80)
//Creates Color Variable //Creates Math Variable
var color c = na, var int k = na
k := nz(k[1], 1) //This Equation Allows the Colors to Loop
//This Code Loops Through 63 Shades of 7 Colors//
if k == 1
c := Red_5
if k == 2
c := Red_4
if k == 3
c := Red_3
if k == 4
c := Red_2
if k == 5
c := Red_1
if k == 6
c := Red_2
if k == 7
c := Red_3
if k == 8
c := Red_4
if k == 9
c := Red_5
if k == 10
c := Orange_5
if k == 11
c := Orange_4
if k == 12
c := Orange_3
if k == 13
c := Orange_2
if k == 14
c := Orange_1
if k == 15
c := Orange_2
if k == 16
c := Orange_3
if k == 17
c := Orange_4
if k == 18
c := Orange_5
if k == 19
c := Yellow_5
if k == 20
c := Yellow_4
if k == 21
c := Yellow_3
if k == 22
c := Yellow_2
if k == 23
c := Yellow_1
if k == 24
c := Yellow_2
if k == 25
c := Yellow_3
if k == 26
c := Yellow_4
if k == 27
c := Yellow_5
if k == 28
c := Green_5
if k == 29
c := Green_4
if k == 30
c := Green_3
if k == 31
c := Green_2
if k == 32
c := Green_1
if k == 33
c := Green_2
if k == 34
c := Green_3
if k == 35
c := Green_4
if k == 36
c := Green_5
if k == 37
c := Blue_5
if k == 38
c := Blue_4
if k == 39
c := Blue_3
if k == 40
c := Blue_2
if k == 41
c := Blue_1
if k == 42
c := Blue_2
if k == 43
c := Blue_3
if k == 44
c := Blue_4
if k == 45
c := Blue_5
if k == 46
c := Indigo_5
if k == 47
c := Indigo_4
if k == 48
c := Indigo_3
if k == 49
c := Indigo_2
if k == 50
c := Indigo_1
if k == 51
c := Indigo_2
if k == 52
c := Indigo_3
if k == 53
c := Indigo_4
if k == 54
c := Indigo_5
if k == 55
c := Purple_5
if k == 56
c := Purple_4
if k == 57
c := Purple_3
if k == 58
c := Purple_2
if k == 59
c := Purple_1
if k == 60
c := Purple_2
if k == 61
c := Purple_3
if k == 62
c := Purple_4
if k == 63
c := Purple_5
k := k + 1
if k > 63
k := 1
//Defines EMA Variables
ema7 = ema(close, 7)
ema8 = ema(close, 8)
ema20 = ema(close, 20)
ema21 = ema(close, 21)
ema200 = ema(close, 200)
ema800 = ema(close, 800)
//Defines Variables Used in Void Lines
basis = sma(close, 20)
twoDev = 2 * stdev(close, 20)
upper3 = basis + twoDev
lower3 = basis - twoDev
threeDev = 3 * stdev(close, 20)
upper4 = basis + threeDev
lower4 = basis - threeDev
//Plots Void Lines
plot(voidLines ? basis : na, "Basis", color.purple, editable=false)
p5 = plot(voidLines ? upper3 : na, "Upper 200%", c, editable=false)
p6 = plot(voidLines ? lower3 : na, "Lower 200%", c, editable=false)
p7 = plot(voidLines ? upper4 : na, "Upper 300%", c, editable=false)
p8 = plot(voidLines ? lower4 : na, "Lower 300%", c, editable=false)
fill(p7, p5, color.teal, 75)
fill(p8, p6, color.purple, 75)
//Plots EMA Lines
plot(emaLines ? ema7 : na, "EMA 7", color.red, 2)
plot(emaLines ? ema8 : na, "EMA 8", color.yellow, 2)
plot(emaLines ? ema20 : na, "EMA 20", color.green, 2)
plot(emaLines ? ema21 : na, "EMA 21", color.blue, 2)
plot(emaLines ? ema200: na, "EMA 200", color.white, 2)
plot(emaLines ? ema800 : na, "EMA 800", color.aqua, 2)
|
predictions_LUKE_MACVICAR | https://www.tradingview.com/script/QUpg6Y2x-predictions-LUKE-MACVICAR/ | civilOatmeal94139 | https://www.tradingview.com/u/civilOatmeal94139/ | 41 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © civilOatmeal94139
//@version=5
indicator("predictions", overlay=true)
var string predictionsInput = ' '
var string separator_space = ','
var float prediction = 12000
predictionsInput := input(" ")
array1 = str.split(predictionsInput, separator_space) // split by space character so there will be 3 elements in the array
var string labelText = na
labelText += '\nContent of array1 = ' + (array.get(array1,0))
for i = 0 to array.size(array1) - 1
prediction := str.tonumber(array.get(array1, i))
line.new(time, prediction, bar_index, prediction, xloc.bar_time, color=color.red)
|
[FrizLabz]PB OLvls | https://www.tradingview.com/script/PfJlWdXm-FrizLabz-PB-OLvls/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 68 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FFriZz
//@version=5
indicator('[FrizLabz]PB OLvls','[FrizLabz]PB OLvls',overlay=true,max_lines_count = 500,max_boxes_count = 500,max_labels_count = 500,max_bars_back = 500,explicit_plot_zorder = true)
days_i = input.int(1,'Days Visable',minval = 1)
regMarket_i = input.bool(true,'Reg. Market Opens')
color_i = input.color(#ffa500,'Reg Market Color')
preMarket_i = input.bool(true,'Premarket Opens')
colorP_i = input.color(#800080,'Pre Market Color')
label_i = input.bool(true,'Label On/Off')
format_i = input.string('E | MM-dd-yyyy','Label Format',tooltip = 'You can google "java date formatting" to find formatting examples')
var line[] aLine = array.new<line>()
var label[] aLabel = array.new<label>()
var line[] aLineP = array.new<line>()
var label[] aLabelP = array.new<label>()
formattedDate(series float timeInMs, series string format = "E | MM-dd-yyyy") =>
string result = str.format("{0,date," + format + "}", int(timeInMs))
if session.isfirstbar_regular and regMarket_i
if bar_index > 500
array.push(aLine,line.new(bar_index,open,last_bar_index + 20,open,xloc.bar_index,extend.none, color_i,line.style_solid,1))
if label_i
array.push(aLabel,label.new(last_bar_index + 20,open,
'[' + formattedDate(time,format_i) + ' | ' + str.tostring(open) + ']', style = label.style_label_left, color = color(na), textcolor = color_i,size = size.small))
if array.size(aLine) > days_i
line.delete(array.shift(aLine))
if label_i
label.delete(array.shift(aLabel))
if session.isfirstbar and preMarket_i
if bar_index > 500
array.push(aLineP,line.new(bar_index,open,last_bar_index + 20,open,xloc.bar_index,extend.none, colorP_i,line.style_solid,1))
if label_i
array.push(aLabelP,label.new(last_bar_index + 20,open,
'[' + formattedDate(time,format_i) + ' | ' + str.tostring(open) + ']', style = label.style_label_left, color = color(na), textcolor = colorP_i,size = size.small))
if array.size(aLineP) > days_i
line.delete(array.shift(aLineP))
if label_i
label.delete(array.shift(aLabelP))
//
|
Chop and explode (ps5) | https://www.tradingview.com/script/L7ydBiKM-Chop-and-explode-ps5/ | capissimo | https://www.tradingview.com/u/capissimo/ | 308 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo
//@version=5
indicator('Chop and explode (ps5)', '', false)
// Description:
// This is a renovated version of my previous mod that was based on the original script from fhenry0331.
// Added are:
// - a data cleaning function
// - a seasonal random index function
// - an updated scaler and
// - a signalling procedure.
// The following description is moved here from the old script.
// The purpose of this script is to decipher chop zones from runs/movement/explosion spans.
// The chop is RSI movement between 40 and 60. Tight chop is RSI movement between 45 and 55.
// There should be an explosion after RSI breaks through 60 (long) or 40 (short).
// Tight chop bars are colored gray, a series of gray bars indicates a tight consolidation and
// should explode imminently. The longer the chop the longer the explosion will go for.
// The tighter the better. Loose chop (jig saw/gray bars on the silver background) will range
// between 40 and 60. The move begins with green and red bars.
// Couple it with your trading system to help stay out of chop and enter when there is a movement.
//-- Inputs
BASE = input.source(close, 'Dataset', inline='data')
CLN = input.bool (false, 'Clean It', inline='data')
LAG = input.int (10, 'Lookback [2..n]', 2)
MMX = input.int (20, 'Minimax [2..n]', 2)
LABELS = input.bool (true, 'Labels', inline='b')
SRI = input.bool (false, 'SRI', inline='b')
minlen = input.int (5, 'Season', 1, group='Seasonal Random Index')
maxlen = input.int (50, 'Lookback', 1, group='Seasonal Random Index')
pct = input.float (10., 'Adaptation (%)', 0, 100, group='Seasonal Random Index') / 100.0
//-- Constants
var int BUY = +1
var int SELL = -1
var int HOLD = 0
//-- Variables
var int signal = HOLD
//-- Functions
clean(data) =>
pi = 2 * math.asin(1)
hpPeriod = .00001
alpha = (1 - math.sin(2 * pi / hpPeriod)) / math.cos(2 * pi / hpPeriod)
hp = 0.0
hp := bar_index <= 5 ? data : (0.5 * (1 + alpha) * (data - data[1])) + (alpha * hp[1])
res = bar_index <= 5 ? data : (hp + (2 * hp[1]) + (3 * hp[2]) + (3 * hp[3]) + (2 * hp[4]) + hp[5]) / 12
res
minimax(X, p, min, max) =>
hi = ta.highest(X, p), lo = ta.lowest(X, p)
(max - min) * (X - lo)/(hi - lo) + min
norm(x, p) => (x - ta.lowest(x, p)) / (ta.highest(x, p) - ta.lowest(x, p))
green(g) => g>9 ? #006400 : g>8 ? #1A741A : g>7 ? #338333 : g>6 ? #4D934D : g>5 ? #66A266 : g>4 ? #80B280 : g>3 ? #99C199 : g>2 ? #B3D1B3 : g>1? #CCE0CC : #E6F0E6
red(g) => g>9 ? #E00000 : g>8 ? #E31A1A : g>7 ? #E63333 : g>6 ? #E94D4D : g>5 ? #EC6666 : g>4 ? #F08080 : g>3 ? #F39999 : g>2 ? #F6B3B3 : g>1? #F9CCCC : #FCE6E6
//-- Logic
float cleaned = CLN ? clean(BASE) : BASE
float data = minimax(cleaned, MMX, 1, 100) // In general, the best solution lies in scaling the price
float up = ta.rma(+math.max(ta.change(data), 0), LAG)
float down = ta.rma(-math.min(ta.change(data), 0), LAG)
float rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
bool long = rsi > 60
bool short = rsi < 40
signal := long ? BUY : short ? SELL : nz(signal[1])
changed = ta.change(signal)
bool startedLong = changed and signal==BUY
bool endedLong = changed and signal==SELL
bool startedShort = changed and signal==SELL
bool endedShort = changed and signal==BUY
color long_range = long ? green(8) : na
color short_range = short ? red(8) : na
//== Dynamic Seasonal Random Index
dlen = math.avg(minlen, maxlen) //-- dynamic len
dlen := ta.atr(10) > ta.atr(40) ? math.max(minlen, dlen * (1 - pct)) : math.min(maxlen, dlen * (1 + pct))
d = int(dlen[0])
sri = cleaned * (cleaned / ( (cleaned + cleaned[minlen]) / 2 )) //-- Seasonal random index
seasoned = norm(sri, d) * 100
deseasoned = norm(cleaned - sri, d) * 100
avs = math.avg(seasoned, deseasoned)
cross = ta.cross(seasoned, deseasoned)
//-- Visuals
plot(0, '', na), plot(100, '', na) //-- dummies
hline(50, '', color.silver, hline.style_dotted)
l1 = hline(70, '', color.silver, hline.style_dotted)
l2 = hline(30, '', color.silver, hline.style_dotted)
l3 = hline(60, '', color.new(color.silver, 100), hline.style_dotted)
l4 = hline(40, '', color.new(color.silver, 100), hline.style_dotted)
l5 = hline(55, '', color.new(color.silver, 100), hline.style_dotted)
l6 = hline(45, '', color.new(color.silver, 100), hline.style_dotted)
fill(l1, l3, color.new(color.green, 60))
fill(l3, l4, color.new(color.silver, 95))
fill(l4, l2, color.new(color.red, 60))
fill(l5, l6, color.new(color.silver, 80))
fill(plot(SRI ? seasoned : na, '', color.new(color.blue,100)),
plot(SRI ? deseasoned : na, '', color.new(color.blue,100)), color.new(seasoned > deseasoned ? green(4) : red(4), 50))
plot(SRI ? avs : na, '', color.silver)
plot(SRI and cross ? avs : na, '', color.black, 1, plot.style_circles)
plot(rsi, '', color.black)
plot(rsi, '', long_range, 3, plot.style_linebr)
plot(rsi, '', short_range, 3, plot.style_linebr)
plotshape(LABELS and startedLong, 'Long', shape.labelup, location.bottom, color.blue, 0, size=size.tiny)
plotshape(LABELS and startedShort, 'Short', shape.labeldown, location.top, color.red, 0, size=size.tiny)
//-- Notification
if changed and signal==BUY
alert('Buy Alert', alert.freq_once_per_bar) // alert.freq_once_per_bar_close
if changed and signal==SELL
alert('Sell Alert', alert.freq_once_per_bar)
alertcondition(startedLong, 'Buy', 'Go long!')
alertcondition(startedShort, 'Sell', 'Go short!')
//alertcondition(startedLong or startedShort, 'Alert', 'Deal Time!') |
RSI + Moving Average | https://www.tradingview.com/script/6uX72IJr-RSI-Moving-Average/ | mojotv1 | https://www.tradingview.com/u/mojotv1/ | 100 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mojotv1
//@version=5
indicator("RSI + Moving Average","RSI+MA", timeframe="", timeframe_gaps=false)
// RSI
i_rsi_show = input.bool(true, title='Show RSI', inline='rsishow', group='RSI')
i_rsi_color = input.color(color.red, title='', inline='rsishow', group='RSI')
i_rsi_length = input.int(34, 'RSI Length', inline='rsishow', group='RSI')
// MA №1
i_ma_show = input.bool(true, title='MA №1', inline='ma1', group='Moving Averages')
i_ma_color = input.color(color.blue, title='', inline='ma1', group='Moving Averages')
i_ma_type = input.string("HMA (Hull)", title="", inline="ma1", options=["HMA (Hull)","SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Moving Averages")
i_ma_length = input.int(55, '', inline='ma1', group='Moving Averages')
// MA №2
i_ma2_show = input.bool(false, title='MA №2', inline='ma2', group='Moving Averages')
i_ma2_color = input.color(color.white, title='', inline='ma2', group='Moving Averages')
i_ma2_type = input.string("HMA (Hull)", title="", inline="ma2", options=["HMA (Hull)","SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Moving Averages")
i_ma2_length = input.int(110, '', inline='ma2', group='Moving Averages')
// MA №3
i_ma3_show = input.bool(false, title='MA №3', inline='ma3', group='Moving Averages')
i_ma3_color = input.color(color.rgb(186, 104, 200, 0), title='', inline='ma3', group='Moving Averages')
i_ma3_type = input.string("VWMA", title="", inline="ma3", options=["HMA (Hull)","SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Moving Averages")
i_ma3_length = input.int(55, '', inline='ma3', group='Moving Averages')
// Horizontal Areas
i_show_center = input.bool(true, title='Show Center Line', group='Horizontal Areas')
i_show_color_fills = input.bool(true, title='Show Area Color Fills', group='Horizontal Areas')
// Over Bought
i_show_over_bought_lines = input.bool(true, title='', inline='ob', group='Horizontal Areas')
i_over_bought = input.int(55, 'Over Bought', inline='ob', group='Horizontal Areas')
i_over_bought_top = input.int(70, 'Top', inline='ob', group='Horizontal Areas')
// Over Sold
i_show_over_sold_lines = input.bool(true, title='', inline='os', group='Horizontal Areas')
i_over_sold = input.int(45, 'Over Sold', inline='os', group='Horizontal Areas')
i_over_sold_bottom = input.int(30, 'Bottom', inline='os', group='Horizontal Areas')
// Fills
// WARNING:Using Color Inputs causes the fill to not show for future bars past the current bar.
// i_show_color_fills = input.bool(true, title='Show Area Color Fills', group='Area Fills')
// i_over_bought_color = input.color(color.rgb(0, 230, 118, 80), 'Over Bought Fill', inline='fill', group='Area Fills')
// i_center_color = input.color(color.rgb(255, 235, 59, 80), 'Center Fill', inline='fill', group='Area Fills')
// i_over_sold_color = input.color(color.rgb(255, 82, 82, 80), '', inline='fill', group='Area Fills')
// Signals
i_show_breakout = input.bool(true, 'Show Breakout Signals', group='Signals')
// Breakout Signal
i_up_signal_color = input.color(color.lime, 'Up Signal', inline='upsignal', group='Signals')
i_up_signal_size = input.int(4, title='Size', minval=1, maxval=10, inline='upsignal', group='Signals')
i_dn_signal_color = input.color(color.fuchsia, 'Down Signal', inline='dnsignal', group='Signals')
i_dn_signal_size = input.int(4, title='Size', minval=1, maxval=10, inline='dnsignal', group='Signals')
// Cross MA №1
i_show_cross = input.bool(true, 'Show RSI & MA №1 Cross', group='Signals')
i_up_cross_color = input.color(color.lime, 'Up Cross', inline='upcross', group='Signals')
i_up_cross_size = input.int(4, title='Size', minval=1, maxval=10, inline='upcross', group='Signals')
i_dn_cross_color = input.color(color.fuchsia, 'Down Cross', inline='dncross', group='Signals')
i_dn_cross_size = input.int(4, title='Size', minval=1, maxval=10, inline='dncross', group='Signals')
// Cross MA №2
i_show_cross2 = input.bool(false, 'Show RSI & MA №2 Cross', group='Signals')
i_up_cross2_color = input.color(color.lime, 'Up Cross', inline='upcross2', group='Signals')
i_up_cross2_size = input.int(4, title='Size', minval=1, maxval=10, inline='upcross2', group='Signals')
i_dn_cross2_color = input.color(color.fuchsia, 'Down Cross', inline='dncross2', group='Signals')
i_dn_cross2_size = input.int(4, title='Size', minval=1, maxval=10, inline='dncross2', group='Signals')
// Cross MA №3
i_show_cross3 = input.bool(false, 'Show RSI & MA №3 Cross', group='Signals')
i_up_cross3_color = input.color(color.lime, 'Up Cross', inline='upcross3', group='Signals')
i_up_cross3_size = input.int(4, title='Size', minval=1, maxval=10, inline='upcross3', group='Signals')
i_dn_cross3_color = input.color(color.fuchsia, 'Down Cross', inline='dncross3', group='Signals')
i_dn_cross3_size = input.int(4, title='Size', minval=1, maxval=10, inline='dncross3', group='Signals')
ma(source, length, type) =>
type == "HMA (Hull)" ? ta.hma(source, length) :
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) :
na
rsi = ta.rsi(close, i_rsi_length)
upSignal = ta.crossover(rsi, i_over_sold) ? i_over_sold : float(na)
dnSignal = ta.crossunder(rsi, i_over_bought) ? i_over_bought : float(na)
rsi_ma = i_ma_show ? ma(rsi, i_ma_length, i_ma_type) : na
rsi_ma2 = i_ma2_show ? ma(rsi, i_ma2_length, i_ma2_type) : na
rsi_ma3 = i_ma3_show ? ma(rsi, i_ma3_length, i_ma3_type) : na
upCross = i_ma_show ? ta.crossover(rsi, rsi_ma) : na
dnCross = i_ma_show ? ta.crossunder(rsi, rsi_ma) : na
upCross2 = i_ma2_show ? ta.crossover(rsi, rsi_ma2) : na
dnCross2 = i_ma2_show ? ta.crossunder(rsi, rsi_ma2) : na
upCross3 = i_ma3_show ? ta.crossover(rsi, rsi_ma3) : na
dnCross3 = i_ma3_show ? ta.crossunder(rsi, rsi_ma3) : na
// Note: Using Display to control visibility causes shifting of the area to top of the area instead of 100 and 0.
// var hl_ob = hline(i_over_bought, title='Over Bought', color=color.yellow, display=i_show_over_bought_lines?display.all:display.none)
// var hl_obt = hline(i_over_bought_top, title='Over Bought Top', color=color.lime, display=i_show_over_bought_lines?display.all:display.none)
// var hl_ctr = hline(50, title='Center', color=color.gray, display=i_show_center?display.all:display.none)
// var hl_os = hline(i_over_sold, title='Over Sold', color=color.yellow, display=i_show_over_sold_lines?display.all:display.none)
// var hl_osb = hline(i_over_sold_bottom, title='Over Sold Bottom', color=color.red, display=i_show_over_sold_lines?display.all:display.none)
// Note: Using transparency to hide ob/os lines, otherwise scale can shift
var hl_ob = hline(i_over_bought, title='Over Bought', color=i_show_over_bought_lines ? color.yellow : color.new(color.yellow, 100))
var hl_obt = hline(i_over_bought_top, title='Over Bought Top', color=i_show_over_bought_lines ? color.lime : color.new(color.lime, 100))
var hl_ctr = hline(50, title='Center', color=i_show_center ? color.gray : color.new(color.gray,100))
var hl_os = hline(i_over_sold, title='Over Sold', color=i_show_over_sold_lines ? color.yellow : color.new(color.yellow, 100))
var hl_osb = hline(i_over_sold_bottom, title='Over Sold Bottom', color=i_show_over_sold_lines ? color.red : color.new(color.red, 100))
// fill(hl_ob, hl_obt, title='Over Bought Fill', color=i_over_bought_color, display=i_show_color_fills?display.all:display.none)
// fill(hl_ob, hl_os, title='Center Fill', color=i_center_color, display=i_show_color_fills?display.all:display.none)
// fill(hl_os, hl_osb, title='Over Sold Fill', color=i_over_sold_color, display=i_show_color_fills?display.all:display.none)
fill(hl_ob, hl_obt, title='Over Bought Fill', color=color.rgb(0, 230, 118, 80), display=i_show_color_fills?display.all:display.none)
fill(hl_ob, hl_os, title='Center Fill', color=color.rgb(255, 235, 59, 80), display=i_show_color_fills?display.all:display.none)
fill(hl_os, hl_osb, title='Over Sold Fill', color=color.rgb(255, 82, 82, 80), display=i_show_color_fills?display.all:display.none)
plot(rsi, title='RSI', color=i_rsi_color, linewidth=2, display=i_rsi_show?display.all:display.none)
plot(rsi_ma, title='RSI №1', color=i_ma_color, linewidth=2, display=i_ma_show?display.all:display.none)
plot(rsi_ma2, title='RSI №2', color=i_ma2_color, linewidth=2, display=i_ma2_show?display.all:display.none)
plot(rsi_ma3, title='RSI №3', color=i_ma3_color, linewidth=2, display=i_ma3_show?display.all:display.none)
plot(i_show_breakout and upSignal ? rsi : na, title="Up Signal", color=i_up_signal_color, style=plot.style_circles, linewidth=i_up_signal_size)
plot(i_show_breakout and dnSignal ? rsi : na, title="Dn Signal", color=i_dn_signal_color, style=plot.style_circles, linewidth=i_dn_signal_size)
plot(i_show_cross and upCross ? rsi_ma : na, title="Up Cross №1", color=i_up_cross_color, style=plot.style_cross, linewidth=i_up_cross_size)
plot(i_show_cross and dnCross ? rsi_ma : na, title="Dn Cross №1", color=i_dn_cross_color, style=plot.style_cross, linewidth=i_dn_cross_size)
plot(i_show_cross2 and upCross2 ? rsi_ma2 : na, title="Up Cross №2", color=i_up_cross2_color, style=plot.style_cross, linewidth=i_up_cross2_size)
plot(i_show_cross2 and dnCross2 ? rsi_ma2 : na, title="Dn Cross №2", color=i_dn_cross2_color, style=plot.style_cross, linewidth=i_dn_cross2_size)
plot(i_show_cross3 and upCross3 ? rsi_ma3 : na, title="Up Cross №3", color=i_up_cross3_color, style=plot.style_cross, linewidth=i_up_cross3_size)
plot(i_show_cross3 and dnCross3 ? rsi_ma3 : na, title="Dn Cross №3", color=i_dn_cross3_color, style=plot.style_cross, linewidth=i_dn_cross3_size)
|
Range Detector Indicator [Misu] | https://www.tradingview.com/script/O9eCvZR0-Range-Detector-Indicator-Misu/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 1,340 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Author : @Misu
// @version=5
indicator("Range Detector Indicator [Misu]", shorttitle="Range DI [Misu]", overlay=true)
import Fontiramisu/fontilab/12 as fontilab
// import Fontiramisu/fontLib/87 as fontilab
// ] —————— Input Vars —————— [
// Get user input
var devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot."
var depthTooltip = "The minimum number of bars that will be taken into account when analyzing pivots."
src = input.source(close, "Source", group="Settings")
thresholdMultiplier = input.float(title="Deviation", defval=2.5, minval=0, tooltip=devTooltip, group="Pivot Settings")
depth = input.int(title="Depth", defval=50, minval=1, tooltip=depthTooltip, group="Pivot Settings")
isRange = input.bool(true, "Activate Range Detection", group = "Range Settings")
rPerOffset = input.float(title="Bands % Offset", defval=0.5, step=0.1, group="Trend Settings")
colorbars = input.bool(true, "Color Bars", group = "UI Settings")
upperBShow = input.bool(true, "Upper Band", group = "UI Settings")
lowerBShow = input.bool(true, "Lower Band", group = "UI Settings")
midBShow = input.bool(false, "Mid Band", group = "UI Settings")
// ] —————— Find Dev Pivots —————— [
// Prepare pivot variables
var line lineLast = na
var int iLast = 0 // Index last
var int iPrev = 0 // Index previous
var float pLast = 0 // Price last
var float pLastHigh = 0 // Price last
var float pLastLow = 0 // Price last
var isHighLast = false // If false then the last pivot was a pivot low
isPivotFound = false
// Get pivot information from dev pivot finding function
[dupLineLast, dupIsHighLast, dupIPrev, dupILast, dupPLast, dupPLastHigh, dupPLastLow] =
fontilab.getDeviationPivots(thresholdMultiplier, depth, lineLast, isHighLast, iLast, pLast, true, close, high, low)
if not na(dupIsHighLast)
lineLast := dupLineLast
isHighLast := dupIsHighLast
iPrev := dupIPrev
iLast := dupILast
pLast := dupPLast
pLastHigh := dupPLastHigh
pLastLow := dupPLastLow
isPivotFound := true
// ] —————— Find Trend —————— [
var tDirUp = true
var pDirStrike = 0
var upB = close
var lowB = close
var midB = close
var nStrike = isRange ? 2 : 1
[midBDup, upBDup, lowBDup, pDirStrikeDup, tDirUpDup] = fontilab.getInterTrend(src, upB, lowB, pLast, tDirUp, pDirStrike, isPivotFound, isHighLast, nStrike, rPerOffset, depth)
pDirStrike := nz(pDirStrikeDup)
tDirUp := nz(tDirUpDup)
upB := nz(upBDup)
lowB := nz(lowBDup)
midB := nz(midBDup)
var stateITB = 0
stateITB := pDirStrike < nStrike ? 0 : not tDirUp ? -1 : tDirUp == 1 ? 1 : nz(stateITB[1])
isTurnGreenITB = (stateITB[1] == 0 or stateITB[1] == -1) and stateITB == 1
isTurnRedITB = (stateITB[1] == 0 or stateITB[1] == 1) and stateITB == -1
isTurnOrangeITB = (stateITB[1] == 1 or stateITB[1] == -1) and stateITB == 0
// ] —————— Plot —————— [
var color colorTrend = na
colorTrend := pDirStrike < nStrike ? color.orange : not tDirUp ? color.red : tDirUp == 1 ? color.green : nz(colorTrend[1])
barcolor(colorbars ? colorTrend : na)
plot(upperBShow ? upB : na, "Upper Band", color = colorTrend, linewidth = 2)
plot(lowerBShow ? lowB : na, "Lower Band", color = colorTrend, linewidth = 2)
plot(midBShow ? midB : na, "Mid Band", color = colorTrend, linewidth = 2)
if isTurnGreenITB
label.new(x = bar_index, y = low - (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "L", style = label.style_label_up, color = color.green, size = size.small, textcolor = color.white, textalign = text.align_center)
else if isTurnRedITB
label.new(x = bar_index, y = high + (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "S", style = label.style_label_down, color = color.red, size = size.small, textcolor = color.white, textalign = text.align_center)
else if isTurnOrangeITB
label.new(x = bar_index, y = high + (ta.atr(30) * 0.3), xloc = xloc.bar_index, text = "R", style = label.style_label_down, color = color.orange, size = size.small, textcolor = color.white, textalign = text.align_center)
// ] —————— Alerts —————— [
alertcondition(isTurnGreenITB, title = "Long", message = "Pivot Trend Bands [Misu]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(isTurnRedITB, title = "Short", message = "Pivot Trend Bands [Misu]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(isTurnOrangeITB, title = "Range", message = "Pivot Trend Bands [Misu]: Range\nSymbol: {{ticker}}\nPrice: {{close}}")
// ]
|
True Strength Index | https://www.tradingview.com/script/AxLDyqqp-True-Strength-Index/ | sxiong1111 | https://www.tradingview.com/u/sxiong1111/ | 81 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sxiong1111
// Script Created On: 9/23/2022
// Script Updated On: 10/5/2022
// Script Version: 1.6
// Description: True Strength Index formula/calculation derived from Investopedia (https://www.investopedia.com/terms/t/tsi.asp)
// The variables and calculations derived from the same exact formula shown from Investopedia site above. Please see the site above for reference information and more information about the True Strength Index.
// The basics of the True Strength Index is utilizing three EMA's. The standard EMA's used are 13, 13 and 25. Then it is smoothed to create a price direction that syncs with the current market trend.
// Key Takeaways of the True Strength Indicator (detailed information can be found on the Investopedia site):
// - TSI is a technical momentum oscillator to identify trends, reversals and can help determine overbought & oversold levels.
// - If above the zero line, it can be thought that the security is in a bull trend and bearish if otherwise.
// - TSI does have a weakness, as the signals shown can generate false signals. Investopedia recommends that the TSI indicator shouldn't be used alone, but with other technical indicator(s) and/or utilizing price action.
//
// Personally, I disagree with the general consensus of just plopping 2 additional lines at fixed levels and call it good as oversold or overbought levels.
// With a couple hours of tinkering & experimentation, I think I've came up with a better oversold and overbought levels (which could probably be optimized further). I'm maintaining 2 other different versions with different algorithms (unpublished for my own use for testing purposes).
// Please note that the oversold & overbought calculations/levels used in this indicator does not follow any official documents or recommendations.
// The only thing shared between this and the original TSI design by William Blau is the number '30' for the oversold/overbought level threshold. I'm just using it in a different manner with this indicator, completely different from the original intention of the True Strength Indicator.
//
// With version 1.6 and in a continued effort to support and improve this indicator, I've decided to make a couple more feature changes/updates starting with this version and not just add some cosmetic changes.
//
// How to Determine Oversold and Overbought Levels?
// Using Version 1 (this version unchanged from the 1.5 public release):
// - If the oversold/overbought line crosses either above or below the TSI line (not just above the TSI moving average line, but also above the TSI line as well), then you are in either oversold or overbought territory.
// - With version 1 of the oversold/overbought levels, you may see the initial spike up/down indicating a strong volume trend upwards/downwards and then slowly fading. The mountain/peaks you see can give you an edge in guessing an entry (or re-entry point).
// - Look for double/triple/quadruple tops/bottoms, followed by a fade back into the TSI line. This indicates a potential reversal. Weak and stocks trending sideways may not even peak below/above the TSI line.
// - Since different chart windows with different timeframes can yield different results, ideally, you'd want to configure the settings to where the highest or lowest point of the security price just about intersects with the TSI line.
// - So the initial reversal has a high mountain/peak and as the security's price starts to reverse, the overbought/oversold line will eventually fade towards the TSI line (ultimately, intersecting it).
//
// Using Version 2 (new with the 1.6 public release):
// - Sorry, still experimenting with the 2nd iteration of the oversold & overbought levels (this is being worked on through different unpublished versions).
//
// New with version 1.6 is a trend direction helper, as sometimes the True Strength Index can often generate false signals (if used alone). By enabling the helper, a mid-line will be shown that generally bounces between the TSI line and the TSI moving average and the color shown here denotes the trend direction.
// Yes, the original TSI trend can often show a bearish or bullish trend, yet the security price can move into the opposite direction. This is why the True Strength Index indicator can sometimes provide false signals. By enabling the trend direction helper, the color of this mid-line can help point you into a potential
// trend reversal, while the main TSI indicator is showing the complete opposite. Keep in mind that if enabling the trend direction helper on lower time frames, you can get that rapid succession of alternating colors between bullish and bearish signals.
//@version=5
indicator(title = "True Strength Index", shorttitle = "TSI", timeframe = "", timeframe_gaps = true, overlay = false)
// User Input
tsi_mode = input.bool(title = "Use Original TSI Design Concept?", defval = true, tooltip = "If enabled, this indicator intends to replicate the original design by William Blau's True Strength Index (but not at 100% of Blau's original design concept, since there's quite a few different customizations).\n\nIf disabled, the modified version will be used, which creates mountains/peaks, which closely follows price action (keeping everything else the same). If using the modified version, you can disable the fill color for better visual clarity (if the lines are too jagged).", group = "True Strength Index Settings")
tsi_maMode = input.string(title = "Moving Average", defval = "EMA", options = ["EMA", "HULL 1", "HULL 2"], tooltip = "The original design concept of the True Strength Indicator is based on the Exponential Moving Average.\n\n● EMA = Use EMA for everything\n\n● HULL 1 = Use HULL MA for everything\n\n● HULL 2 = Use HULL MA; the main ma line stays as EMA", group = "True Strength Index Settings")
tsi_pcpModeSetting = input.int(title = "Closing Price Lookback", defval = 1, options = [1, 2, 3], tooltip = "The original design concept of the True Strength Indicator takes account only the latest prior closing price along with the current closing price. By averaging the prior two or three closing prices, you can achieve a bit more of a smoothing effect allowing you to stay in the trade a bit longer for potential maximum gain. Of course, the opposite can be true, potentially wiping some gains.\n\nThe default value is 1 and the difference between setting this at 2 or 3, aside from leaving it at 1 is nearly neglibile.", group = "True Strength Index Settings")
tsi_smoothS = input.int(title = "TSI MA Smoothing (Fast)", defval = 13, tooltip = "This is the fast EMA is used for the TSI smoothing. The default value is 13.", group = "True Strength Index Settings")
tsi_smoothL = input.int(title = "TSI MA Smoothing (Slow)", defval = 25, tooltip = "This is the slow EMA is used for the TSI smoothing. The default value is 25.", group = "True Strength Index Settings")
tsi_ema = input.int(title = "Moving Average", defval = 13, tooltip = "This is the main TSI moving average line. The default value is 13.\n\nPlease note that since this factors in the TSI value, this moving average line does not represent a normal moving average line (whether that's an Exponential Moving Average or HULL Moving Average).", group = "True Strength Index Settings")
tsi_zeroLine = input.bool(title = "Show the Zero Line?", defval = false, tooltip = "Shows or hides the zero line.", group = "True Strength Index Settings")
tsi_zeroLineColor = input.color(color.new(#FFF72C, 80), title = "Zero Line Color", tooltip = "You can change the zero line color here.", group = "True Strength Index Settings")
tsi_zeroLineWidth = input.int(title = "Zero Line Thickness", defval = 1, options = [1, 2, 3, 4, 5], tooltip = "You can change the zero line thickness here.", group = "True Strength Index Settings")
tsi_lineWidth = input.int(title = "Line Thickness", defval = 1, options = [1, 2, 3, 4, 5], tooltip = "You can change the line thickness for the TSI lines here.", group = "True Strength Index Line & Color Settings")
tsi_maLineBold = input.bool(title = "Accentuate the TSI Moving Average Line?", defval = false, tooltip = "If enabled, the TSI moving average line will have an extra added line thickness for increased visibility.", group = "True Strength Index Line & Color Settings")
tsi_curlup = input.color(color.new(#FFEB3B, 60), title = "TSI Curl Line Color", tooltip = "", group = "True Strength Index Line & Color Settings", inline = "1")
tsi_curldn = input.color(color.new(#FFEB3B, 60), title = "", tooltip = "The color on the left corresponds to the TSI curl line bullish color. The color on the right corresponds to the TSI curl line bearish color.", group = "True Strength Index Line & Color Settings", inline = "1")
tsi_nocurl = input.color(color.new(#9598A1, 60), title = "TSI Line Color", tooltip = "", group = "True Strength Index Line & Color Settings", inline = "2")
tsi_stbull = input.color(color.new(#00BCD4, 60), title = "", tooltip = "", group = "True Strength Index Line & Color Settings", inline = "2")
tsi_stbear = input.color(color.new(#E91E63, 60), title = "", tooltip = "The color on the left corresponds to the neutral TSI line color. The color in the middle corresponds to the bullish TSI line color. The color on the right corresponds to the bearish TSI line color.", group = "True Strength Index Line & Color Settings", inline = "2")
tsi_mabull = input.color(color.new(#00BCD4, 10), title = "TSI Moving Average Line Color", tooltip = "", group = "True Strength Index Line & Color Settings", inline = "3")
tsi_mabear = input.color(color.new(#E91E63, 10), title = "", tooltip = "The color on the left corresponds to the bullish TSI moving average line color. The color on the right corresponds to the bearish TSI moving average line color.", group = "True Strength Index Line & Color Settings", inline = "3")
tsi_fcbull = input.color(color.new(#00BCD4, 80), title = "Fill Color", tooltip = "", group = "True Strength Index Line & Color Settings", inline = "4")
tsi_fcbear = input.color(color.new(#E91E63, 80), title = "", tooltip = "The color on the left corresponds to the bullish TSI fill color. The color on the right corresponds to the bearish TSI fill color.", group = "True Strength Index Line & Color Settings", inline = "4")
tsi_fchide = input.bool(title = "Hide the Fill Color?", defval = false, tooltip = "You can quickly enable and disable the fill color here. This is purely cosmetic and has no effect on the functionality of this indicator.", group = "True Strength Index Line & Color Settings")
tsi_ooLevelEN = input.bool(title = "Enable the Oversold & Overbought Lines?", defval = false, tooltip = "If enabled, the oversold and overbought lines will be shown.", group = "True Strength Index Oversold & Overbought Settings")
tsi_ooLevelMD = input.string(title = "Oversold & Overbought Mode", defval = "Scalp", options = ["Scalp", "Day Trade", "Swing Short", "Swing Long", "Eternity"], tooltip = "Oversold and overbought levels can be configured in different modes. To maximize the effectiveness of this setting, please ensure the chart window you're applying this indicator to has the appropriate timeframe or the timeframe of this indicator is set accordingly. The default mode is Scalp mode.\n\n● Scalp = Ideal for scalps & day trading\n\n● Day Trade = Ideal for day trading\n\n● Swing Short = Ideal for short-term swings\n\n● Swing Long = Ideal for long-term swings\n\n● Eternity = Ideal if you are immortal & holding forever", group = "True Strength Index Oversold & Overbought Settings")
tsi_ooLevelST = input.int(title = "Oversold & Overbought Level", defval = 30, options = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80], tooltip = "TSI is based on price movements and oversold/overbought levels. By default, -30 and +30 is typically defined as the normal threshold. Other securities may vary within a different threshold. You can adjust the oversold and overbought level threshold here.\n\nIf you have the 'Use Original TSI Design Concept' option disabled at the top of this settings window, then you may need to significantly bump up the oversold/overbought level threshold (probably at minimum 50).\n\nThe default value is 30. The minimum value is 10 and the maximum value is 80.", group = "True Strength Index Oversold & Overbought Settings")
tsi_ooLevelLT = input.int(title = "Oversold & Overbought Line Thickness", defval = 1, options = [1, 2, 3, 4, 5], tooltip = "You can change the line thickness of the oversold/overbought lines here.", group = "True Strength Index Oversold & Overbought Settings")
tsi_ooColorNT = input.color(color.new(#9598A1, 60), title = "Oversold/Overbought Line Color", tooltip = "You can assign a color for the oversold/overbought line here.", group = "True Strength Index Oversold & Overbought Settings")
tsi_trendEnable = input.bool(title = "Enable TSI Trend Assist?", defval = false, tooltip = "The True Strength Index (by itself) can be unreliable in visualizing trend direction. By enabling the trend helper, a mid-line will be shown that bounces between the TSI line and the TSI moving average. Most of the time, it's normally centered perfectly mid-way between the TSI line and the TSI moving average.\n\nThe important piece of information here is the color of the line. Is it bullish or bearish? By utilizing price action and comparing the color of this line to the TSI, you can get a better sense of general trend direction (or perhaps a confirmation of trend direction).", group = "True Strength Index Trend Helper")
tsi_trendLineTh = input.int(title = "TSI Trend Line Thickness", defval = 1, options = [1, 2, 3, 4, 5], tooltip = "You can change the thickness of the TSI trend line/circle here.", group = "True Strength Index Trend Helper")
tsi_trendLineSt = input.string(title = "TSI Trend Line Style", defval = "Line", options = ["Line", "Circle"], tooltip = "You can choose from line or circles for the TSI trend line.", group = "True Strength Index Trend Helper")
tsi_trendColorNeut = input.color(color.new(#9598A1, 60), title = "TSI Trend Line Color", tooltip = "", group = "True Strength Index Trend Helper", inline = "5")
tsi_trendColorBull = input.color(color.new(#00BCD4, 60), title = "", tooltip = "", group = "True Strength Index Trend Helper", inline = "5")
tsi_trendColorBear = input.color(color.new(#E91E63, 60), title = "", tooltip = "The color on the left corresponds to the neutral TSI trend line color. The color in the middle corresponds to the bullish TSI trend line color. The color on the right corresponds to the bearish TSI trend line color.", group = "True Strength Index Trend Helper", inline = "5")
// Variables
tsi_sxk = ta.ema(ta.stoch(close, high, ta.change(low), 8), 3)
isToday = ((year(timenow) == year(time)) and (month(timenow) == month(time)) and (dayofmonth(timenow) == dayofmonth(time))) ? true : false
var tsi_Lhigh = 0.0
var tsi_Llow = 0.0
epd_period = 8
tsi_sxd = ta.ema(tsi_sxk, 3)
if (tsi_ooLevelMD == "Scalp")
epd_period := 8
else if (tsi_ooLevelMD == "Day Trade")
epd_period := 13
else if (tsi_ooLevelMD == "Swing Short")
epd_period := 20
else if (tsi_ooLevelMD == "Swing Long")
epd_period := 34
else
epd_period := 55
epd_ema = ta.ema(close, epd_period)
epd_dist = ((close - epd_ema) / epd_ema) * 100
// Double Smoothing (TSI requires that we use double-smoothing)
_doubleSmooth(src, tsi_smoothS, tsi_smoothL) =>
if (tsi_mode)
yi = tsi_maMode == "EMA" ? ta.ema(src, tsi_smoothL) : ta.hma(src, tsi_smoothL)
tsi_maMode == "EMA" ? ta.ema(yi, tsi_smoothS) : ta.hma(yi, tsi_smoothS)
else
yi = ta.hma(src, tsi_smoothL)
er = ta.hma(src, tsi_smoothS)
math.avg(yi, er)
// Calculations (formula and variable names derived from Investopedia)
tsi_tmp3 = close[3]
tsi_tmp2 = close[2]
tsi_tmp1 = close[1]
tsi_pc = ta.change(close) // price change (the built-in function takes care of this work)
if (tsi_pcpModeSetting >= 2)
tsi_tmp = 0.0
if (tsi_pcpModeSetting == 2)
tsi_tmp := math.avg(tsi_tmp1, tsi_tmp2)
else
tsi_tmp := math.avg(tsi_tmp1, tsi_tmp2, tsi_tmp3)
tsi_pc := (close - tsi_tmp)
tsi_pcds = _doubleSmooth(tsi_pc, tsi_smoothS, tsi_smoothL) // price change double smoothed
tsi_apcds = _doubleSmooth(math.abs(tsi_pc), tsi_smoothS, tsi_smoothL) // absolute price change double smoothed
tsi_tsi = (tsi_pcds / tsi_apcds) * 100 // true strength index (this is the basic calculation)
tsi_line = ta.ema(tsi_tsi, tsi_ema)
if (tsi_maMode != "EMA")
tsi_line := tsi_maMode == "HULL 1" ? ta.hma(tsi_tsi, tsi_ema) : ta.ema(tsi_tsi, tsi_ema)
tsi_mPoint = math.avg(tsi_tsi, tsi_line)
t_trendBull = tsi_tsi >= tsi_tsi[1] ? true : false
p_tsiLineColor = tsi_nocurl
p_tsiEMALColor = tsi_nocurl
tsiFillColor = tsi_nocurl
p_tsiTrendLineColor = tsi_trendColorNeut
if (t_trendBull == true)
if (tsi_tsi < tsi_line)
p_tsiLineColor := tsi_curlup
else
p_tsiLineColor := tsi_stbull
if (t_trendBull == false)
if (tsi_tsi >= tsi_line)
p_tsiLineColor := tsi_curldn
else
p_tsiLineColor := tsi_stbear
if (tsi_line >= tsi_line[1])
p_tsiEMALColor := tsi_mabull
else
p_tsiEMALColor := tsi_mabear
if (tsi_tsi >= tsi_line)
tsiFillColor := tsi_fcbull
else
tsiFillColor := tsi_fcbear
if (tsi_fchide == true)
tsiFillColor := color.new(#000000, 100)
epd_dist := epd_dist * tsi_ooLevelST
epd_pAct = (tsi_line + epd_dist)
tsi_sxDist = (tsi_sxk - tsi_sxd)
tsi_sxDistFinal = 0.0
if (math.abs(tsi_sxDist) <= 10)
tsi_sxDistFinal := 0.0
else if ((math.abs(tsi_sxDist) > 10) and (math.abs(tsi_sxDist) <= 20))
tsi_sxDistFinal := 1.0
else
tsi_sxDistFinal := 1.5
if (tsi_sxk >= tsi_sxd)
tsi_mPoint := tsi_mPoint + (tsi_sxDistFinal)
else
tsi_mPoint := tsi_mPoint - (tsi_sxDistFinal)
if ((tsi_tsi > tsi_Lhigh) and isToday and (tsi_tsi > 0))
tsi_Lhigh := tsi_tsi
if ((tsi_tsi < tsi_Llow) and isToday and (tsi_tsi < 0))
tsi_Llow := tsi_tsi
if (tsi_sxk > tsi_sxd)
p_tsiTrendLineColor := tsi_trendColorBull
else
p_tsiTrendLineColor := tsi_trendColorBear
// Alerts
tsi_buy = ta.crossover(tsi_tsi, tsi_line)
tsi_sell = ta.crossunder(tsi_tsi, tsi_line)
tsi_cross = ta.cross(tsi_tsi, tsi_line)
tsi_Trendbuy = ta.crossover(tsi_sxk, tsi_sxd)
tsi_Trendsell = ta.crossunder(tsi_sxk, tsi_sxd)
tsi_Trendcross = ta.cross(tsi_sxk, tsi_sxd)
alertcondition(tsi_buy, title = "TSI Cross Up", message = "{{ticker}}: TSI Crossed Up")
alertcondition(tsi_sell, title = "TSI Cross Down", message = "{{ticker}}: TSI Crossed Down")
alertcondition(tsi_cross, title = "TSI Cross", message = "{{ticker}}: TSI Crossed")
alertcondition(tsi_buy, title = "TSI Trend Cross Up", message = "{{ticker}}: TSI Trend Crossed Up")
alertcondition(tsi_sell, title = "TSI Trend Cross Down", message = "{{ticker}}: TSI Trend Crossed Down")
alertcondition(tsi_cross, title = "TSI Trend Cross", message = "{{ticker}}: TSI Trend Crossed")
// Visuals
p_tsiLine = plot(tsi_tsi, title = "TSI Line", color = p_tsiLineColor, linewidth = tsi_lineWidth, style = plot.style_line, trackprice = false)
p_tsiEMAL = plot(tsi_line, title = "TSI MA Line", color = p_tsiEMALColor, linewidth = tsi_maLineBold == true ? tsi_lineWidth + 1 : tsi_lineWidth, style = plot.style_line, trackprice = false)
fill(p_tsiLine, p_tsiEMAL, title = "TSI Fill", color = tsiFillColor, fillgaps = true)
p_tsiZero = plot(tsi_zeroLine == true ? 0 : na, title = "Zero Line", color = tsi_zeroLineColor, linewidth = tsi_zeroLineWidth, style = plot.style_line, trackprice = false)
p_ooLLine = plot(tsi_ooLevelEN == true ? epd_pAct : na, title = "OB/OS Line", color = tsi_ooColorNT, linewidth = tsi_ooLevelLT, style = plot.style_line, trackprice = false)
p_tsiTrendLine = plot(tsi_trendEnable == true ? tsi_mPoint : na, title = "TSI Trend Line", color = p_tsiTrendLineColor, linewidth = tsi_trendLineTh, style = tsi_trendLineSt == "Line" ? plot.style_line : plot.style_circles, trackprice = false)
|
Equities Risk Tool [vnhilton] | https://www.tradingview.com/script/1p3PHKpJ-Equities-Risk-Tool-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 17 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vnhilton
//@version=5
indicator("Equities Risk Tool [vnhilton]", "your position", overlay=true)
//Account size
account = input.float(50000, "Account", minval=0, group="Account size")
//Manual inputs for entry position
pointA = input.price(0.00, "entry", group="Position Inputs", confirm=true)
pointB = input.price(0.00, "stop loss", group="Position Inputs", confirm=true)
//Account percent risks for position
riskSize1 = input.float(0.5, "Risk #1", minval=0, maxval=100, tooltip="Enter your account 1st risk amount here as a percentage", group="Account Risk Options")
riskSize2 = input.float(0.25, "Risk #2", minval=0, maxval=100, tooltip="Enter your account 2nd risk amount here as a percentage", group="Account Risk Options")
riskSize3 = input.float(0.125, "Risk #3", minval=0, maxval=100, group="Account Risk Options")
riskSize4 = input.float(0.0625, "Risk #4", minval=0, maxval=100, group="Account Risk Options")
//Shares calculation types
longType = input.int(-1, "Round Down Factor (Long Shares)", maxval=0, tooltip="Enter the round down factor used to calculate shares for long positions e.g. a round down factor of '2' will round down to the nearest 2 decimal places. A factor of '-2' will round down to the nearest 100", group="Shares Calculation Types")
shortType = input.int(-1, "Round Down Factor (Short Shares)", maxval=0, tooltip="Enter the round down factor used to calculate shares for short positions", group="Shares Calculation Types")
//Percentage sizes of calculated shares
sharesSize1 = input.float(100, "Shares % #1", minval=0, maxval=100, tooltip="Enter your 1st percentage of calculated shares", group="Shares Percentage Results")
sharesSize2 = input.float(75, "Shares % #2", minval=0, maxval=100, tooltip="Enter your 2nd percentage of calculated shares", group="Shares Percentage Results")
sharesSize3 = input.float(50, "Shares % #3", minval=0, maxval=100, group="Shares Percentage Results")
sharesSize4 = input.float(25, "Shares % #4", minval=0, maxval=100, group="Shares Percentage Results")
//Profit target factors
targetMulti1 = input.float(1, "Profit Target Factor #1", minval=0, tooltip="Enter your 1st profit target factor (the factor is applied to the stop loss distance) e.g. if you're aiming for a 1 risk/reward ratio trade, then enter the factor 1 - Set factors equal to each other if you want to hide them.", group="Profit Target Factors")
targetMulti2 = input.float(2, "Profit Target Factor #2", minval=0, tooltip="Enter your 2nd profit target factor", group="Profit Target Factors")
targetMulti3 = input.float(3, "Profit Target Factor #3", minval=0, group="Profit Target Factors")
targetMulti4 = input.float(4, "Profit Target Factor #4", minval=0, group="Profit Target Factors")
//Calculations
stopLossDistance = pointA - pointB
shares1 = math.abs(((riskSize1 / 100) * account) / stopLossDistance)
shares2 = math.abs(((riskSize2 / 100) * account) / stopLossDistance)
shares3 = math.abs(((riskSize3 / 100) * account) / stopLossDistance)
shares4 = math.abs(((riskSize4 / 100) * account) / stopLossDistance)
//Round down function courtesy of tradingcode
roundDown(number, decimals) => math.floor(number * math.pow(10, decimals)) / math.pow(10, decimals)
//Position drawing configuration
entryColor = color.rgb(255, 255, 255, 0)
stopLossColor = color.rgb(242, 54, 69, 0)
profitTargetColor = color.rgb(129, 199, 132, 0)
stopLossFillColor = color.rgb(242, 54, 69, 90)
profitTargetFillColor = color.rgb(129, 199, 132, 90)
//Position line drawings
pB = plot(pointB, "Stop Loss Line", color=stopLossColor, style=plot.style_line)
pA = plot(pointA, "Entry Line", color=entryColor, style=plot.style_line)
fill(pA, pB, stopLossFillColor, "Stop Loss Fill Background")
p1 = plot(stopLossDistance >= 0 ? pointA + (stopLossDistance * targetMulti1) : pointA - (math.abs(stopLossDistance) * targetMulti1), "Profit Target Line #1", color=profitTargetColor, style=plot.style_line)
fill(pA, p1, profitTargetFillColor, "Profit Target #1 Fill Background")
p2 = plot(stopLossDistance >= 0 ? pointA + (stopLossDistance * targetMulti2) : pointA - (math.abs(stopLossDistance) * targetMulti2), "Profit Target Line #2", color=profitTargetColor, style=plot.style_line, display=display.none)
fill(pA, p2, profitTargetFillColor, "Profit Target #2 Fill Background", display=display.none)
p3 = plot(stopLossDistance >= 0 ? pointA + (stopLossDistance * targetMulti3) : pointA - (math.abs(stopLossDistance) * targetMulti3), "Profit Target Line #3", color=profitTargetColor, style=plot.style_line, display=display.none)
fill(pA, p3, profitTargetFillColor, "Profit Target #3 Fill Background", display=display.none)
p4 = plot(stopLossDistance >= 0 ? pointA + (stopLossDistance * targetMulti4) : pointA - (math.abs(stopLossDistance) * targetMulti4), "Profit Target Line #4", color=profitTargetColor, style=plot.style_line, display=display.none)
fill(pA, p4, profitTargetFillColor, "Profit Target #4 Fill Background", display=display.none)
//Main table configuration
tblePos = input.string("Bottom Left", "Table Position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group="Main table Configuration")
tbleFrameColor = input(defval=color.rgb(209, 212, 220, 0), title="Table Frame Color", group="Main table Configuration")
tbleFrameWidth = input.int(1, "Table Frame Width", minval=0, group="Main table Configuration")
tbleBorderColor = input(defval=color.rgb(255, 255, 255, 0), title="Table Border Color", group="Main table Configuration")
tbleBorderWidth = input.int(0, "Table Border Width", minval=0, group="Main table Configuration")
headerTxtSize = input.string("Tiny", "Header Text Size", options=["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group="Main table Configuration")
bodyTxtSize = input.string("Tiny", "Body Text Size", options=["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group="Main table Configuration")
textColor = input(defval=color.rgb(0, 0, 0, 0), title="Text Color", group="Main table Configuration")
longColor = input(defval=color.rgb(129, 199, 132, 0), title="Long Cell Color", group="Main table Configuration")
shortColor = input(defval=color.rgb(242, 54, 69, 0), title="Short Cell Color", group="Main table Configuration")
risk1Color = input(defval=color.rgb(202, 255, 191, 0), title="Risk #1 Cell Color", group="Main table Configuration")
risk2Color = input(defval=color.rgb(253, 255, 182, 0), title="Risk #2 Cell Color", group="Main table Configuration")
risk3Color = input(defval=color.rgb(255, 214, 165, 0), title="Risk #3 Cell Color", group="Main table Configuration")
risk4Color = input(defval=color.rgb(255, 173, 173, 0), title="Risk #4 Cell Color", group="Main table Configuration")
sharesSize1Color = input(defval=color.rgb(162, 200, 204, 0), title="Shares Size #1 Cell Color", group="Main table Configuration")
sharesSize2Color = input(defval=color.rgb(109, 168, 175, 0), title="Shares Size #2 Cell Color", group="Main table Configuration")
sharesSize3Color = input(defval=color.rgb(72, 125, 131, 0), title="Shares Size #3 Cell Color", group="Main table Configuration")
sharesSize4Color = input(defval=color.rgb(43, 75, 79, 0), title="Shares Size #4 Cell Color", group="Main table Configuration")
shares1Color = input(defval=color.rgb(183, 212, 216, 0), title="Shares % #1 Cell Color", group="Main table Configuration")
shares2Color = input(defval=color.rgb(131, 181, 187, 0), title="Shares % #2 Cell Color", group="Main table Configuration")
shares3Color = input(defval=color.rgb(83, 145, 152, 0), title="Shares % #3 Cell Color", group="Main table Configuration")
shares4Color = input(defval=color.rgb(54, 95, 100, 0), title="Shares % #4 Cell Color", group="Main table Configuration")
//Importing table
tblePosition = tblePos == "Top Left" ? position.top_left :
tblePos == "Top Center" ? position.top_center :
tblePos == "Top Right" ? position.top_right :
tblePos == "Middle Left" ? position.middle_left :
tblePos == "Middle Center" ? position.middle_center :
tblePos == "Middle Right" ? position.middle_right :
tblePos == "Bottom Left" ? position.bottom_left :
tblePos == "Bottom Center" ? position.bottom_center : position.bottom_right
headerTextSize = headerTxtSize == "Auto" ? size.auto :
headerTxtSize == "Tiny" ? size.tiny :
headerTxtSize == "Small" ? size.small :
headerTxtSize == "Normal" ? size.normal :
headerTxtSize == "Large" ? size.large : size.huge
bodyTextSize = bodyTxtSize == "Auto" ? size.auto :
bodyTxtSize == "Tiny" ? size.tiny :
bodyTxtSize == "Small" ? size.small :
bodyTxtSize == "Normal" ? size.normal :
bodyTxtSize == "Large" ? size.large : size.huge
tble = table.new(tblePosition, 5, 5, frame_color=tbleFrameColor, frame_width=tbleFrameWidth, border_width=tbleBorderWidth, border_color=tbleBorderColor)
table.cell(tble, 0, 0, stopLossDistance >= 0 ? "LONG (SL: " + str.tostring(roundDown(stopLossDistance, 2)) + ")" : "SHORT (SL: " + str.tostring(math.abs(roundDown(stopLossDistance, 2))) + ")", text_size=headerTextSize, text_color=textColor, bgcolor=stopLossDistance >= 0 ? longColor : shortColor)
table.cell(tble, 1, 0, str.tostring(riskSize1) + "%", text_size=headerTextSize, text_color=textColor, bgcolor=risk1Color)
table.cell(tble, 2, 0, str.tostring(riskSize2) + "%", text_size=headerTextSize, text_color=textColor, bgcolor=risk2Color)
table.cell(tble, 3, 0, str.tostring(riskSize3) + "%", text_size=headerTextSize, text_color=textColor, bgcolor=risk3Color)
table.cell(tble, 4, 0, str.tostring(riskSize4) + "%", text_size=headerTextSize, text_color=textColor, bgcolor=risk4Color)
table.cell(tble, 0, 1, "Shares (" + str.tostring(sharesSize1) + "%)", text_size=headerTextSize, text_color=textColor, bgcolor=sharesSize1Color)
table.cell(tble, 0, 2, "Shares (" + str.tostring(sharesSize2) + "%)", text_size=headerTextSize, text_color=textColor, bgcolor=sharesSize2Color)
table.cell(tble, 0, 3, "Shares (" + str.tostring(sharesSize3) + "%)", text_size=headerTextSize, text_color=textColor, bgcolor=sharesSize3Color)
table.cell(tble, 0, 4, "Shares (" + str.tostring(sharesSize4) + "%)", text_size=headerTextSize, text_color=textColor, bgcolor=sharesSize4Color)
table.cell(tble, 1, 1, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize1 / 100) * shares1, longType)) : str.tostring(roundDown((sharesSize1 / 100) * shares1, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares1Color)
table.cell(tble, 2, 1, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize1 / 100) * shares2, longType)) : str.tostring(roundDown((sharesSize1 / 100) * shares2, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares1Color)
table.cell(tble, 3, 1, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize1 / 100) * shares3, longType)) : str.tostring(roundDown((sharesSize1 / 100) * shares3, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares1Color)
table.cell(tble, 4, 1, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize1 / 100) * shares4, longType)) : str.tostring(roundDown((sharesSize1 / 100) * shares4, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares1Color)
table.cell(tble, 1, 2, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize2 / 100) * shares1, longType)) : str.tostring(roundDown((sharesSize2 / 100) * shares1, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares2Color)
table.cell(tble, 2, 2, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize2 / 100) * shares2, longType)) : str.tostring(roundDown((sharesSize2 / 100) * shares2, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares2Color)
table.cell(tble, 3, 2, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize2 / 100) * shares3, longType)) : str.tostring(roundDown((sharesSize2 / 100) * shares3, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares2Color)
table.cell(tble, 4, 2, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize2 / 100) * shares4, longType)) : str.tostring(roundDown((sharesSize2 / 100) * shares4, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares2Color)
table.cell(tble, 1, 3, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize3 / 100) * shares1, longType)) : str.tostring(roundDown((sharesSize3 / 100) * shares1, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares3Color)
table.cell(tble, 2, 3, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize3 / 100) * shares2, longType)) : str.tostring(roundDown((sharesSize3 / 100) * shares2, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares3Color)
table.cell(tble, 3, 3, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize3 / 100) * shares3, longType)) : str.tostring(roundDown((sharesSize3 / 100) * shares3, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares3Color)
table.cell(tble, 4, 3, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize3 / 100) * shares4, longType)) : str.tostring(roundDown((sharesSize3 / 100) * shares4, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares3Color)
table.cell(tble, 1, 4, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize4 / 100) * shares1, longType)) : str.tostring(roundDown((sharesSize4 / 100) * shares1, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares4Color)
table.cell(tble, 2, 4, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize4 / 100) * shares2, longType)) : str.tostring(roundDown((sharesSize4 / 100) * shares2, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares4Color)
table.cell(tble, 3, 4, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize4 / 100) * shares3, longType)) : str.tostring(roundDown((sharesSize4 / 100) * shares3, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares4Color)
table.cell(tble, 4, 4, stopLossDistance >= 0 ? str.tostring(roundDown((sharesSize4 / 100) * shares4, longType)) : str.tostring(roundDown((sharesSize4 / 100) * shares4, shortType)), text_size=bodyTextSize, text_color=textColor, bgcolor=shares4Color) |
((Bearish)) Candle Above EMAS | https://www.tradingview.com/script/PL5zkIoc-Bearish-Candle-Above-EMAS/ | LuxTradeVenture | https://www.tradingview.com/u/LuxTradeVenture/ | 69 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MINTYFRESH97
//@version=5
indicator(title="((Bearish)) Candle Above EMAS", overlay=true)
// Calculate moving averages
// Calculate moving averages
var g_ema = "EMA Filter"
emaLength21 = input.int(title="21EMA", defval=21, tooltip="Length of the EMA filter", group=g_ema)
emaLength50 = input.int(title="50EMA", defval=50, tooltip="Length of the EMA filter", group=g_ema)
emaLength100 = input.int(title="100EMA", defval=100 , tooltip="Length of the EMA filter", group=g_ema)
emaLength200 = input.int(title="200EMA", defval=200, tooltip="Length of the EMA filter", group=g_ema)
// Create table
var table myTable = table.new(position.top_right, 5, 6, border_width=4)
if barstate.ishistory
txt1 = "ONLY USE WHEN THE MARKET IS TRENDING \n"
table.cell(myTable, 0, 0, text=txt1, bgcolor=color.white, text_size=size.large , text_color=color.red)
fastMA = ta.ema(close, emaLength21)
fastMA50= ta.ema(close, emaLength50)
fastMA100= ta.ema(close, emaLength100)
// Get EMA filter
ema = ta.ema(close, emaLength200)
emaFilterShort = close < ema
//shortsignal
shortsignal = ta.crossover(fastMA,close)
shortsignal1 = ta.crossover(fastMA50,close)
shortsignal2 = ta.crossover(fastMA100,close)
bearishcandlesfilter1 =shortsignal1 and emaFilterShort and timeframe.isdaily
bearishcandlesfilter2 =shortsignal2 and emaFilterShort and timeframe.isdaily
plotshape(bearishcandlesfilter1, style=shape.diamond, color=color.red, size=size.tiny, text="Above50ema", title="Bearish Price above 50ema" ,location=location.abovebar)
barcolor(bearishcandlesfilter1 ? color.red :na)
alertcondition(bearishcandlesfilter1, "Bearish Price below 50eam{{ticker}}")
plotshape(bearishcandlesfilter2, style=shape.diamond, color=color.red, size=size.tiny, text="Above100ema", title="Bearish Price above 100ema" ,location=location.abovebar)
barcolor(bearishcandlesfilter2 ? color.red :na)
alertcondition(bearishcandlesfilter2, "Bearish Price above 100ema{{ticker}}")
|
Liquidity Heatmap (Nephew_Sam_) | https://www.tradingview.com/script/A4HGnlGH-Liquidity-Heatmap-Nephew-Sam/ | nephew_sam_ | https://www.tradingview.com/u/nephew_sam_/ | 3,737 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Nephew_Sam_
//@version=5
indicator('Liquidity Heatmap (Nephew_Sam_)', overlay=true, max_bars_back=500, max_lines_count=500, max_boxes_count=500, max_labels_count=500)
// --------------- INPUTS ---------------
var GRP1 = "•••••••••• INTRADAY TIMEFRAMES ••••••••••"
// 1
ltimeframe1Show = input.bool(true, title='', inline='1', group=GRP1)
ltimeframe1 = input.timeframe('15', title='', inline='1', group=GRP1)
lleftBars1 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP1, inline='1')
lrightBars1 = input.int(defval=7, title='Right', minval=2, maxval=20, group=GRP1, inline='1', tooltip="Highest/lowest point in x right and left bars.")
// 2
ltimeframe2Show = input.bool(true, title='', inline='2', group=GRP1)
ltimeframe2 = input.timeframe('30', title='', inline='2', group=GRP1)
lleftBars2 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP1, inline='2')
lrightBars2 = input.int(defval=7, title='Right', minval=2, maxval=20, group=GRP1, inline='2', tooltip="Highest/lowest point in x right and left bars.")
// 3
ltimeframe3Show = input.bool(true, title='', inline='3', group=GRP1)
ltimeframe3 = input.timeframe('60', title='', inline='3', group=GRP1)
lleftBars3 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP1, inline='3')
lrightBars3 = input.int(defval=6, title='Right', minval=2, maxval=20, group=GRP1, inline='3', tooltip="Highest/lowest point in x right and left bars.")
// 4
ltimeframe4Show = input.bool(true, title='', inline='4', group=GRP1)
ltimeframe4 = input.timeframe('120', title='', inline='4', group=GRP1)
lleftBars4 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP1, inline='4')
lrightBars4 = input.int(defval=6, title='Right', minval=2, maxval=20, group=GRP1, inline='4', tooltip="Highest/lowest point in x right and left bars.")
// 5
ltimeframe5Show = input.bool(true, title='', inline='5', group=GRP1)
ltimeframe5 = input.timeframe('240', title='', inline='5', group=GRP1)
lleftBars5 = input.int(defval=6, title='Left', minval=2, maxval=20, group=GRP1, inline='5')
lrightBars5 = input.int(defval=6, title='Right', minval=2, maxval=20, group=GRP1, inline='5', tooltip="Highest/lowest point in x right and left bars.")
// 6
ltimeframe6Show = input.bool(true, title='', inline='6', group=GRP1)
ltimeframe6 = input.timeframe('D', title='', inline='6', group=GRP1)
lleftBars6 = input.int(defval=5, title='Left', minval=2, maxval=20, group=GRP1, inline='6')
lrightBars6 = input.int(defval=5, title='Right', minval=2, maxval=20, group=GRP1, inline='6', tooltip="Highest/lowest point in x right and left bars.")
var GRP2 = "•••••••••• HIGHER TIMEFRAMES (> 4HR) ••••••••••"
// 1
htimeframe1Show = input.bool(true, title='', inline='1', group=GRP2)
htimeframe1 = input.timeframe('480', title='', inline='1', group=GRP2)
hleftBars1 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP2, inline='1')
hrightBars1 = input.int(defval=7, title='Right', minval=2, maxval=20, group=GRP2, inline='1', tooltip="Highest/lowest point in x right and left bars.")
// 2
htimeframe2Show = input.bool(true, title='', inline='2', group=GRP2)
htimeframe2 = input.timeframe('D', title='', inline='2', group=GRP2)
hleftBars2 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP2, inline='2')
hrightBars2 = input.int(defval=7, title='Right', minval=2, maxval=20, group=GRP2, inline='2', tooltip="Highest/lowest point in x right and left bars.")
// 3
htimeframe3Show = input.bool(true, title='', inline='3', group=GRP2)
htimeframe3 = input.timeframe('3D', title='', inline='3', group=GRP2)
hleftBars3 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP2, inline='3')
hrightBars3 = input.int(defval=6, title='Right', minval=2, maxval=20, group=GRP2, inline='3', tooltip="Highest/lowest point in x right and left bars.")
// 4
htimeframe4Show = input.bool(true, title='', inline='4', group=GRP2)
htimeframe4 = input.timeframe('W', title='', inline='4', group=GRP2)
hleftBars4 = input.int(defval=7, title='Left', minval=2, maxval=20, group=GRP2, inline='4')
hrightBars4 = input.int(defval=6, title='Right', minval=2, maxval=20, group=GRP2, inline='4', tooltip="Highest/lowest point in x right and left bars.")
// 5
htimeframe5Show = input.bool(true, title='', inline='5', group=GRP2)
htimeframe5 = input.timeframe('M', title='', inline='5', group=GRP2)
hleftBars5 = input.int(defval=6, title='Left', minval=2, maxval=20, group=GRP2, inline='5')
hrightBars5 = input.int(defval=6, title='Right', minval=2, maxval=20, group=GRP2, inline='5', tooltip="Highest/lowest point in x right and left bars.")
// 6
htimeframe6Show = input.bool(false, title='', inline='6', group=GRP2)
htimeframe6 = input.timeframe('2M', title='', inline='6', group=GRP2)
hleftBars6 = input.int(defval=5, title='Left', minval=2, maxval=20, group=GRP2, inline='6')
hrightBars6 = input.int(defval=5, title='Right', minval=2, maxval=20, group=GRP2, inline='6', tooltip="Highest/lowest point in x right and left bars.")
var GRP3 = "•••••••••• Other Settings ••••••••••"
hideLTF = input.bool(true, "Hide lines lower than enabled timeframes?", group = GRP3)
// --------------- INPUTS ---------------
// --------------- COLORS AND LENGTH ---------------
topColor1 = color.new(color.red, 70)
bottomColor1 = color.new(color.green, 70)
lineLength1 = 6
topColor2 = color.new(color.red, 60)
bottomColor2 = color.new(color.green, 60)
lineLength2 = 10
topColor3 = color.new(color.red, 50)
bottomColor3 = color.new(color.green, 50)
lineLength3 = 10
topColor4 = color.new(color.red, 40)
bottomColor4 = color.new(color.green, 40)
lineLength4 = 10
topColor5 = color.new(color.red, 30)
bottomColor5 = color.new(color.green, 30)
lineLength5 = 15
topColor6 = color.new(color.red, 20)
bottomColor6 = color.new(color.green, 20)
lineLength6 = 15
// --------------- COLORS AND LENGTH ---------------
// --------------- FUNCTIONS ---------------
getPivotData(lb, rb) =>
ph = ta.pivothigh(lb, rb)
phtimestart = ph ? time[rb-1] : na
pl = ta.pivotlow(lb, rb)
pltimestart = pl ? time[rb-1] : na
[ph, phtimestart, pl, pltimestart]
getLineStyle(_style) =>
_linestyle = _style == "Solid" ? line.style_solid : _style == "Dashed" ? line.style_dashed : line.style_dotted
_linestyle
resolutionInMinutes(tf = "") =>
chartTf = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
float result = tf == "" ? chartTf : request.security(syminfo.tickerid, tf, chartTf)
f_timeFrom(length, _units) =>
int _timeFrom = na
_unit = str.replace_all(_units, 's', '')
_timeFrom := int(time + resolutionInMinutes() * 60 * 1000 * length)
_timeFrom
notLowerTimeframe(tf) =>
_cond = hideLTF ? resolutionInMinutes() < resolutionInMinutes(tf) : true
_cond
// ▓ ▒ ░ ░
generateText(_n = 5, _large = false) =>
_symbol = "░"
_text = ""
for i = _n to 0
_text := _text + " "
for i = _n to 0
_text := _text + _symbol
if _large
_text := _text + "\n" + _text
_text
// --------------- FUNCTIONS ---------------
isLtf = resolutionInMinutes() < resolutionInMinutes("240")
// --------------- Calculate Pivots ---------------
[phchart, phtimestartchart, plchart, pltimestartchart] = request.security(syminfo.tickerid, "5", getPivotData(6, 6), lookahead = barmerge.lookahead_on)
[lph1, lphtimestart1, lpl1, lpltimestart1] = request.security(syminfo.tickerid, ltimeframe1, getPivotData(lleftBars1, lrightBars1), lookahead = barmerge.lookahead_on)
[lph2, lphtimestart2, lpl2, lpltimestart2] = request.security(syminfo.tickerid, ltimeframe2, getPivotData(lleftBars2, lrightBars2), lookahead = barmerge.lookahead_on)
[lph3, lphtimestart3, lpl3, lpltimestart3] = request.security(syminfo.tickerid, ltimeframe3, getPivotData(lleftBars3, lrightBars3), lookahead = barmerge.lookahead_on)
[lph4, lphtimestart4, lpl4, lpltimestart4] = request.security(syminfo.tickerid, ltimeframe4, getPivotData(lleftBars4, lrightBars4), lookahead = barmerge.lookahead_on)
[lph5, lphtimestart5, lpl5, lpltimestart5] = request.security(syminfo.tickerid, ltimeframe5, getPivotData(lleftBars5, lrightBars5), lookahead = barmerge.lookahead_on)
[lph6, lphtimestart6, lpl6, lpltimestart6] = request.security(syminfo.tickerid, ltimeframe6, getPivotData(lleftBars6, lrightBars6), lookahead = barmerge.lookahead_on)
[hph1, hphtimestart1, hpl1, hpltimestart1] = request.security(syminfo.tickerid, htimeframe1, getPivotData(hleftBars1, hrightBars1), lookahead = barmerge.lookahead_on)
[hph2, hphtimestart2, hpl2, hpltimestart2] = request.security(syminfo.tickerid, htimeframe2, getPivotData(hleftBars2, hrightBars2), lookahead = barmerge.lookahead_on)
[hph3, hphtimestart3, hpl3, hpltimestart3] = request.security(syminfo.tickerid, htimeframe3, getPivotData(hleftBars3, hrightBars3), lookahead = barmerge.lookahead_on)
[hph4, hphtimestart4, hpl4, hpltimestart4] = request.security(syminfo.tickerid, htimeframe4, getPivotData(hleftBars4, hrightBars4), lookahead = barmerge.lookahead_on)
[hph5, hphtimestart5, hpl5, hpltimestart5] = request.security(syminfo.tickerid, htimeframe5, getPivotData(hleftBars5, hrightBars5), lookahead = barmerge.lookahead_on)
[hph6, hphtimestart6, hpl6, hpltimestart6] = request.security(syminfo.tickerid, htimeframe6, getPivotData(hleftBars6, hrightBars6), lookahead = barmerge.lookahead_on)
ph1 = isLtf ? lph1 : hph1
phtimestart1 = isLtf ? lphtimestart1 : hphtimestart1
pl1 = isLtf ? lpl1 : hpl1
pltimestart1 = isLtf ? lpltimestart1 : hpltimestart1
ph2 = isLtf ? lph2 : hph2
phtimestart2 = isLtf ? lphtimestart2 : hphtimestart2
pl2 = isLtf ? lpl2 : hpl2
pltimestart2 = isLtf ? lpltimestart2 : hpltimestart2
ph3 = isLtf ? lph3 : hph3
phtimestart3 = isLtf ? lphtimestart3 : hphtimestart3
pl3 = isLtf ? lpl3 : hpl3
pltimestart3 = isLtf ? lpltimestart3 : hpltimestart3
ph4 = isLtf ? lph4 : hph4
phtimestart4 = isLtf ? lphtimestart4 : hphtimestart4
pl4 = isLtf ? lpl4 : hpl4
pltimestart4 = isLtf ? lpltimestart4 : hpltimestart4
ph5 = isLtf ? lph5 : hph5
phtimestart5 = isLtf ? lphtimestart5 : hphtimestart5
pl5 = isLtf ? lpl5 : hpl5
pltimestart5 = isLtf ? lpltimestart5 : hpltimestart5
ph6 = isLtf ? lph6 : hph6
phtimestart6 = isLtf ? lphtimestart6 : hphtimestart6
pl6 = isLtf ? lpl6 : hpl6
pltimestart6 = isLtf ? lpltimestart6 : hpltimestart6
pivothighchart = na(phchart[1]) and phchart ? phchart : na
pivotlowchart = na(plchart[1]) and plchart ? plchart : na
pivothigh1 = na(ph1[1]) and ph1 ? ph1 : na
pivotlow1 = na(pl1[1]) and pl1 ? pl1 : na
pivothigh2 = na(ph2[1]) and ph2 ? ph2 : na
pivotlow2 = na(pl2[1]) and pl2 ? pl2 : na
pivothigh3 = na(ph3[1]) and ph3 ? ph3 : na
pivotlow3 = na(pl3[1]) and pl3 ? pl3 : na
pivothigh4 = na(ph4[1]) and ph4 ? ph4 : na
pivotlow4 = na(pl4[1]) and pl4 ? pl4 : na
pivothigh5 = na(ph5[1]) and ph5 ? ph5 : na
pivotlow5 = na(pl5[1]) and pl5 ? pl5 : na
pivothigh6 = na(ph6[1]) and ph6 ? ph6 : na
pivotlow6 = na(pl6[1]) and pl6 ? pl6 : na
// --------------- Calculate Pivots ---------------
// --------------- Add to array ---------------
var float[] pivothighs1 = array.new_float(0)
var float[] pivotlows1 = array.new_float(0)
var float[] pivothighs2 = array.new_float(0)
var float[] pivotlows2 = array.new_float(0)
var float[] pivothighs3 = array.new_float(0)
var float[] pivotlows3 = array.new_float(0)
var float[] pivothighs4 = array.new_float(0)
var float[] pivotlows4 = array.new_float(0)
var float[] pivothighs5 = array.new_float(0)
var float[] pivotlows5 = array.new_float(0)
var float[] pivothighs6 = array.new_float(0)
var float[] pivotlows6 = array.new_float(0)
// --------------- Add to array ---------------
// --------------- Plot pivot points ---------------
// if barstate.islast
// label.new(bar_index, high, str.tostring(resolutionInMinutes()) +"\n"+ str.tostring(resolutionInMinutes("3")))
// ONLY LOW TIMEFRAME > 3
showTimeframe1 = isLtf ? ltimeframe1Show : htimeframe1Show
validTimeframe1 = isLtf ? notLowerTimeframe(ltimeframe1) : notLowerTimeframe(htimeframe1)
if showTimeframe1 and pivothighchart and resolutionInMinutes() <= resolutionInMinutes("3")
label.new(phtimestartchart, phchart, xloc=xloc.bar_time, text=generateText(12), style=label.style_none, textcolor=topColor1)
if showTimeframe1 and pivotlowchart and resolutionInMinutes() <= resolutionInMinutes("3")
label.new(pltimestartchart, plchart, xloc=xloc.bar_time, text=generateText(12), style=label.style_none, textcolor=bottomColor1)
// Timeframe 1
if showTimeframe1 and pivothigh1 and validTimeframe1
label.new(phtimestart1, ph1, xloc=xloc.bar_time, text=generateText(lineLength1), style=label.style_none, textcolor=topColor1)
if showTimeframe1 and pivotlow1 and validTimeframe1
label.new(pltimestart1, pl1, xloc=xloc.bar_time, text=generateText(lineLength1), style=label.style_none, textcolor=bottomColor1)
// Timeframe 2
showTimeframe2 = isLtf ? ltimeframe2Show : htimeframe2Show
validTimeframe2 = isLtf ? notLowerTimeframe(ltimeframe2) : notLowerTimeframe(htimeframe2)
if showTimeframe2 and pivothigh2 and validTimeframe2
label.new(phtimestart2, ph2, xloc=xloc.bar_time, text=generateText(lineLength2), style=label.style_none, textcolor=topColor2)
if showTimeframe2 and pivotlow2 and validTimeframe2
label.new(pltimestart2, pl2, xloc=xloc.bar_time, text=generateText(lineLength2), style=label.style_none, textcolor=bottomColor2)
// Timeframe 3
showTimeframe3 = isLtf ? ltimeframe3Show : htimeframe3Show
validTimeframe3 = isLtf ? notLowerTimeframe(ltimeframe3) : notLowerTimeframe(htimeframe3)
if showTimeframe3 and pivothigh3 and validTimeframe3
label.new(phtimestart3, ph3, xloc=xloc.bar_time, text=generateText(lineLength3), style=label.style_none, textcolor=topColor3)
if showTimeframe3 and pivotlow3 and validTimeframe3
label.new(pltimestart3, pl3, xloc=xloc.bar_time, text=generateText(lineLength3), style=label.style_none, textcolor=bottomColor3)
// Timeframe 4
showTimeframe4 = isLtf ? ltimeframe4Show : htimeframe4Show
validTimeframe4 = isLtf ? notLowerTimeframe(ltimeframe4) : notLowerTimeframe(htimeframe4)
if showTimeframe4 and pivothigh4 and validTimeframe4
label.new(phtimestart4, ph4, xloc=xloc.bar_time, text=generateText(lineLength4), style=label.style_none, textcolor=topColor4)
if showTimeframe4 and pivotlow4 and validTimeframe4
label.new(pltimestart4, pl4, xloc=xloc.bar_time, text=generateText(lineLength4), style=label.style_none, textcolor=bottomColor4)
// Timeframe 5
showTimeframe5 = isLtf ? ltimeframe5Show : htimeframe5Show
validTimeframe5 = isLtf ? notLowerTimeframe(ltimeframe5) : notLowerTimeframe(htimeframe5)
if showTimeframe5 and pivothigh5 and validTimeframe5
label.new(phtimestart5, ph5, xloc=xloc.bar_time, text=generateText(lineLength5, true), style=label.style_none, textcolor=topColor5)
if showTimeframe5 and pivotlow5 and validTimeframe5
label.new(pltimestart5, pl5, xloc=xloc.bar_time, text=generateText(lineLength5, true), style=label.style_none, textcolor=bottomColor5)
// Timeframe 6
showTimeframe6 = isLtf ? ltimeframe6Show : htimeframe6Show
validTimeframe6 = isLtf ? notLowerTimeframe(ltimeframe6) : notLowerTimeframe(htimeframe6)
if showTimeframe6 and pivothigh6 and validTimeframe6
label.new(phtimestart6, ph6, xloc=xloc.bar_time, text=generateText(lineLength6, true), style=label.style_none, textcolor=topColor6)
if showTimeframe6 and pivotlow6 and validTimeframe6
label.new(pltimestart6, pl6, xloc=xloc.bar_time, text=generateText(lineLength6, true), style=label.style_none, textcolor=bottomColor6)
// --------------- Plot pivot points ---------------
// --------------- Equal highs ---------------
// WATERMARK
if barstate.islast
_table = table.new("bottom_left", 1, 1)
table.cell(_table, 0, 0, text="@Nephew_Sam_", text_size=size.small, text_color=color.new(color.gray, 50)) |
Strength of Divergence Across Multiple Indicators | https://www.tradingview.com/script/680R1I3Z-Strength-of-Divergence-Across-Multiple-Indicators/ | reees | https://www.tradingview.com/u/reees/ | 3,410 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//@version=5
//inds
// Ultimate indicator and Constance brown composite index
//
// color and shape of labels, lines
indicator("Strength of Divergence Across Multiple Indicators","DivStr",overlay=true,max_lines_count=500,max_labels_count=500,max_bars_back=500)
import reees/TA/11 as t
import reees/Algebra/3 as alg
//import reees/Trig/2 as trig
//import reees/Utilities/2 as u
//-----------------------------------------
// inputs
//-----------------------------------------
var bullSwitch = input.bool(true, "Bullish", inline="dswitch", group="Divergence Params")
var bearSwitch = input.bool(true, "Bearish", inline="dswitch", group="Divergence Params")
var showHidden = input.bool(true, "Hidden", inline="dswitch", group="Divergence Params")
var noBroken = input.bool(true,"Exclude if broken trendline",group="Divergence Params",tooltip="If set, divergence is not considered valid if an intermediate pivot high/low breaks the divergence trendline (on a linear scale). If using a logarithmic scale, you may want to turn this switch off as some trendlines that are broken on a linear scale may not be broken on a log scale. Only relevant if Lookback Pivots > 1.")
var ppLength = input.int(4,"Previous pivot bars before/after",minval=1,group="Divergence Params",tooltip="Min # bars before and after a previous pivot high/low to consider it valid for divergence check")
var cpLengthBefore = input.int(4,"Next (divergent) pivot bars before",minval=1,group="Divergence Params",tooltip="Min # leading bars before the next (divergent) pivot high/low to consider it valid for divergence check")
var cpLengthAfter = input.int(2,"Next (divergent) pivot bars after",minval=1,group="Divergence Params",tooltip="# trailing bars after the next (divergent) pivot high/low to consider it valid for divergence check. Decreasing this value may detect divergence sooner, but with less confidence.")
var lbBars = input.int(50,"Lookback bars",minval=1,maxval=100,group="Divergence Params",inline="lb")
var lbPivs = input.int(2,"Lookback pivots",minval=1,group="Divergence Params",inline="lb",tooltip="# of bars or # of pivot highs/lows to look back across, whichever comes first")
var w_reg = input.float(1.0,"Regular divergence weight",step=.1,minval=0.0,group="Divergence Params",inline="degreg")
var w_hid = input.float(1.0,"Hidden divergence weight",step=.1,minval=0.0,group="Divergence Params",inline="degreg",tooltip="Value/weight of regular divergence versus hidden divergence (applies to all indicators)")
var w_p = input.float(0.5,"Δ price weight",step=.1,minval=0.0,group="Divergence Params",inline="degprice")
var w_i = input.float(1.5,"Δ indicator weight",step=.1,minval=0.0,group="Divergence Params",inline="degprice",tooltip="Value/weight of change in price versus change in indicator value (applies to all indicators)")
bullPsource = input.source(low,"Bullish divergence price source",group="Divergence Params",tooltip="Used for indicators only when appropriate. If the selected source is not technically feasible or otherwise offends the spirit of an indicator, the indicator's natural source will be used instead.")
bearPsource = input.source(high,"Bearish divergence price source",group="Divergence Params",tooltip="Used for indicators only when appropriate. If the selected source is not technically feasible or otherwise offends the spirit of an indicator, the indicator's natural source will be used instead.")
//
var iRsi = input.bool(true,"RSI", group="Indicator", inline="ind_rsi")
var w_rsi = input.float(1.1,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_rsi")
var e_rsi = input.float(1.0,"Extreme value",step=.1,minval=0.0,group="Indicator",inline="ind_rsi",tooltip="Relative Strength Index (RSI)\n\nWeight: Weight of RSI divergence in total divergence strength calculation.\n\nExtreme divergence value: value above which RSI divergence is considered extreme.")
var iObv = input.bool(true,"OBV", group="Indicator", inline="ind_obv")
var w_obv = input.float(0.8,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_obv")
var e_obv = input.float(1.0,"Extreme value",step=.1,minval=0.0,group="Indicator",inline="ind_obv",tooltip="On Balance Volume (OBV)\n\nWeight: Weight of OBV divergence in total divergence strength calculation.\n\nExtreme divergence value: value above which OBV divergence is considered extreme.")
var iMacd = input.bool(true,"MACD", group="Indicator", inline="ind_macd")
var w_macd = input.float(.9,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_macd")
var e_macd = input.float(1.0,"Extreme value",step=.1,minval=0.0,group="Indicator",inline="ind_macd",tooltip="Moving Average Convergence/Divergence (MACD)\n\nWeight: Weight of MACD divergence in total divergence strength calculation.\n\nExtreme divergence value: value above which MACD divergence is considered extreme.")
var iStoch = input.bool(true,"STOCH", group="Indicator", inline="ind_stoch")
var w_stoch = input.float(0.9,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_stoch")
var e_stoch = input.float(1.0,"Extreme value",step=.1,minval=0.0,group="Indicator",inline="ind_stoch",tooltip="Stochastic (STOCH)\n\nWeight: Weight of STOCH divergence in total divergence strength calculation.\n\nExtreme divergence value: value above which STOCH divergence is considered extreme.")
var iCci = input.bool(true,"CCI", group="Indicator", inline="ind_cci")
var w_cci = input.float(1.0,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_cci")
var e_cci = input.float(1.0,"Extreme value",step=.1,minval=0.0,group="Indicator",inline="ind_cci",tooltip="Commodity Channel Index (CCI)\n\nWeight: Weight of CCI divergence in total divergence strength calculation.\n\nExtreme divergence value: value above which CCI divergence is considered extreme.")
var iMfi = input.bool(true,"MFI", group="Indicator", inline="ind_mfi")
var w_mfi = input.float(1.0,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_mfi")
var e_mfi = input.float(1.0,"Extreme value",step=.1,minval=0.0,group="Indicator",inline="ind_mfi",tooltip="Money Flow Index (MFI)\n\nWeight: Weight of MFI divergence in total divergence strength calculation.\n\nExtreme divergence value: value above which MFI divergence is considered extreme.")
var iAo = input.bool(true,"AO", group="Indicator", inline="ind_ao")
var w_ao = input.float(1.0,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_ao")
var e_ao = input.float(1.0,"Extreme value",step=.1,minval=0.0,group="Indicator",inline="ind_ao",tooltip="Awesome Oscillator (AO)\n\nWeight: Weight of AO divergence in total divergence strength calculation.\n\nExtreme divergence value: value above which AO divergence is considered extreme.")
//
var a_on = input.bool(true, "Alert", inline="alert", group="Alerts")
var a_above = input.float(5.0, "for values above", step=.1, inline="alert", group="Alerts")
//
var noLine = input.bool(true,"Show lines",group="Display Settings")==false
var noLab = input.bool(true,"Show labels",group="Display Settings")==false
var extrDiv = input.float(5.0,"Show largest labels for values above: ",minval=0.0,group="Display Settings",tooltip="Total divergence strength greater than this value will show the largest label (extreme divergence). A good rule of thumb is to keep this value slightly less than the number of selected indicators.")
var noLabB = input.float(0.5,"Don't show labels for values below: ",minval=0.0,group="Display Settings",tooltip="Total divergence strength less than this value will not show any label.")
var lTransp = input.int(80,"Line transparency",minval=0,maxval=100)
//-----------------------------------------
// functions
//-----------------------------------------
strengthMap(d,e) =>
if d >= e
5
else if d > e*.8
4
else if d > e*.6
3
else if d > e*.4
2
else if d > e*.2
1
else
0
strengthMapI(d,i="") =>
e = if i=="RSI"
e_rsi
else if i=="OBV"
e_obv
else if i=="MACD"
e_macd
else if i=="STOCH"
e_stoch
else if i=="CCI"
e_cci
else if i=="MFI"
e_mfi
else if i=="AO"
e_ao
else
0
strengthMap(d,e)
strengthDesc(d,i="") =>
s = i!= "" ? strengthMapI(d,i) : strengthMap(d,extrDiv)
if s == 5
"Extreme"
else if s == 4
"Very strong"
else if s == 3
"Strong"
else if s == 2
"Moderate"
else if s == 1
"Weak"
else
"Very weak"
drawLine(x1,y1,x2,y2,dt,h) =>
c = dt==true?color.new(color.red,lTransp):color.new(color.green,lTransp)
if noLine==false and (h==false or showHidden==true)
line.new(x1,y1,x2,y2,color=c,width=1,style=h==true?line.style_dashed:line.style_solid)
drawLabel(bear,c,d,l) =>
if c > 0 and d >= noLabB and noLab==false
labX = bar_index-cpLengthAfter
labY = bear == true ? bearPsource[cpLengthAfter] : bullPsource[cpLengthAfter]
s = strengthMap(d,extrDiv)
dtxt = strengthDesc(d) + " divergence (" + str.tostring(math.round(d,3)) + ")\n"
ttxt = dtxt + " Indicator breakdown (" + str.tostring(c) + "):\n" + l
txt = if s < 3
""
else
str.tostring(math.round(d,2)) + " (" + str.tostring(c) + ")"
transp = s < 4 ? 50 : 10
size = if s == 5
size.normal
else if s == 4
size.small
else
size.tiny
clr = bear == true ? color.new(color.red,transp) : color.new(color.green,transp)
style = bear == true ? label.style_label_down : label.style_label_up
label.new(labX,labY,text=txt,tooltip=ttxt,textalign=text.align_center,style=style,size=size,color=clr,textcolor=color.white)
detail(t,d) =>
" " + t +": " + strengthDesc(d,t) + " (" + str.tostring(math.round(d,3)) + ")\n"
//-----------------------------------------
// test for divergence
//-----------------------------------------
// RSI
bearRsi = false
bullRsi = false
bearRsiDeg = 0.0
bullRsiDeg = 0.0
if iRsi==true
if bearSwitch==true
i_bear = ta.rsi(bearPsource, 14)
[f,d,t,x1,y1,x2,y2] = t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_rsi
if f==true
bearRsi := t==1 or showHidden==true ? true : false
bearRsiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.rsi(bullPsource, 14)
[f,d,t,x1,y1,x2,y2] = t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_rsi
if f==true
bullRsi := t==1 or showHidden==true ? true : false
bullRsiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// OBV
bearObv = false
bullObv = false
bearObvDeg = 0.0
bullObvDeg = 0.0
if iObv==true
if bearSwitch==true
i_bear = ta.obv
[f,d,t,x1,y1,x2,y2] = t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_obv
if f==true
bearObv := t==1 or showHidden==true ? true : false
bearObvDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.obv
[f,d,t,x1,y1,x2,y2] = t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_obv
if f==true
bullObv := t==1 or showHidden==true ? true : false
bullObvDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// MACD
bearMacd = false
bullMacd = false
bearMacdDeg = 0.0
bullMacdDeg = 0.0
if iMacd==true
if bearSwitch==true
[_,_,i_bear] = ta.macd(bearPsource,12,26,9)
[f,d,t,x1,y1,x2,y2] = t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_macd
if f==true
bearMacd := t==1 or showHidden==true ? true : false
bearMacdDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
[_,_,i_bull] = ta.macd(bullPsource,12,26,9)
[f,d,t,x1,y1,x2,y2] = t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_macd
if f==true
bullMacd := t==1 or showHidden==true ? true : false
bullMacdDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// STOCH
bearStoch = false
bullStoch = false
bearStochDeg = 0.0
bullStochDeg = 0.0
if iStoch==true
if bearSwitch==true
i_bear = ta.stoch(close, high, low, 14)
[f,d,t,x1,y1,x2,y2] = t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_stoch
if f==true
bearStoch := t==1 or showHidden==true ? true : false
bearStochDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.stoch(close, high, low, 14)
[f,d,t,x1,y1,x2,y2] = t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_stoch
if f==true
bullStoch := t==1 or showHidden==true ? true : false
bullStochDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// CCI
bearCci = false
bullCci = false
bearCciDeg = 0.0
bullCciDeg = 0.0
if iCci==true
if bearSwitch==true
i_bear = ta.cci(bearPsource,20)
[f,d,t,x1,y1,x2,y2] = t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_cci
if f==true
bearCci := t==1 or showHidden==true ? true : false
bearCciDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.cci(bullPsource,20)
[f,d,t,x1,y1,x2,y2] = t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_cci
if f==true
bullCci := t==1 or showHidden==true ? true : false
bullCciDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// MFI
bearMfi = false
bullMfi = false
bearMfiDeg = 0.0
bullMfiDeg = 0.0
if iMfi==true
if bearSwitch==true
i_bear = ta.mfi(bearPsource,14)
[f,d,t,x1,y1,x2,y2] = t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_mfi
if f==true
bearMfi := t==1 or showHidden==true ? true : false
bearMfiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.mfi(bullPsource,14)
[f,d,t,x1,y1,x2,y2] = t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_mfi
if f==true
bullMfi := t==1 or showHidden==true ? true : false
bullMfiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// AO
bearAo = false
bullAo = false
bearAoDeg = 0.0
bullAoDeg = 0.0
if iAo==true
if bearSwitch==true
i_bear = ta.sma(hl2,5) - ta.sma(hl2,34)
[f,d,t,x1,y1,x2,y2] = t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_ao
if f==true
bearAo := t==1 or showHidden==true ? true : false
bearAoDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.sma(hl2,5) - ta.sma(hl2,34)
[f,d,t,x1,y1,x2,y2] = t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,noBroken,w_p,w_i,w_hid,w_reg)
d := d*w_ao
if f==true
bullAo := t==1 or showHidden==true ? true : false
bullAoDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// Calculate degree of divergence and add labels.
bearCount = 0 // total number of divergent indicators
bearTotalDeg = 0.0 // total degree of divergence across all indicators
bearIndList = "" // list of indicators for tooltip display
bullCount = 0
bullTotalDeg = 0.0
bullIndList = ""
// RSI
if bearRsi==true
bearIndList := bearIndList + detail("RSI",bearRsiDeg)
bearCount+=1
bearTotalDeg += bearRsiDeg
if bullRsi==true
bullIndList := bullIndList + detail("RSI",bullRsiDeg)
bullCount+=1
bullTotalDeg += bullRsiDeg
// OBV
if bearObv==true
bearIndList := bearIndList + detail("OBV",bearObvDeg)
bearCount+=1
bearTotalDeg += bearObvDeg
if bullObv==true
bullIndList := bullIndList + detail("OBV",bullObvDeg)
bullCount+=1
bullTotalDeg += bullObvDeg
// MACD
if bearMacd==true
bearIndList := bearIndList + detail("MACD",bearMacdDeg)
bearCount+=1
bearTotalDeg += bearMacdDeg
if bullMacd==true
bullIndList := bullIndList + detail("MACD",bullMacdDeg)
bullCount+=1
bullTotalDeg += bullMacdDeg
// STOCH
if bearStoch==true
bearIndList := bearIndList + detail("STOCH",bearStochDeg)
bearCount+=1
bearTotalDeg += bearStochDeg
if bullStoch==true
bullIndList := bullIndList + detail("STOCH",bullStochDeg)
bullCount+=1
bullTotalDeg += bullStochDeg
// CCI
if bearCci==true
bearIndList := bearIndList + detail("CCI",bearCciDeg)
bearCount+=1
bearTotalDeg += bearCciDeg
if bullCci==true
bullIndList := bullIndList + detail("CCI",bullCciDeg)
bullCount+=1
bullTotalDeg += bullCciDeg
// MFI
if bearMfi==true
bearIndList := bearIndList + detail("MFI",bearMfiDeg)
bearCount+=1
bearTotalDeg += bearMfiDeg
if bullMfi==true
bullIndList := bullIndList + detail("MFI",bullMfiDeg)
bullCount+=1
bullTotalDeg += bullMfiDeg
// AO
if bearAo==true
bearIndList := bearIndList + detail("AO",bearAoDeg)
bearCount+=1
bearTotalDeg += bearAoDeg
if bullAo==true
bullIndList := bullIndList + detail("AO",bullAoDeg)
bullCount+=1
bullTotalDeg += bullAoDeg
// Draw label(s)
drawLabel(true,bearCount,bearTotalDeg,bearIndList)
drawLabel(false,bullCount,bullTotalDeg,bullIndList)
// Alerts
if a_on and (bullTotalDeg > a_above or bearTotalDeg > a_above)
alert("Divergence strength of " +str.tostring(math.max(bullTotalDeg,bearTotalDeg),"#.##") + " has formed.") |
Barndorff-Nielsen and Shephard Jump Statistic [Loxx] | https://www.tradingview.com/script/UfCrjo2N-Barndorff-Nielsen-and-Shephard-Jump-Statistic-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 95 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
// The following comments and descriptions are from from "Problems in the Application of Jump Detection Tests to Stock Price Data" by
// Michael William Schwert Professor George Tauchen, Faculty Advisor"
//
// This Indicator applies several jump detection tests to intraday stock price data sampled at various
// frequencies. It finds that the choice of sampling frequency has an effect on both the amount
// of jumps detected by these tests, as well as the timing of those jumps. Furthermore, although
// these tests are designed to identify the same phenomenon, they find different amounts and timing
// of jumps when performed on the same data. These results suggest that these jump detection tests
// are probably identifying different types of jump behavior in stock price data, so they are not
// really substitutes for one another.
//@version=5
indicator("Barndorff-Nielsen and Shephard Jump Statistic [Loxx]",
shorttitle = "BNSJS [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import RicardoSantos/MathSpecialFunctionsGamma/1 as gmm
greencolor = #2DD204
redcolor = #D2042D
//
// Inverse of Normal distribution function
//
//
//
// SYNOPSIS:
//
// double x, y, ndtri();
//
// x = ndtri( y );
//
//
//
// DESCRIPTION:
//
// Returns the argument, x, for which the area under the
// Gaussian probability density function (integrated from
// minus infinity to x) is equal to y.
//
//
// For small arguments 0 < y < exp(-2), the program computes
// z = sqrt( -2.0 // log(y) ); then the approximation is
// x = z - log(z)/z - (1/z) P(1/z) / Q(1/z).
// There are two rational functions P/Q, one for 0 < y < exp(-32)
// and the other for y up to exp(-2). For larger arguments,
// w = y - 0.5, and x/sqrt(2pi) = w + w////3 R(w////2)/S(w////2)).
//
//
// ACCURACY:
//
// Relative error:
// arithmetic domain # trials peak rms
// IEEE 0.125, 1 20000 7.2e-16 1.3e-16
// IEEE 3e-308, 0.135 50000 4.6e-16 9.8e-17
//
//
// ERROR MESSAGES:
//
// message condition value returned
// ndtri domain x <= 0 -1E10
// ndtri domain x >= 1 1E10
//
// Evaluates polynomial of degree N
polevl(float x, float[] coef, int n)=>
float ans = array.get(coef, 0)
for i = 1 to n
ans := ans * x + array.get(coef, i)
ans
// Evaluates polynomial of degree N with assumption that coef[N] = 1.0
p1evl(float x, float[] coef, int n)=>
float ans = x + array.get(coef, 0)
for i = 1 to n - 1
ans := ans * x + array.get(coef, i)
ans
// Cephes Math Library Release 2.1: January, 1989
// Copyright 1984, 1987, 1989 by Stephen L. Moshier
// Direct inquiries to 30 Frost Street, Cambridge, MA 02140
// sqrt(2pi)
float s2pi = 2.50662827463100050242E0
// approximation for 0 <= |y - 0.5| <= 3/8
var array<float> P0 = array.new_float(5, 0)
array.set(P0, 0, -5.99633501014107895267E1)
array.set(P0, 1, 9.80010754185999661536E1)
array.set(P0, 2, -5.66762857469070293439E1)
array.set(P0, 3, 1.39312609387279679503E1)
array.set(P0, 4, -1.23916583867381258016E0)
var array<float> Q0 = array.new_float(8, 0)
array.set(Q0, 0, 1.95448858338141759834E0)
array.set(Q0, 1, 4.67627912898881538453E0)
array.set(Q0, 2, 8.63602421390890590575E1)
array.set(Q0, 3, -2.25462687854119370527E2)
array.set(Q0, 4, 2.00260212380060660359E2)
array.set(Q0, 5, -8.20372256168333339912E1)
array.set(Q0, 6, 1.59056225126211695515E1)
array.set(Q0, 7, -1.18331621121330003142E0)
// Approximation for interval z = sqrt(-2 log y ) between 2 and 8
// i.e., y between exp(-2) = .135 and exp(-32) = 1.27e-14.
var array<float> P1 = array.new_float(9, 0)
array.set(P1, 0, 4.05544892305962419923E0)
array.set(P1, 1, 3.15251094599893866154E1)
array.set(P1, 2, 5.71628192246421288162E1)
array.set(P1, 3, 4.40805073893200834700E1)
array.set(P1, 4, 1.46849561928858024014E1)
array.set(P1, 5, 2.18663306850790267539E0)
array.set(P1, 6, -1.40256079171354495875E-1)
array.set(P1, 7, -3.50424626827848203418E-2)
array.set(P1, 8, -8.57456785154685413611E-4)
var array<float> Q1 = array.new_float(8, 0)
array.set(Q1, 0, 1.57799883256466749731E1)
array.set(Q1, 1, 4.53907635128879210584E1)
array.set(Q1, 2, 4.13172038254672030440E1)
array.set(Q1, 3, 1.50425385692907503408E1)
array.set(Q1, 4, 2.50464946208309415979E0)
array.set(Q1, 5, -1.42182922854787788574E-1)
array.set(Q1, 6, -3.80806407691578277194E-2)
array.set(Q1, 7, -9.33259480895457427372E-4)
// Approximation for interval z = sqrt(-2 log y ) between 8 and 64
// i.e., y between exp(-32) = 1.27e-14 and exp(-2048) = 3.67e-890.
var array<float> P2 = array.new_float(9, 0)
array.set(P2, 0, 3.23774891776946035970E0)
array.set(P2, 1, 6.91522889068984211695E0)
array.set(P2, 2, 3.93881025292474443415E0)
array.set(P2, 3, 1.33303460815807542389E0)
array.set(P2, 4, 2.01485389549179081538E-1)
array.set(P2, 5, 1.23716634817820021358E-2)
array.set(P2, 6, 3.01581553508235416007E-4)
array.set(P2, 7, 2.65806974686737550832E-6)
array.set(P2, 8, 6.23974539184983293730E-9)
var array<float> Q2 = array.new_float(8, 0)
array.set(Q2, 0, 6.02427039364742014255E0)
array.set(Q2, 1, 3.67983563856160859403E0)
array.set(Q2, 2, 1.37702099489081330271E0)
array.set(Q2, 3, 2.16236993594496635890E-1)
array.set(Q2, 4, 1.34204006088543189037E-2)
array.set(Q2, 5, 3.28014464682127739104E-4)
array.set(Q2, 6, 2.89247864745380683936E-6)
array.set(Q2, 7, 6.79019408009981274425E-9)
ndtri(float y0)=>
float x = 0
float y = 0
float z = 0
float y2 = 0
float x0 = 0
float x1 = 0
int code = 0
if not(y0 <= 0. or y0 >= 1.)
code := 1
y := y0
// 0.135... = exp(-2)
if y > (1.0 - 0.13533528323661269189)
y := 1.0 - y
code := 0
if y > 0.13533528323661269189
y := y - 0.5
y2 := y * y
x := y + y * (y2 * polevl(y2, P0, 4) / p1evl(y2, Q0, 8))
x := x * s2pi
else
x := math.sqrt(-2.0 * math.log(y))
x0 := x - math.log(x) / x
z := 1.0 / x
// y > exp(-32) = 1.2664165549e-14
if x < 8.
x1 := z * polevl(z, P1, 8) / p1evl(z, Q1, 8)
else
x1 := z * polevl(z, P2, 8) / p1evl(z, Q2, 8)
x := x0 - x1
if (code != 0)
x := -x
else
if y0 <= 0.
x := -1E10
if y0 >= 1
x := 1E10
x
// Barndorff-Nielsen and Shephard (2004, 2006) developed a test that
// uses high-frequency price data to determine whether there is a jump over
// the course of a day. Their test compares two measures of variance: Realized
// Variance, which converges to the integrated variance plus a jump component
// as the time between observations approaches zero; and Bipower Variation,
// which converges to the integrated variance as the time between observations
// approaches zero, and is robust to jumps in the price path, an important
// fact for this application. The integrated variance of a price process is the
// integral of the square of the variance taken over the course of a day.
// Since prices cannot be observed continuously, one cannot calculate integrated
// variance exactly, and must estimate it instead.
//
// For our purposes here, this is caculated as variance = log(p[ti]/p[ti-1]).
// This the geometric return from time ti-1 to time ti. Then, Realized Variance
// and Bipower Variation are described by the following functions:
//
// realizedVariance(float src, int per)
//
// and
//
// bipowerVariance(float src, int per)
realizedVariance(float src, int per)=>
float realizedvariance = 0
for i = 0 to per
realizedvariance += math.pow(src[i], 2)
realizedvariance
bipowerVariance(float src, int per)=>
float tempvar = 0
for i = 1 to per
tempvar += src[i] * src[i - 1]
float bipowervariance = (math.pi / 2.0) * (per / (per - 1.0)) * tempvar
bipowervariance
// To develop a statistical test to determine whether there is a significant difference between
// RV and BV, one needs an estimate of integrated quarticity. Andersen, Bollerslev, and Diebold
// (2004) recommend using a jump-robust realized Tri-Power Quarticity,
// where Barndorff-Nielsen and Shephard recommend the realized Quad-Power Quarticity. Quad-Power
// Quarticity won't be covered here in this indicator
tripowerQuarticity(float src, int per)=>
float mu = math.pow(math.pow(2, 2 / 3) * gmm.GammaLn(7 / 6) * math.pow(gmm.GammaLn(1 / 2), -1), -3)
float tripower = 0
for i = 2 to per
tripower += math.pow(src[i - 2], 4 / 3) * math.pow(src[i - 1], 4 / 3) * math.pow(src[i], 4 / 3)
float tpquarticity = per * mu * (per / (per - 2)) * tripower
tpquarticity
barndorffNielsenStatistic(float src, int per)=>
float logreturns = math.log(src / src[1])
float abslogreturns = math.abs(logreturns)
float realized_variance = realizedVariance(logreturns, per)
float bipower_variance = bipowerVariance(abslogreturns, per)
float tripower = tripowerQuarticity(abslogreturns, per)
// Huang and Tauchen (2005) also consider Relative Jump,
// a measure that approximates the percentage of total
// variance attributable to jumps.This statistic approximates the
// ratio of the sum of squared jumps to the total variance and
// is useful because it scales out long-term trends in volatility
// so one can compare the relative contribution of jumps to
// the variance of two price series with different volatilities.
float relative_jump = (realized_variance - bipower_variance) / realized_variance
// There are numerous potential test statistics that use these
// estimates of integrated variance and integrated quarticity,
// but Huang and Tauchen find that these two asymptotically standard
// normal test statistics perform best in simulations:
float statistic = relative_jump / math.sqrt((math.pow(math.pi / 2, 2) + math.pi - 5) * (1.0 / per) * math.max(1, tripower / (math.pow(bipower_variance, 2))))
statistic
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(16, "Jump Window", group = "Basic Settings", tooltip = "For SPY benchmark: 7, 16, 78, 110, 156, and 270 returns for sampling intervals of 1 week, 1 day, 1 hour, 30 minutes, 15 minutes, and 5 minutes, respectively.")
alpha = input.float(0.1, "Percent-Point Function (PPF) Alpha", group = "Basic Settings", minval = 0, maxval = 1, step = 0.01)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
statistic = barndorffNielsenStatistic(src, per)
quantile = ndtri(1 - alpha)
colorout = statistic < quantile ? greencolor : color.yellow
plot(statistic, "BNSJS", style = plot.style_histogram, linewidth = 2, color = colorout)
plot(quantile, "Cutoff", color = redcolor)
colorout2 = statistic < quantile ? na : color.yellow
barcolor(colorbars ? colorout2 : na)
plot(3, "Empirical Z-Score Maximum", color = bar_index % 2 ? color.gray : na)
gojump = ta.crossover(statistic, quantile)
plotshape(showSigs and gojump, title = "Jump Detected", color = color.yellow, textcolor = color.yellow, text = "J", style = shape.cross, location = location.bottom, size = size.auto)
alertcondition(gojump, title = "Jump Detected", message = "Barndorff-Nielsen and Shephard Jump Statistic [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}") |
RSI+OBV | https://www.tradingview.com/script/QMnblqIB-RSI-OBV/ | email_analysts | https://www.tradingview.com/u/email_analysts/ | 86 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © email_analysts
//@version=5
indicator(title="DMI+RSI+OBV", overlay=false)
lensig = input.int(11, title="ADX Smoothing", minval=1, maxval=50)
len = input.int(11, minval=1, title="DI Length")
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)
trur = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / trur)
minus = fixnan(100 * ta.rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
//plot(adx, color=#F50057, title="ADX")
plot(plus, color=color.green, title="+DI")
plot(minus, color=color.red, title="-DI")
hlineup = hline(40, color=#787B86)
hlinelow = hline(10, color=#787B86)
////////////////////////////////
len1 = input(title="OBV Length 1", defval = 3)
len2 = input(title="OBV Length 2", defval = 21)
ema1 = ta.ema(ta.obv, len1)
ema2 = ta.ema(ta.obv, len2)
obv=ema1-ema2
len3 = input(title="RSI Length 1", defval = 5)
len4 = input(title="RSI Length 2", defval = 9)
len5 = input(title="RSI Length 3", defval = 14)
sh = ta.rsi(close, len3)
sh9 = ta.rsi(close, len4)
ln = ta.ema(sh9, len5)
rsi = sh-ln
backgroundColor = obv >0 and rsi > 0 ? color.green:
obv < 0 and rsi < 0 ? color.red:
na
bgcolor(color=backgroundColor, transp=70)
|
mondy slebew | https://www.tradingview.com/script/JF0K9q0e/ | M_O_N_D_Y | https://www.tradingview.com/u/M_O_N_D_Y/ | 121 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=4
study(title="Buy/Sell by mondy", overlay=true)
source = input(defval=close, title="Source")
quickEMA = ema(close, 9)
plot(series=quickEMA, color=color.green, linewidth=1)
per1 = input(defval=27, minval=1, title="Fast period")
mult1 = input(defval=1.6, minval=0.1, title="Fast range")
per2 = input(defval=55, minval=1, title="Slow period")
mult2 = input(defval=2, minval=0.1, title="Slow range")
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ema(abs(x - x[1]), t)
smoothrng = ema(avrng, wper) * m
smoothrng
smrng1 = smoothrng(source, per1, mult1)
smrng2 = smoothrng(source, per2, mult2)
smrng = (smrng1 + smrng2) / 2
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(source, smrng)
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
hband = filt + smrng
lband = filt - smrng
longCond = bool(na)
shortCond = bool(na)
longCond := source > filt and source > source[1] and upward > 0 or source > filt and source < source[1] and upward > 0
shortCond := source < filt and source < source[1] and downward > 0 or source < filt and source > source[1] and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
long = longCond and CondIni[1] == -1
short = shortCond and CondIni[1] == 1
plotshape(long, title="BUY", text="BUY", style=shape.labelup, textcolor=color.white, size=size.auto, location=location.belowbar, color=color.green, transp=0)
plotshape(short, title="SELL", text="SELL", style=shape.labeldown, textcolor=color.white, size=size.auto, location=location.abovebar, color=color.red, transp=0)
alertcondition(long, title="BUY", message="BUY")
alertcondition(short, title="SELL", message="SELL")
anchor = input(defval = "Session", title="Anchor Period", type=input.string)
MILLIS_IN_DAY = 86400000
dwmBarTime = timeframe.isdwm ? time : time("D")
if na(dwmBarTime)
dwmBarTime := nz(dwmBarTime[1])
var periodStart = time - time // zero
makeMondayZero(dayOfWeek) => (dayOfWeek + 5) % 7
isMidnight(t) =>
hour(t) == 0 and minute(t) == 0
isSameDay(t1, t2) =>
dayofmonth(t1) == dayofmonth(t2) and
month(t1) == month(t2) and
year(t1) == year(t2)
isOvernight() =>
not (isMidnight(dwmBarTime) or security(syminfo.tickerid, "D", isSameDay(time, time_close), lookahead=true))
tradingDayStart(t) =>
y = year(t)
m = month(t)
d = dayofmonth(t)
timestamp(y, m, d, 0, 0)
numDaysBetween(time1, time2) =>
y1 = year(time1)
m1 = month(time1)
d1 = dayofmonth(time1)
y2 = year(time2)
m2 = month(time2)
d2 = dayofmonth(time2)
diff = abs(timestamp("GMT", y1, m1, d1, 0, 0) - timestamp("GMT", y2, m2, d2, 0, 0))
diff / MILLIS_IN_DAY
tradingDay = isOvernight() ? tradingDayStart(dwmBarTime + MILLIS_IN_DAY) : tradingDayStart(dwmBarTime)
isNewPeriod() =>
isNew = false
if tradingDay != nz(tradingDay[1])
if anchor == "Session"
isNew := na(tradingDay[1]) or tradingDay > tradingDay[1]
if anchor == "Week"
DAYS_IN_WEEK = 7
isNew := makeMondayZero(dayofweek(periodStart)) + numDaysBetween(periodStart, tradingDay) >= DAYS_IN_WEEK
if anchor == "Month"
isNew := month(periodStart) != month(tradingDay) or year(periodStart) != year(tradingDay)
if anchor == "Year"
isNew := year(periodStart) != year(tradingDay)
isNew
src = hlc3
sumSrc = float(na)
sumVol = float(na)
sumSrc := nz(sumSrc[1], 0)
sumVol := nz(sumVol[1], 0)
if isNewPeriod()
periodStart := tradingDay
sumSrc := 0.0
sumVol := 0.0
GLlabel=label.new(x=bar_index,y=close,text=" \n\n\n\n\n\n "+" MONDY" ,
style=label.style_label_up,
color=color.new(color.aqua,transp=100),
textcolor=color.new(color.aqua,transp=30),
size=size.normal)
label.delete(GLlabel[1])
if not na(src) and not na(volume)
sumSrc := sumSrc + src * volume
sumVol := sumVol + volume
vwapValue = sumSrc / sumVol
plot(vwapValue, title="VWAP", color=color.red, linewidth=3)
//EOS
|
Percentile Rank of Bollinger Bands | https://www.tradingview.com/script/8lrh98ey-Percentile-Rank-of-Bollinger-Bands/ | TheSaltyAustin | https://www.tradingview.com/u/TheSaltyAustin/ | 52 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheSaltyAustin
//@version=5
indicator(shorttitle="BB ranked", title="Bollinger Bands", overlay=false, timeframe="", timeframe_gaps=true)
length = input.int(20, minval=1, group='Bollinger')
src = input(close, title="Source", group='Bollinger')
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev", group='Bollinger')
lookback = input.int(750, title='Stdev Rank Lookback', group='Ranking')
showStdev = input.bool(true, title='Show Boll Stdev %', group='Display')
showPosition = input.bool(true, title='Show Current Price\'s Relative Height in Band', group='Display')
var stdevArray = array.new_float(lookback,0.0)
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
positionBetweenBands = 100 * (src - lower)/(upper - lower)
array.push(stdevArray, dev/close)
if array.size(stdevArray)>=lookback
array.remove(stdevArray, 0)
rank = array.percentrank(stdevArray, lookback-1)
rankColor = rank[0]>rank[1] ? color.green : color.red
positionColor = positionBetweenBands[0]>positionBetweenBands[1] ? color.aqua : color.blue
hist = 100*dev/close
plot(showStdev ? hist : na, style=plot.style_columns, color=(hist[1] < hist ? #26A69A : #B2DFDB) , title='Stdev %' )
plot(rank, color=rankColor, linewidth=2, title='Boll Percentile')
plot(showPosition ? positionBetweenBands : na, color=positionColor, title='Relative Height')
hline(95, title='High Percentile', color=color.new(color.white,50), linestyle=hline.style_dashed )
hline( 5, title='Low Percentile' , color=color.new(color.white,50), linestyle=hline.style_dashed )
|
Percentile Rank of Moving Average Convergence Divergence | https://www.tradingview.com/script/SZRJmUuz-Percentile-Rank-of-Moving-Average-Convergence-Divergence/ | TheSaltyAustin | https://www.tradingview.com/u/TheSaltyAustin/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheSaltyAustin
//@version=5
indicator(title="Ranked Moving Average Convergence Divergence", shorttitle="MACD ranked", timeframe="", timeframe_gaps=true)
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
lookback = input.int(750, title='MACD Lookback', group='Ranking')
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
var macdArray = array.new_float(lookback,0.0)
var signalArray = array.new_float(lookback,0.0)
var histArray = array.new_float(lookback,0.0)
array.push(macdArray, math.abs(macd) )
array.push(signalArray, math.abs(signal) )
array.push(histArray, math.abs(hist) )
array.remove(macdArray, 0)
array.remove(signalArray, 0)
array.remove(histArray, 0)
macdRank = array.percentrank(macdArray , lookback-1)
signalRank = array.percentrank(signalArray, lookback-1)
histRank = array.percentrank(histArray , lookback-1)
plot(histRank, color=color.new(color.olive,50), linewidth=2, title='Histogram Rank', style=plot.style_columns)
plot(macdRank, color=#4dd0e1, linewidth=2, title='MACD (fast) Rank')
plot(signalRank, color=#056656, linewidth=2, title='Signal (slow) Rank')
hline(75, title='3rd Quartile', color=color.new(color.white,50), linestyle=hline.style_dashed )
hline(50, title='Median' , color=color.new(color.white,50), linestyle=hline.style_dashed )
hline(25, title='1st Quartile' , color=color.new(color.white,50), linestyle=hline.style_dashed )
|
Micro Zigzag | https://www.tradingview.com/script/LHFOtqjs-Micro-Zigzag/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 164 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
indicator("Micro Zigzag", overlay = false, max_lines_count=500)
import HeWhoMustNotBeNamed/_matrix/5 as ma
ltf = input.timeframe('1', 'Lower timeframe')
add_new_pivot(matrix<float> zigzag, array<float> pivot, simple int maxItems=20)=>
newPivot = false
deleteLast = false
if(matrix.rows(zigzag) == 0)
ma.unshift(zigzag, pivot, maxItems)
newPivot := true
else
lastPivot = matrix.row(zigzag, 0)
if array.get(lastPivot,3) == array.get(pivot,3) and array.get(pivot,0)*array.get(pivot,3) > array.get(lastPivot,0)*array.get(pivot,3)
ma.shift(zigzag)
deleteLast := true
if array.get(pivot,0)*array.get(pivot,3) > array.get(lastPivot,0)*array.get(pivot,3)
ma.unshift(zigzag, pivot, maxItems)
newPivot := true
[newPivot, deleteLast]
draw_line(array<float> lastPivot, array<float> currentPivot)=>
lineColor = array.get(currentPivot,3) > 0? color.green : color.red
ln = line.new(int(array.get(lastPivot,2)), array.get(lastPivot,0), int(array.get(currentPivot,2)), array.get(currentPivot,0), xloc.bar_time, extend.none, lineColor, line.style_solid, 1)
ln
draw_zigzag(zigzaglines, zigzag, newPivot, deleteLast)=>
if(deleteLast)
line.delete(array.shift(zigzaglines))
if(newPivot and matrix.rows(zigzag) > 1)
pivot = matrix.row(zigzag, 0)
lastPivot = matrix.row(zigzag, 1)
array.unshift(zigzaglines, draw_line(lastPivot, pivot))
if(array.size(zigzaglines) > 500)
line.delete(array.pop(zigzaglines))
[lh, ll, lv] = request.security_lower_tf(syminfo.tickerid, ltf, [high, low, volume], true)
hIndices = array.sort_indices(lh, order.descending)
highestIndex = array.size(hIndices) >= 5? array.get(hIndices, 0) : na
lIndices = array.sort_indices(ll, order.ascending)
lowestIndex = array.size(lIndices) >= 5? array.get(lIndices, 0) : na
var zigzag = matrix.new<float>()
var zigzaglines = array.new<line>()
if not na(highestIndex) and not na(lowestIndex)
array<float> pivothigh = array.from(high, bar_index, time, 1)
array<float> pivotlow = array.from(low, bar_index, time, -1)
[newPivot1, deleteLast1] = add_new_pivot(zigzag, highestIndex<lowestIndex?pivothigh:pivotlow)
draw_zigzag(zigzaglines, zigzag, newPivot1, deleteLast1)
[newPivot2, deleteLast2] = add_new_pivot(zigzag, highestIndex<lowestIndex?pivotlow:pivothigh)
draw_zigzag(zigzaglines, zigzag, newPivot2, deleteLast2)
|
GFast_%R+stoch+rsi | https://www.tradingview.com/script/YtH0X7xT-GFast-R-stoch-rsi/ | gfastjamwork | https://www.tradingview.com/u/gfastjamwork/ | 4 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gfastjamwork
//@version=4
//udy("GFast")
study("GFast_%R+stoch", shorttitle="%G", overlay=0)
//============================================================================//
// stoch //
smoothK = input(3, "K", minval=1)
smoothD = input(3, "D", minval=1)
lengthRSI = input(14, "RSI Length", minval=1)
lengthStoch = input(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = rsi(src, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)
plot(k, "K", color=#0094FF)
plot(d, "D", color=#FF6A00)
h0 = hline(80, "Upper Band", color=#606060)
h1 = hline(20, "Lower Band", color=#606060)
//fill(h0, h1, color.rgb(153, 21, 255,80), title="Background")
//==========================================================================//
// %R //
length = input(title="Length", type=input.integer, defval=14)
src2 = input(close, "Source", type = input.source)
_pr(length) =>
max = highest(length)
min = lowest(length)
-100 * (src2 - min) / (min - max)
percentR = _pr(length)
plot(percentR, title="%R", color=#FF9800 ,linewidth=2)
//==========================================================================//
///****************************************************************************//
//Bull = _pr(length) < d
//Bear = d > _pr(length)
///=== Display %G lines =====
//GG = plot(percentR, title="%R", color=#7E57C2,linewidth=2)
//StochG = plot(d, "D", color=#FF6A00)
//fillcolor = Bull ? color.rgb(50,205,50,80) : Bear ? color.red : color.rgb(255,3,3,80)
//fill(GG,StochG,fillcolor)
//@version=4
//study(title="Relative Strength Index", shorttitle="RSI", format=format.price, precision=2, resolution="")
len = input(14, minval=1, title="Length")
src3 = input(close, "Source", type = input.source)
up = rma(max(change(src3), 0), len)
down = rma(-min(change(src3), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
plot(rsi, "RSI", color.white , linewidth=2)
band1 = hline(70, "Upper Band", color=#787B86)
bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))
band0 = hline(30, "Lower Band", color=#787B86)
fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background")
|
Market Signals Complex | https://www.tradingview.com/script/gCL20Hdz-Market-Signals-Complex/ | chinmaysk1 | https://www.tradingview.com/u/chinmaysk1/ | 30 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chinmaysk1
//@version=4
study("Market Signals Complex", overlay=true)
// plot(close, title="Option 1", color=color.silver, linewidth=2, style=plot.style_line, trackprice=true, editable=false)
// Relative Strength Index
// RSI Input
rsiSource = input(title="RSI Source", type=input.source, defval=close)
rsiLength = input(title="RSI Length", type=input.integer, defval=14)
rsiOverbought = input(title="RSI Overbought Level", type=input.integer, defval=65)
rsiOversold = input(title="RSI Oversold Level", type=input.integer, defval=35)
// Get RSI Value
rsiValue = rsi(rsiSource, rsiLength)
isRsiOB = rsiValue >= rsiOverbought
isRsiOS = rsiValue <= rsiOversold
// RSI Buy/Sell Signals
plotshape(isRsiOB, title="Overbought", location=location.abovebar, color=color.red, transp=0, style=shape.triangledown, size=size.tiny)
plotshape(isRsiOS, title="Oversold", location=location.belowbar, color=color.green, transp=0, style=shape.triangleup, size=size.tiny)
// Bullish Engulfing Candles
bullEng = close >= open[1] and close[1] < open[1]
bearEng = close <= open[1] and close[1] > open[1]
printEng = ((isRsiOS or isRsiOS[1] and bullEng) or (isRsiOB or isRsiOB[1] and bearEng))
plotshape(printEng and bullEng, title="Bullish Engulfing", location=location.belowbar, color=color.blue, transp=0, style=shape.flag, size=size.tiny, text="Engulfing")
plotshape(printEng and bearEng, title="Bearish Engulfing", location=location.abovebar, color=color.orange, transp=0, style=shape.flag, size=size.tiny, text="Engulfing")
// EMA Bands
showRibbon = input(true, "Show Ribbon")
ema_1 = input(5, title="EMA 1 Length")
ema_2 = input(18, title="EMA 2 Length")
ema_3 = input(21, title="EMA 3 Length")
ema_4 = input(28, title="EMA 4 Length")
ema_5 = input(34, title="EMA 5 Length")
ema1 = ema(close, ema_1)
ema2 = ema(close, ema_2)
ema3 = ema(close, ema_3)
ema4 = ema(close, ema_4)
ema5 = ema(close, ema_5)
ribbonDir = ema5 < ema2
colorEma = ribbonDir ? color.green : color.red
p1 = plot(ema1, color=showRibbon ? ribbonDir ? #1573d4 : color.gray : na, linewidth=2, transp=15, title="EMA 1")
p2 = plot(ema2, color=showRibbon ? ribbonDir ? #3096ff : color.gray : na, linewidth=2, transp=15, title="EMA 2")
plot(ema3, color=showRibbon ? ribbonDir ? #57abff : color.gray : na, linewidth=2, transp=15, title="EMA 3")
plot(ema4, color=showRibbon ? ribbonDir ? #85c2ff : color.gray : na, linewidth=2, transp=15, title="EMA 4")
plot(ema5, color=showRibbon ? ribbonDir ? #9bcdff : color.gray : na, linewidth=2, transp=15, title="EMA 5")
p8 = plot(ema5, color=showRibbon ? na : colorEma, linewidth=2, transp=0, title="EMA 8")
fill(p1, p2, color = #1573d4, transp = 85)
fill(p2, p8, color = #363a45, transp = 85)
// Long EMAs
showLongEMA = input(true, "Show Long EMAs")
emaLong_1 = input(50, title = "Long EMA Length 1")
emaLong_2 = input(200, title = "Long EMA Length 2")
emaLong1 = ema(close, emaLong_1)
emaLong2 = ema(close, emaLong_2)
plot(emaLong1, transp=showLongEMA ? 0 : 100, color = color.purple, linewidth=2, title="EMA Long 1")
plot(emaLong2, transp=showLongEMA ? 0 : 100, color = color.red, linewidth=2, title="EMA Long 2")
// BB Area
showBB = input(true, "Show Bollinger Bands")
length = input(20, minval=1)
src = input(close, title="Source")
mult1 = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis1 = sma(src, length)
dev1 = mult1 * stdev(src, length)
upper1 = basis1 + dev1
lower1 = basis1 - dev1
mult2 = input(3.0, minval=0.001, maxval=50, title="StdDev")
basis2 = sma(src, length)
dev2 = mult2 * stdev(src, length)
upper2 = basis2 + dev2
lower2 = basis2 - dev2
mult3 = input(4.0, minval=0.001, maxval=50, title="StdDev")
basis3 = sma(src, length)
dev3 = mult3 * stdev(src, length)
upper3 = basis3 + dev3
lower3 = basis3 - dev3
mult4 = input(6.0, minval=0.001, maxval=50, title="StdDev")
basis4 = sma(src, length)
dev4 = mult4 * stdev(src, length)
upper4 = basis4 + dev4
lower4 = basis4 - dev4
offset = input(0, "Offset", minval = -500, maxval = 500)
p1_1 = plot(upper1, transp=showBB ? 85 : 100, title="Upper", color=#fc7f03, offset = offset)
p2_2 = plot(lower1, transp=showBB ? 85 : 100, title="Lower", color=#fc7f03, offset = offset)
fill(p1_1, p2_2, transp=showBB ? 0 : 100, title = "Background", color=color.rgb(252, 127, 3, 98))
p1_3 = plot(upper2, transp=showBB ? 85 : 100, title="Upper", color=color.rgb(252, 148, 3, 85), offset = offset)
p2_4 = plot(lower2, transp=showBB ? 85 : 100, title="Lower", color=color.rgb(252, 148, 3, 85), offset = offset)
p1_5 = plot(upper3, transp=showBB ? 85 : 100, title="Upper", color=#fc2803, offset = offset)
p2_6 = plot(lower3, transp=showBB ? 85 : 100, title="Lower", color=#fc2803, offset = offset)
p1_7 = plot(upper4, transp=showBB ? 85 : 100, title="Upper", color=#fc2803, offset = offset)
p2_8 = plot(lower4, transp=showBB ? 85 : 100, title="Lower", color=#fc2803, offset = offset)
// Fill Upper Bands
fill(p1_1, p1_3, transp=showBB ? 0 : 100, title = "Background", color=color.rgb(255, 71, 46, 70))
fill(p1_3, p1_5, transp=showBB ? 0 : 100, title = "Background", color=color.rgb(133, 16, 0, 65))
fill(p1_5, p1_7, transp=showBB ? 0 : 100, title = "Background", color=color.rgb(102, 12, 0, 80))
//Fill Lower Bands
fill(p2_2, p2_4, transp=showBB ? 0 : 100, title = "Background", color=color.rgb(30, 115, 1, 70))
fill(p2_4, p2_6, transp=showBB ? 0 : 100, title = "Background", color=color.rgb(23, 87, 1, 65))
fill(p2_6, p2_8, transp=showBB ? 0 : 100, title = "Background", color=color.rgb(14, 56, 0, 80))
// WT
n1 = input(10, "Channel Length")
n2 = input(21, "Average Length")
obLevel1 = input(60, "Over Bought Level 1")
obLevel2 = input(53, "Over Bought Level 2")
osLevel1 = input(-60, "Over Sold Level 1")
osLevel2 = input(-53, "Over Sold Level 2")
ap = hlc3
esa = ema(ap, n1)
d = ema(abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ema(ci, n2)
wt1 = tci
wt2 = sma(wt1, 4)
cross_01_up = crossover(wt1, wt2)
cross_01_down = crossunder(wt1, wt2)
// Green Cross
plotshape(cross_01_up and (wt2 <= -50), style=shape.labelup, text="↑", textcolor=color.white, transp=1, title="cross 01", color=color.green, size=size.small, location=location.belowbar)
//plotchar(cross_01_up and (rsi_1 <= 45), title="cross_01 Bottom", char="x", location=location.bottom, color=color.green, transp=5, text="Secret Cross", textcolor=color.green)
// Red Cross
plotshape(cross_01_down and (wt2 >= 50), style=shape.labeldown, text="↓", textcolor=color.white, transp=1, title="cross 01", color=color.red, size=size.small)
//plotchar(cross_01_down and (rsi_1 >= 60), title="cross_01 Bottom", char="x", location=location.bottom, color=color.red, transp=5, text="Secret Cross", textcolor=color.red)
|
Money Supply Index (MSI) by zdmre | https://www.tradingview.com/script/zGTdOlof-Money-Supply-Index-MSI-by-zdmre/ | zdmre | https://www.tradingview.com/u/zdmre/ | 193 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © zdmre
//@version=5
indicator("Money Supply Index (MSI) by zdmre")
MS2 = input.symbol("USM2", "Money Supply")
MS = request.security(MS2, "D", close)
crl = input.symbol("NASDAQ:NDX", "Relational Symbol")
vs = request.security(crl, "D", close)
mainsym = input.bool(defval=true, title="Symbol on Chart", tooltip="if Enabled; The Relationship between the Money Supply and Symbol on Chart. Else; MS relation with Relational Symbol" )
rate = mainsym ? MS/close : MS/vs
len = input.int(14, minval=1, title='Length')
up = ta.rma(math.max(ta.change(rate), 0), len)
down = ta.rma(-math.min(ta.change(rate), 0), len)
msi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + down / up)
band1 = hline(70, "Upper Band", color=#787B86)
bandhl = hline(60, "HL Band", color=color.new(#ff3d3d, 70))
bandlh = hline(40, "LH Band", color=color.new(#4cff3d, 70))
band0 = hline(30, "Lower Band", color=#787B86)
ob= ta.cross(msi, 70) == 1 and msi >= 70
os = ta.cross(msi, 30) == 1 and msi <= 30
fill(band1, bandhl, color=color.new(#ff0000, 95), title="Background Upper Band")
fill(bandlh, bandhl, color=color.rgb(126, 87, 194, 90), title="Background Neutral")
fill(band0, bandlh, color=color.new(#32ff00, 95), title="Background Lower Band")
plot(msi, 'MSI', color=color.new(#7E57C2, 0))
plot(ob ? msi : na ,title='Overbought', style=plot.style_circles, color=color.new(color.red, 0), linewidth=5)
plot(os ? msi : na ,title='Oversold ', style=plot.style_circles, color=color.new(color.green, 0), linewidth=5)
var label1 = label.new(100, 65, text="not to Buy!", style=label.style_text_outline, size=size.large, color=color.new(#ff0000, 75))
label.set_xloc(label1, time[50], xloc.bar_time)
var label2 = label.new(0, 35, text="not to Sell!", style=label.style_text_outline, size=size.large, color=color.new(#32ff00, 75))
label.set_xloc(label2, time[50], xloc.bar_time) |
Mahi A E Haveri | https://www.tradingview.com/script/DQVf25YC-Mahi-A-E-Haveri/ | per.mahendra | https://www.tradingview.com/u/per.mahendra/ | 2 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © per.mahendra
//@version=5
indicator(title="ALL_EME", overlay= true)
ema5 = ta.ema(close, 5)
ema9 = ta.ema(close, 9)
ema21 = ta.ema(close, 21)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
plot(series = ema5, color = color.black, linewidth = 2)
plot(series = ema9, color = color.orange, linewidth = 2)
plot(series = ema21, color = color.blue, linewidth = 2)
plot(series = ema50, color = color.red, linewidth = 2)
plot(series = ema200, color = color.green, linewidth = 2) |
CPR with MAs, Super Trend & VWAP by Mackrani | https://www.tradingview.com/script/oKkhDb76-CPR-with-MAs-Super-Trend-VWAP-by-Mackrani/ | raashidmackrani | https://www.tradingview.com/u/raashidmackrani/ | 122 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © raashidmackrani
//@version=4
//***************GUIDE***********************************
//CPR - Applicable only for daily pivots
//CPR - All 3 lines display enabled by default
//CPR - Central Pivot line display cannot changed
//CPR - Central Pivot is a blue line by default and can be changed from settings
//CPR - Top Range & Bottom Ranage display can be changed from settings
//CPR - Top Range & Bottom Ranage are Yellow lines by default and can be chaned from settings
//Daily pivots - Pivot line and CPR Central line are same
//Daily pivots - level 1 & 2 (S1, R1, S2 R2) display enabled by default and can be changed from settings
//Daily pivots - level 3 (S3 & R3) is availale and can be seleted from settings
//Daily pivots - Resistance(R) lines are Red lines and can be changed from settings
//Daily pivots - Support(S) lines are Green lines and can be changed from settings
//Weekly pivots - Pivot is a blue line by default and can be changed from settings
//Weekly pivots - 3 levels (S1, R1, S2, R2, S3 & R3) availale and can be seleted from settings
//Weekly pivots - Resistance(R) lines are crossed (+) Red lines and can be changed from settings
//Weekly pivots - Support(S) lines are crossed (+) Green lines and can be changed from settings
//Monthly pivots - Pivot is a blue line by default and can be changed from settings
//Monthly pivots - 3 levels (S1, R1, S2, R2, S3 & R3) availale and can be seleted from settings
//Monthly pivots - Resistance(R) lines are circled (o) Red lines and can be changed from settings
//Monthly pivots - Support(S) lines are circled (o) Green lines and can be changed from settings
study("CPR with MAs, Super Trend & VWAP by Mackrani", overlay = true, shorttitle="Mackrani CPR",precision=1)
//******************LOGICS**************************
//cenral pivot range
pivot = (high + low + close) /3 //Central Povit
BC = (high + low) / 2 //Below Central povit
TC = (pivot - BC) + pivot //Top Central povot
//3 support levels
S1 = (pivot * 2) - high
S2 = pivot - (high - low)
S3 = low - 2 * (high - pivot)
//3 resistance levels
R1 = (pivot * 2) - low
R2 = pivot + (high - low)
R3 = high + 2 * (pivot-low)
//Checkbox inputs
CPRPlot = input(title = "Plot CPR?", type=input.bool, defval=true)
DayS1R1 = input(title = "Plot Daiy S1/R1?", type=input.bool, defval=true)
DayS2R2 = input(title = "Plot Daiy S2/R2?", type=input.bool, defval=false)
DayS3R3 = input(title = "Plot Daiy S3/R3?", type=input.bool, defval=false)
WeeklyPivotInclude = input(title = "Plot Weekly Pivot?", type=input.bool, defval=false)
WeeklyS1R1 = input(title = "Plot weekly S1/R1?", type=input.bool, defval=false)
WeeklyS2R2 = input(title = "Plot weekly S2/R2?", type=input.bool, defval=false)
WeeklyS3R3 = input(title = "Plot weekly S3/R3?", type=input.bool, defval=false)
MonthlyPivotInclude = input(title = "Plot Montly Pivot?", type=input.bool, defval=false)
MonthlyS1R1 = input(title = "Plot Monthly S1/R1?", type=input.bool, defval=false)
MonthlyS2R2 = input(title = "Plot Monthly S2/R2?", type=input.bool, defval=false)
MonthlyS3R3 = input(title = "Plot Montly S3/R3?", type=input.bool, defval=false)
//******************DAYWISE CPR & PIVOTS**************************
// Getting daywise CPR
DayPivot = security(syminfo.tickerid, "D", pivot[1], barmerge.gaps_off, barmerge.lookahead_on)
DayBC = security(syminfo.tickerid, "D", BC[1], barmerge.gaps_off, barmerge.lookahead_on)
DayTC = security(syminfo.tickerid, "D", TC[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks daywse for CPR
CPColour = DayPivot != DayPivot[1] ? na : color.blue
BCColour = DayBC != DayBC[1] ? na : color.blue
TCColour = DayTC != DayTC[1] ? na : color.blue
//Plotting daywise CPR
plot(DayPivot, title = "CP" , color = CPColour, style = plot.style_linebr, linewidth =2)
plot(CPRPlot ? DayBC : na , title = "BC" , color = BCColour, style = plot.style_line, linewidth =1)
plot(CPRPlot ? DayTC : na , title = "TC" , color = TCColour, style = plot.style_line, linewidth =1)
// Getting daywise Support levels
DayS1 = security(syminfo.tickerid, "D", S1[1], barmerge.gaps_off, barmerge.lookahead_on)
DayS2 = security(syminfo.tickerid, "D", S2[1], barmerge.gaps_off, barmerge.lookahead_on)
DayS3 = security(syminfo.tickerid, "D", S3[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for daywise Support levels
DayS1Color =DayS1 != DayS1[1] ? na : color.green
DayS2Color =DayS2 != DayS2[1] ? na : color.green
DayS3Color =DayS3 != DayS3[1] ? na : color.green
//Plotting daywise Support levels
plot(DayS1R1 ? DayS1 : na, title = "D-S1" , color = DayS1Color, style = plot.style_line, linewidth =1)
plot(DayS2R2 ? DayS2 : na, title = "D-S2" , color = DayS2Color, style = plot.style_line, linewidth =1)
plot(DayS3R3 ? DayS3 : na, title = "D-S3" , color = DayS3Color, style = plot.style_line, linewidth =1)
// Getting daywise Resistance levels
DayR1 = security(syminfo.tickerid, "D", R1[1], barmerge.gaps_off, barmerge.lookahead_on)
DayR2 = security(syminfo.tickerid, "D", R2[1], barmerge.gaps_off, barmerge.lookahead_on)
DayR3 = security(syminfo.tickerid, "D", R3[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for daywise Support levels
DayR1Color =DayR1 != DayR1[1] ? na : color.red
DayR2Color =DayR2 != DayR2[1] ? na : color.red
DayR3Color =DayR3 != DayR3[1] ? na : color.red
//Plotting daywise Resistance levels
plot(DayS1R1 ? DayR1 : na, title = "D-R1" , color = DayR1Color, style = plot.style_line, linewidth =1)
plot(DayS2R2 ? DayR2 : na, title = "D-R2" , color = DayR2Color, style = plot.style_line, linewidth =1)
plot(DayS3R3 ? DayR3 : na, title = "D-R3" , color = DayR3Color, style = plot.style_line, linewidth =1)
//******************WEEKLY PIVOTS**************************
// Getting Weely Pivot
WPivot = security(syminfo.tickerid, "W", pivot[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for Weely Pivot
WeeklyPivotColor =WPivot != WPivot[1] ? na : color.blue
//Plotting Weely Pivot
plot(WeeklyPivotInclude ? WPivot:na, title = "W-P" , color = WeeklyPivotColor, style = plot.style_circles, linewidth =1)
// Getting Weely Support levels
WS1 = security(syminfo.tickerid, "W", S1[1],barmerge.gaps_off, barmerge.lookahead_on)
WS2 = security(syminfo.tickerid, "W", S2[1],barmerge.gaps_off, barmerge.lookahead_on)
WS3 = security(syminfo.tickerid, "W", S3[1],barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for weekly Support levels
WS1Color =WS1 != WS1[1] ? na : color.green
WS2Color =WS2 != WS2[1] ? na : color.green
WS3Color =WS3 != WS3[1] ? na : color.green
//Plotting Weely Support levels
plot(WeeklyS1R1 ? WS1 : na, title = "W-S1" , color = WS1Color, style = plot.style_cross, linewidth =1)
plot(WeeklyS2R2 ? WS2 : na, title = "W-S2" , color = WS2Color, style = plot.style_cross, linewidth =1)
plot(WeeklyS3R3 ? WS3 : na, title = "W-S3" , color = WS3Color, style = plot.style_cross, linewidth =1)
// Getting Weely Resistance levels
WR1 = security(syminfo.tickerid, "W", R1[1], barmerge.gaps_off, barmerge.lookahead_on)
WR2 = security(syminfo.tickerid, "W", R2[1], barmerge.gaps_off, barmerge.lookahead_on)
WR3 = security(syminfo.tickerid, "W", R3[1], barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for weekly Resistance levels
WR1Color = WR1 != WR1[1] ? na : color.red
WR2Color = WR2 != WR2[1] ? na : color.red
WR3Color = WR3 != WR3[1] ? na : color.red
//Plotting Weely Resistance levels
plot(WeeklyS1R1 ? WR1 : na , title = "W-R1" , color = WR1Color, style = plot.style_cross, linewidth =1)
plot(WeeklyS2R2 ? WR2 : na , title = "W-R2" , color = WR2Color, style = plot.style_cross, linewidth =1)
plot(WeeklyS3R3 ? WR3 : na , title = "W-R3" , color = WR3Color, style = plot.style_cross, linewidth =1)
//******************MONTHLY PIVOTS**************************
// Getting Monhly Pivot
MPivot = security(syminfo.tickerid, "M", pivot[1],barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for Monthly Support levels
MonthlyPivotColor =MPivot != MPivot[1] ? na : color.blue
//Plotting Monhly Pivot
plot(MonthlyPivotInclude? MPivot:na, title = " M-P" , color = MonthlyPivotColor, style = plot.style_line, linewidth =1)
// Getting Monhly Support levels
MS1 = security(syminfo.tickerid, "M", S1[1],barmerge.gaps_off, barmerge.lookahead_on)
MS2 = security(syminfo.tickerid, "M", S2[1],barmerge.gaps_off, barmerge.lookahead_on)
MS3 = security(syminfo.tickerid, "M", S3[1],barmerge.gaps_off, barmerge.lookahead_on)
//Adding linebreaks for Montly Support levels
MS1Color =MS1 != MS1[1] ? na : color.green
MS2Color =MS2 != MS2[1] ? na : color.green
MS3Color =MS3 != MS3[1] ? na : color.green
//Plotting Monhly Support levels
plot(MonthlyS1R1 ? MS1 : na, title = "M-S1" , color = MS1Color, style = plot.style_circles, linewidth =1)
plot(MonthlyS2R2 ? MS2 : na, title = "M-S2" , color = MS2Color, style = plot.style_circles, linewidth =1)
plot(MonthlyS3R3 ? MS3 : na, title = "M-S3" , color = MS3Color, style = plot.style_circles, linewidth =1)
// Getting Monhly Resistance levels
MR1 = security(syminfo.tickerid, "M", R1[1],barmerge.gaps_off, barmerge.lookahead_on)
MR2 = security(syminfo.tickerid, "M", R2[1],barmerge.gaps_off, barmerge.lookahead_on)
MR3 = security(syminfo.tickerid, "M", R3[1],barmerge.gaps_off, barmerge.lookahead_on)
MR1Color =MR1 != MR1[1] ? na : color.red
MR2Color =MR2 != MR2[1] ? na : color.red
MR3Color =MR3 != MR3[1] ? na : color.red
//Plotting Monhly Resistance levels
plot(MonthlyS1R1 ? MR1 : na , title = "M-R1", color = MR1Color, style = plot.style_circles , linewidth =1)
plot(MonthlyS2R2 ? MR2 : na , title = "M-R2" , color = MR2Color, style = plot.style_circles, linewidth =1)
plot(MonthlyS3R3 ? MR3 : na, title = "M-R3" , color = MR3Color, style = plot.style_circles, linewidth =1)
//*****************************INDICATORs**************************
//SMA
PlotSMA = input(title = "Plot SMA?", type=input.bool, defval=true)
SMALength = input(title="SMA Length", type=input.integer, defval=50)
SMASource = input(title="SMA Source", type=input.source, defval=close)
SMAvg = sma (SMASource, SMALength)
plot(PlotSMA ? SMAvg : na, color= color.orange, title="SMA")
//EMA
PlotEMA = input(title = "Plot EMA?", type=input.bool, defval=true)
EMALength = input(title="EMA Length", type=input.integer, defval=50)
EMASource = input(title="EMA Source", type=input.source, defval=close)
EMAvg = ema (EMASource, EMALength)
plot(PlotEMA ? EMAvg : na, color= color.red, title="EMA")
//VWAP
PlotVWAP = input(title = "Plot VWAP?", type=input.bool, defval=true)
VWAPSource = input(title="VWAP Source", type=input.source, defval=close)
VWAPrice = vwap (VWAPSource)
plot(PlotVWAP ? VWAPrice : na, color= color.teal, title="VWAP")
//SuperTrend
PlotSTrend = input(title = "Plot Super Trend?", type=input.bool, defval=true)
InputFactor=input(3, minval=1,maxval = 100, title="Factor")
InputLength=input(10, minval=1,maxval = 100, title="Lenght")
BasicUpperBand=hl2-(InputFactor*atr(InputLength))
BasicLowerBand=hl2+(InputFactor*atr(InputLength))
FinalUpperBand=0.0
FinalLowerBand=0.0
FinalUpperBand:=close[1]>FinalUpperBand[1]? max(BasicUpperBand,FinalUpperBand[1]) : BasicUpperBand
FinalLowerBand:=close[1]<FinalLowerBand[1]? min(BasicLowerBand,FinalLowerBand[1]) : BasicLowerBand
IsTrend=0.0
IsTrend:= close > FinalLowerBand[1] ? 1: close< FinalUpperBand[1]? -1: nz(IsTrend[1],1)
STrendline = IsTrend==1? FinalUpperBand: FinalLowerBand
linecolor = IsTrend == 1 ? color.green : color.red
Plotline = (PlotSTrend? STrendline: na)
plot(Plotline, color = linecolor , style = plot.style_line , linewidth = 1,title = "SuperTrend")
PlotShapeUp = cross(close,STrendline) and close>STrendline
PlotShapeDown = cross(STrendline,close) and close<STrendline
plotshape(PlotSTrend? PlotShapeUp: na, "Up Arrow", shape.triangleup,location.belowbar,color.green,0,0)
plotshape(PlotSTrend? PlotShapeDown: na , "Down Arrow", shape.triangledown , location.abovebar, color.red,0,0) |
EMA curves | https://www.tradingview.com/script/Zok4XXeD-EMA-curves/ | aasimaero | https://www.tradingview.com/u/aasimaero/ | 2 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Aasim Aero
//@version=5
indicator('EMA curves', shorttitle='EMA', overlay=true)
src = input(close, title='Source')
len1 = input.int(9, minval=1, title='Length')
out1 = ta.ema(src, len1)
len2 = input.int(21, minval=1, title='Length')
out2 = ta.ema(src, len2)
len3 = input.int(55, minval=1, title='Length')
out3 = ta.ema(src, len3)
len4 = input.int(100, minval=1, title='Length')
out4 = ta.ema(src, len4)
len5 = input.int(200, minval=1, title='Length')
out5 = ta.ema(src, len5)
plot(out1, title='EMA', color=color.rgb(255, 153, 0, 20), linewidth=2)
plot(out2, title='EMA', color=color.rgb(0, 128, 0, 40), linewidth=2)
plot(out3, title='EMA', color=color.rgb(0, 0, 255, 40), linewidth=2)
plot(out4, title='EMA', color=color.rgb(0, 0, 0, 40), linewidth=2)
plot(out5, title='EMA', color=color.rgb(255, 0, 0, 40), linewidth=2) |
Aggregated Rolling VWAP + | https://www.tradingview.com/script/8TdKPb9z-Aggregated-Rolling-VWAP/ | In_Finito_ | https://www.tradingview.com/u/In_Finito_/ | 110 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Orignal Code by © TradingView
// Modified & Added Code by InFinito
//@version=5
indicator("Aggregated Rolling VWAP +", "ARVWAP+", true, precision = 4)
// Rolling VWAP
// v3, 2022.07.24
// InFinito Edit 2022.09.22
// Edit log:
// - Added Volume Aggregation Capabilities to the Script
// - Added Symmetrical Deviations to the Script
// - Switched default option to manual TF instead of automatic TF
// - Added TF Presets for quick switching between different settings. (This feature is mostly intended for mobile charting)
// - Added ON/OFF Switch to all individual deviations to make it easier, faster and cleaner to display different data. (This feature is mostly intended for mobile charting)
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/ConditionalAverages/1 as pc
// ———————————————————— Constants and Inputs {
// ————— Constants
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int MS_IN_DAY = MS_IN_HOUR * 24
string TT_SRC = "The source used to calculate the VWAP. The default is the average of the high, low and close prices."
string TT_WINDOW = "The Script can estimate the ideal TF for the RVWAP at any given TF by selecting this option.
Check this to use a fixed-size time period instead, which you define with the following three values."
string TT_MINBARS = "The minimum number of last values to keep in the moving window, even if these values are outside the time period.
This avoids situations where a large time gap between two bars would cause the time window to be empty."
string TT_STDEV = "The multiplier for the standard deviation bands offset above and below the RVWAP. Example: 1.0 is 100% of the offset value.
\n\nNOTE: A value of 0.0 will hide the bands."
string TT_TABLE = "Displays the time period of the rolling window."
string AGGR_TT = "Disable to check by symbol. Indicator preset to use BTC data, if you are to use another symbol: 1. Disable this option OR 2. Manually select from which symbols to aggregate at the bottom of this menu"
// ————— Inputs
float srcInput = input.source(hlc3, "Source", group = "source", inline ="1", tooltip = TT_SRC)
bool aggr = input.bool(defval=true, title='Use Aggregated Data', group = "source", inline ="1", tooltip= AGGR_TT)
string GRP2 = '═══════════ Time Period ═══════════'
bool fixedTfInput = input.bool(false, "Automatic TF selection", group = GRP2, tooltip = TT_WINDOW)
bool presetDsw = input.bool(true, " ", group = GRP2, inline="1")
int pdaysInput = input.int(7, "Preset Days", group = GRP2, inline="1", options=[1,3,5,7,14,21,28,30,60,90,182,365]) * MS_IN_DAY
int daysInput = presetDsw ? pdaysInput : (input.int(1, "Custom Days", group = GRP2, minval = 0, maxval = 365, inline="1") * MS_IN_DAY)
bool presetHsw = input.bool(false, " ", group = GRP2, inline="2")
int phoursInput = input.int(4, "Preset Hours", group = GRP2, inline="2", options=[1,2,4,8,12]) * MS_IN_HOUR
int hoursInput = presetHsw ? phoursInput : (input.int(0, "Custom Hours", group = GRP2, minval = 0, maxval = 23, inline="2") * MS_IN_HOUR)
bool presetMsw = input.bool(false, " ", group = GRP2, inline="3")
int pminsInput = input.int(15, "Preset Minutes", group = GRP2, inline="3", options=[3,5,15,30,45,90]) * MS_IN_MIN
int minsInput = presetMsw ? pminsInput : ( input.int(0, "Custom Minutes", group = GRP2, minval = 0, maxval = 59, inline="3") * MS_IN_MIN)
bool showInfoBoxInput = input.bool(true, "Show time period", group = GRP2)
string infoBoxSizeInput = input.string("small", "Size ", inline = "21", group = GRP2, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string infoBoxYPosInput = input.string("bottom", "↕", inline = "21", group = GRP2, options = ["top", "middle", "bottom"])
string infoBoxXPosInput = input.string("left", "↔", inline = "21", group = GRP2, options = ["left", "center", "right"])
color infoBoxColorInput = input.color(color.gray, "", inline = "21", group = GRP2)
color infoBoxTxtColorInput = input.color(color.white, "T", inline = "21", group = GRP2)
string GRP3 = '═════════ Standard Deviation Bands ═════════'
bool std1sw = input.bool(false , "" , group = GRP3, inline = "31")
bool std2sw = input.bool(true , "" , group = GRP3, inline = "32")
bool std3sw = input.bool(false , "" , group = GRP3, inline = "33")
float stdevMult1 = input.float(1, "Bands Multiplier 1", group = GRP3, inline = "31", minval = 0.0, step = 0.5)
float stdevMult2 = input.float(2, "Bands Multiplier 2", group = GRP3, inline = "32", minval = 0.0, step = 0.5 )
float stdevMult3 = input.float(3, "Bands Multiplier 3", group = GRP3, inline = "33", minval = 0.0, step = 0.5 )
color stdevColor1 = input.color(color.yellow, "", group = GRP3, inline = "31")
color stdevColor2 = input.color(color.green, "", group = GRP3, inline = "32")
color stdevColor3 = input.color(color.red, "", group = GRP3, inline = "33")
string GRP4 = '═════════ Symmetrical Deviation Bands ═════════'
bool sd1sw = input.bool(false , "" , group = GRP4, inline = "1")
bool sd2sw = input.bool(false , "" , group = GRP4, inline = "2")
bool sd3sw = input.bool(false , "" , group = GRP4, inline = "3")
float sdevMult1 = input.float(3, "Percentage Multiplier 1", group = GRP4, inline = "1", minval = 0.00001, step = 0.5 )/100
float sdevMult2 = input.float(5, "Percentage Multiplier 2", group = GRP4, inline = "2", minval = 0.00001, step = 0.5 )/100
float sdevMult3 = input.float(10, "Percentage Multiplier 3", group = GRP4, inline = "3", minval = 0.00001, step = 0.5 )/100
color sdevColor1 = input.color(color.olive, "", group = GRP4, inline = "1")
color sdevColor2 = input.color(color.yellow, "", group = GRP4, inline = "2")
color sdevColor3 = input.color(color.red, "", group = GRP4, inline = "3")
string GRP5 = '════════ Minimum Window Size ════════'
int minBarsInput = input.int(10, "Bars", group = GRP5, tooltip = TT_MINBARS)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// Inputs FOR AGGREGATION//////////////////////////////////////////////////////////////////////////////
string GRP6 = '════════ Aggregation Symbols ════════'
i_sym1 = input.bool(true, '', inline='1', group=GRP6)
i_sym2 = input.bool(true, '', inline='2', group=GRP6)
i_sym3 = input.bool(true, '', inline='3', group=GRP6)
i_sym4 = input.bool(true, '', inline='4', group=GRP6)
i_sym5 = input.bool(true, '', inline='5', group=GRP6)
i_sym1_ticker = input.symbol('BINANCE:BTCUSDT', '', inline='1', group=GRP6)
i_sym2_ticker = input.symbol('COINBASE:BTCUSD', '', inline='2', group=GRP6)
i_sym3_ticker = input.symbol('BITSTAMP:BTCUSD', '', inline='3', group=GRP6)
i_sym4_ticker = input.symbol('OKX:BTCUSDT', '', inline='4', group=GRP6)
i_sym5_ticker = input.symbol('BITFINEX:BTCUSD', '', inline='5', group=GRP6)
sbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group=GRP6)
sbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group=GRP6)
sbase3 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='3', group=GRP6)
sbase4 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='4', group=GRP6)
sbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group=GRP6)
samount1 = input.float(defval=1, title='#', inline='1', group=GRP6)
samount2 = input.float(defval=1, title='#', inline='2', group=GRP6)
samount3 = input.float(defval=1, title='#', inline='3', group=GRP6)
samount4 = input.float(defval=1, title='#', inline='4', group=GRP6)
samount5 = input.float(defval=1, title='#', inline='5', group=GRP6)
/////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// }
// ———————————————————— Functions {
// @function Determines a time period from the chart's timeframe.
// @returns (int) A value of time in milliseconds that is appropriate for the current chart timeframe. To be used in the RVWAP calculation.
timeStep() =>
int tfInMs = timeframe.in_seconds() * 1000
float step =
switch
tfInMs <= MS_IN_MIN => MS_IN_HOUR
tfInMs <= MS_IN_MIN * 5 => MS_IN_HOUR * 4
tfInMs <= MS_IN_HOUR => MS_IN_DAY * 1
tfInMs <= MS_IN_HOUR * 4 => MS_IN_DAY * 3
tfInMs <= MS_IN_HOUR * 12 => MS_IN_DAY * 7
tfInMs <= MS_IN_DAY => MS_IN_DAY * 30.4375
tfInMs <= MS_IN_DAY * 7 => MS_IN_DAY * 90
=> MS_IN_DAY * 365
int result = int(step)
// @function Produces a string corresponding to the input time in days, hours, and minutes.
// @param (series int) A time value in milliseconds to be converted to a string variable.
// @returns (string) A string variable reflecting the amount of time from the input time.
tfString(int timeInMs) =>
int s = timeInMs / 1000
int m = s / 60
int h = m / 60
int tm = math.floor(m % 60)
int th = math.floor(h % 24)
int d = math.floor(h / 24)
string result =
switch
d == 30 and th == 10 and tm == 30 => "1M"
d == 7 and th == 0 and tm == 0 => "1W"
=>
string dStr = d ? str.tostring(d) + "D " : ""
string hStr = th ? str.tostring(th) + "H " : ""
string mStr = tm ? str.tostring(tm) + "min" : ""
dStr + hStr + mStr
// }
//// VOLUME REQUEST FUNCTION/////////////////////////////////////////
f_volume(_ticker) =>
request.security(_ticker, timeframe.period, volume)
/////////////////////////////////////////////////////////////////////////
///////////SPOT////////////////////////////////////////////////////////////////////
var float finvol = 0
if aggr==true ///////////SPOT//////////////////////////////////////////////////////////////////////////////////////////////////////
v1x = (i_sym1 ? f_volume(i_sym1_ticker) : 0)
v1 = sbase1=='Coin' ? v1x*samount1 : sbase1=='USD' or sbase1=='Other' ? (v1x*samount1)/ohlc4 : v1x
v2x = (i_sym2 ? f_volume(i_sym2_ticker) : 0)
v2 = sbase2=='Coin' ? v2x*samount2 : sbase2=='USD' or sbase2=='Other' ? (v2x*samount2)/ohlc4 : v2x
v3x = (i_sym3 ? f_volume(i_sym3_ticker) : 0)
v3 = sbase2=='Coin' ? v3x*samount3 : sbase3=='USD' or sbase3=='Other' ? (v3x*samount4)/ohlc4 : v3x
v4x = (i_sym4 ? f_volume(i_sym4_ticker) : 0)
v4 = sbase4=='Coin' ? v4x*samount4 : sbase4=='USD' or sbase4=='Other' ? (v4x*samount4)/ohlc4 : v4x
v5x = (i_sym5 ? f_volume(i_sym5_ticker) : 0)
v5 = sbase5=='Coin' ? v5x*samount5 : sbase5=='USD' or sbase5=='Other' ? (v5x*samount5)/ohlc4 : v5x
vsf=v1+v2+v3+v4+v5
/////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////FINAL AGGREGATION SELECTION////////////////////////////////////////
finvol := vsf
/////////////////////////////////////////////////////////////////////////////////////////////////
else if aggr==false
finvol := volume
/////////////////////////////////////////////////////////////////////////////////////////////////
// ———————————————————— Calculations and Plots {
// Stop the indicator on charts with no volume.
if barstate.islast and ta.cum(nz(finvol)) == 0
runtime.error("No volume is provided by the data vendor.")
// RVWAP + stdev bands
int timeInMs = not fixedTfInput ? minsInput + hoursInput + daysInput : timeStep()
float sumSrcVol = pc.totalForTimeWhen(srcInput * finvol, timeInMs, true, minBarsInput)
float sumVol = pc.totalForTimeWhen(finvol, timeInMs, true, minBarsInput)
float sumSrcSrcVol = pc.totalForTimeWhen(finvol * math.pow(srcInput, 2), timeInMs, true, minBarsInput)
float rollingVWAP = sumSrcVol / sumVol
float variance = sumSrcSrcVol / sumVol - math.pow(rollingVWAP, 2)
variance := math.max(0, variance)
float stDev = math.sqrt(variance)
float upperBand1 = rollingVWAP + stDev * stdevMult1
float lowerBand1 = rollingVWAP - stDev * stdevMult1
float upperBand2 = rollingVWAP + stDev * stdevMult2
float lowerBand2 = rollingVWAP - stDev * stdevMult2
float upperBand3 = rollingVWAP + stDev * stdevMult3
float lowerBand3 = rollingVWAP - stDev * stdevMult3
float uppersd1 = rollingVWAP + sdevMult1 * rollingVWAP
float lowersd1 = rollingVWAP - sdevMult1 * rollingVWAP
float uppersd2 = rollingVWAP + sdevMult2 * rollingVWAP
float lowersd2 = rollingVWAP - sdevMult2 * rollingVWAP
float uppersd3 = rollingVWAP + sdevMult3 * rollingVWAP
float lowersd3 = rollingVWAP - sdevMult3 * rollingVWAP
plot(rollingVWAP, "Rolling VWAP", color.orange, linewidth = sd1sw or sd2sw or sd3sw ? 2 : 1)
p1 = plot(std1sw ? upperBand1 : na, "Upper Band 1", stdevColor1)
p2 = plot(std1sw ? lowerBand1 : na, "Lower Band 1", stdevColor1)
p3 = plot(std2sw ? upperBand2 : na, "Upper Band 2", stdevColor2)
p4 = plot(std2sw ? lowerBand2 : na, "Lower Band 2", stdevColor2)
p5 = plot(std3sw ? upperBand3 : na, "Upper Band 3", stdevColor3)
p6 = plot(std3sw ? lowerBand3 : na, "Lower Band 3", stdevColor3)
s1 = plot(sd1sw ? uppersd1 : na, "Upper Symmetrical Dev 1", sdevColor1)
s2 = plot(sd1sw ? lowersd1 : na, "Lower Symmetrical Dev 1", sdevColor1)
s3 = plot(sd2sw ? uppersd2 : na, "Upper Symmetrical Dev 2", sdevColor2)
s4 = plot(sd2sw ? lowersd2 : na, "Lower Symmetrical Dev 2", sdevColor2)
s5 = plot(sd3sw ? uppersd3 : na, "Upper Symmetrical Dev 3", sdevColor3)
s6 = plot(sd3sw ? lowersd3 : na, "Lower Symmetrical Dev 3", sdevColor3)
fill(p1, p2, color.new(color.green, 95), "Bands Fill")
fill(p3, p4, color.new(color.green, 95), "Bands Fill")
fill(p5, p6, color.new(color.green, 95), "Bands Fill")
// Display of time period.
var table tfDisplay = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 1, 1)
if showInfoBoxInput and barstate.islastconfirmedhistory
table.cell(tfDisplay, 0, 0, tfString(timeInMs), bgcolor = infoBoxColorInput, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput)
// } |
7EMA_6MA + Fill EMA++ | https://www.tradingview.com/script/oZyE8pBO-7ema-6ma-fill-ema/ | FollowTheTrendForever | https://www.tradingview.com/u/FollowTheTrendForever/ | 22 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Andrey Semenov
//@version=4
study("7EMA_6MA + Fill EMA++" , overlay=true)
// INPUT
e1 = input(title="EMA-1", type=input.integer, defval=5)
e2 = input(title="EMA-2", type=input.integer, defval=10)
e3 = input(title="EMA-3", type=input.integer, defval=20)
e4 = input(title="EMA-4", type=input.integer, defval=50)
e5 = input(title="EMA-5", type=input.integer, defval=100)
e6 = input(title="EMA-6", type=input.integer, defval=200)
e7 = input(title="EMA-7", type=input.integer, defval=150)
S1 = input(title="MA-1", type=input.integer, defval=5)
S2 = input(title="MA-2", type=input.integer, defval=10)
S3 = input(title="MA-3", type=input.integer, defval=20)
S4 = input(title="MA-4", type=input.integer, defval=50)
S5 = input(title="MA-5", type=input.integer, defval=100)
S6 = input(title="MA-6", type=input.integer, defval=200)
// FIX ema/ma
res1 = input(title="EMA-1 fix at", type=input.resolution, defval="")
res2 = input(title="EMA-2 fix at", type=input.resolution, defval="")
res3 = input(title="EMA-3 fix at", type=input.resolution, defval="")
res4 = input(title="EMA-4 fix at", type=input.resolution, defval="")
res5 = input(title="EMA-5 fix at", type=input.resolution, defval="")
res6 = input(title="EMA-6 fix at", type=input.resolution, defval="")
res7 = input(title="EMA-7 fix at", type=input.resolution, defval="")
resS1 = input(title="MA-1 fix at", type=input.resolution, defval="")
resS2 = input(title="MA-2 fix at", type=input.resolution, defval="")
resS3 = input(title="MA-3 fix at", type=input.resolution, defval="")
resS4 = input(title="MA-4 fix at", type=input.resolution, defval="")
resS5 = input(title="MA-5 fix at", type=input.resolution, defval="")
resS6 = input(title="MA-6 fix at", type=input.resolution, defval="")
// VIEWING ema/ma on screen
on1 = input(title="EMA-1", type=input.bool, defval=true)
on2 = input(title="EMA-2", type=input.bool, defval=true)
on3 = input(title="EMA-3", type=input.bool, defval=true)
on4 = input(title="EMA-4", type=input.bool, defval=true)
on5 = input(title="EMA-5", type=input.bool, defval=true)
on6 = input(title="EMA-6", type=input.bool, defval=true)
on7 = input(title="EMA-7", type=input.bool, defval=false)
onS1 = input(title="MA-1", type=input.bool, defval=false)
onS2 = input(title="MA-2", type=input.bool, defval=false)
onS3 = input(title="MA-3", type=input.bool, defval=false)
onS4 = input(title="MA-4", type=input.bool, defval=false)
onS5 = input(title="MA-5", type=input.bool, defval=false)
onS6 = input(title="MA-6", type=input.bool, defval=true)
// EMAs
ema1 = on1 ? security(syminfo.tickerid, res1, ema(close,e1), barmerge.gaps_on, barmerge.lookahead_off) : na
ema2 = on2 ? security(syminfo.tickerid, res2, ema(close,e2), barmerge.gaps_on, barmerge.lookahead_off) : na
ema3 = on3 ? security(syminfo.tickerid, res3, ema(close,e3), barmerge.gaps_on, barmerge.lookahead_off) : na
ema4 = on4 ? security(syminfo.tickerid, res4, ema(close,e4), barmerge.gaps_on, barmerge.lookahead_off) : na
ema5 = on5 ? security(syminfo.tickerid, res5, ema(close,e5), barmerge.gaps_on, barmerge.lookahead_off) : na
ema6 = on6 ? security(syminfo.tickerid, res6, ema(close,e6), barmerge.gaps_on, barmerge.lookahead_off) : na
ema7 = on7 ? security(syminfo.tickerid, res7, ema(close,e7), barmerge.gaps_on, barmerge.lookahead_off) : na
// SMAs
sma1 = onS1 ? security(syminfo.tickerid, resS1, sma(close,S1), barmerge.gaps_on, barmerge.lookahead_off) : na
sma2 = onS2 ? security(syminfo.tickerid, resS2, sma(close,S2), barmerge.gaps_on, barmerge.lookahead_off) : na
sma3 = onS3 ? security(syminfo.tickerid, resS3, sma(close,S3), barmerge.gaps_on, barmerge.lookahead_off) : na
sma4 = onS4 ? security(syminfo.tickerid, resS4, sma(close,S4), barmerge.gaps_on, barmerge.lookahead_off) : na
sma5 = onS5 ? security(syminfo.tickerid, resS5, sma(close,S5), barmerge.gaps_on, barmerge.lookahead_off) : na
sma6 = onS6 ? security(syminfo.tickerid, resS6, sma(close,S6), barmerge.gaps_on, barmerge.lookahead_off) : na
//COLOR FOR EMA/MA
ema1plot = plot(ema1, title = "EMA-1", color = #787b86)
ema2plot = plot(ema2, title = "EMA-2", color = #66bb6a)
ema3plot = plot(ema3, title = "EMA-3", color = #42a5f5)
ema4plot = plot(ema4, title = "EMA-4", color = #f44336)
plot(ema5, title = "EMA-5", color = #ab47bc)
plot(ema6, title = "EMA-6", color = #ffa726)
plot(ema7, title = "EMA-7", color = #ffa726)
plot(sma1, title = "MA-1", color = #7e57c2)
plot(sma2, title = "MA-2", color = #26c6da)
plot(sma3, title = "MA-3", color = #26c6da)
plot(sma4, title = "MA-4", color = #26c6da)
plot(sma5, title = "MA-5", color = #26c6da)
plot(sma6, title = "MA-6", color = #000000)
//Fill
fill(ema1plot, ema2plot, color=ema1>ema2? color.rgb(0,150,0,75):color.rgb(250,0,0,75), title="Fill Cloud EMA-1/EMA-2", editable=true)
fill(ema2plot, ema3plot, color=ema2>ema3? color.rgb(0,150,0,75):color.rgb(250,0,0,75), title="Fill Cloud EMA-2/EMA-3", editable=true)
fill(ema3plot, ema4plot, color=ema3>ema4? color.rgb(0,150,0,75):color.rgb(250,0,0,75), title="Fill Cloud EMA-3/EMA-4", editable=true)
|
Amit Advance CPR | https://www.tradingview.com/script/xpUN5aIO-Amit-Advance-CPR/ | amit16aks | https://www.tradingview.com/u/amit16aks/ | 120 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © amit16aks
//@version=4
study("Amit", shorttitle="Floorpivot+CPR", overlay=true)
// User inputs for intraday
showTomorrowCPR = input(title="Show tomorrow's CPR", type=input.bool, defval=true)
showHistoricalCPR = input(title="Show historical CPR", type=input.bool, defval=false)
//showR3S3 = input(title="Show R3 & S3", type=input.bool, defval=false)
//showR4S4 = input(title="Show R4 & S4", type=input.bool, defval=false)
showR5S5 = input(title="Show R5 & S5", type=input.bool, defval=false)
showPDHL = input(title="Show previous day's High & Low", type=input.bool, defval=false)
showPDC = input(title="Show previous day's Close", type=input.bool, defval=false)
//userinput for weekly CPR & PIVOT
showWeeklyCPR = input(title="Show weekly CPR", type=input.bool, defval=false)
showWeeklyPivot = input(title="Show weekly Pivot", type=input.bool, defval=false)
//userinput for MONTHLY CPR & PIVOT
showMonthlyCPR = input(title="Show monthly CPR", type=input.bool, defval=false)
showMonthlyPivot = input(title="Show monthly Pivot", type=input.bool, defval=false)
// Defaults
//Day CPR Colors
cprColor = color.navy
rColor = color.red
sColor = color.green
cColor = color.black
// Line style & Transparency
lStyle = plot.style_line
lTransp = 0
mTransp = 0
//Fill Transparency
fTransp = 70
// Global Variables & Flags
// TODO : Update the No of Holidays
noOfHolidays = 12
// Global Functions
// TODO : Update the list of Holiday here in format YYYY, MM, DD, 09, 15
// **09, 15 are session start hour & minutes
IsHoliday(_date) =>
iff(_date == timestamp(2020, 02, 21, 09, 15), true,
iff(_date == timestamp(2020, 03, 10, 09, 15), true,
iff(_date == timestamp(2020, 04, 02, 09, 15), true,
iff(_date == timestamp(2020, 04, 06, 09, 15), true,
iff(_date == timestamp(2020, 04, 10, 09, 15), true,
iff(_date == timestamp(2020, 04, 14, 09, 15), true,
iff(_date == timestamp(2020, 05, 01, 09, 15), true,
iff(_date == timestamp(2020, 05, 25, 09, 15), true,
iff(_date == timestamp(2020, 10, 02, 09, 15), true,
iff(_date == timestamp(2020, 11, 16, 09, 15), true,
iff(_date == timestamp(2020, 11, 30, 09, 15), true,
iff(_date == timestamp(2020, 12, 25, 09, 15), true,
false))))))))))))
// Note: Week of Sunday=1...Saturday=7
IsWeekend(_date) =>
dayofweek(_date) == 7 or dayofweek(_date) == 1
// Skip Weekend
SkipWeekend(_date) =>
_d = dayofweek(_date)
_mul = _d == 6 ? 3 : _d == 7 ? 2 : 1
_date + (_mul * 86400000)
// Get Next Working Day
GetNextWorkingDay(_date) =>
_dt = SkipWeekend(_date)
for i = 1 to noOfHolidays
if IsHoliday(_dt)
_dt := SkipWeekend(_dt)
continue
else
break
_dt
// Today's Session Start timestamp
y = year(timenow)
m = month(timenow)
d = dayofmonth(timenow)
// Start & End time for Today's CPR
start = timestamp(y, m, d, 09, 15)
end = start + 86400000
// Plot Today's CPR
shouldPlotToday = timenow > start
tom_start = start
tom_end = end
// Start & End time for Tomorrow's CPR
if shouldPlotToday
tom_start := GetNextWorkingDay(start)
tom_end := tom_start + 86400000
// Get series
getSeries(e, timeFrame) => security(syminfo.tickerid, "D", e, lookahead=barmerge.lookahead_on)
// Calculate Today's CPR
//Get High, Low and Close
H = getSeries(high[1], 'D')
L = getSeries(low[1], 'D')
C = getSeries(close[1], 'D')
// Pivot Range
P = (H + L + C) / 3
TC = (H + L)/2
BC = (P - TC) + P
// Resistance Levels
R5 = H + 4*(P - L)
R4 = H + 3*(P - L)
R3 = H + 2*(P - L)
R2 = P + (H - L)
R1 = (P * 2) - L
// Support Levels
S1 = (P * 2) - H
S2 = P - (H - L)
S3 = L - 2*(H - P)
S4 = L - 3*(H - P)
S5 = L - 4*(H - P)
// Plot Today's CPR
if not(IsHoliday(start)) and not(IsWeekend(start)) and shouldPlotToday
// if showR3S3
// if showR4S4
if showR5S5
_r3 = line.new(start, R3, end, R3, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_r3[1])
_r4 = line.new(start, R4, end, R4, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_r4[1])
_r5 = line.new(start, R5, end, R5, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_r5[1])
_r2 = line.new(start, R2, end, R2, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_r2[1])
_r1 = line.new(start, R1, end, R1, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_r1[1])
_tc = line.new(start, TC, end, TC, xloc.bar_time, color=color.new(cprColor, lTransp))
line.delete(_tc[1])
_p = line.new(start, P, end, P, xloc.bar_time, color=color.new(cprColor, lTransp))
line.delete(_p[1])
_bc = line.new(start, BC, end, BC, xloc.bar_time, color=color.new(cprColor, lTransp))
line.delete(_bc[1])
_s1 = line.new(start, S1, end, S1, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_s1[1])
_s2 = line.new(start, S2, end, S2, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_s2[1])
// if showR3S3
// if showR4S4
if showR5S5
_s3 = line.new(start, S3, end, S3, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_s3[1])
_s4 = line.new(start, S4, end, S4, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_s4[1])
_s5 = line.new(start, S5, end, S5, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_s5[1])
if showPDHL
_pdh = line.new(start, H, end, H, xloc.bar_time, color=color.new(rColor, lTransp), style=line.style_dotted, width=2)
line.delete(_pdh[1])
_pdl = line.new(start, L, end, L, xloc.bar_time, color=color.new(sColor, lTransp), style=line.style_dotted, width=2)
line.delete(_pdl[1])
if showPDC
_pdc = line.new(start, C, end, C, xloc.bar_time, color=color.new(cColor, lTransp), style=line.style_dotted, width=2)
line.delete(_pdc[1])
// Plot Today's Labels
if not(IsHoliday(start)) and not(IsWeekend(start)) and shouldPlotToday
// if showR3S3
// if showR4S4
if showR5S5
l_r4 = label.new(start, R4, text="R4", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_r4[1])
l_r3 = label.new(start, R3, text="R3", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_r3[1])
l_r5 = label.new(start, R5, text="R5", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_r5[1])
l_r2 = label.new(start, R2, text="R2", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_r2[1])
l_r1 = label.new(start, R1, text="R1", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_r1[1])
l_tc = label.new(start, TC, text="TC", xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
label.delete(l_tc[1])
l_p = label.new(start, P, text="P", xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
label.delete(l_p[1])
l_bc = label.new(start, BC, text="BC", xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
label.delete(l_bc[1])
l_s1 = label.new(start, S1, text="S1", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_s1[1])
l_s2 = label.new(start, S2, text="S2", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_s2[1])
// if showR3S3
// if showR4S4
if showR5S5
l_s3 = label.new(start, S3, text="S3", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_s3[1])
l_s4 = label.new(start, S4, text="S4", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_s4[1])
l_s5 = label.new(start, S5, text="S5", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_s5[1])
if showPDHL
l_pdh = label.new(start, H, text="PD High", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_pdh[1])
l_pdl = label.new(start, L, text="PD Low", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_pdl[1])
if showPDC
l_pdc = label.new(start, C, text="PD Close", xloc=xloc.bar_time, textcolor=cColor, style=label.style_none)
label.delete(l_pdc[1])
// Calculate Tomorrow's CPR
// Get High, Low and Close
tH = getSeries(high, 'D')
tL = getSeries(low, 'D')
tC = getSeries(close, 'D')
// Pivot Range
tP = (tH + tL + tC) / 3
tTC = (tH + tL)/2
tBC = (tP - tTC) + tP
// Resistance Levels
tR5 = tH + 4*(tP - tL)
tR4 = tH + 3*(tP - tL)
tR3 = tH + 2*(tP - tL)
tR2 = tP + (tH - tL)
tR1 = (tP * 2) - tL
// Support Levels
tS1 = (tP * 2) - tH
tS2 = tP - (tH - tL)
tS3 = tL - 2*(tH - tP)
tS4 = tL - 3*(tH - tP)
tS5 = tL - 4*(tH - tP)
// Plot Tomorrow's CPR
if showTomorrowCPR
// if showR3S3
// if showR4S4
if showR5S5
_t_r3 = line.new(tom_start, tR3, tom_end, tR3, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_t_r3[1])
_t_r4 = line.new(tom_start, tR4, tom_end, tR4, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_t_r4[1])
_t_r5 = line.new(tom_start, tR5, tom_end, tR5, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_t_r5[1])
_t_r2 = line.new(tom_start, tR2, tom_end, tR2, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_t_r2[1])
_t_r1 = line.new(tom_start, tR1, tom_end, tR1, xloc.bar_time, color=color.new(rColor, lTransp))
line.delete(_t_r1[1])
_t_tc = line.new(tom_start, tTC, tom_end, tTC, xloc.bar_time, color=color.new(cprColor, lTransp))
line.delete(_t_tc[1])
_t_p = line.new(tom_start, tP, tom_end, tP, xloc.bar_time, color=color.new(cprColor, lTransp))
line.delete(_t_p[1])
_t_bc = line.new(tom_start, tBC, tom_end, tBC, xloc.bar_time, color=color.new(cprColor, lTransp))
line.delete(_t_bc[1])
_t_s1 = line.new(tom_start, tS1, tom_end, tS1, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_t_s1[1])
_t_s2 = line.new(tom_start, tS2, tom_end, tS2, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_t_s2[1])
// if showR3S3
// if showR4S4
if showR5S5
_t_s3 = line.new(tom_start, tS3, tom_end, tS3, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_t_s3[1])
_t_s4 = line.new(tom_start, tS4, tom_end, tS4, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_t_s4[1])
_t_s5 = line.new(tom_start, tS5, tom_end, tS5, xloc.bar_time, color=color.new(sColor, lTransp))
line.delete(_t_s5[1])
if showPDHL
_pdth = line.new(tom_start, tH, tom_end, tH, xloc.bar_time, color=color.new(rColor, lTransp), style=line.style_dotted, width=2)
line.delete(_pdth[1])
_pdtl = line.new(tom_start, tL, tom_end, tL, xloc.bar_time, color=color.new(sColor, lTransp), style=line.style_dotted, width=2)
line.delete(_pdtl[1])
if showPDC
_pdtc = line.new(tom_start, tC, tom_end, tC, xloc.bar_time, color=color.new(cColor, lTransp), style=line.style_dotted, width=2)
line.delete(_pdtc[1])
// Plot Tomorrow's Labels
if showTomorrowCPR
// if showR3S3
// if showR4S4
if showR5S5
l_t_r3 = label.new(tom_start, tR3, text="R3", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_t_r3[1])
l_t_r4 = label.new(tom_start, tR4, text="R4", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_t_r4[1])
l_t_r5 = label.new(tom_start, tR5, text="R5", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_t_r5[1])
l_t_r2 = label.new(tom_start, tR2, text="R2", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_t_r2[1])
l_t_r1 = label.new(tom_start, tR1, text="R1", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_t_r1[1])
l_t_tc = label.new(tom_start, tTC, text="TC", xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
label.delete(l_t_tc[1])
l_t_p = label.new(tom_start, tP, text="P", xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
label.delete(l_t_p[1])
l_t_bc = label.new(tom_start, tBC, text="BC", xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
label.delete(l_t_bc[1])
l_t_s1 = label.new(tom_start, tS1, text="S1", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_t_s1[1])
l_t_s2 = label.new(tom_start, tS2, text="S2", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_t_s2[1])
// if showR3S3
// if showR4S4
if showR5S5
l_t_s3 = label.new(tom_start, tS3, text="S3", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_t_s3[1])
l_t_s4 = label.new(tom_start, tS4, text="S4", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_t_s4[1])
l_t_s5 = label.new(tom_start, tS5, text="S5", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_t_s5[1])
if showPDHL
l_pdth = label.new(tom_start, tH, text="PD High", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_pdth[1])
l_pdtl = label.new(tom_start, tL, text="PD Low", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_pdtl[1])
if showPDC
l_pdtc = label.new(tom_start, tC, text="PD Close", xloc=xloc.bar_time, textcolor=cColor, style=label.style_none)
label.delete(l_pdtc[1])
//Plot Historical CPR
p_r5 = plot(showHistoricalCPR ? showR5S5 ? R5 : na : na, title=' R5', color=rColor, transp=lTransp, style=lStyle)
p_r4 = plot(showHistoricalCPR ? showR5S5 ? R4 : na : na, title=' R4', color=rColor, transp=lTransp, style=lStyle)
p_r3 = plot(showHistoricalCPR ? showR5S5 ? R3 : na : na, title=' R3', color=rColor, transp=lTransp, style=lStyle)
p_r2 = plot(showHistoricalCPR ? R2 : na, title=' R2', color=rColor, transp=lTransp, style=lStyle)
p_r1 = plot(showHistoricalCPR ? R1 : na, title=' R1', color=rColor, transp=lTransp, style=lStyle)
p_cprTC = plot(showHistoricalCPR ? TC : na, title=' TC', color=cprColor, transp=lTransp, style=lStyle)
p_cprP = plot(showHistoricalCPR ? P : na, title=' P', color=cprColor, transp=lTransp, style=lStyle)
p_cprBC = plot(showHistoricalCPR ? BC : na, title=' BC', color=cprColor, transp=lTransp, style=lStyle)
s1 = plot(showHistoricalCPR ? S1 : na, title=' S1', color=sColor, transp=lTransp, style=lStyle)
s2 = plot(showHistoricalCPR ? S2 : na, title=' S2', color=sColor, transp=lTransp, style=lStyle)
s3 = plot(showHistoricalCPR ? showR5S5 ? S3 : na : na, title=' S3', color=sColor, transp=lTransp, style=lStyle)
s4 = plot(showHistoricalCPR ? showR5S5 ? S4 : na : na, title=' S4', color=sColor, transp=lTransp, style=lStyle)
s5 = plot(showHistoricalCPR ? showR5S5 ? S5 : na : na, title=' S5', color=sColor, transp=lTransp, style=lStyle)
fill(p_cprTC, p_cprBC, color=color.yellow, transp=fTransp)
//
// GET Weekly data
WH = security(syminfo.tickerid, 'W', high)
WL = security(syminfo.tickerid, 'W', low)
WC = security(syminfo.tickerid, 'W', close)
// WEEKLY CPR
WP = (WH + WL + WC) / 3
WBC = (WH + WL)/2
WTC = (WP - WBC) + WP
// WEEKLY Resistence Levels
WR5 = WH + 4*(WP - WL)
WR4 = WH + 3*(WP - WL)
WR3 = WH + 2*(WP - WL)
WR2 = WP + (WH - WL)
WR1 = (WP * 2) - WL
// WEEKLY Support Levels
WS1 = (WP * 2) - WH
WS2 = WP - (WH - WL)
WS3 = WL - 2*(WH - WP)
WS4 = WL - 3*(WH - WP)
WS5 = WL - 4*(WH - WP)
//PLOT WEEKLY RESISTANCE
w_r5 = plot(showWeeklyPivot ? showR5S5 ? WR5 : na : na, title=' WR5', color=color.red, transp=lTransp, style=plot.style_circles)
w_r4 = plot(showWeeklyPivot ? showR5S5 ? WR4 : na : na, title=' WR4', color=color.red, transp=lTransp, style=plot.style_circles)
w_r3 = plot(showWeeklyPivot ? showR5S5 ? WR3 : na : na, title=' WR3', color=color.red, transp=lTransp, style=plot.style_circles)
w_r2 = plot(showWeeklyPivot ? WR2 : na, title=' WR2', color=color.red, transp=lTransp, style=plot.style_circles)
w_r1 = plot(showWeeklyPivot ? WR1 : na, title=' WR1', color=color.red, transp=lTransp, style=plot.style_circles)
//PLOT weekly CPR
w_cprP = plot(showWeeklyCPR ? WP : na, title=' WP', color=color.maroon, transp=lTransp, style=lStyle)
w_cprBC= plot(showWeeklyCPR ? WBC : na, title=' WBC', color=color.maroon, transp=lTransp, style=lStyle)
w_cprTC= plot(showWeeklyCPR ? WTC : na, title=' WTC', color=color.maroon, transp=lTransp, style=lStyle)
fill(w_cprTC, w_cprBC, color=color.red, transp=fTransp)
//PLOT WEEKLY SUPPORT
w_s1 = plot(showWeeklyPivot ? WS1 : na, title=' WS1', color=color.green, transp=lTransp, style=plot.style_circles)
w_s2 = plot(showWeeklyPivot ? WS2 : na, title=' WS2', color=color.green, transp=lTransp, style=plot.style_circles)
w_s3 = plot(showWeeklyPivot ? showR5S5 ? WS3 : na : na, title=' WS3', color=color.green, transp=lTransp, style=plot.style_circles)
w_s4 = plot(showWeeklyPivot ? showR5S5 ? WS4 : na : na, title=' WS4', color=color.green, transp=lTransp, style=plot.style_circles)
w_s5 = plot(showWeeklyPivot ? showR5S5 ? WS5 : na : na, title=' WS5', color=color.green, transp=lTransp, style=plot.style_circles)
// GET Monthly data
MH = security(syminfo.tickerid, 'M', high)
ML = security(syminfo.tickerid, 'M', low)
MC = security(syminfo.tickerid, 'M', close)
// monthly CPR
MP = (MH + ML + MC) / 3
MBC = (MH + ML)/2
MTC = (MP - MBC) + MP
// Resistence Levels
MR5 = MH + 4*(MP - ML)
MR4 = MH + 3*(MP - ML)
MR3 = MH + 2*(MP - ML)
MR2 = MP + (MH - ML)
MR1 = (MP * 2) - ML
// Support Levels
MS1 = (MP * 2) - MH
MS2 = MP - (MH - ML)
MS3 = ML - 2*(MH - MP)
MS4 = ML - 3*(MH - MP)
MS5 = ML - 4*(MH - MP)
//PLOT MONTHLY RESISTANCE
m_r5 = plot(showMonthlyPivot ? showR5S5 ? MR5 : na : na, title=' MR5', color=color.red, transp=mTransp, style=plot.style_cross)
m_r4 = plot(showMonthlyPivot ? showR5S5 ? MR4 : na : na, title=' MR4', color=color.red, transp=mTransp, style=plot.style_cross)
m_r3 = plot(showMonthlyPivot ? showR5S5 ? MR3 : na : na, title=' MR3', color=color.red, transp=mTransp, style=plot.style_cross)
m_r2 = plot(showMonthlyPivot ? MR2 : na, title=' MR2', color=color.red, transp=mTransp, style=plot.style_cross)
m_r1 = plot(showMonthlyPivot ? MR1 : na, title=' MR1', color=color.red, transp=mTransp, style=plot.style_cross)
//PLOT MONTHLY CPR
m_cprP= plot(showMonthlyCPR ? MP : na, title=' MP', color=color.black, transp=lTransp, style=lStyle)
m_cprBC= plot(showMonthlyCPR ? MBC : na, title=' MBC', color=color.black, transp=lTransp, style=lStyle)
m_cprTC= plot(showMonthlyCPR ? MTC : na, title=' MTC', color=color.black, transp=lTransp, style=lStyle)
fill(m_cprTC, m_cprBC, color=color.gray, transp=fTransp)
//PLOT WEEKLY SUPPORT
m_s1 = plot(showMonthlyPivot ? MS1 : na, title=' MS1', color=color.green, transp=mTransp, style=plot.style_cross)
m_s2 = plot(showMonthlyPivot ? MS2 : na, title=' MS2', color=color.green, transp=mTransp, style=plot.style_cross)
m_s3 = plot(showMonthlyPivot ? showR5S5 ? MS3 : na : na, title=' MS3', color=color.green, transp=mTransp, style=plot.style_cross)
m_s4 = plot(showMonthlyPivot ? showR5S5 ? MS4 : na : na, title=' MS4', color=color.green, transp=mTransp, style=plot.style_cross)
m_s5 = plot(showMonthlyPivot ? showR5S5 ? MS5 : na : na, title=' MS5', color=color.green, transp=mTransp, style=plot.style_cross)
|
Poo Belt V1 | https://www.tradingview.com/script/Q1eBo9CK-Poo-Belt-V1/ | Anon_LineDraw | https://www.tradingview.com/u/Anon_LineDraw/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Anon_LineDraw
//@version=5
indicator('Poo Belt', overlay=true)
ma_length = input(100, title='MA Length')
//3 different indicators
ema_1 = ta.rma (high, ma_length)
ema_2 = ta.rma (close, ma_length)
ema_3 = ta.rma (low, ma_length)
p1 = plot (ema_1 * 1.04, linewidth=3, title='High', color=color.rgb(63, 21, 21), transp=0)
p2 = plot (ema_2 * 1.02, linewidth=3, title='Close', color=color.rgb(160, 86, 17), transp=0)
p3 = plot (ema_3, linewidth=3, title='Low', color= color.rgb(77, 36, 10), transp=0)
fill(p1, p3, color=color.rgb(185, 104, 29), color=color.rgb(192, 89, 21), transp=70)
|
Moving Average Convergence Divergence On Alter OBV | https://www.tradingview.com/script/BecokqfY-Moving-Average-Convergence-Divergence-On-Alter-OBV/ | stocktechbot | https://www.tradingview.com/u/stocktechbot/ | 40 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © stocktechbot
//@version=5
indicator(title="Moving Average Convergence Divergence On Alter OBV", shorttitle="MACDOBV", timeframe="", timeframe_gaps=true)
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
chng = 0
obv = ta.cum(math.sign(ta.change(close)) * volume)
if close < close[1] and (open < close)
chng := 1
else if close > close[1]
chng := 1
else
chng := -1
obvalt = ta.cum(math.sign(chng) * volume)
//src = input(title="Source", defval=close)
src = obvalt
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(macd, title="MACD", color=col_macd)
plot(signal, title="Signal", color=col_signal)
|
RSI-Adaptive, GKYZ-Filtered DEMA [Loxx] | https://www.tradingview.com/script/oIP0U33J-RSI-Adaptive-GKYZ-Filtered-DEMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 423 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("RSI-Adaptive, GKYZ-Filtered DEMA [Loxx]",
shorttitle="RSIAGKYZFDEMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * gkyzvol(len) * src
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
ema(float src, float alpha)=>
float out = src
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
demaAlpha(float src, float alpha)=>
float e1 = ema(src, alpha)
float e2 = ema(e1, alpha)
float out = 2 * e1 - e2
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(32, "Period", group= "Basic Settings")
rsiper = input.int(15, "RSI Period", group= "Basic Settings")
hot = input.float(0.7, "T3 Hot", group= "Basic Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "RSIAGKYZFDEMA", "Both", "None"], group= "Filter Settings")
filter = input.float(2, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show Signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? gkyzFilter(src, filterperiod, filter) : src
alpha = math.abs(ta.rsi(src, rsiper) / 100.0 - 0.5) * 2.0
out = demaAlpha(src, alpha)
out := filterop == "Both" or filterop == "RSIAGKYZFDEMA" and filter > 0 ? gkyzFilter(out, filterperiod, filter) : out
sig = out[1]
goLong_pre = ta.crossover(out, sig)
goShort_pre = ta.crossunder(out, sig)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
colorout = contSwitch == 1 ? greencolor : redcolor
barcolor(colorbars ? colorout : na)
plot(out, "RSIAATRFT3", color = colorout, linewidth = 3)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="RSI-Adaptive, GKYZ-Filtered DEMA [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="RSI-Adaptive, GKYZ-Filtered DEMA [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
TradingView Alerts (Expo) | https://www.tradingview.com/script/a0LJc0Tx-TradingView-Alerts-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 2,771 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman
//@version=5
indicator("TradingView Alerts (Expo)",overlay=true,max_labels_count=500)
// ~~ Inputs {
// ~~ Inputs General {
inputSrc = input.source(close, title="Indicator",group="Indicator Input", tooltip="Select any indicator you have on your chart and the alerts you create will be based on this input.")
plot = input.bool(true, title="Plot Alert",inline="plot", tooltip="Display where the alert is triggered on the chart. Set location and icon size.")
loc = input.string("Above Price", title="", options= ["Above Price", "Below Price"],inline="plot")
size = input.string(size.normal, options =[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],inline="plot")
bg = input.bool(false,title="BG Alert",inline="bg")
bgcol = input.color(color.new(#4F772D, 70),title="", inline="bg", tooltip="Display a background color when an alert is triggered and set its color.")
//~~~}
// ~~ Input Alert Conditions {
cond = input.string("Select Condition", title="Condition",
options=["Crossing","Crossing Up","Crossing Down",
"Greater Than","Equal To","Less Than",
"Entering Channel","Exiting Channel",
"Inside Channel","Outside Channel",
"Moving Up","Moving Down","Moving Up %",
"Moving Down %","Turning Up","Turning Down","Select Condition"],
group="Condition", inline="cond")
//~~~}
// ~~ Inputs Conditions {
element = input.string("Value", title="", options=["Price","Value","Channel"],group="Condition",inline="cond")
shift = input.bool(false, title="Reverse (Price Crossings)",group="Condition",inline="cond",tooltip="Select the alert condition and element. For example, if you select [Crossing Up] and [Value], the alert will be triggered when the selected input source crosses up the selected value.\n\nReverse means the following 'The PRICE crosses the indicator' if you disable this option it means 'The INDICATOR crosses the price'.")
price = input.string("close", title="Price", options=["open","high","low","close","hl2","hlc3","ohlc4","hlcc4"], tooltip="If you have selected [Price] above, you set the preferred price here.")
val = input.float(10.00, title="Value",step=.1, tooltip="If you have selected [Value] above, you set the preferred value here.")
channel1 = input.float(70.00, title="Upper Channel Boundary",step=10, tooltip="If you have selected [Channel] above, you set the preferred Upper Channel Boundary value here.")
channel2 = input.float(30.00, title="Lower Channel Boundary",step=10, tooltip="If you have selected [Channel] above, you set the preferred Lower Channel Boundary value here.")
xbars = input.float(5, title="Number of bars",step=1,tooltip="If you have selected 'Moving Up/Down or Moving Up/Down %' set the number of bars where the condition has to be met within.")
//~~~}
// ~~ Input Momentum Conditions {
Mom = input.string("Select Momentum", title="Source Momentum",
options=["Positive Momentum","Negative Momentum","Select Momentum"],
group="", inline="Momentum")
len = input.int(0, title="for numbers of bars", minval=0, inline = "Momentum", tooltip="Set how many consecutive bars in the positive or negative direction it must have been to trigger an alert. \n\nFor example, you have selected 'positive momentum, and the number for bars is set to '5', which means that the source input must have had at least 5 consecutive positive bars. \n\nThe higher the number of bars is set to, the higher the momentum it must have been.")
//~~~}
// ~~ Input Sign Conditions {
shiftSign = input.string("Select Sign", title="", options=[">= (src bigger or equal than value)","<= (src less or equal than value)","Select Sign"],group="For Input indicators Below the chart",inline="vv")
signValue = input.float(0., title="value",group="For Input indicators Below the chart",inline="vv", tooltip="If you want to set alerts for indicators such as RSI, MACD, or any indicator that is displayed on a fixed scale below the chart, you can use this option. \n\nYou set if the selected source has to be ABOVE or BELOW the value you set.")
//~~~}
// ~~ Trend Conditions {
TREND = input(false, title='─────── Trend ───────',group="", inline="", tooltip='Set a trend filter. An alert is triggered if the price is above or below the trend filter.')
// ~~ Input Trend Conditions {
trendType = input.string("Select Trend Type", title="Select Trend Type",
options=["Average","SuperTrend","WVAP","SAR","Donchian channel","Select Trend Type"],
inline="Trend", group="Select Trend")
abovebelow = input.string("Above", title="",
options=["Above","Below"],
inline="Trend", group="Select Trend")
plotTrend = input.bool(true,title="Plot Trend on Chart", inline = "Trend", group="Select Trend", tooltip="Select the trend type. The settings for the different trend types can be found below. \n\nSet if the price should be ABOVE or BELOW the selected trend! \n\nPlot the trend on the chart.\n\nSo if you only want to get an alert if the price is above or below the trend you can enable this option.")
// ~~ Input Average Conditions {
maType = input.string("SMA", title="Select MA",
options=["SMA","EMA","WMA","RMA","VWMA"],
inline="MA", group="Average")
length = input.int(200, title="", minval=1, inline = "MA", group="Average", tooltip="Select the MA type and its length.")
//~~~}
// ~~ Input SuperTrend Conditions {
factor = input.int(3, minval=0, title="Factor",group="SuperTrend", inline="SuperTrend")
atrPeriod = input.int(7, minval=0, title="Atr Period",group="SuperTrend", inline="SuperTrend", tooltip="Set the supertrend factor and its ATR Period.")
var supertrendup = 0.0
var supertrenddn = 0.0
var supertrend = 0.0
mult = factor*ta.atr(atrPeriod)
supertrendup:=close[1]>supertrendup[1]? math.max(close-mult,supertrendup[1]) : close-mult
supertrenddn:=close[1]<supertrenddn[1]? math.min(close+mult,supertrenddn[1]) : close+mult
supertrend := close > supertrenddn[1]? 1: close<supertrendup[1]?-1: nz(supertrend[1],1)
tsl = supertrend==1?supertrendup:supertrenddn
//~~~}
// ~~ Input WVAP Trend Conditions {
wvap = ta.vwap(close)
//~~~}
// ~~ Input SAR Trend Conditions {
start = input.float(0.02, minval=0, title="Start",group="SAR", inline="SAR")
inc = input.float(0.02, minval=0, title="Inc",group="SAR", inline="SAR")
max = input.float(0.2, minval=0, title="Max",group="SAR", inline="SAR", tooltip="Set the sar, start, increment, and max values.")
sar = ta.sar(start,inc,max)
//~~~}
// ~~ Input Donchian channel Trend Conditions {
donlen = input.int(20, minval=0, title="Donchian Length",group="Donchian", inline="Donchian", tooltip="Set the Donchian Length.")
highest = ta.highest(donlen)
lowest = ta.lowest(donlen)
mid = math.avg(highest,lowest)
//~~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
FILTER = input(false, title='─────── Filter ───────',group="", inline="", tooltip='If you want to filter the signals even more you can use the inbuilt filters below.')
// ~~ Inputs RSI Filter {
rsi_src = input.string("RSI", title="RSI Source",
options =["RSI","RSI Signal Line"],
inline="rsi", group="RSI Filter", tooltip="")
rsiEnable = input.string("RSI Filter", title="RSI Filter",
options =["RSI(src) has a positive slope", "RSI(src) has a negative slope", "RSI is above the Signal line","RSI is below the Signal line","RSI(src) has the same slope (UP) as the input source","RSI(src) has the same slope (DOWN) as the input source","RSI Filter"],
inline="rsi", group="RSI Filter", tooltip="Select if the RSI filter should be based on the RSI line or the RSI signal line. \n\nSelect any of the filters in the list.")
rsilen = input.int(14, minval=0,title="RSI Period", group="RSI Filter", inline="RSI")
rsisignallen = input.int(12, minval=0,title="MA Length", group="RSI Filter", inline="RSI",tooltip="Set the RSI Period and the Signal line length.")
//~~~}
// ~~ Inputs Volume Filter {
volumeEnable = input.string("Volume Filter", title="Volume Filter",
options =["Volume(ma) has a positive slope", "Volume(ma) has a negative slope", "Volume is above the Ma line","Volume is below the Ma line","Volume(ma) has the same slope (UP) as the input source","Volume(ma) has the same slope (DOWN) as the input source","Volume Filter"],
inline="vol", group="Volume Filter", tooltip="")
volumesignallen = input.int(20, minval=0,title="MA Length", group="Volume Filter", inline="vol", tooltip="Select a volume filter. \n\nSet the Signal line length.")
//~~~}
// ~~ Inputs Alerts {
ALERT = input(false, title='─────── Alert Message ───────',group="", inline="", tooltip='')
alert = input.string("Auto", title="Alert Message", options=["Auto","Custom"],group="Create Any alert() function call",inline="alert")
trigger = input.string(alert.freq_once_per_bar_close, title="", options=[alert.freq_once_per_bar_close,alert.freq_once_per_bar],group="Create Any alert() function call",inline="alert")
options = input.string("Only Once", title="", options=["Only Once","Every Time"],group="Create Any alert() function call",inline="alert", tooltip="Set alert message and set alert frequency.\n\nOnly Once: The condition will only be triggered at the first bar when the condition is met.\n\nEvery Time: The alert will trigger every time the condition is met. ")
msg = input.string("", title="Custom Message", tooltip="If you have selected the custom alert message above you can set the alert message here.")
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
var float perc = float(na)
var int bars = int(na)
var posMom = 0
var negMom = 0
var total = 0
var days = 0
var weeks = 0
var months = 0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alert Condition {
float src = switch price
"open" => open
"high" => high
"low" => low
"close"=> close
"hl2" => hl2
"hlc3" => hlc3
"ohlc4"=> ohlc4
"hlcc4"=> hlcc4
// ~~ Price Above/Below Average Condition {
ma = switch maType
"SMA" => ta.sma(src,length)
"EMA" => ta.ema(src,length)
"WMA" => ta.wma(src,length)
"RMA" => ta.rma(src,length)
"VWMA" => ta.vwma(src,length)
trend = switch trendType
"Average" => ma
"SuperTrend" => tsl
"WVAP" => wvap
"SAR" => sar
"Donchian channel" => mid
"Select Trend Type"=> close
trendcolor = switch trendType
"Average" => ma>ma[1]?color.green:color.red
"SuperTrend" => supertrend==1?color.green:color.red
"WVAP" => wvap>wvap[1]?color.green:color.red
"SAR" => trend>trend[1]?color.green:color.red
"Donchian channel" => color.aqua
plot(plotTrend?trend:na, color=trendcolor, title="Trend")
priceabovebelow = switch abovebelow
"Above" => src>=trend and trendType!="Select Trend Type"
"Below" => src<=trend and trendType!="Select Trend Type"
if trendType == "Select Trend Type"
priceabovebelow := close
//~~~}
// ~~ Momentum Condition {
Count(src,sign)=>
var count = 0
if Mom=="Positive Momentum"?src>src[1]:Mom=="Negative Momentum"?src<src[1]:src
count += 1
else
count := 0
positiveMom = Count(inputSrc,posMom)
negativeMom = Count(inputSrc,negMom)
momupdown = Mom!="Negative Momentum"?negativeMom[1]>=len:Mom!="Positive Momentum"?positiveMom[1]>=len:close
//~~~}
// ~~ Src bigger/less Condition {
srcbiggerless = shiftSign==">= (src bigger or equal than value)"?inputSrc >= signValue:shiftSign=="<= (src less or equal than value)"?inputSrc<= signValue:close
//~~~}
// ~~ Trend/Momentum/Src bigger/less Condition {
TrendMom = momupdown and priceabovebelow and srcbiggerless
//~~~}
// ~~ Additional Condition {
Positiveslope(src)=>
posslope = src>src[1]
Negativeslope(src)=>
negslope = src<src[1]
Above(src1,src2)=>
above = src1>src2
Below(src1,src2)=>
below = src1<src2
Samedirectionup(src1,src2)=>
sameup = src1>src1[1] and src2>src2[1]
Samedirectiondown(src1,src2)=>
samedown = src1<src1[1] and src2<src2[1]
//~~~}
// ~~ RSI {
rsi = ta.rsi(close,rsilen)
rsisignal = ta.sma(rsi,rsisignallen)
//RSI Cond
rsipos = rsiEnable=="RSI(src) has a positive slope"?Positiveslope(rsi_src=="RSI"?rsi:rsisignal):close
rsineg = rsiEnable=="RSI(src) has a negative slope"?Negativeslope(rsi_src=="RSI"?rsi:rsisignal):close
rsiabove = rsiEnable=="RSI is above the Signal line"?Above(rsi,rsisignal):close
rsibelow = rsiEnable=="RSI is below the Signal line"?Below(rsi,rsisignal):close
rsisameup = rsiEnable=="RSI(src) has the same slope (UP) as the input source"?Samedirectionup(rsi_src=="RSI"?rsi:rsisignal,inputSrc):close
rsisamedn = rsiEnable=="RSI(src) has the same slope (DOWN) as the input source"?Samedirectiondown(rsi_src=="RSI"?rsi:rsisignal,inputSrc):close
rsicond = rsipos and rsineg and rsiabove and rsibelow and rsisameup and rsisamedn
//~~~}
// ~~ Volume {
vol = volume
volsignal = ta.sma(vol,volumesignallen)
volpos = volumeEnable=="Volume(ma) has a positive slope"?Positiveslope(volsignal):close
volneg = volumeEnable=="Volume(ma) has a negative slope"?Negativeslope(volsignal):close
volabove = volumeEnable=="Volume is above the Ma line"?Above(vol,volsignal):close
volbelow = volumeEnable=="Volume is below the Ma line"?Below(vol,volsignal):close
volsameup = volumeEnable=="Volume(ma) has the same slope (UP) as the input source"?Samedirectionup(volsignal,inputSrc):close
volsamedn = volumeEnable=="Volume(ma) has the same slope (DOWN) as the input source"?Samedirectiondown(volsignal,inputSrc):close
volcond = volpos and volneg and volabove and volbelow and volsameup and volsamedn
//~~~}
// ~~ All Additinal Cond {
ALL = rsicond and volcond
//~~~}
Condition(src,val1,val2)=>
output = switch cond
"Crossing" =>shift?ta.cross(val1,src) and TrendMom and ALL :ta.cross(src,val1) and TrendMom and ALL
"Crossing Up" =>shift?ta.crossover(val1,src) and TrendMom and ALL:ta.crossover(src,val1) and TrendMom and ALL
"Crossing Down" =>shift?ta.crossunder(val1,src) and TrendMom and ALL:ta.crossunder(src,val1) and TrendMom and ALL
"Greater Than" =>shift?(val1>src) and TrendMom and ALL:(src>val1) and TrendMom and ALL
"Equal To" =>(src==val1) and TrendMom and ALL
"Less Than" =>shift?(val1<src) and TrendMom and ALL:(src<val1) and TrendMom and ALL
"Entering Channel" =>shift?(val2[1]<src and val2>=src) or (val1[1]>src and val1<src) and TrendMom and ALL:(src[1]<val2 and src>=val2) or (src[1]>val1 and src<val1) and TrendMom and ALL
"Exiting Channel" =>shift?(val2[1]>=src and val2<src) or (val1[1]<=src and val1>src) and TrendMom and ALL:(src[1]>=val2 and src<val2) or (src[1]<=val1 and src>val1) and TrendMom and ALL
"Inside Channel" =>shift?(val2>src) and (val1<src) and TrendMom and ALL :(src>val2) and (src<val1) and TrendMom and ALL
"Outside Channel" =>shift?(val2<src) or (val1>src) and TrendMom and ALL:(src<val2) or (src>val1) and TrendMom and ALL
"Moving Up" =>shift?ta.crossover(val1,src) and (bar_index - bars<=xbars) and TrendMom and ALL:ta.crossover(src,val1) and (bar_index - bars<=xbars) and TrendMom and ALL
"Moving Down" =>shift?ta.crossunder(val1,src) and (bar_index - bars<=xbars) and TrendMom and ALL:ta.crossunder(src,val1) and (bar_index - bars<=xbars) and TrendMom and ALL
"Moving Up %" =>(src>=perc+((perc/100)*val1)) and (bar_index - bars<=xbars) and TrendMom and ALL
"Moving Down %" =>(src<=perc-((perc/100)*val1)) and (bar_index - bars<=xbars) and TrendMom and ALL
"Turning Up" =>(src[1]<src and (src[1]<=src[2])) and TrendMom and ALL
"Turning Down" =>(src[1]>src and (src[1]>=src[2])) and TrendMom and ALL
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alert String {
Alert(val1)=>
s = str.tostring(val1)
u = str.tostring(channel1)
d = str.tostring(channel2)
b = str.tostring(bar_index-bars)
ba= (bar_index-bars)>1?" bars":" bar"
output = switch cond
"Crossing" => "Crossing " + s
"Crossing Up" => "Crossing Up " + s
"Crossing Down" => "Crossing Down " + s
"Greater Than" => "Greater Than " + s
"Equal To" => "Equal To" + s
"Less Than" => "Less Than " + s
"Entering Channel" => "Entering Channel (Upper Bound: " +u+ ", Lower Bound: " +d+ ")"
"Exiting Channel" => "Exiting Channel (Upper Bound: " +u+ ", Lower Bound: " +d+ ")"
"Inside Channel" => "Inside Channel (Upper Bound: " +u+ ", Lower Bound: " +d+ ")"
"Outside Channel" => "Outside Channel (Upper Bound: " +u+ ", Lower Bound: " +d+ ")"
"Moving Up" => "Moving Up " +s+ " in " +b+ba
"Moving Down" => "Moving Down " +s+ " in " +b+ba
"Moving Up %" => "Moving Up % " +s+ " in " +b+ba
"Moving Down %" => "Moving Down % " +s+ " in " +b+ba
"Turning Up" => "Turning Up"
"Turning Down" => "Turning Down"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Check Condition {
if barstate.islast and na(perc)
perc := inputSrc
bars := bar_index
alertTrigger = false
alertPlot = false
if element=="Price"
alertTrigger := Condition(inputSrc,src,float(na))
else if element=="Value"
alertTrigger := Condition(inputSrc,val,float(na))
else if element=="Channel"
alertTrigger := Condition(inputSrc,channel1,channel2)
if options=="Only Once"?alertTrigger and not alertTrigger[1]:alertTrigger
total += 1
pv = element=="Price"?src:val
str = alert=="Auto"?syminfo.ticker + ", " + timeframe.period + ", " + Alert(pv):msg
alert(str,freq = alert.freq_once_per_bar_close)
alertPlot := true
perc := float(na)
bars := int(na)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot Alert and Bg {
bgcolor(bg and alertPlot?bgcol:na)
if plot and alertPlot
yloc = loc=="Above Price"?high:low
style = loc=="Above Price"?label.style_label_down:label.style_label_up
label.new(bar_index,yloc,text="🔔",style=style,color=color(na),size=size)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alertcondition {
alertcondition(alertPlot,"Alert","Alert Fired! {{ticker}} {{interval}}")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alert Frequency {
if ta.change(dayofmonth(time))
days += 1
if ta.change(weekofyear(time))
weeks += 1
if ta.change(month(time))
months += 1
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alert Table {
var table tbl = table.new(position.top_right, 1, 9, bgcolor=color.new(color.gray,80), border_width=1)
var table noticeTbl = table.new(position.bottom_center,1, 1,bgcolor=color.new(color.red,0))
if barstate.islast
aDays = math.round(total/days,2)
aWeeks= math.round(total/weeks,2)
aMonths=math.round(total/months,2)
table.cell(tbl,0,0,text="Alert Frequency",text_color = chart.fg_color)
table.cell(tbl,0,1,"Per Day: "+str.tostring(aDays),text_color = chart.fg_color)
table.cell(tbl,0,2,"Per Week: "+str.tostring(aWeeks),text_color = chart.fg_color)
table.cell(tbl,0,3,"Per Month: "+str.tostring(aMonths),text_color = chart.fg_color)
if total<=0
table.cell(noticeTbl, 0, 0, "Please select an indicator input and alert condition!",text_color=color.white,text_size=size.large)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
End-Pointed SSA of Normalized Price Corridor [Loxx] | https://www.tradingview.com/script/EvwNj6qE-End-Pointed-SSA-of-Normalized-Price-Corridor-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 307 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("End-Pointed SSA of Normalized Price Corridor [Loxx]",
shorttitle = "EPSSANPC [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
lightgreencolor = #96E881
lightredcolor = #DF4F6C
int Maxncomp = 25
int MaxLag = 200
int MaxArrayLength = 1000
// Calculation of the function Sn, needed to calculate the eigenvalues
// Negative determinants are counted there
gaussSn(matrix<float> A, float l, int n)=>
array<float> w = array.new<float>(n, 0)
matrix<float> B = matrix.copy(A)
int count = 0
int cp = 0
float c = 0.
float s1 = 0.
float s2 = 0.
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp := cp + 1
c := matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
count := 0
s1 := 1
for i = 0 to n - 1
s2 := matrix.get(B, i, i)
if s2 < 0
count := count + 1
count
// Calculation of eigenvalues by the bisection method}
// The good thing is that as many eigenvalues are needed, so many will count,
// saves a lot of resources
gaussbisectionl(matrix<float> A, int k, int n)=>
float e1 = 0.
float maxnorm = 0.
float cn = 0.
float a1 = 0.
float b1 = 0.
float c = 0.
for i = 0 to n - 1
cn := 0
for j = 0 to n - 1
cn := cn + matrix.get(A, i, i)
if maxnorm < cn
maxnorm := cn
a1 := 0
b1 := 10 * maxnorm
e1 := 1.0 * maxnorm / 10000000
while math.abs(b1 - a1) > e1
c := 1.0 * (a1 + b1) / 2
if gaussSn(A, c, n) < k
a1 := c
else
b1 := c
float out = (a1 + b1) / 2.0
out
// Calculates eigenvectors for already computed eigenvalues
svector(matrix<float> A, float l, int n, array<float> V)=>
int cp = 0
matrix<float> B = matrix.copy(A)
float c = 0
array<float> w = array.new<float>(n, 0)
for i = 0 to n - 1
matrix.set(B, i, i, matrix.get(B, i, i) - l)
for k = 0 to n - 2
for i = k + 1 to n - 1
if matrix.get(B, k, k) == 0
for i1 = 0 to n - 1
array.set(w, i1, matrix.get(B, i1, k))
matrix.set(B, i1, k, matrix.get(B, i1, k + 1))
matrix.set(B, i1, k + 1, array.get(w, i1))
cp += 1
c := 1.0 * matrix.get(B, i, k) / matrix.get(B, k, k)
for j = 0 to n - 1
matrix.set(B, i, j, matrix.get(B, i, j) - matrix.get(B, k, j) * c)
array.set(V, n - 1, 1)
c := 1
for i = n - 2 to 0
array.set(V, i, 0)
for j = i to n - 1
array.set(V, i, array.get(V, i) - matrix.get(B, i, j) * array.get(V, j))
array.set(V, i, array.get(V, i) / matrix.get(B, i, i))
c += math.pow(array.get(V, i), 2)
for i = 0 to n - 1
array.set(V, i, array.get(V, i) / math.sqrt(c))
// Fast Singular SSA - "Caterpillar" method
// X-vector of the original series
// n-length
// l-lag length
// s-number of eigencomponents
// (there the original series is divided into components, and then restored, here you set how many components you need)
// Y - the restored row (smoothed by the caterpillar)
fastsingular(array<float> X, int n1, int l1, int s1)=>
int n = math.min(MaxArrayLength, n1)
int l = math.min(MaxLag, l1)
int s = math.min(Maxncomp, s1)
matrix<float> A = matrix.new<float>(l, l, 0.)
matrix<float> B = matrix.new<float>(n, l, 0.)
matrix<float> Bn = matrix.new<float>(l, n, 0.)
matrix<float> V = matrix.new<float>(l, n, 0.)
matrix<float> Yn = matrix.new<float>(l, n, 0.)
var array<float> vtarr = array.new<float>(l, 0.)
array<float> ls = array.new<float>(MaxLag, 0)
array<float> Vtemp = array.new<float>(MaxLag, 0)
array<float> Y = array.new<float>(n, 0)
int k = n - l + 1
// We form matrix A in the method that I downloaded from the site of the creators of this matrix S
for i = 0 to l - 1
for j = 0 to l - 1
matrix.set(A, i, j, 0)
for m = 0 to k - 1
matrix.set(A, i, j, matrix.get(A, i, j) + array.get(X, i + m) * array.get(X, m + j))
matrix.set(B, m, j, array.get(X, m + j))
//Find the eigenvalues and vectors of the matrix A
for i = 0 to s - 1
array.set(ls, i, gaussbisectionl(A, l - i, l))
svector(A, array.get(ls, i), l, Vtemp)
for j = 0 to l - 1
matrix.set(V, i, j, array.get(Vtemp, j))
// The restored matrix is formed
for i1 = 0 to s - 1
for i = 0 to k - 1
matrix.set(Yn, i1, i, 0)
for j = 0 to l - 1
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(B, i, j) * matrix.get(V, i1, j))
for i = 0 to l - 1
for j = 0 to k - 1
matrix.set(Bn, i, j, matrix.get(V, i1, i) * matrix.get(Yn, i1, j))
//Diagonal averaging (series recovery)
kb = k
lb = l
for i = 0 to n - 1
matrix.set(Yn, i1, i, 0)
if i < lb - 1
for j = 0 to i
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (i + 1)))
if (lb - 1 <= i) and (i < kb - 1)
for j = 0 to lb - 1
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * lb))
if kb - 1 <= i
for j = i - kb + 1 to n - kb
if l <= k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, j, i - j))
if l > k
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) + matrix.get(Bn, i - j, j))
matrix.set(Yn, i1, i, matrix.get(Yn, i1, i) / (1.0 * (n - i)))
// Here, if not summarized, then there will be separate decomposition components
// process by own functions
for i = 0 to n - 1
array.set(Y, i, 0)
for i1 = 0 to s - 1
array.set(Y, i, array.get(Y, i) + matrix.get(Yn, i1, i))
Y
srctype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcin = input.string("Median", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
lag = input.int(10, "Lag", group = "Basic Settings")
ncomp = input.int(2, "Number of Computations", group = "Basic Settings")
ssapernorm = input.int(50, "SSA Period Normalization", group = "Basic Settings")
numbars = input.int(330, "Number of Bars", group = "Basic Settings")
backbars = input.int(400, "Number of Back", group = "Basic Settings", tooltip ="How many bars to plot.The higher the number the slower the computation.")
HighLowStep = input.float(0.005, "High/Low Step", group = "Basic Settings", step = 0.001)
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
//Inputs for Loxx's Expanded Source Types
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(srctype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(srctype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(srctype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(srctype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(srctype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(srctype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(srctype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(srctype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(srctype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(srctype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(srctype, amafl, amasl, kfl, ksl)
=> haclose
ma = ta.sma(src, ssapernorm)
dev = 3.0 * ta.stdev(src, ssapernorm)
if (dev == 0)
dev := 0.000001
no = (src - ma) / dev
fmin = 0.
fmax = 0.
out = 0.
sig = 0.
arr = array.new_float(numbars + 1, 0)
for i = 0 to numbars - 1
array.set(arr, i, nz(no[i]))
if last_bar_index - bar_index < backbars
pv = fastsingular(arr, numbars, lag, ncomp)
out := array.get(pv, 0)
fmax := math.max(out, nz(fmax[1]) - HighLowStep)
fmin := math.min(out, nz(fmin[1]) + HighLowStep)
sig := out[1]
plot(last_bar_index - bar_index < backbars ? fmax : na, "max", color = lightredcolor )
plot(last_bar_index - bar_index < backbars ? fmin : na, "min", color = lightgreencolor )
plot(last_bar_index - bar_index < backbars ? .5 : na, "min", color = bar_index % 2 ? color.gray : na)
plot(last_bar_index - bar_index < backbars ? -.5 : na, "min", color = bar_index % 2 ? color.gray : na )
plot(last_bar_index - bar_index < backbars ? 0 : na, "min", color = bar_index % 2 ? color.gray : na )
colorout = out > sig ? greencolor : out < sig ? redcolor : color.gray
plot(last_bar_index - bar_index < backbars ? out : na, "EPSSANPC", color = colorout, linewidth = 2)
goLong = ta.crossover(out, sig)
goShort = ta.crossunder(out, sig)
barcolor(last_bar_index - bar_index < backbars and colorbars ? colorout : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title = "Long", message = "End-Pointed SSA of Normalized Price Corridor [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "End-Pointed SSA of Normalized Price Corridor [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Time Offset | https://www.tradingview.com/script/glHteGEl-Time-Offset/ | MrJulius | https://www.tradingview.com/u/MrJulius/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MrJulius
//@version=5
indicator("TimeOffset", overlay=true, scale=scale.left)
sym = input.symbol("NASDAQ:AAPL", "Compare to ticker")
lag = input.int(0, "Shift number of bars")
src = input.source(close, "Plot source")
sym_src = request.security(sym, timeframe.period, src)
plot(sym_src, "Lagged", color.yellow, offset=lag)
|
ETH Dominance Excluding BTC | https://www.tradingview.com/script/tLftH14U-ETH-Dominance-Excluding-BTC/ | MrCryptoholic | https://www.tradingview.com/u/MrCryptoholic/ | 1 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MrCryptoholic
//@version=5
indicator("ETH Dominance Excluding BTC")
total2 = request.security('TOTAL2', timeframe='', expression=close, ignore_invalid_symbol=true)
eth = request.security('CRYPTOCAP:ETH', timeframe='', expression=close, ignore_invalid_symbol=true)
plot(eth / total2, linewidth=2, editable=true) |
Multiple Non-Anchored VWAP | https://www.tradingview.com/script/0f9MNX7Q-Multiple-Non-Anchored-VWAP/ | jlb05013 | https://www.tradingview.com/u/jlb05013/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jlb05013
//@version=5
indicator("Multiple Non-Anchored VWAP", overlay=true, shorttitle="VWAP")
show_vwap_1 = input.bool(defval=true, title='Show VWAP #1', group='Display VWAP')
show_vwap_2 = input.bool(defval=false, title='Show VWAP #2', group='Display VWAP')
show_vwap_3 = input.bool(defval=false, title='Show VWAP #3', group='Display VWAP')
show_vwap_4 = input.bool(defval=false, title='Show VWAP #4', group='Display VWAP')
show_vwap_5 = input.bool(defval=false, title='Show VWAP #5', group='Display VWAP')
input_stdev_1 = input.bool(defval=true, title='Show StDev #1', group='Display StDev')
input_stdev_2 = input.bool(defval=true, title='Show StDev #2', group='Display StDev')
input_stdev_3 = input.bool(defval=true, title='Show StDev #3', group='Display StDev')
cumulativePeriod_1 = input.int(21, "Period #1", step=1, group='Choose Period for VWAP', minval=1)
cumulativePeriod_2 = input.int(63, "Period #2", step=1, group='Choose Period for VWAP', minval=1)
cumulativePeriod_3 = input.int(126, "Period #3", step=1, group='Choose Period for VWAP', minval=1)
cumulativePeriod_4 = input.int(252, "Period #4", step=1, group='Choose Period for VWAP', minval=1)
cumulativePeriod_5 = input.int(756, "Period #5", step=1, group='Choose Period for VWAP', minval=1)
stdev_band_1 = input.float(defval=1.0, title="StDev Band #1", step=0.1, group="Choose # of StDev's", minval=0.1)
stdev_band_2 = input.float(defval=2.0, title="StDev Band #2", step=0.1, group="Choose # of StDev's", minval=0.1)
stdev_band_3 = input.float(defval=3.0, title="StDev Band #3", step=0.1, group="Choose # of StDev's", minval=0.1)
typicalPrice = (high + low + close) / 3
typicalPriceVolume = typicalPrice * volume
cumulativeTypicalPriceVolume_1 = math.sum(typicalPriceVolume, cumulativePeriod_1)
cumulativeVolume_1 = math.sum(volume, cumulativePeriod_1)
vwapValue_1 = cumulativeTypicalPriceVolume_1 / cumulativeVolume_1
vwap_hi_1_1 = vwapValue_1 + (stdev_band_1 * ta.stdev(vwapValue_1, cumulativePeriod_1))
vwap_lo_1_1 = vwapValue_1 - (stdev_band_1 * ta.stdev(vwapValue_1, cumulativePeriod_1))
vwap_hi_1_2 = vwapValue_1 + (stdev_band_2 * ta.stdev(vwapValue_1, cumulativePeriod_1))
vwap_lo_1_2 = vwapValue_1 - (stdev_band_2 * ta.stdev(vwapValue_1, cumulativePeriod_1))
vwap_hi_1_3 = vwapValue_1 + (stdev_band_3 * ta.stdev(vwapValue_1, cumulativePeriod_1))
vwap_lo_1_3 = vwapValue_1 - (stdev_band_3 * ta.stdev(vwapValue_1, cumulativePeriod_1))
cumulativeTypicalPriceVolume_2 = math.sum(typicalPriceVolume, cumulativePeriod_2)
cumulativeVolume_2 = math.sum(volume, cumulativePeriod_2)
vwapValue_2 = cumulativeTypicalPriceVolume_2 / cumulativeVolume_2
vwap_hi_2_1 = vwapValue_2 + (stdev_band_1 * ta.stdev(vwapValue_2, cumulativePeriod_2))
vwap_lo_2_1 = vwapValue_2 - (stdev_band_1 * ta.stdev(vwapValue_2, cumulativePeriod_2))
vwap_hi_2_2 = vwapValue_2 + (stdev_band_2 * ta.stdev(vwapValue_2, cumulativePeriod_2))
vwap_lo_2_2 = vwapValue_2 - (stdev_band_2 * ta.stdev(vwapValue_2, cumulativePeriod_2))
vwap_hi_2_3 = vwapValue_2 + (stdev_band_3 * ta.stdev(vwapValue_2, cumulativePeriod_2))
vwap_lo_2_3 = vwapValue_2 - (stdev_band_3 * ta.stdev(vwapValue_2, cumulativePeriod_2))
cumulativeTypicalPriceVolume_3 = math.sum(typicalPriceVolume, cumulativePeriod_3)
cumulativeVolume_3 = math.sum(volume, cumulativePeriod_3)
vwapValue_3 = cumulativeTypicalPriceVolume_3 / cumulativeVolume_3
vwap_hi_3_1 = vwapValue_3 + (stdev_band_1 * ta.stdev(vwapValue_3, cumulativePeriod_3))
vwap_lo_3_1 = vwapValue_3 - (stdev_band_1 * ta.stdev(vwapValue_3, cumulativePeriod_3))
vwap_hi_3_2 = vwapValue_3 + (stdev_band_2 * ta.stdev(vwapValue_3, cumulativePeriod_3))
vwap_lo_3_2 = vwapValue_3 - (stdev_band_2 * ta.stdev(vwapValue_3, cumulativePeriod_3))
vwap_hi_3_3 = vwapValue_3 + (stdev_band_3 * ta.stdev(vwapValue_3, cumulativePeriod_3))
vwap_lo_3_3 = vwapValue_3 - (stdev_band_3 * ta.stdev(vwapValue_3, cumulativePeriod_3))
cumulativeTypicalPriceVolume_4 = math.sum(typicalPriceVolume, cumulativePeriod_4)
cumulativeVolume_4 = math.sum(volume, cumulativePeriod_4)
vwapValue_4 = cumulativeTypicalPriceVolume_4 / cumulativeVolume_4
vwap_hi_4_1 = vwapValue_4 + (stdev_band_1 * ta.stdev(vwapValue_4, cumulativePeriod_4))
vwap_lo_4_1 = vwapValue_4 - (stdev_band_1 * ta.stdev(vwapValue_4, cumulativePeriod_4))
vwap_hi_4_2 = vwapValue_4 + (stdev_band_2 * ta.stdev(vwapValue_4, cumulativePeriod_4))
vwap_lo_4_2 = vwapValue_4 - (stdev_band_2 * ta.stdev(vwapValue_4, cumulativePeriod_4))
vwap_hi_4_3 = vwapValue_4 + (stdev_band_3 * ta.stdev(vwapValue_4, cumulativePeriod_4))
vwap_lo_4_3 = vwapValue_4 - (stdev_band_3 * ta.stdev(vwapValue_4, cumulativePeriod_4))
cumulativeTypicalPriceVolume_5 = math.sum(typicalPriceVolume, cumulativePeriod_5)
cumulativeVolume_5 = math.sum(volume, cumulativePeriod_5)
vwapValue_5 = cumulativeTypicalPriceVolume_5 / cumulativeVolume_5
vwap_hi_5_1 = vwapValue_5 + (stdev_band_1 * ta.stdev(vwapValue_5, cumulativePeriod_5))
vwap_lo_5_1 = vwapValue_5 - (stdev_band_1 * ta.stdev(vwapValue_5, cumulativePeriod_5))
vwap_hi_5_2 = vwapValue_5 + (stdev_band_2 * ta.stdev(vwapValue_5, cumulativePeriod_5))
vwap_lo_5_2 = vwapValue_5 - (stdev_band_2 * ta.stdev(vwapValue_5, cumulativePeriod_5))
vwap_hi_5_3 = vwapValue_5 + (stdev_band_3 * ta.stdev(vwapValue_5, cumulativePeriod_5))
vwap_lo_5_3 = vwapValue_5 - (stdev_band_3 * ta.stdev(vwapValue_5, cumulativePeriod_5))
plot(show_vwap_1 ? vwapValue_1 : na, title='VWAP #1', color=color.teal)
plot(show_vwap_1 and input_stdev_1 ? vwap_hi_1_1 : na, title='VWAP #1 + Stdev 1', color=color.teal, linewidth=1)
plot(show_vwap_1 and input_stdev_1 ? vwap_lo_1_1 : na, title='VWAP #1 - Stdev 1', color=color.teal, linewidth=1)
plot(show_vwap_1 and input_stdev_2 ? vwap_hi_1_2 : na, title='VWAP #1 + Stdev 2', color=color.teal, linewidth=2)
plot(show_vwap_1 and input_stdev_2 ? vwap_lo_1_2 : na, title='VWAP #1 + Stdev 2', color=color.teal, linewidth=2)
plot(show_vwap_1 and input_stdev_3 ? vwap_hi_1_3 : na, title='VWAP #1 + Stdev 3', color=color.teal, linewidth=3)
plot(show_vwap_1 and input_stdev_3 ? vwap_lo_1_3 : na, title='VWAP #1 + Stdev 3', color=color.teal, linewidth=3)
plot(show_vwap_2 ? vwapValue_2 : na, title='VWAP #2', color=color.blue)
plot(show_vwap_2 and input_stdev_1 ? vwap_hi_2_1 : na, title='VWAP #2 + Stdev 1', color=color.blue, linewidth=1)
plot(show_vwap_2 and input_stdev_1 ? vwap_lo_2_1 : na, title='VWAP #2 - Stdev 1', color=color.blue, linewidth=1)
plot(show_vwap_2 and input_stdev_2 ? vwap_hi_2_2 : na, title='VWAP #2 + Stdev 2', color=color.blue, linewidth=2)
plot(show_vwap_2 and input_stdev_2 ? vwap_lo_2_2 : na, title='VWAP #2 + Stdev 2', color=color.blue, linewidth=2)
plot(show_vwap_2 and input_stdev_3 ? vwap_hi_2_3 : na, title='VWAP #2 + Stdev 3', color=color.blue, linewidth=3)
plot(show_vwap_2 and input_stdev_3 ? vwap_lo_2_3 : na, title='VWAP #2 + Stdev 3', color=color.blue, linewidth=3)
plot(show_vwap_3 ? vwapValue_3 : na, title='VWAP #3', color=color.purple)
plot(show_vwap_3 and input_stdev_1 ? vwap_hi_3_1 : na, title='VWAP #3 + Stdev 1', color=color.purple, linewidth=1)
plot(show_vwap_3 and input_stdev_1 ? vwap_lo_3_1 : na, title='VWAP #3 - Stdev 1', color=color.purple, linewidth=1)
plot(show_vwap_3 and input_stdev_2 ? vwap_hi_3_2 : na, title='VWAP #3 + Stdev 2', color=color.purple, linewidth=2)
plot(show_vwap_3 and input_stdev_2 ? vwap_lo_3_2 : na, title='VWAP #3 + Stdev 2', color=color.purple, linewidth=2)
plot(show_vwap_3 and input_stdev_3 ? vwap_hi_3_3 : na, title='VWAP #3 + Stdev 3', color=color.purple, linewidth=3)
plot(show_vwap_3 and input_stdev_3 ? vwap_lo_3_3 : na, title='VWAP #3 + Stdev 3', color=color.purple, linewidth=3)
plot(show_vwap_4 ? vwapValue_4 : na, title='VWAP #4', color=color.red)
plot(show_vwap_4 and input_stdev_1 ? vwap_hi_4_1 : na, title='VWAP #4 + Stdev 1', color=color.red, linewidth=1)
plot(show_vwap_4 and input_stdev_1 ? vwap_lo_4_1 : na, title='VWAP #4 - Stdev 1', color=color.red, linewidth=1)
plot(show_vwap_4 and input_stdev_2 ? vwap_hi_4_2 : na, title='VWAP #4 + Stdev 2', color=color.red, linewidth=2)
plot(show_vwap_4 and input_stdev_2 ? vwap_lo_4_2 : na, title='VWAP #4 + Stdev 2', color=color.red, linewidth=2)
plot(show_vwap_4 and input_stdev_3 ? vwap_hi_4_3 : na, title='VWAP #4 + Stdev 3', color=color.red, linewidth=3)
plot(show_vwap_4 and input_stdev_3 ? vwap_lo_4_3 : na, title='VWAP #4 + Stdev 3', color=color.red, linewidth=3)
plot(show_vwap_5 ? vwapValue_5 : na, title='VWAP #5', color=color.green)
plot(show_vwap_5 and input_stdev_1 ? vwap_hi_5_1 : na, title='VWAP #5 + Stdev 1', color=color.green, linewidth=1)
plot(show_vwap_5 and input_stdev_1 ? vwap_lo_5_1 : na, title='VWAP #5 - Stdev 1', color=color.green, linewidth=1)
plot(show_vwap_5 and input_stdev_2 ? vwap_hi_5_2 : na, title='VWAP #5 + Stdev 2', color=color.green, linewidth=2)
plot(show_vwap_5 and input_stdev_2 ? vwap_lo_5_2 : na, title='VWAP #5 + Stdev 2', color=color.green, linewidth=2)
plot(show_vwap_5 and input_stdev_3 ? vwap_hi_5_3 : na, title='VWAP #5 + Stdev 3', color=color.green, linewidth=3)
plot(show_vwap_5 and input_stdev_3 ? vwap_lo_5_3 : na, title='VWAP #5 + Stdev 3', color=color.green, linewidth=3)
//
//
// |
JFD-Adaptive, GKYZ-Filtered KAMA [Loxx] | https://www.tradingview.com/script/KJQp4GrB-JFD-Adaptive-GKYZ-Filtered-KAMA-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 461 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx
//@version=5
indicator("JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]",
shorttitle = "JFDAGKYZFKAMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
fdRange(int size)=>
out = math.max(nz(close[size]), ta.highest(high, size)) - math.min(nz(close[size]), ta.lowest(low, size))
out
jurikFractalDimension(int size, int count)=>
int window1 = size * (count - 1)
int window2 = size * count
float smlRange = 0
float smlSumm = 0
smlRange := fdRange(size)
smlSumm := nz(smlSumm[1]) + smlRange
smlSumm -= nz(smlRange[window1])
out = 2.0 - math.log(fdRange(window2) / (smlSumm / window1)) / math.log(count)
out
kama(float src, int period, float fast, float slow, float power, bool JurikFD)=>
float fastend = (2.0 / (fast + 1))
float slowend = (2.0 / (slow + 1))
float efratio = 0
float diff = 0
float signal = 0
float noise = 0
float fract = jurikFractalDimension(period, 2)
if (JurikFD)
efratio := math.min(2.0 - fract, 1.0)
else
signal := math.abs(src - nz(src[period]))
diff := math.abs(src - nz(src[1]))
for k = 0 to period - 1
noise += nz(diff[k])
if (noise != 0)
efratio := signal / noise
else
efratio := 1
float smooth = math.pow(efratio * (fastend - slowend) + slowend, power)
float kama = src
kama := nz(kama[1]) + smooth * (src - nz(kama[1]))
kama
gkyzvol(int per)=>
float gzkylog = math.log(open / nz(close[1]))
float pklog = math.log(high / low)
float gklog = math.log(close / open)
float garmult = (2 * math.log(2) - 1)
float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per)
float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per)
float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per)
float sum = gkyzsum + parkinsonsum - garmansum
float devpercent = math.sqrt(sum)
devpercent
gkyzFilter(float src, int len, float filter)=>
float price = src
float filtdev = filter * gkyzvol(len) * src
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
AmaPeriod = input.int(10, "AMA Period", group = "Basic Settings")
FastEnd = input.int(2, "Fast-End", group = "Basic Settings")
SlowEnd = input.int(20, "Slow-End", group = "Basic Settings")
SmoothPower = input.int(2, "Smooth Power", group = "Basic Settings")
JurikFDAdaptive = input.bool(false, "Jurik Fractal Dimension Adaptive?", group = "Basic Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "JFDAGKYZFKAMA", "Both", "None"], group= "Filter Settings")
filter = input.float(0.5, "Filter Multiple", minval = 0, group= "Filter Settings")
filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showSigs = input.bool(true, "Show Signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src := filterop == "Both" or filterop == "Price" and filter > 0 ? gkyzFilter(src, filterperiod, filter) : src
out = kama(src, AmaPeriod, FastEnd, SlowEnd, SmoothPower, JurikFDAdaptive)
out := filterop == "Both" or filterop == "JFDAGKYZFKAMA" and filter > 0 ? gkyzFilter(out, filterperiod, filter) : out
sig = out[1]
goLong_pre = ta.crossover(out, sig)
goShort_pre = ta.crossunder(out, sig)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
colorout = contSwitch == 1 ? greencolor : redcolor
barcolor(colorbars ? colorout : na)
plot(out, "JFDAGKYZFKAMA", color = colorout, linewidth = 3)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.