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
Economic Calendar Events: FOMC, CPI, and more
https://www.tradingview.com/script/HLYDwa0N-Economic-Calendar-Events-FOMC-CPI-and-more/
jdehorty
https://www.tradingview.com/u/jdehorty/
1,778
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/ // © jdehorty // @version=5 indicator('Economic Calendar Events', overlay=true, scale=scale.none, max_lines_count=500) import jdehorty/EconomicCalendar/2 as calendar // ================== // ==== Settings ==== // ================== show_fomc_meetings = input.bool(defval = true, title = "📅 FOMC", inline = "FOMC", group="⚙️ Settings", tooltip="The FOMC meets eight times a year to determine the course of monetary policy. The FOMC's decisions are announced in a press release at 2:15 p.m. ET on the day of the meeting. The press release is followed by a press conference at 2:30 p.m. ET. The FOMC's decisions are based on a review of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.") c_fomcMeeting = input.color(color.new(color.red, 50), title = "Color", group="⚙️ Settings", inline = "FOMC") show_fomc_minutes = input.bool(defval = true, title = "📅 FOMC Minutes", inline = "FOMCMinutes", group="⚙️ Settings", tooltip="The FOMC minutes are released three weeks after each FOMC meeting. The minutes provide a detailed account of the FOMC's discussion of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.") c_fomcMinutes = input.color(color.new(color.orange, 50), title = "Color", group="⚙️ Settings", inline = "FOMCMinutes") show_ppi = input.bool(defval = true, title = "📅 Producer Price Index (PPI)", inline = "PPI", group="⚙️ Settings", tooltip="The Producer Price Index (PPI) measures changes in the price level of goods and services sold by domestic producers. The PPI is a weighted average of prices of a basket of goods and services, such as transportation, food, and medical care. The PPI is a leading indicator of CPI.") c_ppi = input.color(color.new(color.yellow, 50), title = "Color", group="⚙️ Settings", inline = "PPI") show_cpi = input.bool(defval = true, title = "📅 Consumer Price Index (CPI)", inline = "CPI", group="⚙️ Settings", tooltip="The Consumer Price Index (CPI) measures changes in the price level of goods and services purchased by households. The CPI is a weighted average of prices of a basket of consumer goods and services, such as transportation, food, and medical care. The CPI-U is the most widely used measure of inflation. The CPI-U is based on a sample of about 87,000 households and measures the change in the cost of a fixed market basket of goods and services purchased by urban consumers.") c_cpi = input.color(color.new(color.lime, 50), title = "Color", group="⚙️ Settings", inline = "CPI") show_csi = input.bool(defval = true, title = "📅 Consumer Sentiment Index (CSI)", inline = "CSI", group="⚙️ Settings", tooltip="The University of Michigan's Consumer Sentiment Index (CSI) is a measure of consumer attitudes about the economy. The CSI is based on a monthly survey of 500 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CSI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.") c_csi = input.color(color.new(color.aqua, 50), title = "Color", group="⚙️ Settings", inline = "CSI") show_cci = input.bool(defval = true, title = "📅 Consumer Confidence Index (CCI)", inline = "CCI", group="⚙️ Settings", tooltip="The Conference Board's Consumer Confidence Index (CCI) is a measure of consumer attitudes about the economy. The CCI is based on a monthly survey of 5,000 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CCI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.") c_cci = input.color(color.new(color.fuchsia, 50), title = "Color", group="⚙️ Settings", inline = "CCI") show_nfp = input.bool(defval = true, title = "📅 Non-Farm Payroll (NFP)", inline = "NFP", group="⚙️ Settings", tooltip="The Non-Farm Payroll (NFP) is a measure of the change in the number of employed persons, excluding farm workers and government employees. The NFP is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.") c_nfp = input.color(color.new(color.silver, 50), title = "Color", group="⚙️ Settings", inline = "NFP") show_legend = input.bool(true, "Show Legend", group="⚙️ Settings", inline = "Legend", tooltip="Show the color legend for the economic calendar events.") use_alt_date_resolution = input.bool(false, "Use Alternative Date Resolution", group="⚙️ Settings", inline = "AlternativeDateResolution", tooltip="Use alternative date resolution for the economic calendar events. May help in scenarios where the daily timeframe is off by a day.") // ======================= // ==== Dates & Times ==== // ======================= getUnixTime(eventArr, i) => int t = array.get(eventArr, i) switch timeframe.isdaily => timestamp(year(t), month(t), dayofmonth(t)-timeframe.multiplier+1, 00, 00, 00) timeframe.isweekly => timestamp(year(t), month(t), dayofmonth(t)-7*timeframe.multiplier+1, 00, 00, 00) timeframe.ismonthly => timestamp(year(t), month(t)-timeframe.multiplier+1, 00, 00, 00, 00) timeframe.isminutes and timeframe.multiplier > 60 => timestamp(year(t), month(t), dayofmonth(t), hour(t)-timeframe.multiplier/60+1, minute(t), second(t)) => timestamp(year(t), month(t), dayofmonth(t), hour(t), minute(t), second(t)) // Note: The following is an alternative implementation of getUnixTime. It is useful for independently double-checking the resulting vertical lines of the above function. getUnixTimeAlt(eventArr, i) => int t = array.get(eventArr, i) switch timeframe.isdaily and timeframe.multiplier >= 1 => t - timeframe.multiplier*86400000 // -n days timeframe.isweekly => t - timeframe.multiplier*604800000 // -n week(s) timeframe.ismonthly => t - timeframe.multiplier*2592000000 // -n month(s) timeframe.isminutes and timeframe.multiplier > 60 => t - timeframe.multiplier*60000 // -n minutes => t // Note: An offset of -n units is needed to realign events with the timeframe in which they occurred if show_fomc_meetings fomcMeetingsArr = calendar.fomcMeetings() for i = 0 to array.size(fomcMeetingsArr) - 1 unixTime = use_alt_date_resolution ? getUnixTimeAlt(fomcMeetingsArr, i) : getUnixTime(fomcMeetingsArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMeeting, width=2, xloc=xloc.bar_time) if show_fomc_minutes fomcMinutesArr = calendar.fomcMinutes() for i = 0 to array.size(fomcMinutesArr) - 1 unixTime = use_alt_date_resolution ? getUnixTimeAlt(fomcMinutesArr, i) : getUnixTime(fomcMinutesArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMinutes, width=2, xloc=xloc.bar_time) if show_ppi ppiArr = calendar.ppiReleases() for i = 0 to array.size(ppiArr) - 1 unixTime = use_alt_date_resolution ? getUnixTimeAlt(ppiArr, i) : getUnixTime(ppiArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_ppi, width=2, xloc=xloc.bar_time) if show_cpi cpiArr = calendar.cpiReleases() for i = 0 to array.size(cpiArr) - 1 unixTime = use_alt_date_resolution ? getUnixTimeAlt(cpiArr, i) : getUnixTime(cpiArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cpi, width=2, xloc=xloc.bar_time) if show_csi csiArr = calendar.csiReleases() for i = 0 to array.size(csiArr) - 1 unixTime = use_alt_date_resolution ? getUnixTimeAlt(csiArr, i) : getUnixTime(csiArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_csi, width=2, xloc=xloc.bar_time) if show_cci cciArr = calendar.cciReleases() for i = 0 to array.size(cciArr) - 1 unixTime = use_alt_date_resolution ? getUnixTimeAlt(cciArr, i) : getUnixTime(cciArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cci, width=2, xloc=xloc.bar_time) if show_nfp nfpArr = calendar.nfpReleases() for i = 0 to array.size(nfpArr) - 1 unixTime = use_alt_date_resolution ? getUnixTimeAlt(nfpArr, i) : getUnixTime(nfpArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_nfp, width=2, xloc=xloc.bar_time) // ================ // ==== Legend ==== // ================ if show_legend var tbl = table.new(position.top_right, columns=1, rows=8, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.black, 100)) units = timeframe.isminutes ? "m" : "" if barstate.islast table.cell(tbl, 0, 0, syminfo.ticker + ' | ' + str.tostring(timeframe.period) + units, text_halign=text.align_center, text_color=color.gray, text_size=size.normal) table.cell(tbl, 0, 1, 'FOMC Meeting', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_fomcMeeting, 10), text_size=size.small) table.cell(tbl, 0, 2, 'FOMC Minutes', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_fomcMinutes, 10), text_size=size.small) table.cell(tbl, 0, 3, 'Producer Price Index (PPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_ppi, 10), text_size=size.small) table.cell(tbl, 0, 4, 'Consumer Price Index (CPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_cpi, 10), text_size=size.small) table.cell(tbl, 0, 5, 'Consumer Sentiment Index (CSI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_csi, 10), text_size=size.small) table.cell(tbl, 0, 6, 'Consumer Confidence Index (CCI)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_cci, 10), text_size=size.small) table.cell(tbl, 0, 7, 'Non-Farm Payrolls (NFP)', text_halign=text.align_center, bgcolor=color.black, text_color=color.new(c_nfp, 10), text_size=size.small)
Wick-off Check Moving Average [Misu]
https://www.tradingview.com/script/NBRO3jSQ-Wick-off-Check-Moving-Average-Misu/
Fontiramisu
https://www.tradingview.com/u/Fontiramisu/
266
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("Wick-off Check Moving Average [Misu]", shorttitle="Wickoff Check MA [Misu]", overlay = true, max_lines_count = 500, max_labels_count = 500) //, initial_capital=50000, default_qty_type=strategy.percent_of_equity, default_qty_value=100) import Fontiramisu/fontilab/12 as fontilab // ] —————— Input Vars —————— [ // General src = input(close, title="Source") // MA. var maTypeTooltip = "SMA: Simple moving average // EMA: Exponential MA // SMMA (RMA): Running MA // WMA: Weighted MA // VWMA: Volume weighted MA // DEMA: Double exponential MA " + "// TEMA: Triple exponential MA// ZLSMA: Zero lag sma //ZLDEMA: Zero lag dema// ZLTEMA: Zero lag tema // McGinley-D: McGinley Dynamic// HMA: Hull ma" typeMA = input.string(title = "Method Multi MA", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "DEMA", "TEMA", "ZLSMA", "ZLDEMA", "ZLTEMA", "McGinley-D", "HMA"] , tooltip=maTypeTooltip , group="MA") srcMA = input(close, title="MA Source", group="MA") lenMA = input.int(36, minval=1, title="Length Multi MA", group="MA") // Trend. lenBarTrendValidation = input.int(10, title="Length Bar - Trend Validation", minval=1, group="Trend", tooltip="Define the number of bar needed to validate a trend. When price is above the MA, trend is up. When price is under MA, trend is down.") // Wick-off. wickoffMode = input.string("continuation pattern", title="Wickoff Mode", options=["no trend in progress", "continuation pattern", "both"], group="Wickoff Mode") lenWickValidation = input.int(10, title="Lenght Avg Wick Validation", group="Wickoff Settings") factorWickValidation = input.float(1, step=0.1, title="Factor Avg Wick Validation", group="Wickoff Settings") // Wick off cond. isWickoffUpBull = false isWickoffUpBear = false isWickoffDownBull = false isWickoffDownBear = false // ] —————— Util Functions —————— [ // Cond Vars. _bodyHi = math.max(close, open) _bodyLo = math.min(close, open) _body = _bodyHi - _bodyLo _upperWick = high - _bodyHi _greenBody = open < close _redBody = open > close _highWick = high - _bodyHi _lowWick = _bodyLo - low _avgHighWick = ta.sma(_highWick, lenWickValidation) _avgLowWick = ta.sma(_lowWick, lenWickValidation) // Wick-off & MA conf. multiMA = fontilab.multiMa(srcMA, lenMA, typeMA) var upTCounter = 0 var downTCounter = 0 upTCounter := src > multiMA ? upTCounter + 1 : 0 downTCounter := src < multiMA ? downTCounter + 1 : 0 _uptInProgress = src > multiMA and upTCounter >= lenBarTrendValidation _downtInProgress = src < multiMA and downTCounter >= lenBarTrendValidation // @function detect wickoff. isWickCrossPattern (src, isCrossUp, factor) => isCross = false if isCrossUp isCross := _bodyHi < src and src < high and _highWick > _avgHighWick * factor else isCross := low < src and src < _bodyLo and _lowWick > _avgLowWick * factor isCross // ] —————— Logic —————— [ // Invalidate wickoff other conditions isWickoffUpBull := _uptInProgress and isWickCrossPattern(multiMA, false, factorWickValidation) isWickoffDownBear := _downtInProgress and isWickCrossPattern(multiMA, true, factorWickValidation) isWickoffDownBull := not _downtInProgress and not _uptInProgress and isWickCrossPattern(multiMA, false, factorWickValidation) isWickoffUpBear := not _downtInProgress and not _uptInProgress and isWickCrossPattern(multiMA, true, factorWickValidation) // ----- // BUY / SELL COND. buyCond = wickoffMode == "continuation pattern" ? isWickoffUpBull : wickoffMode == "both" ? isWickoffUpBull or isWickoffDownBull : isWickoffDownBull sellCond = wickoffMode == "continuation pattern" ? isWickoffDownBear : wickoffMode == "both" ? isWickoffUpBear or isWickoffDownBear : isWickoffUpBear // ] —————— Strategy & alerts Part —————— [ // if buyCond // strategy.entry("L", strategy.long, alert_message="Buy Signal") // if sellCond // strategy.entry("S", strategy.short, alert_message="Sell Signal") alertcondition(buyCond, title = "Long", message = "Wick-off check MA [Misu]: Long\nSymbol: {{ticker}}\nPrice: {{close}}") alertcondition(sellCond, title = "Short", message = "Wick-off check MA [Misu]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") // ] —————— Plot —————— [ plot(multiMA, title = "Moving Average", color=color.aqua, linewidth = 2) if isWickoffDownBull and wickoffMode != "continuation pattern" label.new(x = bar_index, y = low - (ta.atr(30) * 0.2), xloc = xloc.bar_index, text = "W", style = label.style_label_up, color = color.green, size = size.small, textcolor = color.white, textalign = text.align_center) else if isWickoffUpBull and wickoffMode != "no trend in progress" label.new(x = bar_index, y = low - (ta.atr(30) * 0.2), xloc = xloc.bar_index, text = "W", style = label.style_label_up, color = color.green, size = size.small, textcolor = color.white, textalign = text.align_center) else if isWickoffUpBear and wickoffMode != "continuation pattern" label.new(x = bar_index, y = high + (ta.atr(30) * 0.2), xloc = xloc.bar_index, text = "W", style = label.style_label_down, color = color.red, size = size.small, textcolor = color.white, textalign = text.align_center) else if isWickoffDownBear and wickoffMode != "no trend in progress" label.new(x = bar_index, y = high + (ta.atr(30) * 0.2), xloc = xloc.bar_index, text = "W", style = label.style_label_down, color = color.red, size = size.small, textcolor = color.white, textalign = text.align_center) // ]
Daily RTH Moving Average On Intraday Timeframes [vnhilton]
https://www.tradingview.com/script/AbvppS9v-Daily-RTH-Moving-Average-On-Intraday-Timeframes-vnhilton/
vnhilton
https://www.tradingview.com/u/vnhilton/
36
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © vnhilton //@version=5 indicator("Daily RTH Moving Average On Intraday Timeframes [vnhilton]", "Daily RTH MA", true) //RTH Timezone rth = time(timeframe.period, session.regular, syminfo.timezone) //Get Chart Timeframe timeframe = timeframe.multiplier //Minutes Used For Calculating MA Length (up to daily timeframe) minutes = timeframe.isintraday ? 390 : 1 //MA Inputs len = input.int(5, minval=1, title="MA Daily Length") src = input(close, title="Source") //Bollinger Band Inputs mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev") //Logic ma = ta.sma(src, (len * minutes) / timeframe) dayPrice = ta.stdev(src, (len * minutes) / timeframe) maRTH = request.security(ticker.modify(syminfo.tickerid, session.regular), timeframe.period, ma) stdevPriceRTH = mult * request.security(ticker.modify(syminfo.tickerid, session.regular), timeframe.period, dayPrice) upper = maRTH + stdevPriceRTH lower = maRTH - stdevPriceRTH //Plot averageLine = plot(rth ? maRTH : na, "RTH Daily MA", color.red, style=plot.style_linebr) upperLine = plot(rth ? upper : na, "Upper Band", color.gray, style=plot.style_linebr) lowerLine = plot(rth ? lower : na, "Lower Band", color.gray, style=plot.style_linebr) //Fill fill(plot1=upperLine, plot2=averageLine, top_value=upper, bottom_value=maRTH, top_color=color.rgb(120, 123, 134, 99), bottom_color=color.rgb(255, 82, 82, 95), title="Upper Band Fill") fill(plot1=averageLine, plot2=lowerLine, top_value=maRTH, bottom_value=lower, top_color=color.rgb(255, 82, 82, 95), bottom_color=color.rgb(120, 123, 134, 99), title="Lower Band Fill")
stochastic + tsv
https://www.tradingview.com/script/gwkkJbST/
goonerholic
https://www.tradingview.com/u/goonerholic/
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/ // © goonerholic //@version=5 indicator("stochastic + tsv", overlay=true) // ======================================================================================================== // ======================================================================================================== // EMA ==================================================================================================== useEma = input.bool(true, title="Ema 사용여부", tooltip="지표의 계산에 ema 조건을 포함시킬지 결정합니다", group="EMA") emaPeriod = input.int(200, title="EMA Period", group="EMA") ema = ta.ema(close, emaPeriod) emaLongCond = useEma ? close > ema : true emaShortCond = useEma ? close < ema : true plot(ema, "ema") // ======================================================================================================== // ======================================================================================================== // Stochastic ============================================================================================= periodK = input.int(7, title="%K Length", minval=1, group="Stochastic") smoothK = input.int(3, title="%K Smoothing", minval=1, group="Stochastic") k = ta.sma(ta.stoch(close, high, low, periodK), smoothK) stochUpper = 80 stochLower = 20 stochMiddle = 50 var int direction = na if (ta.crossunder(k, stochLower)) direction := 1 if (ta.crossover(k, stochUpper)) direction := -1 if (ta.cross(k, stochMiddle)) direction := 0 stochLongCond = direction == 1 and k <= stochMiddle stochShortCond = direction == -1 and k >= stochMiddle // ======================================================================================================== // ======================================================================================================== // Stochastic RSI ========================================================================================= lengthStoch = input.int(14, "%K Length", minval=1, group="Stochastic RSI") smoothKRSI = input.int(3, "%K Smoothing", minval=1, group="Stochastic RSI") lengthRSI = input.int(14, "RSI Length", minval=1, group="Stochastic RSI") src = input(close, title="RSI Source", group="Stochastic RSI") rsi1 = ta.rsi(src, lengthRSI) rsik = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothKRSI) var int stochRsiDirection = na if (ta.crossunder(rsik, stochLower)) stochRsiDirection := 1 if (ta.crossover(rsik, stochUpper)) stochRsiDirection := -1 if (ta.cross(rsik, stochMiddle)) stochRsiDirection := 0 stochRsiLongCond = stochRsiDirection == 1 and rsik <= stochMiddle stochRsiShortCond = stochRsiDirection == -1 and rsik >= stochMiddle plotchar(direction, "direction", display=display.data_window) plotchar(stochRsiDirection, "RSI direction", display=display.data_window) // ======================================================================================================== // ======================================================================================================== // Supertrend 3n1 ========================================================================================= PeriodsA = input.int(title="ATR Period", defval=12) srcA = input.source(hl2, title="Source") MultiplierA = input.float(title="ATR Multiplier", step=0.1, defval=3.0) changeATRA= input.bool(title="Change ATR Calculation Method ?", defval=true) // showsignalsA = input.bool(title="Show Buy/Sell Signals ?", defval=true) // highlightingA = input.bool(title="Highlighter On/Off ?", defval=true) atr2A = ta.sma(ta.tr, PeriodsA) atrA= changeATRA ? ta.atr(PeriodsA) : atr2A upA=srcA-(MultiplierA*atrA) up1A = nz(upA[1],upA) upA := close[1] > up1A ? math.max(upA,up1A) : upA dnA=srcA+(MultiplierA*atrA) dn1A = nz(dnA[1], dnA) dnA := close[1] < dn1A ? math.min(dnA, dn1A) : dnA trendA = 1 trendA := nz(trendA[1], trendA) trendA := trendA == -1 and close > dn1A ? 1 : trendA == 1 and close < up1A ? -1 : trendA PeriodsB = input.int(title="ATR Period", defval=11) srcB = input.source(hl2, title="Source") MultiplierB = input.float(title="ATR Multiplier", step=0.1, defval=2.0) changeATRB= input.bool(title="Change ATR Calculation Method ?", defval=true) // showsignalsB = input.bool(title="Show Buy/Sell Signals ?", defval=true) // highlightingB = input.bool(title="Highlighter On/Off ?", defval=true) atr2B = ta.sma(ta.tr, PeriodsB) atrB= changeATRB ? ta.atr(PeriodsB) : atr2B upB=srcB-(MultiplierB*atrB) up1B = nz(upB[1],upB) upB := close[1] > up1B ? math.max(upB,up1B) : upB dnB=srcB+(MultiplierB*atrB) dn1B = nz(dnB[1], dnB) dnB := close[1] < dn1B ? math.min(dnB, dn1B) : dnB trendB = 1 trendB := nz(trendB[1], trendB) trendB := trendB == -1 and close > dn1B ? 1 : trendB == 1 and close < up1B ? -1 : trendB PeriodsC = input.int(title="ATR Period", defval=10) srcC = input.source(hl2, title="Source") MultiplierC = input.float(title="ATR Multiplier", step=0.1, defval=1.0) changeATRC= input.bool(title="Change ATR Calculation Method ?", defval=true) atr2C = ta.sma(ta.tr, PeriodsC) atrC= changeATRC ? ta.atr(PeriodsC) : atr2C upC=srcC-(MultiplierC*atrC) up1C = nz(upC[1],upC) upC := close[1] > up1C ? math.max(upC,up1C) : upC dnC=srcC+(MultiplierC*atrC) dn1C = nz(dnC[1], dnC) dnC := close[1] < dn1C ? math.min(dnC, dn1C) : dnC trendC = 1 trendC := nz(trendC[1], trendC) trendC := trendC == -1 and close > dn1C ? 1 : trendC == 1 and close < up1C ? -1 : trendC supertrendCount = trendA + trendB + trendC // plotchar(trendA, "trendA", display=display.data_window) // plotchar(trendB, "trendB", display=display.data_window) // plotchar(trendC, "trendC", display=display.data_window) supertrendLongCond = supertrendCount >= 1 supertrendShortCond = supertrendCount <= -1 // ======================================================================================================== // ======================================================================================================== // TSV ==================================================================================================== tsv_length = input.int(13, "TSV Length") tsv = math.sum(close > close[1] or close < close[1] ? volume * (close - close[1]) : 0, tsv_length) tsvLongCond = tsv > 0 tsvShortCond = tsv < 0 longAlertCond = emaLongCond and (stochLongCond or stochRsiLongCond) and supertrendLongCond and tsvLongCond shortAlertCond = emaShortCond and (stochShortCond or stochRsiShortCond) and supertrendShortCond and tsvShortCond plotshape(longAlertCond, "Long", style=shape.labelup, location=location.belowbar, color=color.green) plotshape(shortAlertCond, "Short", style=shape.labeldown, location=location.abovebar, color=color.red) alertcondition(longAlertCond, "Long", "Long") alertcondition(shortAlertCond, "Short", "Short")
Expansion of EMA
https://www.tradingview.com/script/JYiM2AQP-Expansion-of-EMA/
Prashant_Vibhute
https://www.tradingview.com/u/Prashant_Vibhute/
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/ // © Prashant_Vibhute //@version=5 indicator("Expansion of EMA", overlay=true) exp1 = ta.ema(hl2, 20) exp2 = ta.ema(hl2, 25) exp3 = ta.ema(hl2, 30) exp4 = ta.ema(hl2, 35) exp5 = ta.ema(hl2, 40) exp6 = ta.ema(hl2, 45) exp7 = ta.ema(hl2, 50) exp8 = ta.ema(hl2, 55) exp9 = ta.ema(hl2, 60) exp10 = ta.ema(hl2, 65) exp11 = ta.ema(hl2, 70) exp12 = ta.ema(hl2, 75) exp13 = ta.ema(hl2, 80) exp14 = ta.ema(hl2, 85) exp15 = ta.ema(hl2, 90) exp16 = ta.ema(hl2, 95) exp17 = ta.ema(hl2, 100) exp18 = ta.ema(hl2, 150) exp19 = ta.ema(hl2, 175) exp20 = ta.ema(hl2, 200) exp21 = ta.ema(hl2, 500) exp22 = ta.ema(hl2, 900) plot(exp1, 'EMA 20') plot(exp2, 'EMA 25') plot(exp3, 'EMA 30') plot(exp4, 'EMA 35') plot(exp5, 'EMA 40') plot(exp6, 'EMA 45') plot(exp7, 'EMA 50') plot(exp8, 'EMA 55') plot(exp9, 'EMA 60') plot(exp10, 'EMA 65') plot(exp11, 'EMA 70') plot(exp12, 'EMA 75') plot(exp13, 'EMA 80') plot(exp14, 'EMA 85') plot(exp15, 'EMA 90') plot(exp16, 'EMA 95') plot(exp17, 'EMA 100') plot(exp18, 'EMA 150') plot(exp19, 'EMA 175') plot(exp20, 'EMA 200') plot(exp21, 'EMA 500') plot(exp22, 'EMA 900')
Average Volume Profile
https://www.tradingview.com/script/dQ9Wjj11-Average-Volume-Profile/
SamRecio
https://www.tradingview.com/u/SamRecio/
744
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © SamRecio //@version=5 indicator("Average Volume Profile", shorttitle = "AVP", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_bars_back = 5000) tf = input.timeframe("D", title = "Timeframe", inline = "0", group = "PROFILE SETTINGS") mdr = input.float(4, minval = 1,maxval = 4,title = "Sensitivity ", inline = "1", group = "PROFILE SETTINGS", tooltip = "Higher = More Granular\nLower = Less Granular") vap = input.float(70, title = "Value Area %", inline = "1_1", group = "PROFILE SETTINGS")/100 disp_size = input.int(-50, minval = -500,maxval = 500,title = "Display Size   ", inline = "3", group = "DISPLAY SETTINGS", tooltip = "The entire range of your profile will scale to fit inside this range.\nNotes:\n-This value is # bars away from your profile's axis.\n-The larger this value is, the more granular your (horizontal) view will be. This does not change the Profiles' value; because of this, sometimes the HAV looks tied with other values widely different. The HAV CAN be tied to values close to it, but if the value is far away it is likely to just be a visual constraint.\n-This Value CAN be negative") prof_offset = input.int(50, minval = -500,maxval = 500, title = "Display Offset", inline = "4", group = "DISPLAY SETTINGS", tooltip = "Offset your profile's axis (Left/Right) to customize your display to fit your style.\nNotes:\n-Zero = Current Bar\n-This Value CAN be negative") extend_day = input.bool(false, title = "Display Current HAV/VAH/VAL", inline = "5", group = "Additional Data Displays") hist = input.bool(false, title = "Display Historical HAV/VAH/VAL", inline = "6", group = "Additional Data Displays") poc_color = input.color(#03afff, title = "Highest Avg Volume Color", group = "Colors") var_color = input.color(color.white, title = "Value High/Low Color", group = "Colors") vaz_color = input.color(color.new(#555555,50), title = "Value Zone Color", group = "Colors") ov_color = input.color(#555555, title = "Profile Color", group = "Colors") sp_color = input.color(#014f74, title = "Lowest Avg Volume Color", group = "Colors") vl_color = input.color(color.aqua, title = "Volume Line Color") //Error messages //no volume, by checking if volume == na if na(volume) runtime.error("No Volume Data. Please Use a Ticker with Volume Data.") //checking if we have the bar index of the last time the selscte timeframe changed. if not we're not able to calculate the granularity. if barstate.islast and na(ta.valuewhen(timeframe.change(tf),bar_index,1)) runtime.error("Profile Timeframe is Too Large. Please Increase Chart Timeframe, or Decrease Profile Timeframe.") //Round to Function round_to(_round,_to) => math.round(_round/_to)*_to //Below is a modified version of my volume profile calculation from "Volume/Market Profile" //This version handles 3 arrays in parallel holding values of a volume profile, market profile, and the average of the 2 vol_prof(_tf,_mdr) => tf_change = timeframe.change(_tf) var main = array.new_float(na) var mp_main = array.new_float(na) var avg = array.new_float(na) var float base = na var float roof = na max_array_dol_range = syminfo.mintick*(_mdr*100) change_dif = nz(ta.valuewhen(tf_change,bar_index,0) - ta.valuewhen(tf_change,bar_index,1),1) rng_get = ta.valuewhen(tf_change,ta.highest(high,change_dif) - ta.lowest(low,change_dif),0) tick_size = rng_get>max_array_dol_range?math.ceil(rng_get/max_array_dol_range)*syminfo.mintick:syminfo.mintick c_hi = round_to(high,tick_size) c_lo = round_to(low,tick_size) candle_range = c_hi - c_lo candle_index = (candle_range/tick_size)+1 tick_vol = volume/candle_index //Start if tf_change array.clear(main) array.clear(mp_main) array.clear(avg) base := c_lo roof := c_hi for i = 0 to candle_index-1 array.push(main,tick_vol) array.push(mp_main,1) array.push(avg,nz(tick_vol/1)) //Expand Down down_dif = math.abs((base - c_lo)/tick_size) if c_lo < base for i = 1 to down_dif array.unshift(main,0) array.unshift(mp_main,0) array.unshift(avg,0) base := c_lo z_point = math.abs((base - c_lo)/tick_size) //Expand Up up_dif = math.abs((roof - c_hi)/tick_size) if c_hi > roof for i = 1 to up_dif array.push(main,0) array.push(mp_main,0) array.push(avg,0) roof := c_hi //Input Values for i = 0 to array.size(main) if (i >= z_point) and (i <= (z_point + candle_index)-1) v = array.get(main,int(i)) mpv = array.get(mp_main,int(i)) array.set(main,int(i),v + tick_vol) array.set(mp_main,int(i),mpv + 1) array.set(avg,int(i),nz((v + tick_vol)/(mpv + 1))) max_index = math.round(math.avg(array.indexof(avg,array.max(avg)),array.lastindexof(avg,array.max(avg)))) poc = base + (tick_size*max_index) //Value Zones max_vol = array.sum(avg)*vap vol_count = max_index >=0?array.get(avg, max_index):0.0 up_count = max_index down_count = max_index for x = 0 to array.size(avg)-1 if vol_count >= max_vol break uppervol = up_count<array.size(avg)-1?array.get(avg, up_count + 1):na lowervol = down_count>0?array.get(avg, down_count - 1):na if ((uppervol >= lowervol) and not na(uppervol)) or na(lowervol) vol_count += uppervol up_count += 1 else vol_count += lowervol down_count -= 1 val = base + (tick_size*down_count) vah = base + (tick_size*up_count) pd_vah = ta.valuewhen(tf_change,vah[1],0) pd_val = ta.valuewhen(tf_change,val[1],0) pd_poc = ta.valuewhen(tf_change,poc[1],0) [poc,vah,val,pd_poc,pd_vah,pd_val,avg,base,tick_size,up_count,down_count,max_index,roof,candle_index] [poc,vah,val,pd_poc,pd_vah,pd_val,avg,base,tick_size,up_count,down_count,mv,roof,ci] = vol_prof(tf,mdr) //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //Determining how many bars are inbetween tf changes day_len = ta.valuewhen(timeframe.change(tf),bar_index,0)-ta.valuewhen(timeframe.change(tf),bar_index,1) //Drawing the profile var profile = array.new_line(na) var box_profile = array.new_box(na) if array.size(profile) > 0 for i = 0 to array.size(profile) - 1 line.delete(array.get(profile, i)) if i == (array.size(profile) - 1) array.clear(profile) if array.size(box_profile) > 0 for i = 0 to array.size(box_profile) - 1 box.delete(array.get(box_profile, i)) if i == (array.size(box_profile) - 1) array.clear(box_profile) min_array = array.copy(avg) if array.size(min_array) > 0 for i = array.size(min_array)-1 to 0 if array.get(min_array,i) == 0 array.remove(min_array,i) prof_color(_num) => _num==mv?poc_color: (_num==up_count or _num==down_count)?var_color: array.get(avg,_num) == array.min(min_array)?sp_color: (_num>up_count or _num<down_count)?ov_color: vaz_color bi_nd = ta.valuewhen(timeframe.change(tf),bar_index,0) if barstate.islast if array.size(avg) > 0 for i = 0 to array.size(avg) - 1 scale = disp_size/array.max(avg) scaled = math.round(array.get(avg,i)*scale) if ((i>up_count) or (i<down_count)) or (array.size(box_profile) >= 450) array.push(profile,line.new(bar_index+prof_offset,base+(i*tick_size),(bar_index+scaled)+prof_offset,base+(i*tick_size), color = (base+(i*tick_size)==round_to(close,tick_size))?vl_color:prof_color(i), style = (i<down_count or i>up_count?line.style_dotted:line.style_solid))) else array.push(box_profile,box.new(bar_index+prof_offset,base+(i*tick_size),(bar_index+scaled)+prof_offset,base+(i*tick_size), border_color = (base+(i*tick_size)==round_to(close,tick_size))?vl_color:prof_color(i), border_style = (i<down_count or i>up_count?line.style_dotted:line.style_solid), border_width = 1)) //Making moving labels and lines. if array.size(avg) > 0 cur = math.abs((round_to(close,tick_size)-base)/tick_size) a = math.round(array.get(avg,int(cur))) lab0 = label.new(bar_index+prof_offset,round_to(close,tick_size), style = (disp_size<0?label.style_label_left:label.style_label_right), text = "Avg: " + str.tostring(a,format.volume), color = color.new(color.black,100), textcolor = math.round(volume/ci)>a?vl_color:chart.fg_color, tooltip = "Average Volume at Price") label.delete(lab0[1]) mv_lab = label.new(bar_index+prof_offset, base+(mv*tick_size), style = (disp_size<0?label.style_label_left:label.style_label_right), text = "Max Avg: " + str.tostring(array.get(avg,mv),format.volume), color = color.new(color.black,100), textcolor = chart.fg_color) label.delete(mv_lab[1]) sc = disp_size/array.max(avg) scd = math.round((volume/ci)*sc) vlab = line.new((bar_index+scd)+prof_offset,roof,(bar_index+scd)+prof_offset,base, color = vl_color) line.delete(vlab[1]) lab0_0 = label.new((bar_index+scd)+prof_offset,base, style = label.style_label_up, text = "\nVol: " + str.tostring(math.round(volume/ci),format.volume), color = color.new(color.black,100), textcolor = math.round(volume/ci)>a?vl_color:chart.fg_color, tooltip = "Distributed Volume\nCandle Volume/Candle Range = Distributed Volume") label.delete(lab0_0[1]) //Drawing previous day lines at the start of new day var pd_lines = array.new_line(na) if timeframe.change(tf) and hist array.push(pd_lines,line.new(bar_index-day_len,pd_poc,bar_index-1,pd_poc,color = poc_color, width = 2)) array.push(pd_lines,line.new(bar_index-day_len,pd_vah,bar_index-1,pd_vah,color = var_color, width = 2)) array.push(pd_lines,line.new(bar_index-day_len,pd_val,bar_index-1,pd_val,color = var_color, width = 2)) if array.size(pd_lines) > 90 line.delete(array.get(pd_lines,0)) array.remove(pd_lines,0) //drawing current day's lines if extend_day d_poc = line.new(bi_nd,poc,bar_index,poc,color = poc_color, width = 2) d_vah = line.new(bi_nd,vah,bar_index,vah,color = var_color, width = 2) d_val = line.new(bi_nd,val,bar_index,val,color = var_color, width = 2) line.delete(d_poc[1]) line.delete(d_vah[1]) line.delete(d_val[1]) //Profile title Label lab = label.new(bar_index+prof_offset,roof, text = ("Average Volume Profile [") + tf + "]\nGranularity: " + str.tostring(tick_size,"$#.##########"), style = (disp_size<0?label.style_label_lower_right:label.style_label_lower_left), color = color.rgb(0,0,0,100), textcolor = chart.fg_color, textalign = (disp_size<0?text.align_left:text.align_right), text_font_family = font.family_monospace) label.delete(lab[1]) //Alerts alertcondition(ta.crossover(close,poc), "Cross-Over Highest Average Volume") alertcondition(ta.crossunder(close,poc), "Cross-Under Highest Average Volume") alertcondition(ta.crossover(close,vah), "Cross-Over Value High") alertcondition(ta.crossunder(close,vah), "Cross-Under Value High") alertcondition(ta.crossover(close,val), "Cross-Over Value Low") alertcondition(ta.crossunder(close,val),"Cross-Under Value Low")
Extreme Trend Reversal Points [HeWhoMustNotBeNamed]
https://www.tradingview.com/script/eBB5mW6b-Extreme-Trend-Reversal-Points-HeWhoMustNotBeNamed/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
4,137
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("Extreme Trend Reversal Points [HeWhoMustNotBeNamed]", shorttitle = "ETRP[HWMNBN]", overlay=true) import HeWhoMustNotBeNamed/_matrix/5 as ma import HeWhoMustNotBeNamed/arrayutils/21 as ar import HeWhoMustNotBeNamed/enhanced_ta/14 as eta import HeWhoMustNotBeNamed/drawingutils/8 as dr import HeWhoMustNotBeNamed/arrays/1 as pa source = input.source(close, "Source", group="Moving Average") type = input.string("sma", "Type", options = ["sma", "ema", "rma", "wma"], group="Moving Average") length = input.int(20, "Length", step=5, group="Moving Average") level = input.int(10, "Level", minval = 5, step=5, group="Moving Average") minMaxRangePercentile = input.int(20, 'Range Percentile', minval=5, maxval=45, step=5) extremeMinMaxRangePercentile = input.int(45, 'Extreme Range Percentile', minval=40, maxval=48, step=2) history = input.int(1000, 'Percentile History', minval=1000, maxval=5000, step=500) realTimeAlerts = input.bool(false, 'Real Time Alerts', 'If set to true, alerts are fired on latest candle - which may repaint. For safer option set this to false') maxHistory = length-1 ema(float currentEma, float source, simple int length) => k = 2 / (length + 1) ema = source * k + (1 - k) * currentEma ema rma(float currentRma, float source, simple int length) => k = 2 / (length + 1) rma = (currentRma * (length-1) + source)/length rma var maMatrix = matrix.new<float>(1, level+1, source) if(type == "ema") emaArray = array.new<float>(1, source) for i=1 to matrix.columns(maMatrix)-1 ema = ema(matrix.get(maMatrix, 0, i), array.get(emaArray, array.size(emaArray)-1), length) array.push(emaArray, ema) ma.unshift(maMatrix, emaArray, maxHistory) if(type == "rma") rmaArray = array.new<float>(1, source) for i=1 to matrix.columns(maMatrix)-1 rma = rma(matrix.get(maMatrix, 0, i), array.get(rmaArray, array.size(rmaArray)-1), length) array.push(rmaArray, rma) ma.unshift(maMatrix, rmaArray, maxHistory) if(type == "sma" or type == "wma") maArray = array.new<float>(1, source) for i=1 to matrix.columns(maMatrix)-1 values = matrix.col(maMatrix, i-1) tmpArray = array.new<float>(1, array.get(maArray, i-1)) tmpArray := array.concat(tmpArray, values) array.push(maArray, ar.ma(tmpArray, type, length)) ma.unshift(maMatrix, maArray, maxHistory) strength = 0 bearishStrength = 0 diffMatrix = matrix.new<float>(level+1, level+1, 0) var linesArray = array.new<line>() var labelsArray = array.new<label>() ar.clear(linesArray) ar.clear(labelsArray) for i = 0 to level for j = 0 to level pma = matrix.get(maMatrix, 0, i) nma = matrix.get(maMatrix, 0, j) //strength := pma > nma ? strength+1 : strength if(j > i) strength := pma > nma ? strength+1 : strength matrix.set(diffMatrix, i, j, math.sign(pma-nma)) lastRow = matrix.row(maMatrix, 0) lastRowIndex = array.sort_indices(array.slice(lastRow, 1, array.size(lastRow)), order.descending) if(barstate.islast) for i=1 to level levelColor = color.from_gradient(i, 1, level, color.green, color.red) dr.draw_labelled_line(array.get(lastRow, i), type+'('+str.tostring(i)+')',levelColor, levelColor, 0, true, linesArray, labelsArray) minRange = ta.percentile_nearest_rank(strength, history, 50-minMaxRangePercentile) maxRange = ta.percentile_nearest_rank(strength, history, 50+minMaxRangePercentile) extremeMinRange = ta.percentile_nearest_rank(strength, history, 50-extremeMinMaxRangePercentile) extremeMaxRange = ta.percentile_nearest_rank(strength, history, 50+extremeMinMaxRangePercentile) plotColor = strength > extremeMaxRange? color.green : strength > maxRange? color.lime : strength < extremeMinRange ? color.red : strength < minRange? color.orange : color.silver strengthRange = strength > extremeMaxRange? 2 : strength > maxRange? 1 : strength > minRange ? 0 : strength < extremeMinRange? -1 : -2 maxStrength = level * (level+1)/2 ma = eta.ma(source, type, length) bullishTrendReversalPoint = strength[1]== maxStrength and ta.crossunder(source, ma) bearishTrendReversalPoint = strength[1]==0 and ta.crossover(source, ma) plotshape(bullishTrendReversalPoint, 'Bullish Trend Reversal Point', style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small) plotshape(bearishTrendReversalPoint, 'Bearish Trend Reversal Point', style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small) plot(strength, "Strength", color=color.silver, display = display.data_window) plot(minRange, "Min Range", color=color.orange, display = display.data_window) plot(maxRange, "Max Range", color=color.lime, display = display.data_window) plot(extremeMinRange, "Extreme Min Range", color=color.red, display = display.data_window) plot(extremeMaxRange, "Extreme Max Range", color=color.green, display = display.data_window) plot(strengthRange, "Strength Range", color=color.blue, display = display.data_window) plot(ma, "Moving Average", plotColor) alertcondition(bullishTrendReversalPoint[realTimeAlerts?0:1], "Bullish Trend Reversal", "Possible reversal of bullish trend") alertcondition(bearishTrendReversalPoint[realTimeAlerts?0:1], "Bearish Trend Reversal", "Possible reversal of bearish trend")
Correlation with P-Value & Confidence Interval (alt)
https://www.tradingview.com/script/QphOKMXQ-Correlation-with-P-Value-Confidence-Interval-alt/
tartigradia
https://www.tradingview.com/u/tartigradia/
115
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/ // © balipour // extended by tartigradia // // Pearson correlation coefficient measures the linear correlation between two variables. It has a value between +1 and −1, where 1 is total positive linear correlation, 0 is no linear correlation and −1 is total negative linear correlation. It’s often denoted by r for sample correlation and ρ for population correlation. // // Note: Pearson Correlation only measures the linear relationship between two variables, such as y = a*x + b. There are other measurements for nonlinear correlations. // // When option “R” for "Correlation variants" is chosen, the value would be the same as TradingView's built in correlation() function. For "Adjusted R ", the calculation is based on the traditional Pearson. The sample r is a biased estimate of population ρ. The adjusted r gets rid of some of the bias but not all. As the sample size or lookback period increases, adjusted r will be closer to r. // // The confidence interval is computed for population ρ estimation based on sample r. Correlation coefficient itself doesn’t follow a normal distribution. Fisher transformation is applied to transform the data into an approximately normal distribution. We compute the standard error based on the transformed data, then use an inverse fisher transform to transform back the standard error in terms of r. // // Note: the confidence interval band is an approximation of population, it proposes a range of plausible r values (instead of a point). The confidence level represents the frequency (i.e. the proportion) of possible confidence intervals that contain the true value of the unknown population parameter. The proportion of those intervals that contain the true value of the parameter will be equal to the confidence level. For example, if the confidence level is 95% then in hypothetical indefinite data collection, in 95% of the samples the interval estimate will contain the population parameter. The default setting is 1.96* standard error which is 95% confidence interval. // // The most important and distinguishable feature of this indicator is the p-value provided along with the correlation. // // The value of Correlation Coefficient alone doesn’t provide any information regarding its statistical significance. For example, two sets of independent samples have 0 correlation in theory. However, your correlation coefficient on these samples will never actually show 0 correlation (small correlation value but not 0). Therefore without a significance test, one would be fooled by the value of r when there’s no linear relationship at all. // // In statistical hypothesis testing, the p-value or probability value is the probability of obtaining test results at least as extreme as the results actually observed during the test, assuming that the null hypothesis is correct. The smaller the p-value, the stronger the evidence that the null hypothesis should be rejected and that the alternate hypothesis might be more credible. Since one could be deceived by r showing values while correlation is actually 0. The null hypothesis here is the “r is 0”. The alternative hypothesis is “ r is not 0”. The default setting for p critical value is 0.05. It means that when p is lower than 0.05, there’s less than 5% chance that correlation is 0, and we consider that to be "significant correlation". To get the p-value, We use a t distribution with n – 2 degrees of freedom to find the probability. P-value will adjust automatically when the sample size or lookback changes. // // Displays : // When p is lower than 0.05 and r > 0, correlation coefficient shows red, p-value shows yellow, panel shows “Significant Positive Correlation”. // When p is lower than 0.05 and r < 0, correlation coefficient shows green, p-value shows yellow, panel shows “Significant Negative Correlation”. // When p is higher than 0.05, correlation, correlation coefficient shows white, p-value shows grey, panel shows “Insignificant Correlation”. // // r² (r squared) also known as the coefficient of determination, is the square of correlation r. r² measures how well the data fit the linear regression model used in correlation. When two assets show significant correlation, r squared can be used to compare which one fits the data better. r² is displayed on the panel and has a different lookback by default than the correlation coefficient . // // Contributors : Pig (ideas, code, math and design), Balipour (ideas), midtownsk8rguy(applying/employing Pine etiquette), tartigradia (optimizing SMA, add EMA, add multi-timeframe resolution, conversion from pinescript v4 to v5). //@version=5 indicator('Correlation with P-Value & Confidence Interval [pig, tartigradia]', 'BA🐷 CC (TG)', false, format.price, 3, timeframe="", timeframe_gaps=false) var invisible = color(na) bgcolor(#000000c0) var cPI = 2.0 * math.asin(1.0) // 3.1415926536 Constant //===== Functions =====// custom_sma(src, src_cur, len) => sum = 0.0 sum := nz(sum[1]) - nz(src[len]) + src // compute the updated rolling sum (nz(sum[1]) - nz(src) + src_cur) / len cc(x, y, len, ma_type) => // Correlation Coefficent function lenMinusOne = len - 1 //meanx = 0.0, meany = 0.0 //for i=0.0 to lenMinusOne // meanx := meanx + nz(x[i]) // meany := meany + nz(y[i]) //meanx := meanx / len //meany := meany / len meanx = ma_type == 'ema' ? ta.ema(x, lenMinusOne) : ta.sma(x, lenMinusOne) meany = ma_type == 'ema' ? ta.ema(y, lenMinusOne) : ta.sma(y, lenMinusOne) sumxy = 0.0 sumx = 0.0 sumy = 0.0 for i = 0 to lenMinusOne by 1 sumxy += (nz(x[i]) - meanx) * (nz(y[i]) - meany) sumx += math.pow(nz(x[i]) - meanx, 2) sumy += math.pow(nz(y[i]) - meany, 2) sumxy / math.sqrt(sumy * sumx) adj(r, n) => // Unbiased Adjusted R Estimation Approximate Function (1 + (1 - math.pow(r, 2)) / (2 * n)) * r Round(src, digits) => // Round Function p = math.pow(10, digits) math.round(math.abs(src) * p) / p * math.sign(src) xp(offset) => // Offset time + math.round(ta.change(time) * offset) //label Panel Function //Note: removed by Tartigradia because it causes side effects which prevents MTF implementation (timeframe argument). Remove timeframe argument in the indicator call and uncomment these lines if you want to use panel again. //_label(T, color_PnL) => // label PnL_Label = na // label.delete(PnL_Label[1]) // PnL_Label := label.new(time, 0.0, text=T, color=color_PnL, textcolor=color.white, size=size.normal, style=label.style_label_left, xloc=xloc.bar_time, textalign=text.align_left) // label.set_x(PnL_Label, label.get_x(PnL_Label) + math.round(ta.change(time) * 3)) //===== Inputs =====// src = input(close, 'Source') sec1in = input.symbol('DXY', 'Comparison Symbol', confirm=true) mode = input.string('Adjusted R', 'Correlation Variants ', options=['R', 'Adjusted R']) len = input.int(14, 'Correlation Lookback Length', minval=2) ma_type = input.string('sma', 'Moving Average Type', options=['sma', 'ema']) //Stats Settings sc = input(true, 'Show Confidence Interval for Population') csd = input.float(1.96, 'Confidence Interval SD Multiplier', minval=0.1, step=0.1) //Default 95% sp = input(true, 'Show P-Values') cp = input.float(0.1, 'P-Value Significant Confidence Level', minval=0.0, step=0.01) //Default = 1- 0.05 = 95% //pan = input(true, ' Show Information Panel') rlen = input.int(50, '  R Squared Length', minval=2) os = input.int(40, '  Panel Position Offset', minval=0) lT = input.int(1, '--- Line Thickness ---', options=[1, 2, 3]) sec1 = request.security(sec1in, timeframe.period, close) //===== Calculations =====// R = cc(src, sec1, len, ma_type) // Traditional Pearson adjr = adj(R, len) // Adjusted R float r = na if mode == 'R' r := R r if mode == 'Adjusted R' r := adjr r R2 = math.pow(cc(src, sec1, rlen, ma_type), 2) // R Squared adjR2 = math.pow(adj(cc(src, sec1, rlen, ma_type), rlen), 2) // R Sqaured Based on Adjusted R float r2 = na if mode == 'R' r2 := R2 r2 if mode == 'Adjusted R' r2 := adjR2 r2 // Fisher Transform z = 0.5 * math.log((r + 1.0) / (1.0 - r)) // Fisher se = 1.0 / math.sqrt(len - 3) // Standard Error zl = z - csd * se // Lower Limit for fisher z zu = z + csd * se // Upper Limit for fisher z 95% confidence // Inverse Fisher Transform to Transform Back to r rl = (math.exp(2.0 * zl) - 1.0) / (math.exp(2.0 * zl) + 1.0) // Lower limit for r ru = (math.exp(2.0 * zu) - 1.0) / (math.exp(2.0 * zu) + 1.0) // Upper limit for r //T distribution For P Value v = len - 2 x = math.abs(r * math.sqrt(v) / math.sqrt(1 - math.pow(r, 2))) //student t cdf tcdf(t, df) => Z = t * (1 - 1 / (4 * df)) * math.pow(1 + 1 / (2 * df) * math.pow(t, 2), -0.5) a = 0.0 for n = 0 to 12 by 1 a := 1 / (n + 0.5) * math.exp(-math.pow(n + 0.5, 2) / 9) * math.sin(math.sqrt(2) / 3 * (n + 0.5) * Z) + a a p = t > 7 ? 1.0 : t < -7 ? 0.0 : 0.5 + 1 / math.pi * a 2 * (1 - p) pro = tcdf(x, v) //===== Plotting =====// colorCC = pro < cp and r < 0.0 ? #FF0000ff : pro < cp and r > 0.0 ? #00FF00ff : #FFFFFFff colorP = pro < cp ? #FFFF00ff : #C0C0C040 plot(sp ? pro : na, color=colorP, title='P Value', style=plot.style_columns) plotUpper = plot(rl, color=sc ? color.new(#00C0FFff, 100) : invisible, style=plot.style_linebr, title='Confidence Interval Lower') plotLower = plot(ru, color=sc ? color.new(#00C0FFff, 100) : invisible, style=plot.style_linebr, title='Confidence Interval Higher') fill(plotUpper, plotLower, color=sc ? color.new(#00C0FFff, 85) : invisible) plot(r, linewidth=lT, color=colorCC, style=plot.style_linebr, title='🐷 Correlation') plot(sp ? cp : na, color=color.new(#C0C0C0ff, 30), trackprice=true, show_last=1, title='P value Threshold', style=plot.style_linebr) plot(sp ? na : 0, color=color.new(#C0C0C0ff, 30), trackprice=true, show_last=1, title='Zero Line') hline(1.0, color=color.new(#00FFFFff, 30)) hline(-1.0, color=color.new(#FF00FFff, 30)) // Information Panel //Note: removed by Tartigradia because it causes side effects which prevents MTF implementation (timeframe argument). Remove timeframe argument in the indicator call and uncomment these lines if you want to use panel again. //sig() => // return_1 = pro < cp and r > 0 ? 'Significant Positive Correlation' : pro < cp and r < 0 ? 'Significant Negative Correlation' : 'Insignificant Correlation' // return_1 //if pan // txt = 'R : ' + str.tostring(Round(r, 3)) + '\n\n R Squared : ' + str.tostring(Round(r2, 4)) + '\n\n P Value : ' + str.tostring(Round(pro, 4)) + '\n\n' + sig() // _label(txt, #000000c0)
Auto SuperTrend+
https://www.tradingview.com/script/nMb2Jd80-Auto-SuperTrend/
Electrified
https://www.tradingview.com/u/Electrified/
490
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/ // © Electrified (electrifiedtrading) //@version=5 indicator("Auto SuperTrend+", overlay = true, format=format.price) import Electrified/DataCleaner/7 as DC import Electrified/Time/7 // Constants CONFIRM = "Confirmation (Tolerance)", VOLATILITY = "Volatility", DEVIATION = "Deviation Measurement", DISPLAY = "Display", THEME = "Theme" MINUTES = "Minutes", DAYS = "Days", BARS = "Bars" UP = +1, DOWN = -1 clearColor = color.new(color.gray, 100) // Parameters volLen = math.min(4000, Time.spanToIntLen( input.float(2.5, "", minval = 0.1, group=VOLATILITY, inline = VOLATILITY), input.string(DAYS, "", options=[BARS, MINUTES, DAYS], group=VOLATILITY, inline = VOLATILITY, tooltip = "The amount of time/bars to measure the range of movement."))) devMul = input.float(2.5, "Level", minval = 0.1, step = 0.1, group = DEVIATION, tooltip = "The maximum deviation before a trend has been broken/reversed.") devLen = Time.spanToIntLen( input.float(1000, "", minval = 0.1, group=DEVIATION, inline = DEVIATION), input.string(BARS, "", options=[BARS, MINUTES, DAYS], group=DEVIATION, inline = DEVIATION, tooltip = "The amount of time/bars to measure the deviation of the range.")) atrMul = input.float(0.5, "ATR Multiple", minval = 0, step = 0.5, group=CONFIRM, tooltip="The tolerance to give confirmation based upon the weighted average true range.") confirmBars = input.int(2, "Closed Bars", minval = 0, group=CONFIRM, tooltip="The number of closed Bars that have to exceed the super-trend value before the trend reversal is confirmed.") highlighting = input(true, "Show Highlighter ?", group=DISPLAY, tooltip = "Paints the background depending on whether the trend is up or down.") showLabels = input(false, title="Show Reversal Labels ?", group=DISPLAY, tooltip = "Adds labels to identify the point of reversal.") showMidpoint = input(false, "Show Middle Point ?", group=DISPLAY, tooltip = "Displays the average of the upper and lower boundary.") // Theme upColor = input.color(color.green, "▲", group = THEME, inline = THEME) dnColor = input.color(color.red, "▼", group = THEME, inline = THEME) warnColor = input.color(color.yellow, "⚠", group = THEME, inline = THEME) upPen = color.new(upColor, 25) dnPen = color.new(dnColor, 25) warnPen = color.new(warnColor, 25) // Clamp/adjust lenghts that are too large if(volLen>devLen) devLen := volLen * 2 if(devLen > 4000) devLen := 4000 // Determine the normalized true range (for Bars) atr = ta.wma(DC.naOutliers(ta.tr, devLen, 2.5), devLen) // Because the outliers become NA we need to carry over the tolerance from the previous bar if na(atr) atr := atr[1] tolerance = atr * atrMul calcDev(series float source) => ta.wma(source, devLen) + ta.wma(ta.stdev(source, math.min(devLen * 2, 4000)), devLen) * devMul // Determine the range for the delta length upDev = calcDev(math.max(high - low[volLen], 0)) dnDev = calcDev(math.max(high[volLen] - low, 0)) // Trend var trend = 0 var upper = high var lower = low var brokenCount = 0 var wasTouched = false warn = false reversal = false upperWarning = close > upper lowerWarning = close < lower upperBroken = close[1] - tolerance > upper lowerBroken = close[1] + tolerance < lower if trend == UP // Touching the lower boundary resets the warning condition if upperWarning brokenCount := 0 wasTouched := false if lowerWarning wasTouched := true warn := true else if lowerBroken lower := low[1] if upperBroken brokenCount += 1 if trend == DOWN // Touching the upper boundary resets the warning condition if lowerWarning brokenCount := 0 wasTouched := false if upperWarning wasTouched := true warn := true else if upperBroken upper := high[1] if lowerBroken warn := true brokenCount += 1 if trend != UP // If the low exceeds the threshold then confirmation is not required. if brokenCount > confirmBars or low > upper + tolerance trend := UP upper := high[1] reversal := true else if trend != DOWN // If the high exceeds the threshold then confirmation is not required. if brokenCount > confirmBars or high < lower - tolerance trend := DOWN lower := low[1] reversal := true if reversal wasTouched := false brokenCount := 0 // Range adjustment if low[1] + tolerance < upper - dnDev upper := low[1] + dnDev if high[1] - tolerance > lower + upDev lower := high[1] - upDev trendChange = ta.change(trend) signalUp = trend == UP and trendChange > 0 signalDn = trend == DOWN and trendChange < 0 isTrendUp = trend[1] == UP isTrendDn = trend[1] == DOWN // Plots upperPlot = plot(upper, "Upper Boundary", isTrendDn ? wasTouched[1] ? warnPen : dnPen : clearColor, 2, plot.style_linebr) middle = (lower + upper) / 2 plot(middle, "Mid-Point", isTrendUp ? upPen : isTrendDn ? dnPen : clearColor, 1, plot.style_circles, display = showMidpoint ? display.all : display.status_line) lowerPlot = plot(lower, "Lower Boundary", isTrendUp ? wasTouched[1]?warnPen:upPen : clearColor, 2, plot.style_linebr) // Labels labelTextColor = showLabels ? color.black : clearColor plotshape(signalDn[1] ? upper[1] : na, "▼ Reversal", showLabels?shape.labeldown:shape.circle, location.absolute, dnColor, -1, "▼", labelTextColor, size=size.tiny, display = display.pane) plotshape(signalUp[1] ? lower[1] : na, "▲ Reversal", showLabels?shape.labelup:shape.circle, location.absolute, upColor, -1, "▲", labelTextColor, size=size.tiny, display = display.pane) // Highlight highlight = plot(highlighting ? ohlc4 : na, "OHLC4", clearColor, display=display.none) fill(highlight, upperPlot, upper, ohlc4, isTrendDn ? color.new(dnColor, 75) : clearColor, isTrendDn ? color.new(dnColor, 90) : clearColor, "▼ Highlight", display = highlighting ? display.all : display.none) fill(highlight, lowerPlot, lower, ohlc4, isTrendUp ? color.new(upColor, 75) : clearColor, isTrendUp ? color.new(upColor, 90) : clearColor, "▲ Highlight", display = highlighting ? display.all : display.none) // Alerts alertcondition(warn or reversal, "1) Warning", message="Auto SuperTrend+ Warning ({{ticker}} {{interval}})") alertcondition(reversal, "2) Reversal", message="Auto SuperTrend+ Reversal ({{ticker}} {{interval}})") alertcondition(isTrendUp ? close<middle : isTrendDn ? close>middle : false, "3) Pullback", message="Auto SuperTrend+ Pullback ({{ticker}} {{interval}})") alertcondition(signalUp, "4) Up ▲ (+)", message="Auto SuperTrend+ Up ▲ (+) ({{ticker}} {{interval}})") alertcondition(signalDn, "5) Down ▼ (-)", message="Auto SuperTrend+ Down ▼ (-) ({{ticker}} {{interval}})")
HMA w/ SSE-Dynamic EWMA Volatility Bands [Loxx]
https://www.tradingview.com/script/t9iZrp5c-HMA-w-SSE-Dynamic-EWMA-Volatility-Bands-Loxx/
loxx
https://www.tradingview.com/u/loxx/
151
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/ // © SegaRKO //@version=5 indicator('HMA w/ SSE-Dynamic EWMA Volatility Bands [Loxx]', shorttitle ="HMASSEDEWMAVB [Loxx]", overlay = true, max_bars_back = 4000, precision = 3) if not timeframe.isdaily runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.") logfast(x)=> logfast = -1.7417939 + (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x) * x logfast // constants int MAX_COUNT = 100 // could be incrased for more refined lambda values color darkGreenColor = #1B7E02 color greencolor = #2DD204 float src = input.source(close, "Source") int per = input.int(252, "Lookback Period for Mean of Squared Log-returns") int lambper = input.int(252, "Lookback Period for Mean of Lambda") int daysperyear = input.int(252, "Days per Year") int hmaper = input.int(65, "HMA Period") bool fastLog = input.bool(true, "Use fast Log2 approximation?") int barsbark = input.int(1000, "Number of bars to calculate") int bandsmult = input.int(1, "Bands Volatility Multiplier") float logr = fastLog ? logfast(src/src[1]) : math.log(src/src[1]) float logr2 = math.pow(logr, 2) float logr2mean = ta.sma(logr2, per) float ewma = 0 float out = 0 float lambda = 0 float hma = 0 var testTable = table.new(position = position.middle_right, columns = 1, rows = 5, bgcolor = color.gray, border_width = 1) if last_bar_index - bar_index < barsbark float[] lambdaarray = array.new_float(0) for i = 0 to MAX_COUNT - 1 float sseLambda = 0 for j = 0 to per - 1 sseLambda += math.pow( nz(i / MAX_COUNT) * nz(ewma[j + 1], logr2[j + 1]) + nz(1 - i / MAX_COUNT) * nz(logr2[j + 1]) - logr2mean, 2) array.push(lambdaarray, sseLambda) opLambdaPos = array.min(lambdaarray) lambda := (array.indexof(lambdaarray, opLambdaPos) + 1) / MAX_COUNT ewma := lambda * nz(ewma[1], logr2[1]) + (1 - lambda) * logr2[1] out := math.sqrt(ewma) meanlambda = ta.sma(lambda, lambper) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Ouputs", bgcolor=darkGreenColor, text_color = color.white, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 1, text = "EWMA Volatility (daily): " + str.tostring(out * 100, format = format.percent), bgcolor=color.yellow, text_color = color.black, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, text = "EWMA Volatility (annulaized): " + str.tostring(out * math.sqrt(daysperyear) * 100, format = format.percent), bgcolor=color.yellow, text_color = color.black, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 3, text = "Mean of Lambda: " + str.tostring(meanlambda, "#.###"), bgcolor=color.yellow, text_color = color.black, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "The popular RiskMetrics developed by\nJ.P. Morgan uses an EWMA with Lambda = 0.94.", bgcolor=color.yellow, text_color = color.black, text_halign = text.align_left) hma := ta.hma(src, hmaper) plot(last_bar_index - bar_index < barsbark ? hma + out * src * bandsmult : na, 'Upper band', color=color.new(color.yellow, 0)) plot(last_bar_index - bar_index < barsbark ? hma : na, 'HMA', color=greencolor, linewidth = 2) plot(last_bar_index - bar_index < barsbark ? hma - out * src * bandsmult : na, 'Lower band', color=color.new(color.yellow, 0)) plotchar(last_bar_index - bar_index < barsbark ? lambda : na, "Lambda", display = display.data_window)
The TrendLiner
https://www.tradingview.com/script/CTYf8ACy-The-TrendLiner/
UnknownUnicorn36161431
https://www.tradingview.com/u/UnknownUnicorn36161431/
243
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/ // © zathruswriter //@version=5 indicator("The TrendLiner", overlay = true, max_bars_back = 5000, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500) GROUP_GENERAL = "General Options" GROUP_TF1 = "Timeframe 1" GROUP_TF1_APPEARANCE = "Timeframe 1 Appearance" GROUP_TF2 = "Timeframe 2" GROUP_TF2_APPEARANCE = "Timeframe 2 Appearance" GROUP_TF3 = "Timeframe 3" GROUP_TF3_APPEARANCE = "Timeframe 3 Appearance" GROUP_TF4 = "Timeframe 4" GROUP_TF4_APPEARANCE = "Timeframe 4 Appearance" CHECK_TYPE_BODY = "Body" CHECK_TYPE_WICK = "Wick" // GENERAL i_min_distance_threshold = input.float( 0.4, "Min Distance from Previous Trendline (%)", minval = 0, step = 0.1, group = GROUP_GENERAL, tooltip = "Minimum distance of a new trendline from the last one in order for it to be shown on chart. Prevents cluttering of your chart by hiding trendlines that would otherwise appear much too close to each other." ) i_text_offset = input.int( 5, "Text Offset on Trendline", minval = 0, group = GROUP_GENERAL, tooltip = "How many candles to the right from current candle should a trendline text be offset to the right." ) i_right_line_width = input.int( 10, "Off-Chart Lines Width", minval = 2, group = GROUP_GENERAL, tooltip = "How long should right-hand-side trend lines be.\nThese trendlines are off-chart, i.e. not present in between of candles to prevent unneccessary clutter.\n\nYou can set up how many maximum on-chart trendlines you want to see for each timeframe used. The rest will be displayed off-chart, on the right hand side, into the future." ) i_check_type = input.string( CHECK_TYPE_WICK, "Trendline At", options = [ CHECK_TYPE_BODY, CHECK_TYPE_WICK ], group = GROUP_GENERAL ) i_show_price_on_labels = input.bool( true, "Show Price on Labels", group = GROUP_GENERAL ) // TIMEFRAME 1 i_use_tf1 = input.bool( true, "Use Timeframe 1", group = GROUP_TF1 ) i_tf_t1 = input.timeframe( "", "Timeframe", group = GROUP_TF1 ) i_text_t1 = input.string( "", "Text on Trendline", group = GROUP_TF1, inline = "t1_txt") i_text_use_period_t1 = input.bool( false, "Use Period Name", group = GROUP_TF1, inline = "t1_txt" ) i_text_size_t1 = input.string( size.normal, "Text Size", options = [ size.auto, size.huge, size.large, size.normal, size.small, size.tiny ], group = GROUP_TF1 ) i_untested_max_t1 = input.int( 12, "Max Untested Trendlines", group = GROUP_TF1, maxval = 500, minval = 1, tooltip = "This is the number of untested trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. At least a single untested trendline must be present on chart for this indicator to work, but you can use the Style tab to hide even this one." ) //i_untested_lines_on_chart_t1 = input.int( 5, "Untested Trendlines Directly on Chart", group = GROUP_TF1, minval = -1, maxval = 500, tooltip = "This is the number of untested trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all untested trendlines directly on chart\n-1 = show all untested trendlines as lines to the right of the chart\n1-500 = show that many untested trendlines directly on chart and the rest to the right of the chart" ) i_untested_display_off_chart_t1 = input.bool( false, "Display Untested Trendlines off Chart", group = GROUP_TF1) i_untested_show_label_t1 = input.bool( true, "Show Untested Labels", group = GROUP_TF1 ) i_touched_max_t1 = input.int( 12, "Max Touched Trendlines", group = GROUP_TF1, maxval = 500, minval = 0, tooltip = "This is the number of touched trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all touched trendlines." ) //i_touched_lines_on_chart_t1 = input.int( 5, "Touched Trendlines Directly on Chart", group = GROUP_TF1, minval = -1, maxval = 500, tooltip = "This is the number of touched trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all touched trendlines directly on chart\n-1 = show all touched trendlines as lines to the right of the chart\n1-500 = show that many touched trendlines directly on chart and the rest to the right of the chart" ) i_touched_display_off_chart_t1 = input.bool( false, "Display Touched Trendlines off Chart", group = GROUP_TF1) i_touched_show_label_t1 = input.bool( true, "Show Touched Labels", group = GROUP_TF1 ) i_mitigated_max_t1 = input.int( 8, "Max Mitigated Trendlines", group = GROUP_TF1, maxval = 500, minval = 0, tooltip = "This is the number of mitigated trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all mitigated trendlines." ) //i_mitigated_lines_on_chart_t1 = input.int( 5, "Mitigated Trendlines Directly on Chart", group = GROUP_TF1, minval = -1, maxval = 500, tooltip = "This is the number of mitigated trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all mitigated trendlines directly on chart\n-1 = show all mitigated trendlines as lines to the right of the chart\n1-500 = show that many mitigated trendlines directly on chart and the rest to the right of the chart" ) i_mitigated_display_off_chart_t1 = input.bool( true, "Display Mitigated Trendlines off Chart", group = GROUP_TF1) i_mitigated_show_label_t1 = input.bool( false, "Show Mitigated Labels", group = GROUP_TF1 ) i_line_color_untested_t1 = input.color( color.green, "Untested Trendline", group = GROUP_TF1_APPEARANCE, inline = "1_untested" ) i_line_size_untested_t1 = input.int( 1, "", group = GROUP_TF1_APPEARANCE, inline = "1_untested" ) i_line_style_untested_t1 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF1_APPEARANCE, inline = "1_untested" ) i_line_extend_untested_t1 = input.bool( false, "Extend", group = GROUP_TF1_APPEARANCE, inline = "1_untested", tooltip = "Untested trendlines are the ones where price made a swing high / low but the price did not return there yet." ) i_line_color_touched_t1 = input.color( color.orange, "Touched Trendline", group = GROUP_TF1_APPEARANCE, inline = "1_touched" ) i_line_size_touched_t1 = input.int( 1, "", group = GROUP_TF1_APPEARANCE, inline = "1_touched" ) i_line_style_touched_t1 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF1_APPEARANCE, inline = "1_touched" ) i_line_extend_touched_t1 = input.bool( false, "Extend", group = GROUP_TF1_APPEARANCE, inline = "1_touched", tooltip = "Touched trendlines are the ones where price returned but failed to cross over that swing high/low." ) i_line_color_mitigated_t1 = input.color( color.rgb(205, 206, 209), "Mitigated Trendline", group = GROUP_TF1_APPEARANCE, inline = "1_mitigated" ) i_line_size_mitigated_t1 = input.int( 1, "", group = GROUP_TF1_APPEARANCE, inline = "1_mitigated" ) i_line_style_mitigated_t1 = input.string( line.style_dashed, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF1_APPEARANCE, inline = "1_mitigated" ) i_line_extend_mitigated_t1 = input.bool( false, "Extend", group = GROUP_TF1_APPEARANCE, inline = "1_mitigated", tooltip = "Mitigated trendlines are the ones where price returned and crossed over, thus rendering the trendline invalid." ) // TIMEFRAME 2 i_use_tf2 = input.bool( false, "Use Timeframe 2", group = GROUP_TF2 ) i_tf_t2 = input.timeframe( "60", "Timeframe", group = GROUP_TF2 ) i_text_t2 = input.string( "", "Text on Trendline", group = GROUP_TF2, inline = "t2_txt") i_text_use_period_t2 = input.bool( false, "Use Period Name", group = GROUP_TF2, inline = "t2_txt" ) i_text_size_t2 = input.string( size.normal, "Text Size", options = [ size.auto, size.huge, size.large, size.normal, size.small, size.tiny ], group = GROUP_TF2 ) i_untested_max_t2 = input.int( 12, "Max Untested Trendlines", group = GROUP_TF2, maxval = 500, minval = 1, tooltip = "This is the number of untested trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. At least a single untested trendline must be present on chart for this indicator to work, but you can use the Style tab to hide even this one." ) //i_untested_lines_on_chart_t2 = input.int( 5, "Untested Trendlines Directly on Chart", group = GROUP_TF2, minval = -1, maxval = 500, tooltip = "This is the number of untested trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all untested trendlines directly on chart\n-1 = show all untested trendlines as lines to the right of the chart\n1-500 = show that many untested trendlines directly on chart and the rest to the right of the chart" ) i_untested_display_off_chart_t2 = input.bool( false, "Display Untested Trendlines off Chart", group = GROUP_TF2) i_untested_show_label_t2 = input.bool( true, "Show Untested Labels", group = GROUP_TF2 ) i_touched_max_t2 = input.int( 12, "Max Touched Trendlines", group = GROUP_TF2, maxval = 500, minval = 0, tooltip = "This is the number of touched trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all touched trendlines." ) //i_touched_lines_on_chart_t2 = input.int( 5, "Touched Trendlines Directly on Chart", group = GROUP_TF2, minval = -1, maxval = 500, tooltip = "This is the number of touched trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all touched trendlines directly on chart\n-1 = show all touched trendlines as lines to the right of the chart\n1-500 = show that many touched trendlines directly on chart and the rest to the right of the chart" ) i_touched_display_off_chart_t2 = input.bool( false, "Display Touched Trendlines off Chart", group = GROUP_TF2) i_touched_show_label_t2 = input.bool( true, "Show Touched Labels", group = GROUP_TF2 ) i_mitigated_max_t2 = input.int( 8, "Max Mitigated Trendlines", group = GROUP_TF2, maxval = 500, minval = 0, tooltip = "This is the number of mitigated trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all mitigated trendlines." ) //i_mitigated_lines_on_chart_t2 = input.int( 5, "Mitigated Trendlines Directly on Chart", group = GROUP_TF2, minval = -1, maxval = 500, tooltip = "This is the number of mitigated trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all mitigated trendlines directly on chart\n-1 = show all mitigated trendlines as lines to the right of the chart\n1-500 = show that many mitigated trendlines directly on chart and the rest to the right of the chart" ) i_mitigated_display_off_chart_t2 = input.bool( true, "Display Mitigated Trendlines off Chart", group = GROUP_TF2) i_mitigated_show_label_t2 = input.bool( false, "Show Mitigated Labels", group = GROUP_TF2 ) i_line_color_untested_t2 = input.color( color.aqua, "Untested Trendline", group = GROUP_TF2_APPEARANCE, inline = "2_untested" ) i_line_size_untested_t2 = input.int( 1, "", group = GROUP_TF2_APPEARANCE, inline = "2_untested" ) i_line_style_untested_t2 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF2_APPEARANCE, inline = "2_untested" ) i_line_extend_untested_t2 = input.bool( false, "Extend", group = GROUP_TF2_APPEARANCE, inline = "2_untested", tooltip = "Untested trendlines are the ones where price made a swing high / low but the price did not return there yet." ) i_line_color_touched_t2 = input.color( color.yellow, "Touched Trendline", group = GROUP_TF2_APPEARANCE, inline = "2_touched" ) i_line_size_touched_t2 = input.int( 1, "", group = GROUP_TF2_APPEARANCE, inline = "2_touched" ) i_line_style_touched_t2 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF2_APPEARANCE, inline = "2_touched" ) i_line_extend_touched_t2 = input.bool( false, "Extend", group = GROUP_TF2_APPEARANCE, inline = "2_touched", tooltip = "Touched trendlines are the ones where price returned but failed to cross over that swing high/low." ) i_line_color_mitigated_t2 = input.color( #b2b5be, "Mitigated Trendline", group = GROUP_TF2_APPEARANCE, inline = "2_mitigated" ) i_line_size_mitigated_t2 = input.int( 1, "", group = GROUP_TF2_APPEARANCE, inline = "2_mitigated" ) i_line_style_mitigated_t2 = input.string( line.style_dashed, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF2_APPEARANCE, inline = "2_mitigated" ) i_line_extend_mitigated_t2 = input.bool( false, "Extend", group = GROUP_TF2_APPEARANCE, inline = "2_mitigated", tooltip = "Mitigated trendlines are the ones where price returned and crossed over, thus rendering the trendline invalid." ) // TIMEFRAME 3 i_use_tf3 = input.bool( false, "Use Timeframe 3", group = GROUP_TF3 ) i_tf_t3 = input.timeframe( "60", "Timeframe", group = GROUP_TF3 ) i_text_t3 = input.string( "", "Text on Trendline", group = GROUP_TF3, inline = "t3_txt") i_text_use_period_t3 = input.bool( false, "Use Period Name", group = GROUP_TF3, inline = "t3_txt" ) i_text_size_t3 = input.string( size.normal, "Text Size", options = [ size.auto, size.huge, size.large, size.normal, size.small, size.tiny ], group = GROUP_TF3 ) i_untested_max_t3 = input.int( 12, "Max Untested Trendlines", group = GROUP_TF3, maxval = 500, minval = 1, tooltip = "This is the number of untested trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. At least a single untested trendline must be present on chart for this indicator to work, but you can use the Style tab to hide even this one." ) //i_untested_lines_on_chart_t3 = input.int( 5, "Untested Trendlines Directly on Chart", group = GROUP_TF3, minval = -1, maxval = 500, tooltip = "This is the number of untested trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all untested trendlines directly on chart\n-1 = show all untested trendlines as lines to the right of the chart\n1-500 = show that many untested trendlines directly on chart and the rest to the right of the chart" ) i_untested_display_off_chart_t3 = input.bool( false, "Display Untested Trendlines off Chart", group = GROUP_TF3) i_untested_show_label_t3 = input.bool( true, "Show Untested Labels", group = GROUP_TF3 ) i_touched_max_t3 = input.int( 12, "Max Touched Trendlines", group = GROUP_TF3, maxval = 500, minval = 0, tooltip = "This is the number of touched trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all touched trendlines." ) //i_touched_lines_on_chart_t3 = input.int( 5, "Touched Trendlines Directly on Chart", group = GROUP_TF3, minval = -1, maxval = 500, tooltip = "This is the number of touched trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all touched trendlines directly on chart\n-1 = show all touched trendlines as lines to the right of the chart\n1-500 = show that many touched trendlines directly on chart and the rest to the right of the chart" ) i_touched_display_off_chart_t3 = input.bool( false, "Display Touched Trendlines off Chart", group = GROUP_TF3) i_touched_show_label_t3 = input.bool( true, "Show Touched Labels", group = GROUP_TF3 ) i_mitigated_max_t3 = input.int( 8, "Max Mitigated Trendlines", group = GROUP_TF3, maxval = 500, minval = 0, tooltip = "This is the number of mitigated trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all mitigated trendlines." ) //i_mitigated_lines_on_chart_t3 = input.int( 5, "Mitigated Trendlines Directly on Chart", group = GROUP_TF3, minval = -1, maxval = 500, tooltip = "This is the number of mitigated trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all mitigated trendlines directly on chart\n-1 = show all mitigated trendlines as lines to the right of the chart\n1-500 = show that many mitigated trendlines directly on chart and the rest to the right of the chart" ) i_mitigated_display_off_chart_t3 = input.bool( true, "Display Mitigated Trendlines off Chart", group = GROUP_TF3) i_mitigated_show_label_t3 = input.bool( false, "Show Mitigated Labels", group = GROUP_TF3 ) i_line_color_untested_t3 = input.color( color.blue, "Untested Trendline", group = GROUP_TF3_APPEARANCE, inline = "2_untested" ) i_line_size_untested_t3 = input.int( 1, "", group = GROUP_TF3_APPEARANCE, inline = "2_untested" ) i_line_style_untested_t3 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF3_APPEARANCE, inline = "2_untested" ) i_line_extend_untested_t3 = input.bool( false, "Extend", group = GROUP_TF3_APPEARANCE, inline = "2_untested", tooltip = "Untested trendlines are the ones where price made a swing high / low but the price did not return there yet." ) i_line_color_touched_t3 = input.color( #801922, "Touched Trendline", group = GROUP_TF3_APPEARANCE, inline = "2_touched" ) i_line_size_touched_t3 = input.int( 1, "", group = GROUP_TF3_APPEARANCE, inline = "2_touched" ) i_line_style_touched_t3 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF3_APPEARANCE, inline = "2_touched" ) i_line_extend_touched_t3 = input.bool( false, "Extend", group = GROUP_TF3_APPEARANCE, inline = "2_touched", tooltip = "Touched trendlines are the ones where price returned but failed to cross over that swing high/low." ) i_line_color_mitigated_t3 = input.color( #9598a1, "Mitigated Trendline", group = GROUP_TF3_APPEARANCE, inline = "2_mitigated" ) i_line_size_mitigated_t3 = input.int( 1, "", group = GROUP_TF3_APPEARANCE, inline = "2_mitigated" ) i_line_style_mitigated_t3 = input.string( line.style_dashed, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF3_APPEARANCE, inline = "2_mitigated" ) i_line_extend_mitigated_t3 = input.bool( false, "Extend", group = GROUP_TF3_APPEARANCE, inline = "2_mitigated", tooltip = "Mitigated trendlines are the ones where price returned and crossed over, thus rendering the trendline invalid." ) // TIMEFRAME 4 i_use_tf4 = input.bool( false, "Use Timeframe 4", group = GROUP_TF4 ) i_tf_t4 = input.timeframe( "60", "Timeframe", group = GROUP_TF4 ) i_text_t4 = input.string( "", "Text on Trendline", group = GROUP_TF4, inline = "t4_txt") i_text_use_period_t4 = input.bool( false, "Use Period Name", group = GROUP_TF4, inline = "t4_txt" ) i_text_size_t4 = input.string( size.normal, "Text Size", options = [ size.auto, size.huge, size.large, size.normal, size.small, size.tiny ], group = GROUP_TF4 ) i_untested_max_t4 = input.int( 12, "Max Untested Trendlines", group = GROUP_TF4, maxval = 500, minval = 1, tooltip = "This is the number of untested trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. At least a single untested trendline must be present on chart for this indicator to work, but you can use the Style tab to hide even this one." ) //i_untested_lines_on_chart_t4 = input.int( 5, "Untested Trendlines Directly on Chart", group = GROUP_TF4, minval = -1, maxval = 500, tooltip = "This is the number of untested trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all untested trendlines directly on chart\n-1 = show all untested trendlines as lines to the right of the chart\n1-500 = show that many untested trendlines directly on chart and the rest to the right of the chart" ) i_untested_display_off_chart_t4 = input.bool( false, "Display Untested Trendlines off Chart", group = GROUP_TF4) i_untested_show_label_t4 = input.bool( true, "Show Untested Labels", group = GROUP_TF4 ) i_touched_max_t4 = input.int( 12, "Max Touched Trendlines", group = GROUP_TF4, maxval = 500, minval = 0, tooltip = "This is the number of touched trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all touched trendlines." ) //i_touched_lines_on_chart_t4 = input.int( 5, "Touched Trendlines Directly on Chart", group = GROUP_TF4, minval = -1, maxval = 500, tooltip = "This is the number of touched trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all touched trendlines directly on chart\n-1 = show all touched trendlines as lines to the right of the chart\n1-500 = show that many touched trendlines directly on chart and the rest to the right of the chart" ) i_touched_display_off_chart_t4 = input.bool( false, "Display Touched Trendlines off Chart", group = GROUP_TF4) i_touched_show_label_t4 = input.bool( true, "Show Touched Labels", group = GROUP_TF4 ) i_mitigated_max_t4 = input.int( 8, "Max Mitigated Trendlines", group = GROUP_TF4, maxval = 500, minval = 0, tooltip = "This is the number of mitigated trendlines for this timeframe to show, displayed either directly over candles on the chart or indirectly as lines to the right side of the chart. Set to 0 to hide all mitigated trendlines." ) //i_mitigated_lines_on_chart_t4 = input.int( 5, "Mitigated Trendlines Directly on Chart", group = GROUP_TF4, minval = -1, maxval = 500, tooltip = "This is the number of mitigated trendlines to show over candles on your chart.\n\nTrendlines can be either shown directly between candles on the chart or as lines to the right of the chart, so they don't get in the way.\n\n0 = show all mitigated trendlines directly on chart\n-1 = show all mitigated trendlines as lines to the right of the chart\n1-500 = show that many mitigated trendlines directly on chart and the rest to the right of the chart" ) i_mitigated_display_off_chart_t4 = input.bool( true, "Display Mitigated Trendlines off Chart", group = GROUP_TF4) i_mitigated_show_label_t4 = input.bool( false, "Show Mitigated Labels", group = GROUP_TF4 ) i_line_color_untested_t4 = input.color( color.fuchsia, "Untested Trendline", group = GROUP_TF4_APPEARANCE, inline = "2_untested" ) i_line_size_untested_t4 = input.int( 1, "", group = GROUP_TF4_APPEARANCE, inline = "2_untested" ) i_line_style_untested_t4 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF4_APPEARANCE, inline = "2_untested" ) i_line_extend_untested_t4 = input.bool( false, "Extend", group = GROUP_TF4_APPEARANCE, inline = "2_untested", tooltip = "Untested trendlines are the ones where price made a swing high / low but the price did not return there yet." ) i_line_color_touched_t4 = input.color( color.black, "Touched Trendline", group = GROUP_TF4_APPEARANCE, inline = "2_touched" ) i_line_size_touched_t4 = input.int( 1, "", group = GROUP_TF4_APPEARANCE, inline = "2_touched" ) i_line_style_touched_t4 = input.string( line.style_solid, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF4_APPEARANCE, inline = "2_touched" ) i_line_extend_touched_t4 = input.bool( false, "Extend", group = GROUP_TF4_APPEARANCE, inline = "2_touched", tooltip = "Touched trendlines are the ones where price returned but failed to cross over that swing high/low." ) i_line_color_mitigated_t4 = input.color( #787b86, "Mitigated Trendline", group = GROUP_TF4_APPEARANCE, inline = "2_mitigated" ) i_line_size_mitigated_t4 = input.int( 1, "", group = GROUP_TF4_APPEARANCE, inline = "2_mitigated" ) i_line_style_mitigated_t4 = input.string( line.style_dashed, "", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_TF4_APPEARANCE, inline = "2_mitigated" ) i_line_extend_mitigated_t4 = input.bool( false, "Extend", group = GROUP_TF4_APPEARANCE, inline = "2_mitigated", tooltip = "Mitigated trendlines are the ones where price returned and crossed over, thus rendering the trendline invalid." ) // VARIABLES transparentcolor = color.new(color.white,100) var untested_t1 = array.new_line() var labels_untested_t1 = array.new_label() var touched_t1 = array.new_line() var labels_touched_t1 = array.new_label() var mitigated_t1 = array.new_line() var labels_mitigated_t1 = array.new_label() var labels_orig_x_t1 = matrix.new<float>( 0, 2 ) // 0 = X line parameter (in bars or a timestamp), 1 = Y line parameter var untested_t2 = array.new_line() var labels_untested_t2 = array.new_label() var touched_t2 = array.new_line() var labels_touched_t2 = array.new_label() var mitigated_t2 = array.new_line() var labels_mitigated_t2 = array.new_label() var labels_orig_x_t2 = matrix.new<float>( 0, 2 ) // 0 = X line parameter (in bars or a timestamp), 1 = Y line parameter var untested_t3 = array.new_line() var labels_untested_t3 = array.new_label() var touched_t3 = array.new_line() var labels_touched_t3 = array.new_label() var mitigated_t3 = array.new_line() var labels_mitigated_t3 = array.new_label() var labels_orig_x_t3 = matrix.new<float>( 0, 2 ) // 0 = X line parameter (in bars or a timestamp), 1 = Y line parameter var untested_t4 = array.new_line() var labels_untested_t4 = array.new_label() var touched_t4 = array.new_line() var labels_touched_t4 = array.new_label() var mitigated_t4 = array.new_line() var labels_mitigated_t4 = array.new_label() var labels_orig_x_t4 = matrix.new<float>( 0, 2 ) // 0 = X line parameter (in bars or a timestamp), 1 = Y line parameter // FUNCTIONS s_( float txt ) => str.tostring( txt ) f_debug_label( txt ) => label.new(bar_index, high, str.tostring( txt ), color = color.lime, textcolor = color.black) f_debug_label_down( txt ) => label.new(bar_index, low, str.tostring( txt ), color = color.lime, textcolor = color.black, style = label.style_label_up) f_find_orig_x_for_y( y, matrixVar ) => ret = -1.0 for i = 0 to matrix.rows( matrixVar ) if matrix.get( matrixVar, i, 1 ) == y ret := matrix.get( matrixVar, i, 0 ) break ret f_remove_orig_x_for_y( y, matrixVar ) => for i = 0 to matrix.rows( matrixVar ) if matrix.get( matrixVar, i, 1 ) == y matrix.remove_row( matrixVar, i ) break f_get_tf_diff( tf ) => // calculate the bars difference between current TF and the one we're processing, // so we can position the beginning of trendlines correctly (otherwise lines from 1H chart on 30m display would be half the bars offset to the left) current_tf_minutes = timeframe.in_seconds( timeframe.period ) scanned_tf_minutes = timeframe.in_seconds( tf ) tf_bars_difference = math.floor( scanned_tf_minutes / current_tf_minutes ) tf_bars_difference f_move_line_off_chart( ln ) => line.set_xloc( ln, bar_index + i_text_offset - 1, bar_index + i_text_offset - 1 + i_right_line_width, xloc.bar_index ) f_return_line_to_chart( ln, y, matrixVar ) => line.set_xloc( ln, math.round( f_find_orig_x_for_y( y, matrixVar ) ), time, xloc.bar_time ) f_check_line_within_threshold( theLineArray, is_swing_high, is_swing_low, hHigh1, hLow1 ) => is_within_threshold = true for theLine in theLineArray if is_swing_high if math.abs( ( ( hHigh1 - line.get_y1( theLine ) ) / line.get_y1( theLine ) ) * 100 ) < i_min_distance_threshold is_within_threshold := false break if is_swing_low if math.abs( ( ( hLow1 - line.get_y1( theLine ) ) / line.get_y1( theLine ) ) * 100 ) < i_min_distance_threshold is_within_threshold := false break is_within_threshold f_get_real_label_text( tf, label_use_period, label_text ) => ret = label_text tf_real = tf if tf == "" tf_real := timeframe.period if label_use_period if tf_real == "1" ret := "1m" else if tf_real == "2" ret := "2m" else if tf_real == "3" ret := "3m" else if tf_real == "5" ret := "5m" else if tf_real == "15" ret := "15m" else if tf_real == "45" ret := "45m" else if tf_real == "60" ret := "1H" ret := "1H" else if tf_real == "120" ret := "2H" else if tf_real == "180" ret := "3H" else if tf_real == "240" ret := "4H" else ret := tf_real ret f_check_trendlines( which, tf ) => [ hOpen, hOpen1, hOpen2, hClose, hClose1, hClose2, hHigh, hHigh1, hHigh2, hLow, hLow1, hLow2, hBar, hBar1, hBar2 ] = request.security(syminfo.tickerid, tf, [ open, open[ 1 ], open[ 2 ], close, close[ 1 ], close[ 2 ], high, high[ 1 ], high[ 2 ], low, low[ 1 ], low[ 2 ], bar_index, bar_index[ 1 ], bar_index[ 2 ] ], barmerge.gaps_off, barmerge.lookahead_on) array<line> untested = na array<label> labels_untested = na int untested_lines_on_chart = na int untested_max = na bool untested_show_label = na array<line> touched = na array<label> labels_touched = na int touched_lines_on_chart = na int touched_max = na bool touched_show_label = na array<line> mitigated = na array<label> labels_mitigated = na int mitigated_lines_on_chart = na matrix<float> labels_orig_x = na int mitigated_max = na bool mitigated_show_label = na string label_text = na bool label_use_period = na string label_size = na color i_line_color_untested = na int i_line_size_untested = na string i_line_style_untested = na bool i_line_extend_untested = na color i_line_color_touched = na int i_line_size_touched = na string i_line_style_touched = na bool i_line_extend_touched = na color i_line_color_mitigated = na int i_line_size_mitigated = na string i_line_style_mitigated = na bool i_line_extend_mitigated = na if which == 1 untested := untested_t1 labels_untested := labels_untested_t1 untested_lines_on_chart := i_untested_display_off_chart_t1 ? -1 : 0 untested_max := i_untested_max_t1 untested_show_label := i_untested_show_label_t1 touched := touched_t1 labels_touched := labels_touched_t1 touched_lines_on_chart := i_touched_display_off_chart_t1 ? -1 : 0 touched_max := i_touched_max_t1 touched_show_label := i_touched_show_label_t1 mitigated := mitigated_t1 labels_mitigated := labels_mitigated_t1 mitigated_lines_on_chart := i_mitigated_display_off_chart_t1 ? -1 : 0 mitigated_max := i_mitigated_max_t1 mitigated_show_label := i_mitigated_show_label_t1 labels_orig_x := labels_orig_x_t1 label_text := i_text_t1 label_size := i_text_size_t1 label_use_period := i_text_use_period_t1 i_line_color_untested := i_line_color_untested_t1 i_line_size_untested := i_line_size_untested_t1 i_line_style_untested := i_line_style_untested_t1 i_line_extend_untested := i_line_extend_untested_t1 i_line_color_touched := i_line_color_touched_t1 i_line_size_touched := i_line_size_touched_t1 i_line_style_touched := i_line_style_touched_t1 i_line_extend_touched := i_line_extend_touched_t1 i_line_color_mitigated := i_line_color_mitigated_t1 i_line_size_mitigated := i_line_size_mitigated_t1 i_line_style_mitigated := i_line_style_mitigated_t1 i_line_extend_mitigated := i_line_extend_mitigated_t1 if which == 2 untested := untested_t2 labels_untested := labels_untested_t2 untested_lines_on_chart := i_untested_display_off_chart_t2 ? -1 : 0 untested_max := i_untested_max_t2 untested_show_label := i_untested_show_label_t2 touched := touched_t2 labels_touched := labels_touched_t2 touched_lines_on_chart := i_touched_display_off_chart_t3 ? -1 : 0 touched_max := i_touched_max_t2 touched_show_label := i_touched_show_label_t2 mitigated := mitigated_t2 labels_mitigated := labels_mitigated_t2 mitigated_lines_on_chart := i_mitigated_display_off_chart_t3 ? -1 : 0 mitigated_max := i_mitigated_max_t2 mitigated_show_label := i_mitigated_show_label_t2 labels_orig_x := labels_orig_x_t2 label_text := i_text_t2 label_use_period := i_text_use_period_t2 label_size := i_text_size_t2 i_line_color_untested := i_line_color_untested_t2 i_line_size_untested := i_line_size_untested_t2 i_line_style_untested := i_line_style_untested_t2 i_line_extend_untested := i_line_extend_untested_t2 i_line_color_touched := i_line_color_touched_t2 i_line_size_touched := i_line_size_touched_t2 i_line_style_touched := i_line_style_touched_t2 i_line_extend_touched := i_line_extend_touched_t2 i_line_color_mitigated := i_line_color_mitigated_t2 i_line_size_mitigated := i_line_size_mitigated_t2 i_line_style_mitigated := i_line_style_mitigated_t2 i_line_extend_mitigated := i_line_extend_mitigated_t2 if which == 3 untested := untested_t3 labels_untested := labels_untested_t3 untested_lines_on_chart := i_untested_display_off_chart_t3 ? -1 : 0 untested_max := i_untested_max_t3 untested_show_label := i_untested_show_label_t3 touched := touched_t3 labels_touched := labels_touched_t3 touched_lines_on_chart := i_touched_display_off_chart_t3 ? -1 : 0 touched_max := i_touched_max_t3 touched_show_label := i_touched_show_label_t3 mitigated := mitigated_t3 labels_mitigated := labels_mitigated_t3 mitigated_lines_on_chart := i_mitigated_display_off_chart_t3 ? -1 : 0 mitigated_max := i_mitigated_max_t3 mitigated_show_label := i_mitigated_show_label_t3 labels_orig_x := labels_orig_x_t3 label_text := i_text_t3 label_size := i_text_size_t3 label_use_period := i_text_use_period_t3 i_line_color_untested := i_line_color_untested_t3 i_line_size_untested := i_line_size_untested_t3 i_line_style_untested := i_line_style_untested_t3 i_line_extend_untested := i_line_extend_untested_t3 i_line_color_touched := i_line_color_touched_t3 i_line_size_touched := i_line_size_touched_t3 i_line_style_touched := i_line_style_touched_t3 i_line_extend_touched := i_line_extend_touched_t3 i_line_color_mitigated := i_line_color_mitigated_t3 i_line_size_mitigated := i_line_size_mitigated_t3 i_line_style_mitigated := i_line_style_mitigated_t3 i_line_extend_mitigated := i_line_extend_mitigated_t3 if which == 4 untested := untested_t4 labels_untested := labels_untested_t4 untested_lines_on_chart := i_untested_display_off_chart_t4 ? -1 : 0 untested_max := i_untested_max_t4 untested_show_label := i_untested_show_label_t4 touched := touched_t4 labels_touched := labels_touched_t4 touched_lines_on_chart := i_touched_display_off_chart_t4 ? -1 : 0 touched_max := i_touched_max_t4 touched_show_label := i_touched_show_label_t4 mitigated := mitigated_t4 labels_mitigated := labels_mitigated_t4 mitigated_lines_on_chart := i_mitigated_display_off_chart_t4 ? -1 : 0 mitigated_max := i_mitigated_max_t4 mitigated_show_label := i_mitigated_show_label_t4 labels_orig_x := labels_orig_x_t4 label_text := i_text_t4 label_size := i_text_size_t4 label_use_period := i_text_use_period_t4 i_line_color_untested := i_line_color_untested_t4 i_line_size_untested := i_line_size_untested_t4 i_line_style_untested := i_line_style_untested_t4 i_line_extend_untested := i_line_extend_untested_t4 i_line_color_touched := i_line_color_touched_t4 i_line_size_touched := i_line_size_touched_t4 i_line_style_touched := i_line_style_touched_t4 i_line_extend_touched := i_line_extend_touched_t4 i_line_color_mitigated := i_line_color_mitigated_t4 i_line_size_mitigated := i_line_size_mitigated_t4 i_line_style_mitigated := i_line_style_mitigated_t4 i_line_extend_mitigated := i_line_extend_mitigated_t4 // update label if we're using period label_text := f_get_real_label_text( tf, label_use_period, label_text ) // calculate the bars difference between current TF and the one we're processing, // so we can position the beginning of trendlines correctly (otherwise lines from 1H chart on 30m display would be half the bars offset to the left) tf_bars_difference = f_get_tf_diff( tf ) // when a new swing low/high is found, add it into the untested array if nz( hHigh1 ) is_swing_high = false is_swing_low = false if i_check_type == CHECK_TYPE_BODY if hClose > hOpen or hClose < hOpen is_swing_high := hClose1 > hClose and hClose1 > hClose2 is_swing_low := hOpen1 < hOpen and hOpen1 < hOpen2 else is_swing_high := hHigh1 > hHigh and hHigh1 > hHigh2 is_swing_low := hLow1 < hLow and hLow1 < hLow2 //f_debug_label_down( s_( hHigh2 ) + " / " + s_( hHigh1 ) + " / " + s_( hHigh ) + "\n" + s_( hLow2 ) + " / " + s_( hLow1 ) + " / " + s_( hLow ) ) if is_swing_high or is_swing_low // prepare line coordinates x1_high = 0 x2_high = 0 xloc_high = "" x1_low = 0 x2_low = 0 xloc_low = "" highest = 0.0 lowest = high + 10000 starting_bar = ( hBar2 * tf_bars_difference ) - 1 ending_bar = ( hBar * tf_bars_difference ) - 1 // if we're on the same TF, our trendline point is the middle bar - hBar1 trendline_bar_high = ( hBar1 * tf_bars_difference ) - 1 trendline_bar_low = ( hBar1 * tf_bars_difference ) - 1 // if we're showing all trendlines on the right, we must set xloc to use bars parameter, // as TV has a bug (or functionality) which prevents time-based xloc to create lines into the future if untested_lines_on_chart == -1 x1_high := bar_index + i_text_offset x1_low := bar_index + i_text_offset x2_high := bar_index + i_text_offset + i_right_line_width x2_low := bar_index + i_text_offset + i_right_line_width xloc_high := xloc.bar_index xloc_low := xloc.bar_index else // check where our high/low is between the starting and ending bar on our TF if starting_bar != hBar2 or ending_bar != hBar // go through all bars up to the last hBar2 on the HTF loop_end = ( 3 * tf_bars_difference ) loop_end := loop_end > 4999 ? 4999 : loop_end if i_check_type == CHECK_TYPE_BODY for b = 0 to loop_end if is_swing_high and ( hBar[ b ] == hBar or hBar[ b ] == hBar1 or hBar[ b ] == hBar2 ) and ( highest < open[ b ] or highest < close[ b ] ) highest := highest < open[ b ] ? open [ b ] : close[ b ] trendline_bar_high := bar_index - b if is_swing_low and ( hBar[ b ] == hBar or hBar[ b ] == hBar1 or hBar[ b ] == hBar2 ) and ( lowest > open[ b ] or lowest > close[ b ] ) lowest := lowest > open[ b ] ? open[ b ] : close[ b ] trendline_bar_low := bar_index - b else for b = 0 to loop_end if is_swing_high and ( hBar[ b ] == hBar or hBar[ b ] == hBar1 or hBar[ b ] == hBar2 ) and highest < high[ b ] highest := high[ b ] trendline_bar_high := bar_index - b if is_swing_low and ( hBar[ b ] == hBar or hBar[ b ] == hBar1 or hBar[ b ] == hBar2 ) and lowest > low[ b ] lowest := low[ b ] trendline_bar_low := bar_index - b // convert bar values into UNIX timestamps, so we don't get "bar too far in the past" errors x1_high := time - ( ( bar_index - trendline_bar_high ) * ( timeframe.in_seconds( timeframe.period ) * 1000 ) ) x2_high := time xloc_high := xloc.bar_time x1_low := time - ( ( bar_index - trendline_bar_low ) * ( timeframe.in_seconds( timeframe.period ) * 1000 ) ) x2_low := time xloc_low := xloc.bar_time // we may have both - swing high and swing low - on the same candle, // so we need to store both of their Y positions for later checks y_high = -1.0 y_low = -1.0 if i_check_type == CHECK_TYPE_BODY y_high := is_swing_high ? hClose1 : -1.0 y_low := is_swing_low ? hOpen1 : -1.0 else y_high := is_swing_high ? hHigh1 : -1.0 y_low := is_swing_low ? hLow1 : -1.0 // check whether we should remove LFT trendline which would be on the same Y level as our new one (HTF trendlines are stronger) if which != 1 and timeframe.in_seconds( tf ) > timeframe.in_seconds( i_tf_t1 ) if y_high > -1 and array.size( untested_t1 ) > 0 for t = 0 to array.size( untested_t1 ) - 1 if line.get_y1( array.get( untested_t1, t ) ) == y_high line.delete( array.remove( untested_t1, t ) ) if i_text_t1 != "" or i_text_use_period_t1 label.delete( array.remove( labels_untested_t1, t ) ) break if y_low > -1 and array.size( untested_t1 ) > 0 for t = 0 to array.size( untested_t1 ) - 1 if line.get_y1( array.get( untested_t1, t ) ) == y_low line.delete( array.remove( untested_t1, t ) ) if i_text_t1 != "" or i_text_use_period_t1 label.delete( array.remove( labels_untested_t1, t ) ) break if which != 2 and timeframe.in_seconds( tf ) > timeframe.in_seconds( i_tf_t2 ) if y_high > -1 and array.size( untested_t2 ) > 0 for t = 0 to array.size( untested_t2 ) - 1 if line.get_y1( array.get( untested_t2, t ) ) == y_high line.delete( array.remove( untested_t2, t ) ) if i_text_t2 != "" or i_text_use_period_t2 label.delete( array.remove( labels_untested_t2, t ) ) break if y_low > -1 and array.size( untested_t2 ) > 0 for t = 0 to array.size( untested_t2 ) - 1 if line.get_y1( array.get( untested_t2, t ) ) == y_low line.delete( array.remove( untested_t2, t ) ) if i_text_t2 != "" or i_text_use_period_t2 label.delete( array.remove( labels_untested_t2, t ) ) break if which != 3 and timeframe.in_seconds( tf ) > timeframe.in_seconds( i_tf_t3 ) if y_high > -1 and array.size( untested_t3 ) > 0 for t = 0 to array.size( untested_t3 ) - 1 if line.get_y1( array.get( untested_t3, t ) ) == y_high line.delete( array.remove( untested_t3, t ) ) if i_text_t3 != "" or i_text_use_period_t3 label.delete( array.remove( labels_untested_t3, t ) ) break if y_low > -1 and array.size( untested_t3 ) > 0 for t = 0 to array.size( untested_t3 ) - 1 if line.get_y1( array.get( untested_t3, t ) ) == y_low line.delete( array.remove( untested_t3, t ) ) if i_text_t3 != "" or i_text_use_period_t3 label.delete( array.remove( labels_untested_t3, t ) ) break if which != 4 and timeframe.in_seconds( tf ) > timeframe.in_seconds( i_tf_t4 ) if y_high > -1 and array.size( untested_t4 ) > 0 for t = 0 to array.size( untested_t4 ) - 1 if line.get_y1( array.get( untested_t4, t ) ) == y_high line.delete( array.remove( untested_t4, t ) ) if i_text_t4 != "" or i_text_use_period_t4 label.delete( array.remove( labels_untested_t4, t ) ) break if y_low > -1 and array.size( untested_t4 ) > 0 for t = 0 to array.size( untested_t4 ) - 1 if line.get_y1( array.get( untested_t4, t ) ) == y_low line.delete( array.remove( untested_t4, t ) ) if i_text_t4 != "" or i_text_use_period_t4 label.delete( array.remove( labels_untested_t4, t ) ) break // check this trendline's distance from the nearest ones threshold_check_t1_1 = f_check_line_within_threshold( untested_t1, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t1_2 = f_check_line_within_threshold( touched_t1, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t1_3 = f_check_line_within_threshold( mitigated_t1, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t2_1 = f_check_line_within_threshold( untested_t2, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t2_2 = f_check_line_within_threshold( touched_t2, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t2_3 = f_check_line_within_threshold( mitigated_t2, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t3_1 = f_check_line_within_threshold( untested_t3, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t3_2 = f_check_line_within_threshold( touched_t3, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t3_3 = f_check_line_within_threshold( mitigated_t3, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t4_1 = f_check_line_within_threshold( untested_t4, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t4_2 = f_check_line_within_threshold( touched_t4, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) threshold_check_t4_3 = f_check_line_within_threshold( mitigated_t4, is_swing_high, is_swing_low, i_check_type == CHECK_TYPE_BODY ? ( hOpen1 > hClose1 ? hOpen1 : hClose1 ) : hHigh1, i_check_type == CHECK_TYPE_BODY ? ( hClose1 < hOpen1 ? hClose1 : hOpen1 ) : hLow1 ) is_within_threshold = threshold_check_t1_1 and threshold_check_t1_2 and threshold_check_t1_3 and threshold_check_t2_1 and threshold_check_t2_2 and threshold_check_t2_3 and threshold_check_t3_1 and threshold_check_t3_2 and threshold_check_t3_3 and threshold_check_t4_1 and threshold_check_t4_2 and threshold_check_t4_3 if is_within_threshold //f_debug_label( "tf: " + tf + "\nbar: " + s_( bar_index ) + "\nstarting: " + s_( starting_bar ) + " (" + s_( hBar2 ) + ")\nending: " + s_( ending_bar ) + " (" + s_( hBar ) + ")\ntrendline high: " + s_( trendline_bar_high ) + "\ntrendline low: " + s_( trendline_bar_low ) + "\nhighest: " + s_( highest ) + "\nlowest: " + s_( lowest ) + "\ntime: " + s_( time ) + "\nx1: " + s_( x1_high ) + ", x2: " + s_( x2_high ) + "\nhigh: " + str.tostring( is_swing_high ) + ", low: " + str.tostring( is_swing_low ) ) // remove the oldest trendline along with its label and add a new one if array.size( untested ) == untested_max line.delete( array.pop( untested ) ) if label_text != "" label.delete( array.pop( labels_untested ) ) if y_high > -1 //f_debug_label_down( s_( x1_high ) + " / " + s_( x2_high ) ) newLine = line.new( x1_high, y_high, x2_high, y_high, xloc = xloc_high, color = i_line_color_untested, width = i_line_size_untested, style = i_line_style_untested, extend = i_line_extend_untested ? extend.right : extend.none ) array.unshift( untested, newLine ) // check if we should make the previous trendline off-chart if untested_lines_on_chart > 0 and array.size( untested ) > untested_lines_on_chart line2change = array.get( untested, untested_lines_on_chart ) f_move_line_off_chart( line2change ) // store this label's original X in case we need to return it there matrix.add_row( labels_orig_x ) matrix.set( labels_orig_x, matrix.rows( labels_orig_x ) - 1, 0, x1_high ) matrix.set( labels_orig_x, matrix.rows( labels_orig_x ) - 1, 1, y_high ) // add label, if any if label_text != "" array.unshift( labels_untested, label.new( bar_index + i_text_offset, y_high, label_text + ( i_show_price_on_labels ? " (" + s_( line.get_y1( newLine ) ) + ")" : ""), size = label_size, textcolor = ( untested_show_label ? i_line_color_untested : transparentcolor ), textalign = text.align_right, style = label.style_none ) ) //array.unshift( labels_untested, label.new( bar_index + i_text_offset, y_high, label_text + ( i_show_price_on_labels ? " (" + s_( line.get_y1( newLine ) ) + ")" : "") + " / " + s_( x1_high ), size = label_size, textcolor = ( untested_show_label ? i_line_color_untested : transparentcolor ), textalign = text.align_right, style = label.style_none ) ) if y_low > -1 newLine = line.new( x1_low, y_low, x2_low, y_low, xloc = xloc_low, color = i_line_color_untested, width = i_line_size_untested, style = i_line_style_untested, extend = i_line_extend_untested ? extend.right : extend.none ) array.unshift( untested, newLine ) // check if we should make the previous trendline off-chart if untested_lines_on_chart > 0 and array.size( untested ) > untested_lines_on_chart line2change = array.get( untested, untested_lines_on_chart ) f_move_line_off_chart( line2change ) // store this label's original X in case we need to return it there matrix.add_row( labels_orig_x ) matrix.set( labels_orig_x, matrix.rows( labels_orig_x ) - 1, 0, x1_low ) matrix.set( labels_orig_x, matrix.rows( labels_orig_x ) - 1, 1, y_low ) // add label, if any if label_text != "" //array.unshift( labels_untested, label.new( bar_index + i_text_offset, y_low, label_text + ( i_show_price_on_labels ? " (" + s_( line.get_y1( newLine ) ) + ")" : "") + " / " + s_( x1_low ), size = label_size, textcolor = ( untested_show_label ? i_line_color_untested : transparentcolor ), textalign = text.align_right, style = label.style_none ) ) array.unshift( labels_untested, label.new( bar_index + i_text_offset, y_low, label_text + ( i_show_price_on_labels ? " (" + s_( line.get_y1( newLine ) ) + ")" : ""), size = label_size, textcolor = ( untested_show_label ? i_line_color_untested : transparentcolor ), textalign = text.align_right, style = label.style_none ) ) // check all previously untested trendlines to see if we should promote them to touched or mitigated, if enabled if array.size( untested ) > 0 loop_index = 0 untested_items_left = array.new_line() untested_labels_left = array.new_label() for untested_line in untested // don't check the newly added untested trendline, if one was just added if ( hOpen < line.get_y1( untested_line ) and hHigh >= line.get_y1( untested_line ) ) or ( hOpen > line.get_y1( untested_line ) and hLow <= line.get_y1( untested_line ) ) if touched_max > 0 and ( hOpen < line.get_y1( untested_line ) and hHigh == line.get_y1( untested_line ) ) or ( hOpen > line.get_y1( untested_line ) and hLow == line.get_y1( untested_line ) ) line.set_color( untested_line, i_line_color_touched ) line.set_width( untested_line, i_line_size_touched ) line.set_style( untested_line, i_line_style_touched ) line.set_extend( untested_line, i_line_extend_touched ? extend.right : extend.none ) // check if we should make the previous trendline off-chart if touched_lines_on_chart > 0 and array.size( touched ) > touched_lines_on_chart line2change = array.get( touched, touched_lines_on_chart ) f_move_line_off_chart( line2change ) // remove the oldest trendline with its label if we're full if array.size( touched ) == touched_max removedLine = array.pop( touched ) f_remove_orig_x_for_y( line.get_y1( removedLine ), labels_orig_x ) line.delete( removedLine ) if label_text != "" label.delete( array.pop( labels_touched ) ) array.unshift( touched, untested_line ) // change label color and move it to mitigated if label_text != "" label_to_move = array.get( labels_untested, loop_index ) array.unshift( labels_touched, label_to_move ) label.set_textcolor(label_to_move, touched_show_label ? i_line_color_touched : transparentcolor ) loop_index := loop_index + 1 else if mitigated_max > 0 // if we don't have touched enabled but we do have mitigated enabled OR when we crossed the price directly, move this to mitigated line.set_color( untested_line, i_line_color_mitigated ) line.set_width( untested_line, i_line_size_mitigated ) line.set_style( untested_line, i_line_style_mitigated ) line.set_extend( untested_line, i_line_extend_mitigated ? extend.right : extend.none ) // check if we should make the previous trendline off-chart if mitigated_lines_on_chart > 0 and array.size( mitigated ) > mitigated_lines_on_chart line2change = array.get( mitigated, mitigated_lines_on_chart ) f_move_line_off_chart( line2change ) // remove the oldest trendline with its label if we're full if array.size( mitigated ) == mitigated_max removedLine = array.pop( mitigated ) f_remove_orig_x_for_y( line.get_y1( removedLine ), labels_orig_x ) line.delete( removedLine ) if label_text != "" label.delete( array.pop( labels_mitigated ) ) array.unshift( mitigated, untested_line ) // change label color and move it to mitigated if label_text != "" label_to_move = array.get( labels_untested, loop_index ) array.unshift( labels_mitigated, label_to_move ) label.set_textcolor(label_to_move , mitigated_show_label ? i_line_color_mitigated : transparentcolor ) loop_index := loop_index + 1 else f_remove_orig_x_for_y( line.get_y1( untested_line ), labels_orig_x ) line.delete( untested_line ) if label_text != "" label.delete( array.get( labels_untested, loop_index ) ) else array.push( untested_items_left, untested_line ) if label_text != "" array.push( untested_labels_left, array.get( labels_untested, loop_index ) ) loop_index := loop_index + 1 // re-populate the untested array if we've touched or mitigated some of its lines if array.size( untested ) != array.size( untested_items_left ) array.clear( untested ) if label_text != "" array.clear( labels_untested ) loop_index2 = 0 for new_untested_line in untested_items_left array.push( untested, new_untested_line ) if label_text != "" array.push( labels_untested, array.get( untested_labels_left, loop_index2 ) ) loop_index2 := loop_index2 + 1 // check all previously touched trendlines to see if we should promote them to mitigated, if enabled if array.size( touched ) > 0 loop_index = 0 touched_items_left = array.new_line() touched_labels_left = array.new_label() for touched_line in touched if ( hOpen < line.get_y1( touched_line ) and hHigh > line.get_y1( touched_line ) ) or ( hOpen > line.get_y1( touched_line ) and hLow < line.get_y1( touched_line ) ) if mitigated_max > 0 line.set_color( touched_line, i_line_color_mitigated ) line.set_width( touched_line, i_line_size_mitigated ) line.set_style( touched_line, i_line_style_mitigated ) line.set_extend( touched_line, i_line_extend_mitigated ? extend.right : extend.none ) // check if we should make the previous trendline off-chart if touched_lines_on_chart > 0 and array.size( touched ) > touched_lines_on_chart line2change = array.get( touched, touched_lines_on_chart ) f_move_line_off_chart( line2change ) // remove the oldest trendline with its label if we're full if array.size( mitigated ) == mitigated_max removedLine = array.pop( mitigated ) f_remove_orig_x_for_y( line.get_y1( removedLine ), labels_orig_x ) line.delete( removedLine ) if label_text != "" label.delete( array.pop( labels_mitigated ) ) array.unshift( mitigated, touched_line ) // change label color and move it to mitigated if label_text != "" label_to_move = array.get( labels_touched, loop_index ) array.unshift( labels_mitigated, label_to_move ) label.set_textcolor(label_to_move , mitigated_show_label ? i_line_color_mitigated : transparentcolor ) loop_index := loop_index + 1 else f_remove_orig_x_for_y( line.get_y1( touched_line ), labels_orig_x ) line.delete( touched_line ) if label_text != "" label.delete( array.get( labels_touched, loop_index ) ) else array.push( touched_items_left, touched_line ) if label_text != "" array.push( touched_labels_left, array.get( labels_touched, loop_index ) ) loop_index := loop_index + 1 // re-populate the touched array if we've touched or mitigated some of its lines if array.size( touched ) != array.size( touched_items_left ) array.clear( touched ) if label_text != "" array.clear( labels_touched ) loop_index2 = 0 for new_touched_line in touched_items_left array.push( touched, new_touched_line ) if label_text != "" array.push( labels_touched, array.get( touched_labels_left, loop_index2 ) ) loop_index2 := loop_index2 + 1 [ untested, touched, mitigated, labels_untested, labels_touched, labels_mitigated, labels_orig_x ] f_extend_lines_to_current_bar( which ) => ret = true string tf = na array<line> untested = na int untested_lines_on_chart = na array<line> touched = na array<label> labels_touched = na int touched_lines_on_chart = na array<line> mitigated = na array<label> labels_mitigated = na int mitigated_lines_on_chart = na matrix<float> labels_orig_x = na if which == 1 untested := untested_t1 touched := touched_t1 mitigated := mitigated_t1 untested_lines_on_chart := i_untested_display_off_chart_t1 ? -1 : 0 touched_lines_on_chart := i_touched_display_off_chart_t1 ? -1 : 0 mitigated_lines_on_chart := i_mitigated_display_off_chart_t1 ? -1 : 0 labels_orig_x := labels_orig_x_t1 if which == 2 untested := untested_t2 touched := touched_t2 mitigated := mitigated_t2 untested_lines_on_chart := i_untested_display_off_chart_t2 ? -1 : 0 touched_lines_on_chart := i_touched_display_off_chart_t2 ? -1 : 0 mitigated_lines_on_chart := i_mitigated_display_off_chart_t2 ? -1 : 0 labels_orig_x := labels_orig_x_t2 if which == 3 untested := untested_t3 touched := touched_t3 mitigated := mitigated_t3 untested_lines_on_chart := i_untested_display_off_chart_t3 ? -1 : 0 touched_lines_on_chart := i_touched_display_off_chart_t3 ? -1 : 0 mitigated_lines_on_chart := i_mitigated_display_off_chart_t3 ? -1 : 0 labels_orig_x := labels_orig_x_t3 if which == 4 untested := untested_t4 touched := touched_t4 mitigated := mitigated_t4 untested_lines_on_chart := i_untested_display_off_chart_t4 ? -1 : 0 touched_lines_on_chart := i_touched_display_off_chart_t4 ? -1 : 0 mitigated_lines_on_chart := i_mitigated_display_off_chart_t4 ? -1 : 0 labels_orig_x := labels_orig_x_t4 counter = 1 for untested_line in untested if ( untested_lines_on_chart > 0 and counter > untested_lines_on_chart ) or untested_lines_on_chart == -1 f_move_line_off_chart( untested_line ) else // if this line was previously off-chart, move it back if line.get_x1( untested_line ) == bar_index + i_text_offset - 2 f_return_line_to_chart( untested_line, line.get_y1( untested_line ), labels_orig_x ) line.set_x2( untested_line, time ) counter := counter + 1 counter := 1 for touched_line in touched if ( touched_lines_on_chart > 0 and counter > touched_lines_on_chart ) or touched_lines_on_chart == -1 f_move_line_off_chart( touched_line ) else // if this line was previously off-chart, move it back if line.get_x1( touched_line ) == bar_index + i_text_offset - 2 f_return_line_to_chart( touched_line, line.get_y1( touched_line ), labels_orig_x ) line.set_x2( touched_line, time ) counter := counter + 1 counter := 1 for mitigated_line in mitigated if ( mitigated_lines_on_chart > 0 and counter > mitigated_lines_on_chart ) or mitigated_lines_on_chart == -1 f_move_line_off_chart( mitigated_line ) else // if this line was previously off-chart, move it back if line.get_x1( mitigated_line ) == bar_index + i_text_offset - 2 f_return_line_to_chart( mitigated_line, line.get_y1( mitigated_line ), labels_orig_x ) line.set_x2( mitigated_line, time ) counter := counter + 1 ret f_extend_labels_to_current_bar( labels_untested_array, labels_touched_array, labels_mitigated_array ) => ret = true for lab in labels_untested_array label.set_x( lab, bar_index + i_text_offset ) for lab in labels_touched_array label.set_x( lab, bar_index + i_text_offset ) for lab in labels_mitigated_array label.set_x( lab, bar_index + i_text_offset ) ret // LOGIC errors = array.new_string() if i_use_tf1 if timeframe.in_seconds( timeframe.period ) <= timeframe.in_seconds( i_tf_t1 ) [ untested, touched, mitigated, labels_untested, labels_touched, labels_mitigated, labels_orig_x ] = f_check_trendlines( 1, i_tf_t1 ) untested_t1 := untested touched_t1 := touched mitigated_t1 := mitigated labels_untested_t1 := labels_untested labels_touched_t1 := labels_touched labels_mitigated_t1 := labels_mitigated labels_orig_x_t1 := labels_orig_x f_extend_lines_to_current_bar( 1 ) f_extend_labels_to_current_bar( labels_untested_t1, labels_touched_t1, labels_mitigated_t1 ) else array.push( errors, "Timeframe 1 on lower timeframe than current - not showing trendlines") if i_use_tf2 if timeframe.in_seconds( timeframe.period ) <= timeframe.in_seconds( i_tf_t2 ) [ untested, touched, mitigated, labels_untested, labels_touched, labels_mitigated, labels_orig_x ] = f_check_trendlines( 2, i_tf_t2 ) untested_t2 := untested touched_t2 := touched mitigated_t2 := mitigated labels_untested_t2 := labels_untested labels_touched_t2 := labels_touched labels_mitigated_t2 := labels_mitigated labels_orig_x_t2 := labels_orig_x f_extend_lines_to_current_bar( 2 ) f_extend_labels_to_current_bar( labels_untested_t2, labels_touched_t2, labels_mitigated_t2 ) else array.push( errors, "Timeframe 2 on lower timeframe than current - not showing trendlines") if i_use_tf3 if timeframe.in_seconds( timeframe.period ) <= timeframe.in_seconds( i_tf_t3 ) [ untested, touched, mitigated, labels_untested, labels_touched, labels_mitigated, labels_orig_x ] = f_check_trendlines( 3, i_tf_t3 ) untested_t3 := untested touched_t3 := touched mitigated_t3 := mitigated labels_untested_t3 := labels_untested labels_touched_t3 := labels_touched labels_mitigated_t3 := labels_mitigated labels_orig_x_t3 := labels_orig_x f_extend_lines_to_current_bar( 3 ) f_extend_labels_to_current_bar( labels_untested_t3, labels_touched_t3, labels_mitigated_t3 ) else array.push( errors, "Timeframe 3 on lower timeframe than current - not showing trendlines") if i_use_tf4 if timeframe.in_seconds( timeframe.period ) <= timeframe.in_seconds( i_tf_t4 ) [ untested, touched, mitigated, labels_untested, labels_touched, labels_mitigated, labels_orig_x ] = f_check_trendlines( 4, i_tf_t4 ) untested_t4 := untested touched_t4 := touched mitigated_t4 := mitigated labels_untested_t4 := labels_untested labels_touched_t4 := labels_touched labels_mitigated_t4 := labels_mitigated labels_orig_x_t4 := labels_orig_x f_extend_lines_to_current_bar( 4 ) f_extend_labels_to_current_bar( labels_untested_t4, labels_touched_t4, labels_mitigated_t4 ) else array.push( errors, "Timeframe 4 on lower timeframe than current - not showing trendlines") if array.size( errors ) > 0 var err_table = table.new(position = position.bottom_right, columns = 1, rows = array.size( errors ), border_width = 1) for i = 0 to array.size( errors ) - 1 table.cell(table_id = err_table, column = 0, row = i , text = array.get( errors, i ), bgcolor=color.black, text_color=color.white, text_halign = text.align_left)
NIFTY IT volume
https://www.tradingview.com/script/z4YXPZ3L-NIFTY-IT-volume/
bullseyetrading_lko
https://www.tradingview.com/u/bullseyetrading_lko/
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/ // © carefulTortois38674 //@version=5 indicator('IT volume', timeframe='', format=format.volume) barColorsOnPrevClose = input(title='Color bars based on previous close', defval=false) palette = barColorsOnPrevClose ? close[1] > close ? color.red : color.green : open > close ? color.red : color.green a = request.security('NSE:COFORGE', timeframe.period, volume) b = request.security('NSE:HCLTECH', timeframe.period, volume) c = request.security('NSE:INFY', timeframe.period, volume) d = request.security('NSE:LTI', timeframe.period, volume) e = request.security('NSE:LTTS', timeframe.period, volume) f = request.security('NSE:MPHASIS', timeframe.period, volume) g = request.security('NSE:PERSISTENT', timeframe.period, volume) h = request.security('NSE:TCS', timeframe.period, volume) i = request.security('NSE:TECHM', timeframe.period, volume) j = request.security('NSE:WIPRO', timeframe.period, volume) IT_volume = a + b + c + d + e + f + g + h + i + j IT_average = ta.sma(IT_volume, length=input(defval=10)) plot(IT_volume, color=palette, style=plot.style_columns, title='IT volume') plot(IT_average, color=color.new(color.black, 0), title='moving average') plot(close)
Converging Pullbacks and Peaks
https://www.tradingview.com/script/3sEKDcUT-Converging-Pullbacks-and-Peaks/
EsIstTurnt
https://www.tradingview.com/u/EsIstTurnt/
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/ // © EsIstTurnt //@version=5 indicator("Converging Pullbacks and Peaks",overlay=true) //Multi Timeframe Converging Lines Indicator. Using the highest/lowest Values at 2 seperate lengths, //all changeable in settings. Convergence created by taking the highest/lowest value and subtracting/adding the # of bars //since the highest/lowest bar was set multiplied by the price multiplied by the float. //Curves are created from averaging out the emas of the center lines of the extremeties. //Helps show trendlines automatically alot of the time but can be tweaked by changing the floats or Fast/Slow lengths tf1=input.timeframe('60') tf2=input.timeframe('640') float1=input.float(0.0000618,"Converge Float TimeFrame 1",step=0.00001) float2=input.float(0.0000618,"Converge Float TimeFrame 2",step=0.00001) bool1=input.bool(true,'Enable TimeFrame 1') bool2=input.bool(true,'Enable TimeFrame 2') bool3=input.bool(true,'Fast') bool4=input.bool(true,'Slow') bool5=input.bool(false,'Curves') bool6=input.bool(false,'Toggle Custom Source') src=input.source(close,'Custom Sourcing') Fast=input.int(64,'Fast Length') Slow=input.int(256,'Slow Length') //TimeFrame 1 highest and lowest values high1a =request.security(syminfo.ticker,tf1,ta.highest(bool6 ?src : high,Fast )) low1a =request.security(syminfo.ticker,tf1,ta.lowest (bool6 ?src : low ,Fast )) high2a =request.security(syminfo.ticker,tf1,ta.highest(bool6 ?src : high,Slow )) low2a =request.security(syminfo.ticker,tf1,ta.lowest (bool6 ?src : low ,Slow )) //TimeFrame 2 highest and lowest values high1b =request.security(syminfo.ticker,tf2,ta.highest(bool6 ?src : high,Fast )) low1b =request.security(syminfo.ticker,tf2,ta.lowest (bool6 ?src : low ,Fast )) high2b =request.security(syminfo.ticker,tf2,ta.highest(bool6 ?src : high,Slow )) low2b =request.security(syminfo.ticker,tf2,ta.lowest (bool6 ?src : low ,Slow )) //Count since new Highs , Lows new_high1a=ta.barssince(high1a==high ) new_high1b=ta.barssince(high1b==high ) new_high2a=ta.barssince(high2a==high ) new_high2b=ta.barssince(high2b==high ) new_low1a =ta.barssince(low1a ==low ) new_low1b =ta.barssince(low1b ==low ) new_low2a =ta.barssince(low2a ==low ) new_low2b =ta.barssince(low2b ==low ) //get the value of the highest/lowest high/low in 4 bars when a new high/low occurs, and add/subtract //the Bar counters above and multiply by its price roughly and multiply by a float //highs subtract , lows add for converging lines hformula1a=ta.valuewhen(high1a==high,ta.highest(high,4),1) - (new_high1a * ta.swma(ta.vwap(close) * (float1))) hformula1b=ta.valuewhen(high1b==high,ta.highest(high,4),1) - (new_high1b * ta.swma(ta.vwap(close) * (float1))) hformula2a=ta.valuewhen(high2a==high,ta.highest(high,4),1) - (new_high2a * ta.swma(ta.vwap(close) * (float2))) hformula2b=ta.valuewhen(high2b==high,ta.highest(high,4),1) - (new_high2b * ta.swma(ta.vwap(close) * (float2))) lformula1a=ta.valuewhen(low1a ==low ,ta.lowest(low,4),1) + (new_low1a * ta.swma(ta.vwap(close) * (float1))) lformula1b=ta.valuewhen(low1b ==low ,ta.lowest(low,4),1) + (new_low1b * ta.swma(ta.vwap(close) * (float1))) lformula2a=ta.valuewhen(low2a ==low ,ta.lowest(low,4),1) + (new_low2a * ta.swma(ta.vwap(close) * (float2))) lformula2b=ta.valuewhen(low2b ==low ,ta.lowest(low,4),1) + (new_low2b * ta.swma(ta.vwap(close) * (float2))) //get the centerlines, average it all up and apply an ema avg1=math.avg(hformula1a,lformula1a) avg2=math.avg(hformula2a,lformula2a) avg3=math.avg(hformula1b,lformula1b) avg4=math.avg(hformula2b,lformula2b) centercurve=ta.linreg(ta.swma(math.avg(avg1,avg4,avg3,avg2)),Slow/2,0) curve1 =ta.ema(centercurve,Slow) curve2 =ta.ema(centercurve[Fast],Fast) cond1=curve1>curve2 //Plotting plot(bool1?bool3?hformula1a:na:na,style=plot.style_circles,color=color.new(hformula1a<=hformula1a[4]?#acfb00:na,75)) plot(bool2?bool4?hformula1b:na:na,style=plot.style_cross,color=color.new(hformula1b<=hformula1b[4] ?#ff0000:na,85)) plot(bool1?bool3?hformula2a:na:na,style=plot.style_circles,color=color.new(hformula1a<=hformula1a[4]?color.olive:na ,75)) plot(bool2?bool4?hformula2b:na:na,style=plot.style_cross,color=color.new(hformula2b<=hformula2b[4] ?color.orange:na,85)) plot(bool1?bool3?lformula1a:na:na,style=plot.style_circles,color=color.new(lformula1a>=lformula1a[4]?#acfb00:na,75)) plot(bool2?bool4?lformula1b:na:na,style=plot.style_cross,color=color.new(lformula1b>=lformula1b[4] ?#ff0000:na,85)) plot(bool1?bool3?lformula2a:na:na,style=plot.style_circles,color=color.new(lformula2a<=lformula2a[4]?color.olive:na ,75)) plot(bool2?bool4?lformula2b:na:na,style=plot.style_cross,color=color.new(lformula2b>=lformula2b[4] ?color.orange:na,85)) centercurve1 = plot( curve1,color =bool5?math.round(avg3) == math.round(avg3[1]) and math.round(avg3)==math.round(avg3[4]) ?avg3<close?#acfb00:#ff0000:color.orange:na,style=plot.style_linebr) centercurve2 = plot( curve2,color =bool5? math.round(avg4) == math.round(avg4[1]) and math.round(avg4)==math.round(avg4[4]) ?avg4 < close?#acfb00:#ff0000:color.orange:na,style=plot.style_linebr) color=color.new(bool5?cond1?#ff0000:#acfb00:na,80) fill(centercurve1,centercurve2,color=color)
Outback RSI & Hull [TTF]
https://www.tradingview.com/script/yrK0aSQh-Outback-RSI-Hull-TTF/
TheTrdFloor
https://www.tradingview.com/u/TheTrdFloor/
506
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/ // © TheTrdFloor // // We built this indicator to help simplify some of the setup for our Outback strategy, was many were having trouble setting up the // Hull Suite on top of the RSI using the Indicator on Indicator method. // //@version=5 indicator(title="Outback RSI & Hull [TTF]", shorttitle="Outback RSI & Hull [TTF]", format=format.price, precision=2, timeframe="", timeframe_gaps=true) ///////////////////////////// Standard RSI ///////////////////////////// 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) rsiLengthInput = input.int(618, minval=1, title="RSI Length", group="RSI Settings") rsiSourceInput = input.source(close, "Source", group="RSI Settings") rsitrigger = input.int(50, title="RSI Trigger Level", group="RSI Settings", tooltip="RSI Trigger Level for safe entry") usersitrigger = input.bool(false, title="Display Safe Entries", group="RSI Settings", tooltip="If activated, background coloring will differentiate between risk entry and safe entry (RSI above/below RSI trigger level") maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings") maLengthInput = input.int(200, title="MA Length", group="MA Settings") bbMultInput = input.float(2.0, minval=0.001, maxval=50, 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)) rsiMA = ma(rsi, maLengthInput, maTypeInput) isBB = maTypeInput == "Bollinger Bands" plot(rsi, "RSI", color=#7E57C2) plot(rsiMA, "RSI-based MA", color=color.white) hline(50, "RSI Middle Band", color=color.new(#787B86, 50)) ///////////////////////////// Hull Suite by Insilico /////////////////////////////////// length3 = input(227, title='MA Length', group = "Hull Suite") lengthMult = input(2.0, title="Length multiplier", group = "Hull Suite") MHULL = ta.wma(2 * ta.wma(rsi,int(length3 * lengthMult) / 2) - ta.wma(rsi, int(length3 * lengthMult)), math.round(math.sqrt(int(length3 * lengthMult)))) plot(MHULL, "Hull", color=color.yellow) ///////////////////////////// Background filled based on Outback Criteria /////////////////////////////////// riskentrylong = usersitrigger ? (rsi>rsiMA and rsi>MHULL and rsi<rsitrigger ? true : false) : rsi>rsiMA and rsi>MHULL ? true : false entrylong = rsi>rsiMA and rsi>MHULL and rsi>rsitrigger ? true : false riskentryshort = usersitrigger ? (rsi<rsiMA and rsi<MHULL and rsi>rsitrigger ? true : false) : rsi<rsiMA and rsi<MHULL ? true : false entryshort = rsi<rsiMA and rsi<MHULL and rsi<rsitrigger ? true : false bgcolor(riskentrylong ? color.new(#056656,50) : na, title="Risk Entry Long") bgcolor(entrylong and usersitrigger ? color.new(#00332a,50) : na, title="Safe Entry Long") bgcolor(riskentryshort ? color.new(#ff9800, 50) : na, title="Risk Entry Short") bgcolor(entryshort and usersitrigger ? color.new(#e65100, 50) : na, title="Safe Entry Short") ///// Adding alerts for risk entries m_alertMsgBull = "ORSI - Bullish" m_alertMsgBear = "ORSI - Bearish" alertcondition(riskentrylong and not riskentrylong[1] ? true : false, title=m_alertMsgBull, message=m_alertMsgBull) alertcondition(riskentryshort and not riskentryshort[1] ? true : false, title=m_alertMsgBear, message=m_alertMsgBear) // if (riskentrylong) // alert(message=m_alertMsgBull, freq=alert.freq_once_per_bar) // if (riskentryshort) // alert(message=m_alertMsgBear, freq=alert.freq_once_per_bar)
RTH & ETH VWAPs [vnhilton]
https://www.tradingview.com/script/kI63hLO9-RTH-ETH-VWAPs-vnhilton/
vnhilton
https://www.tradingview.com/u/vnhilton/
63
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("RTH & ETH VWAPs [vnhilton]", "RTH&ETH VWAPS", true) //RTH Timezone rth = time(timeframe.period, session.regular, syminfo.timezone) //Parameters ethRTHToggle = input.bool(false, "Hide ETH VWAP Lines During RTH Session?", "Recommended to turn on if using closest VWAP Bands") vwapSize = input.int(2, "VWAP Circle Size", 1) srcrth = input(hlc3, "Source For RTH VWAP", group="RTH Parameters") stddevRTHM1 = input.float(1, "STDDEV Bands Multiplier #1", 0, group="RTH Parameters") stddevRTHM2 = input.float(2, "STDDEV Bands Multiplier #2", 0, group="RTH Parameters") stddevRTHM3 = input.float(3, "STDDEV Bands Multiplier #3", 0, group="RTH Parameters") srceth = input(hlc3, "Source For ETH VWAP", group="ETH Parameters") stddevETHM1 = input.float(1, "STDDEV Bands Multiplier #1", 0, group="ETH Parameters") stddevETHM2 = input.float(2, "STDDEV Bands Multiplier #2", 0, group="ETH Parameters") stddevETHM3 = input.float(3, "STDDEV Bands Multiplier #3", 0, group="ETH Parameters") //Base VWAPs [vwapR1, upperR1, lowerR1] = ta.vwap(srcrth, timeframe.change("D"), stddevRTHM1) [vwapE1, upperE1, lowerE1] = ta.vwap(srceth, timeframe.change("D"), stddevRTHM1) [vwapR2, upperR2, lowerR2] = ta.vwap(srcrth, timeframe.change("D"), stddevRTHM2) [vwapE2, upperE2, lowerE2] = ta.vwap(srceth, timeframe.change("D"), stddevRTHM2) [vwapR3, upperR3, lowerR3] = ta.vwap(srcrth, timeframe.change("D"), stddevRTHM3) [vwapE3, upperE3, lowerE3] = ta.vwap(srceth, timeframe.change("D"), stddevRTHM3) //RTH & ETH VWAPs [rthVWAP1, rthVWAPUpper1, rthVWAPLower1] = request.security(ticker.modify(syminfo.tickerid, session.regular), timeframe.period, [vwapR1, upperR1, lowerR1]) [ethVWAP1, ethVWAPUpper1, ethVWAPLower1] = request.security(ticker.modify(syminfo.tickerid, session.extended), timeframe.period, [vwapE1, upperE1, lowerE1]) [rthVWAP2, rthVWAPUpper2, rthVWAPLower2] = request.security(ticker.modify(syminfo.tickerid, session.regular), timeframe.period, [vwapR2, upperR2, lowerR2]) [ethVWAP2, ethVWAPUpper2, ethVWAPLower2] = request.security(ticker.modify(syminfo.tickerid, session.extended), timeframe.period, [vwapE2, upperE2, lowerE2]) [rthVWAP3, rthVWAPUpper3, rthVWAPLower3] = request.security(ticker.modify(syminfo.tickerid, session.regular), timeframe.period, [vwapR3, upperR3, lowerR3]) [ethVWAP3, ethVWAPUpper3, ethVWAPLower3] = request.security(ticker.modify(syminfo.tickerid, session.extended), timeframe.period, [vwapE3, upperE3, lowerE3]) //Plots rthPlot = plot(rth ? rthVWAP1 : na, "RTH VWAP", color.rgb(255, 244, 1, 0), style=plot.style_linebr) plot(rthVWAP1 <= high and rthVWAP1 >= low and rth ? rthVWAP1 : na, "RTH VWAP Circles", color.rgb(255, 244, 1, 0), vwapSize, style=plot.style_circles) upperRPlot1 = plot(rth ? rthVWAPUpper1 : na, "Upper RTH VWAP Band #1", color.rgb(255, 244, 1, 50), style=plot.style_linebr) lowerRPlot1 = plot(rth ? rthVWAPLower1 : na, "Lower RTH VWAP Band #1", color.rgb(255, 244, 1, 50), style=plot.style_linebr) upperRPlot2 = plot(rth ? rthVWAPUpper2 : na, "Upper RTH VWAP Band #2", color.rgb(255, 244, 1, 55), style=plot.style_linebr) lowerRPlot2 = plot(rth ? rthVWAPLower2 : na, "Lower RTH VWAP Band #2", color.rgb(255, 244, 1, 55), style=plot.style_linebr) upperRPlot3 = plot(rth ? rthVWAPUpper3 : na, "Upper RTH VWAP Band #3", color.rgb(255, 244, 1, 60), style=plot.style_linebr) lowerRPlot3 = plot(rth ? rthVWAPLower3 : na, "Lower RTH VWAP Band #3", color.rgb(255, 244, 1, 60), style=plot.style_linebr) ethPlot = plot(ethRTHToggle ? rth ? na : ethVWAP1 : ethVWAP1, "ETH VWAP", color.rgb(255, 255, 255, 0), style=plot.style_linebr) plot(ethVWAP1 <= high and ethVWAP1 >= low ? ethVWAP1 : na, "ETH VWAP Circles", color.rgb(255, 255, 255, 0), vwapSize, style=plot.style_circles) upperEPlot1 = plot(ethRTHToggle ? rth ? na : ethVWAPUpper1 : ethVWAPUpper1, "Upper ETH VWAP Band #1", color.rgb(255, 255, 255, 50), style=plot.style_linebr) lowerEPlot1 = plot(ethRTHToggle ? rth ? na : ethVWAPLower1 : ethVWAPLower1, "Lower ETH VWAP Band #1", color.rgb(255, 255, 255, 50), style=plot.style_linebr) upperEPlot2 = plot(ethRTHToggle ? rth ? na : ethVWAPUpper2 : ethVWAPUpper2, "Upper ETH VWAP Band #2", color.rgb(255, 255, 255, 55), style=plot.style_linebr) lowerEPlot2 = plot(ethRTHToggle ? rth ? na : ethVWAPLower2 : ethVWAPLower2, "Lower ETH VWAP Band #2", color.rgb(255, 255, 255, 55), style=plot.style_linebr) upperEPlot3 = plot(ethRTHToggle ? rth ? na : ethVWAPUpper3 : ethVWAPUpper3, "Upper ETH VWAP Band #3", color.rgb(255, 255, 255, 60), style=plot.style_linebr) lowerEPlot3 = plot(ethRTHToggle ? rth ? na : ethVWAPLower3 : ethVWAPLower3, "Lower ETH VWAP Band #3", color.rgb(255, 255, 255, 60), style=plot.style_linebr) closestUPlot1 = plot(rth ? rthVWAPUpper1 < ethVWAPUpper1 ? rthVWAPUpper1 : ethVWAPUpper1 : na, "Closest VWAP Upper Band #1", color.rgb(255, 255, 255, 50), style=plot.style_linebr, display=display.none) closestDPlot1 = plot(rth ? rthVWAPLower1 >= ethVWAPLower1 ? rthVWAPLower1 : ethVWAPLower1 : na, "Closest VWAP Lower Band #1", color.rgb(255, 255, 255, 50), style=plot.style_linebr, display=display.none) closestUPlot2 = plot(rth ? rthVWAPUpper2 < ethVWAPUpper2 ? rthVWAPUpper2 : ethVWAPUpper2 : na, "Closest VWAP Upper Band #2", color.rgb(255, 255, 255, 55), style=plot.style_linebr, display=display.none) closestDPlot2 = plot(rth ? rthVWAPLower2 >= ethVWAPLower2 ? rthVWAPLower2 : ethVWAPLower2 : na, "Closest VWAP Lower Band #2", color.rgb(255, 255, 255, 55), style=plot.style_linebr, display=display.none) closestUPlot3 = plot(rth ? rthVWAPUpper3 < ethVWAPUpper3 ? rthVWAPUpper3 : ethVWAPUpper3 : na, "Closest VWAP Upper Band #3", color.rgb(255, 255, 255, 60), style=plot.style_linebr, display=display.none) closestDPlot3 = plot(rth ? rthVWAPLower3 >= ethVWAPLower3 ? rthVWAPLower3 : ethVWAPLower3 : na, "Closest VWAP Lower Band #3", color.rgb(255, 255, 255, 60), style=plot.style_linebr, display=display.none) fill(plot1=rthPlot, plot2=ethPlot, top_value=rthVWAP1 >= ethVWAP1 ? rthVWAP1 : ethVWAP1, bottom_value=rthVWAP1 >= ethVWAP1 ? ethVWAP1 : rthVWAP1, top_color=rthVWAP1 >= ethVWAP1 ? color.rgb(255, 244, 1, 90) : color.rgb(255, 255, 255, 100), bottom_color=rthVWAP1 >= ethVWAP1 ? color.rgb(255, 255, 255, 100) : color.rgb(255, 244, 1, 90), title="RTH & ETH VWAPs Plot Fill") fill(plot1=upperRPlot1, plot2=upperEPlot1, top_value=rthVWAPUpper1 >= ethVWAPUpper1 ? rthVWAPUpper1 : ethVWAPUpper1, bottom_value=rthVWAPUpper1 >= ethVWAPUpper1 ? ethVWAPUpper1 : rthVWAPUpper1, top_color=rthVWAPUpper1 >= ethVWAPUpper1 ? color.rgb(255, 244, 1, 90) : color.rgb(255, 255, 255, 100), bottom_color=rthVWAPUpper1 >= ethVWAPUpper1 ? color.rgb(255, 255, 255, 100) : color.rgb(255, 244, 1, 90), title="RTH & ETH VWAPs Upper Band #1 Plot Fill") fill(plot1=upperRPlot2, plot2=upperEPlot2, top_value=rthVWAPUpper2 >= ethVWAPUpper2 ? rthVWAPUpper2 : ethVWAPUpper2, bottom_value=rthVWAPUpper2 >= ethVWAPUpper2 ? ethVWAPUpper2 : rthVWAPUpper2, top_color=rthVWAPUpper2 >= ethVWAPUpper2 ? color.rgb(255, 244, 1, 90) : color.rgb(255, 255, 255, 100), bottom_color=rthVWAPUpper2 >= ethVWAPUpper2 ? color.rgb(255, 255, 255, 100) : color.rgb(255, 244, 1, 90), title="RTH & ETH VWAPs Upper Band #2 Plot Fill") fill(plot1=upperRPlot3, plot2=upperEPlot3, top_value=rthVWAPUpper3 >= ethVWAPUpper3 ? rthVWAPUpper3 : ethVWAPUpper3, bottom_value=rthVWAPUpper3 >= ethVWAPUpper3 ? ethVWAPUpper3 : rthVWAPUpper3, top_color=rthVWAPUpper3 >= ethVWAPUpper3 ? color.rgb(255, 244, 1, 90) : color.rgb(255, 255, 255, 100), bottom_color=rthVWAPUpper3 >= ethVWAPUpper3 ? color.rgb(255, 255, 255, 100) : color.rgb(255, 244, 1, 90), title="RTH & ETH VWAPs Upper Band #3 Plot Fill") fill(plot1=lowerRPlot1, plot2=lowerEPlot1, top_value=rthVWAPLower1 >= ethVWAPLower1 ? rthVWAPLower1 : ethVWAPLower1, bottom_value=rthVWAPLower1 >= ethVWAPLower1 ? ethVWAPLower1 : rthVWAPLower1, top_color=rthVWAPLower1 >= ethVWAPLower1 ? color.rgb(255, 244, 1, 90) : color.rgb(255, 255, 255, 100), bottom_color=rthVWAPLower1 >= ethVWAPLower1 ? color.rgb(255, 255, 255, 100) : color.rgb(255, 244, 1, 90), title="RTH & ETH VWAPs Lower Band #1 Plot Fill") fill(plot1=lowerRPlot2, plot2=lowerEPlot2, top_value=rthVWAPLower2 >= ethVWAPLower2 ? rthVWAPLower2 : ethVWAPLower2, bottom_value=rthVWAPLower2 >= ethVWAPLower2 ? ethVWAPLower2 : rthVWAPLower2, top_color=rthVWAPLower2 >= ethVWAPLower2 ? color.rgb(255, 244, 1, 90) : color.rgb(255, 255, 255, 100), bottom_color=rthVWAPLower2 >= ethVWAPLower2 ? color.rgb(255, 255, 255, 100) : color.rgb(255, 244, 1, 90), title="RTH & ETH VWAPs Lower Band #2 Plot Fill") fill(plot1=lowerRPlot3, plot2=lowerEPlot3, top_value=rthVWAPLower3 >= ethVWAPLower3 ? rthVWAPLower3 : ethVWAPLower3, bottom_value=rthVWAPLower3 >= ethVWAPLower3 ? ethVWAPLower3 : rthVWAPLower3, top_color=rthVWAPLower3 >= ethVWAPLower3 ? color.rgb(255, 244, 1, 90) : color.rgb(255, 255, 255, 100), bottom_color=rthVWAPLower3 >= ethVWAPLower3 ? color.rgb(255, 255, 255, 100) : color.rgb(255, 244, 1, 90), title="RTH & ETH VWAPs Lower Band #3 Plot Fill")
Normalized Volume
https://www.tradingview.com/script/1npbvr6U-Normalized-Volume/
bjr117
https://www.tradingview.com/u/bjr117/
34
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/ // © bjr117 //@version=5 indicator(title = "Normalized Volume", shorttitle = "NVOL", overlay = false) //============================================================================== // User inputs //============================================================================== nvol_ma_length = input.int(title = "Normalized Volume MA Length", defval = 14) //============================================================================== //============================================================================== // Calculating the normalized volume //============================================================================== // Calculate cumulative volume to see if there is any volume at all in the selected instrument // Throw an error if there is no volume data in the selected instrument var cumulative_vol = 0.0 cumulative_vol += nz(volume) if barstate.islast and cumulative_vol == 0 runtime.error("No volume is provided by the data vendor.") // Calculate a moving average of volume nvol_ma = ta.sma(volume, nvol_ma_length) // Calculate normalized volume // Normalized volume = current volume / average volume * 100 nvol = volume / nvol_ma * 100 //============================================================================== //============================================================================== // Plot the normalized volume //============================================================================== // Calculate the color for each of the normalized volume columns nvol_color = nvol > 100 ? color.green : color.red // Plot the normalized volume with the appropriate colored columns plot(nvol, title = "Normalized Volume", color = nvol_color, style = plot.style_columns) //==============================================================================
Normalized Volatility
https://www.tradingview.com/script/Gj8qaKLO-Normalized-Volatility/
bjr117
https://www.tradingview.com/u/bjr117/
26
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/ // © bjr117 //@version=5 indicator(title = "Normalized Volatility", shorttitle = "NVOLT", overlay = false) //============================================================================== // User inputs //============================================================================== nvolt_ma_length = input.int(title = "Normalized Volatility MA Length", defval = 14) //============================================================================== //============================================================================== // Calculating the normalized volatility //============================================================================== // Calculate the volatility in the market nvolt_volatility = ta.tr // Calculate a moving average of volatility nvolt_ma = ta.sma(nvolt_volatility, nvolt_ma_length) // Calculate normalized volatility // Normalized volatility = current volatility / average volatility * 100 nvolt = nvolt_volatility / nvolt_ma * 100 //============================================================================== //============================================================================== // Plot the normalized volatility //============================================================================== // Calculate the color for each of the normalized volatility columns nvolt_color = nvolt > 100 ? color.green : color.red // Plot the normalized volatility with the appropriate colored columns plot(nvolt, title = "Normalized Volatility", color = nvolt_color, style = plot.style_columns) //==============================================================================
RRP Daily
https://www.tradingview.com/script/HJryJ0o9-RRP-Daily/
Nyanderfull
https://www.tradingview.com/u/Nyanderfull/
38
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/ // © Nyanderfull //@version=4 study("RRP Flex", format = format.volume, max_labels_count=100) //Input / Colors and Base lines plot_lineWidth = input(1, " Line Width", input.integer, minval=1, maxval=11 ) p1 = plot(0, title="Baseline", linewidth = 0, color=#00000000, display=display.none) hline(0,color=#FFFFFF35,linestyle=hline.style_solid) startofnewmonth = month != month[1] startofnewday = dayofweek != dayofweek[1] //////US////// US_TreasuryMA = security("TREASURY", "1D", close) //in billions US_TreasuryWed = security("WDTGAL", "1D", close) //in millions US_TreasuryWA = security("WTREGEN", "1D", close) //in billions US_EFFR = security("FEDFUNDS", "1D", close[1]) //Rate: no change in % US_SOFR = security("SOFR", "1D", close[1]) //Rate: no change in % US_OBFR = security("OBFR", "1D", close[1]) //Rate: no change in % US_EFFRVOL = security("EFFRVOL", "1D", close) //in billions US_SOFRVOL = security("SOFRVOL", "1D", close) //in billions US_OBFRVOL = security("OBFRVOL", "1D", close) //in billions US_RCVOL = (US_EFFRVOL + US_OBFRVOL) US_ORRP = security("RRPONTTLD", "1D", close) //in billions US_ORRPR = security("RRPONTSYAWARD", "1D", close[1]) //no change, in % US_LRRP = security("WLRRAL", "1D", close) //in millions US_IRRP = security("WLRRAFOIAL", "1D", close) //in millions US_MMFSRP = security("BOGZ1FL632051103Q", "1D", close) //in millions US_ELRRP = US_ORRP + US_IRRP /////Input / Colors //US_Treasury_plot_color = input(title="US Treasury Monthly", type=input.color, defval=#CCFFFF) //CCFFFF //US_MMFSRP_plot_color = input(title="US MMF SRP", type=input.color, defval=#FF26FF) //FF26FF US_Treasury_plot_color1 = input(title="US Treasury Wednsday", type=input.color, defval=#00FFFF) //00FFFF US_Treasury_plot_color2 = input(title="US Treasury Weekly", type=input.color, defval=color.yellow) //yellow // US_EFFRVOL_plot_color = input(title="US EFFR Volume", type=input.color, defval=color.green) //green // US_OBFRVOL_plot_color = input(title="US OBFR Volume", type=input.color, defval=color.green) //green US_SOFRVOL_plot_color = input(title="US SOFR Volume", type=input.color, defval=color.green) //green US_RCVOL_plot_color = input(title="US RCVOL", type=input.color, defval=color.lime) //lime US_ORRP_plot_color = input(title="US Overnight RRP", type=input.color, defval=#4801ff) //0026FF US_IRRP_plot_color = input(title="US Foreign RRP", type=input.color, defval=#CD26FF) //CD26FF US_LRRP_plot_color = input(title="US Liabilities RRP", type=input.color, defval=#ff02ff) //5D26FF US_ELRRP_plot_color = input(title="US Expected RRP", type=input.color, defval=#ff0143) //color.red /////Plots //US_MMFSRP_plot = plot(US_MMFSRP, title="US - Money Market Fund SRP (3 Months)", color=US_MMFSRP_plot_color, linewidth = plot_lineWidth, display=display.none), //US_Treasury_plot = plot(US_TreasuryMA, title="US - Treasury Deposits (Montly Average)", color=US_Treasury_plot_color, linewidth = plot_lineWidth, display=display.all), //fill(US_Treasury_plot, p1, color=color.blue) US_TreasuryFR_plot = plot(US_TreasuryWed, title="US - Treasury Deposits (Wednesday)", color=US_Treasury_plot_color1, linewidth = plot_lineWidth, display=display.all), US_Treasuryhh_plot = plot(US_TreasuryWA, title="US - Treasury Deposits (Weekly Average)", color=US_Treasury_plot_color2, linewidth = plot_lineWidth, display=display.all), US_RCVOL_plot = plot(US_RCVOL, title="US - EFFR + OBFR Volume (Daily)", color=US_RCVOL_plot_color, linewidth = plot_lineWidth) US_SOFRVOL_plot = plot(US_SOFRVOL, title="US - SOFR Volume (Daily)", color=US_SOFRVOL_plot_color, linewidth = plot_lineWidth) US_ORRP_plot = plot(US_ORRP, title="US - Total Overnight RRP (Daily)", color=US_ORRP_plot_color, linewidth = plot_lineWidth, display=display.all), US_IRRP_plot = plot(US_IRRP, title="US - Foreign / International RRP (Wednesday)", color=US_IRRP_plot_color, linewidth = plot_lineWidth, display=display.all), US_LRRP_plot = plot(US_LRRP, title="US - Liabilities RRP (Wednesday)", color=US_LRRP_plot_color, linewidth = plot_lineWidth, display=display.all), US_ELRRP_plot = plot(US_ELRRP, title="US - Expected Liabilities RRP (International + Overnight)", color=US_ELRRP_plot_color, linewidth = plot_lineWidth, display=display.all), US_LRRPtoELRRP_plot = plot((US_LRRP==US_ELRRP) and startofnewday ? US_ELRRP : na, title="Liabilities overlap", color=US_ELRRP_plot_color, style=plot.style_circles, linewidth=plot_lineWidth+2, display=display.none) /////labels //EFFR / SOFR / OBFR rates monthly if ((US_RCVOL != 0) and startofnewmonth) string US_RCVOL_Label_Text = "MONTHLY RATES\n"+ tostring(US_EFFR)+"% EFFR\n"+ tostring(US_SOFR)+"% SOFR\n"+ tostring(US_OBFR)+"% OBFR" label.new(x=bar_index, y=0, text=US_RCVOL_Label_Text, yloc=yloc.price, color=US_RCVOL_plot_color, style=label.style_label_up, textcolor=color.white) //RRP Award Rate if ((US_ORRPR != US_ORRPR[1]) and startofnewday) string US_ORRPR_Text = "ORRP Award\n"+tostring(US_ORRPR)+"%" label.new(x=bar_index, y=US_ELRRP, text=US_ORRPR_Text, yloc=yloc.price, color=US_ELRRP_plot_color, textcolor=color.white)
Bearish Market Indicator V2
https://www.tradingview.com/script/kTotXabd-Bearish-Market-Indicator-V2/
fourkhansolo
https://www.tradingview.com/u/fourkhansolo/
36
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © fourkhansolo //@version=5 indicator("Bearish Market Indicator - 4khansolo", shorttitle="BMI-4khansolo", overlay = true) import fourkhansolo/L_Index_4khansolo/7 as index // Color whiteColor = color.white yellowColor = color.yellow // collecting closing at different ranges high_ticker_d = request.security(syminfo.tickerid, "D", high, currency = syminfo.currency) high_ticker_w = request.security(syminfo.tickerid, "W", high_ticker_d, currency = syminfo.currency) high_ticker_m = request.security(syminfo.tickerid, "M", high_ticker_d, currency = syminfo.currency) // Source: https://www.tradingview.com/pine-script-reference/v5/#fun_request{dot}security // collecting highest from highest at different ranges highest_highest_ticker_w = ta.highest(high_ticker_d,5) // 1 Week highest_highest_ticker_d_m = ta.highest(high_ticker_d,30) // 1 Month highest_highest_ticker_w_m = ta.highest(high_ticker_w,4) // 1 Month // Source: https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}highest // ************************************************************ Parameter for Bearish Market Definition ****************************************************************************************************************************************************** // ........................................ Parameters for Bearish Market ..................................................................................................................................................... // Added Options for the Days of the Year ( Market Days Opened) bmi_period = input.int(251, title="BMI-Period", options=[250,251,252,253,254,255,256,257,258,259,260]) daily_highs = request.security(syminfo.tickerid,"D",high, currency=syminfo.currency) week52High= ta.highest(daily_highs,bmi_period) bearish_market_value = week52High*(1-0.2) bearish_by_definition = if close < bearish_market_value color.new(color.purple,0) // Source: https://www.investopedia.com/terms/b/bearmarket.asp plot(bearish_market_value, "Bearish Market By Definiton Value", color=color.new(color.yellow,50),style=plot.style_stepline_diamond) week52High_p = plot(week52High, title="52-Week High", color=color.green) bearish_plot_1 = plot(week52High*(1.01), title="Bearish Market Low", display=display.none) bearish_plot_2 = plot(week52High*(1.02), title="Bearish Market High", display=display.none) fill(bearish_plot_1,bearish_plot_2, color=bearish_by_definition) // ************************************************************ Dynamic Trends ****************************************************************************************************************************************************** // ........................................ Trends Based on Highs (exclusive) // Period Based Trends trying to Mimicing manual trend lines [will improve further in the future update] high_ticker_d_w = request.security(syminfo.tickerid, "W", highest_highest_ticker_w, currency = syminfo.currency) smooth_high_1= ta.sma(high_ticker_d_w,5) smooth_high_2 = ta.sma(smooth_high_1,5) smooth_high_3 = ta.sma(smooth_high_2,5) smooth_high_4 = ta.sma(smooth_high_3,5) smooth_high_5 = ta.sma(smooth_high_4,5) smooth_high_6 = ta.sma(smooth_high_5,5) smooth_high_7 = ta.sma(smooth_high_6,5) smooth_high_8 = ta.sma(smooth_high_7,5) smooth_high_9 = ta.sma(smooth_high_8,5) //plot(smooth_high_1,color=color.new(color.yellow,70)) //plot(smooth_high_2,color=color.new(color.yellow,60)) //plot(smooth_high_3,color=color.new(color.yellow,50)) //plot(smooth_high_4,color=color.new(color.yellow,40)) //plot(smooth_high_5,color=color.new(color.yellow,30)) //plot(smooth_high_6,color=color.new(color.yellow,20)) //plot(smooth_high_7,color=color.new(color.yellow,15)) //plot(smooth_high_8,color=color.new(color.yellow,10)) //plot(smooth_high_9,color=color.yellow) // collecting closing at different ranges low_ticker_d = request.security(syminfo.tickerid, "D", low, currency = syminfo.currency) low_ticker_w = request.security(syminfo.tickerid, "W", low_ticker_d, currency = syminfo.currency) low_ticker_m = request.security(syminfo.tickerid, "M", low_ticker_d, currency = syminfo.currency) // Fiftytwo Week High week51Low = ta.lowest(low_ticker_d,251) plot(week51Low,"52 Week Low", color=color.red) // collecting highest from highest at different ranges lowest_lowest_ticker_w = ta.lowest(low_ticker_d,5) // 1 Week lowest_lowest_ticker_d_m = ta.lowest(low_ticker_d,30) // 1 Month lowest_lowest_ticker_w_m = ta.lowest(low_ticker_d,4) // 1 Month //plot(highest_highest_ticker_d_m) low_ticker_d_w = request.security(syminfo.tickerid, "W", lowest_lowest_ticker_w, currency = syminfo.currency) //plot(high_ticker_d_w) smooth_low_1= ta.sma(low_ticker_d_w,5) smooth_low_2 = ta.sma(smooth_low_1,5) smooth_low_3 = ta.sma(smooth_low_2,5) smooth_low_4 = ta.sma(smooth_low_3,5) smooth_low_5 = ta.sma(smooth_low_4,5) smooth_low_6 = ta.sma(smooth_low_5,5) smooth_low_7 = ta.sma(smooth_low_6,5) smooth_low_8 = ta.sma(smooth_low_7,5) smooth_low_9 = ta.sma(smooth_low_8,5) //plot(smooth_low_1,color=color.new(color.green,70)) //plot(smooth_low_2,color=color.new(color.green,60)) //plot(smooth_low_3,color=color.new(color.green,50)) //plot(smooth_low_4,color=color.new(color.green,40)) //plot(smooth_low_5,color=color.new(color.green,30)) //plot(smooth_low_6,color=color.new(color.green,20)) //plot(smooth_low_7,color=color.new(color.green,15)) //plot(smooth_low_8,color=color.new(color.green,10)) //plot(smooth_low_9,color=color.green) // ........................................ Super-Trends ..................................................................................................................................................... [supertrend, direction] = ta.supertrend(3, 10) super_trend_red = ta.crossover(direction,0) super_trend_green = ta.crossover(0,direction) // Source: https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}supertrend green_1 = ta.crossover(close,smooth_high_9) green_2 = ta.crossover (close[1],smooth_high_9[1]) red_green_signal = if (smooth_high_9 > close) and super_trend_red color.new(color.red,30) else if (smooth_high_9 > close) or (direction > 0) color.new(color.red,70) else if green_1 and (direction < 0) color.new(color.white,70) else if green_2 and super_trend_green color.new(color.green,10) filer_52 = plot(week52High*1.04,display=display.none) fill(week52High_p,filer_52 ,color=red_green_signal) // ************************************************************ Parameter for Bearish Market Definition ****************************************************************************************************************************************************** // ............................................... Used in the Technical Indicators .............................................................................................. close_d = request.security(syminfo.tickerid, "D", close) close_w = request.security(syminfo.tickerid, "W", close) close_m = request.security(syminfo.tickerid, "M", close) open_d = request.security(syminfo.tickerid, "D", open) open_w = request.security(syminfo.tickerid, "W", open) open_m = request.security(syminfo.tickerid, "M", open) // ************************************************************************ Technical Indicators ************************************************************************************************************************************************ // ************************************************************ RSI ************************************************************************************************************************ rsi_normal = ta.rsi(close,14) rsi_ma_normal = ta.sma(rsi_normal,14) fourteen_D_RSI = request.security(syminfo.tickerid, "D", rsi_normal) fourteen_W_RSI = request.security(syminfo.tickerid, "W", rsi_normal) fourteen_M_RSI = request.security(syminfo.tickerid, "M", rsi_normal) // RSI Based fourteen_D_RSI_ma = request.security(syminfo.tickerid, "D", rsi_ma_normal) fourteen_W_RSI_ma = request.security(syminfo.tickerid, "W", rsi_ma_normal) fourteen_M_RSI_ma = request.security(syminfo.tickerid, "M", rsi_ma_normal) // RSI Color fourteen_D_RSI_color = index.colorRSIfull(fourteen_D_RSI,fourteen_D_RSI_ma) fourteen_W_RSI_color = index.colorRSIfull(fourteen_W_RSI,fourteen_W_RSI_ma) fourteen_M_RSI_color = index.colorRSIfull(fourteen_M_RSI,fourteen_M_RSI_ma) // RSI: String Conversion fourteen_D_RSI_string= str.tostring(math.round(fourteen_D_RSI,2)) fourteen_W_RSI_string= str.tostring(math.round(fourteen_W_RSI,2)) fourteen_M_RSI_string= str.tostring(math.round(fourteen_M_RSI,2)) // RSI-MA: String Conversion fourteen_D_RSI_ma_string= str.tostring(math.round(fourteen_D_RSI_ma,2)) fourteen_W_RSI_ma_string= str.tostring(math.round(fourteen_W_RSI_ma,2)) fourteen_M_RSI_ma_string= str.tostring(math.round(fourteen_M_RSI_ma,2)) fourteen_d_rsi_color = if fourteen_D_RSI >= 70 color.red else if fourteen_D_RSI <= 30 color.red else color.black fourteen_m_rsi_color = if fourteen_M_RSI >= 70 color.red else if fourteen_M_RSI <= 30 color.red else color.black // ************************************************************ Stochastic RSI ************************************************************************************************************************ normal_daily_k = ta.sma(ta.stoch(rsi_normal, rsi_normal, rsi_normal, 14), 3) normal_daily_d = ta.sma(normal_daily_k, 3) // Stoch. RSI: K fourteen_D_stochastic_RSI_k = request.security(syminfo.tickerid, "D", normal_daily_k) fourteen_W_stochastic_RSI_k = request.security(syminfo.tickerid, "W", normal_daily_k) fourteen_M_stochastic_RSI_k = request.security(syminfo.tickerid, "M", normal_daily_k) // Stoch. RSI: D fourteen_D_stochastic_RSI_d = request.security(syminfo.tickerid, "D", normal_daily_d) fourteen_W_stochastic_RSI_d = request.security(syminfo.tickerid, "W", normal_daily_d) fourteen_M_stochastic_RSI_d = request.security(syminfo.tickerid, "M", normal_daily_d) // Stoch. RSI: String Conversion: K fourteen_stoch_RSI_D_color =index.colorRSIfull(fourteen_D_stochastic_RSI_k,fourteen_D_stochastic_RSI_d) fourteen_stoch_RSI_W_color =index.colorRSIfull(fourteen_W_stochastic_RSI_k,fourteen_W_stochastic_RSI_d) fourteen_stoch_RSI_M_color =index.colorRSIfull(fourteen_M_stochastic_RSI_k,fourteen_M_stochastic_RSI_d) // Stoch. RSI: String Conversion: K fourteen_D_stoch_RSI_k_string = str.tostring(math.round(fourteen_D_stochastic_RSI_k,2)) fourteen_W_stoch_RSI_k_string = str.tostring(math.round(fourteen_W_stochastic_RSI_k,2)) fourteen_M_stoch_RSI_k_string = str.tostring(math.round(fourteen_M_stochastic_RSI_k,2)) // Stoch. RSI: String Conversion: D fourteen_D_stoch_RSI_d_string = str.tostring(math.round(fourteen_D_stochastic_RSI_d,2)) fourteen_W_stoch_RSI_d_string = str.tostring(math.round(fourteen_W_stochastic_RSI_d,2)) fourteen_M_stoch_RSI_d_string = str.tostring(math.round(fourteen_M_stochastic_RSI_d,2)) // ************************************************************ MACD *********************************************************************************************************************** // ............................................... MACD .............................................................................................. [macd_normal, signal_normal, histLine_d] = ta.macd(close, 12, 26, 9) macdLine_d = request.security(syminfo.tickerid, "D", macd_normal) signalLine_d = request.security(syminfo.tickerid, "D", signal_normal) macdLine_w = request.security(syminfo.tickerid, "W", macd_normal) signalLine_w = request.security(syminfo.tickerid, "W", signal_normal) macdLine_m = request.security(syminfo.tickerid, "M", macd_normal) signalLine_m = request.security(syminfo.tickerid, "M", signal_normal) // MACD: String Conversion macdLine_d_string= str.tostring(math.round(macdLine_d,2)) macdLine_w_string= str.tostring(math.round(macdLine_w,2)) macdLine_m_string= str.tostring(math.round(macdLine_m,2)) signalLine_d_string= str.tostring(math.round(signalLine_d,2)) signalLine_w_string= str.tostring(math.round(signalLine_w,2)) signalLine_m_string= str.tostring(math.round(signalLine_m,2)) // MACD Color macdLine_d_color = index.colorMACD(macdLine_d,signalLine_d) macdLine_w_color = index.colorMACD(macdLine_w,signalLine_w) macdLine_m_color = index.colorMACD(macdLine_m,signalLine_m) // ............................................... Moving Average Metrics .............................................................................................. // MA based on Daily Close ma20_d = ta.sma(close_d,20) ma50_d = ta.sma(close_d,50) ma100_d = ta.sma(close_d,100) ma200_d = ta.sma(close_d,200) // MA 20 based sma_20_d = request.security(syminfo.tickerid, "D", ma20_d) sma_20_w = request.security(syminfo.tickerid, "W", ma20_d) sma_20_m = request.security(syminfo.tickerid, "M", ma20_d) // MA 50 based sma_50_d = request.security(syminfo.tickerid, "D", ma50_d) sma_50_w = request.security(syminfo.tickerid, "W", ma50_d) sma_50_m = request.security(syminfo.tickerid, "M", ma50_d) // MA 100 based sma_100_d = request.security(syminfo.tickerid, "D", ma100_d) sma_100_w = request.security(syminfo.tickerid, "W", ma100_d) sma_100_m = request.security(syminfo.tickerid, "M", ma100_d) // MA 200 based sma_200_d = request.security(syminfo.tickerid, "D", ma200_d) sma_200_w = request.security(syminfo.tickerid, "W", ma200_d) sma_200_m = request.security(syminfo.tickerid, "M", ma200_d) //Color color_sma_20_d = index.colour(close_d,sma_20_d) color_sma_20_w = index.colour(close_w,sma_20_w) color_sma_20_m = index.colour(close_m,sma_20_m) color_sma_50_d = index.colour(close_d,sma_50_d) color_sma_50_w = index.colour(close_w,sma_50_w) color_sma_50_m = index.colour(close_m,sma_50_m) color_sma_100_d = index.colour(close_d,sma_100_d) color_sma_100_w = index.colour(close_w,sma_100_w) color_sma_100_m = index.colour(close_m,sma_100_m) color_sma_200_d = index.colour(close_d,sma_200_d) color_sma_200_w = index.colour(close_w,sma_200_w) color_sma_200_m = index.colour(close_m,sma_200_m) // String Conversion sma_20_d_string = str.tostring(math.round(((close_d-sma_20_d)/sma_20_d)*100,2)) sma_20_w_string = str.tostring(math.round(((close_w-sma_20_w)/sma_20_w)*100,2)) sma_20_m_string = str.tostring(math.round(((close_m-sma_20_m)/sma_20_m)*100,2)) sma_50_d_string = str.tostring(math.round(((close_d-sma_50_d)/sma_50_d)*100,2)) sma_50_w_string = str.tostring(math.round(((close_w-sma_50_w)/sma_50_w)*100,2)) sma_50_m_string = str.tostring(math.round(((close_m-sma_50_m)/sma_50_m)*100,2)) sma_100_d_string = str.tostring(math.round(((close_d-sma_100_d)/sma_100_d)*100,2)) sma_100_w_string = str.tostring(math.round(((close_w-sma_100_w)/sma_100_w)*100,2)) sma_100_m_string = str.tostring(math.round(((close_m-sma_100_m)/sma_100_m)*100,2)) sma_200_d_string = str.tostring(math.round(((close_d-sma_200_d)/sma_200_d)*100,2)) sma_200_w_string = str.tostring(math.round(((close_w-sma_200_w)/sma_200_w)*100,2)) sma_200_m_string = str.tostring(math.round(((close_m-sma_200_m)/sma_200_m)*100,2)) // ************************************************************ Moving Average ************************************************************ // ............................................... Lagging: Indicators .............................................................................................. technical_table = table.new(position = position.middle_right, rows = 5, columns = 4, bgcolor = color.new(color.black,0), border_width=1) table.cell(technical_table, row = 0, column = 1, text = "D", text_color = whiteColor) table.cell(technical_table, row = 0, column = 2, text = "W", text_color = whiteColor) table.cell(technical_table, row = 0, column = 3, text = "M", text_color = whiteColor) // Simple Moving Average: 20MA table.cell(technical_table, row = 1, column = 0, text = "20MA (%)", text_color = whiteColor) table.cell(technical_table, row = 1, column = 1, text = sma_20_d_string, text_color = whiteColor, bgcolor = color_sma_20_d) table.cell(technical_table, row = 1, column = 2, text = sma_20_w_string, text_color = whiteColor, bgcolor = color_sma_20_w) table.cell(technical_table, row = 1, column = 3, text = sma_20_m_string, text_color = whiteColor, bgcolor = color_sma_20_m) // Simple Moving Average: 50MA table.cell(technical_table, row = 2, column = 0, text = "50MA (%)", text_color = whiteColor) table.cell(technical_table, row = 2, column = 1, text = sma_50_d_string, text_color = whiteColor, bgcolor = color_sma_50_d) table.cell(technical_table, row = 2, column = 2, text = sma_50_w_string, text_color = whiteColor, bgcolor = color_sma_50_w) table.cell(technical_table, row = 2, column = 3, text = sma_50_m_string, text_color = whiteColor, bgcolor = color_sma_50_m) // Simple Moving Average: 100MA table.cell(technical_table, row = 3, column = 0, text = "100MA (%)", text_color = whiteColor) table.cell(technical_table, row = 3, column = 1, text = sma_100_d_string, text_color = whiteColor, bgcolor = color_sma_100_d) table.cell(technical_table, row = 3, column = 2, text = sma_100_w_string, text_color = whiteColor, bgcolor = color_sma_100_w) table.cell(technical_table, row = 3, column = 3, text = sma_100_m_string, text_color = whiteColor, bgcolor = color_sma_100_m) // Simple Moving Average: 200MA table.cell(technical_table, row = 4, column = 0, text = "200MA (%)", text_color = whiteColor) table.cell(technical_table, row = 4, column = 1, text = sma_200_d_string, text_color = whiteColor, bgcolor = color_sma_200_d) table.cell(technical_table, row = 4, column = 2, text = sma_200_w_string, text_color = whiteColor, bgcolor = color_sma_200_w) table.cell(technical_table, row = 4, column = 3, text = sma_200_m_string, text_color = whiteColor, bgcolor = color_sma_200_m) // ************************************************************ Technical Oscillator ************************************************************************************************************************ // ............................................... Technical Oscillator.............................................................................................. technical_table_oscillator = table.new(position = position.bottom_right, rows = 4, columns = 9, bgcolor = color.new(color.black,10), border_width=2) table.cell(technical_table_oscillator, row = 0, column = 0, text = "", text_color = yellowColor) table.cell(technical_table_oscillator, row = 1, column = 0, text = "D", text_color = whiteColor) table.cell(technical_table_oscillator, row = 2, column = 0, text = "W", text_color = whiteColor) table.cell(technical_table_oscillator, row = 3, column = 0, text = "M", text_color = whiteColor) // Stochastic RSI table.cell(technical_table_oscillator, row = 0, column = 1, text = "Stochastic-RSI", text_color = whiteColor) table.cell(technical_table_oscillator, row = 1, column = 1, text = fourteen_D_stoch_RSI_k_string + " | "+fourteen_D_stoch_RSI_d_string, text_color = whiteColor, bgcolor=fourteen_stoch_RSI_D_color) table.cell(technical_table_oscillator, row = 2, column = 1, text = fourteen_W_stoch_RSI_k_string + " | "+fourteen_W_stoch_RSI_d_string, text_color = whiteColor, bgcolor=fourteen_stoch_RSI_W_color) table.cell(technical_table_oscillator, row = 3, column = 1, text = fourteen_M_stoch_RSI_k_string + " | "+fourteen_M_stoch_RSI_d_string, text_color = whiteColor, bgcolor=fourteen_stoch_RSI_M_color) // RSI table.cell(technical_table_oscillator, row = 0, column = 2, text = "RSI", text_color = whiteColor) table.cell(technical_table_oscillator, row = 1, column = 2, text = fourteen_D_RSI_string + " | "+fourteen_D_RSI_ma_string, text_color = whiteColor, bgcolor=fourteen_D_RSI_color) table.cell(technical_table_oscillator, row = 2, column = 2, text = fourteen_W_RSI_string + " | "+fourteen_W_RSI_ma_string, text_color = whiteColor, bgcolor=fourteen_W_RSI_color) table.cell(technical_table_oscillator, row = 3, column = 2, text = fourteen_M_RSI_string + " | "+fourteen_M_RSI_ma_string, text_color = whiteColor, bgcolor=fourteen_M_RSI_color) // MACD table.cell(technical_table_oscillator, row = 0, column = 3, text = "MACD", text_color = whiteColor) table.cell(technical_table_oscillator, row = 1, column = 3, text = macdLine_d_string+" | "+ signalLine_d_string, text_color = whiteColor, bgcolor = macdLine_d_color) table.cell(technical_table_oscillator, row = 2, column = 3, text = macdLine_w_string+" | "+ signalLine_w_string, text_color = whiteColor, bgcolor = macdLine_w_color) table.cell(technical_table_oscillator, row = 3, column = 3, text = macdLine_m_string+" | "+ signalLine_m_string, text_color = whiteColor, bgcolor = macdLine_m_color)
Adaptive Rebound Line Bands (ARL Bands)
https://www.tradingview.com/script/7EGiRUxc-Adaptive-Rebound-Line-Bands-ARL-Bands/
More-Than-Enough
https://www.tradingview.com/u/More-Than-Enough/
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/ // © More-Than-Enough //@version=5 indicator(title = "Adaptive Rebound Line Bands", shorttitle = "ARL Bands", overlay = true, precision = 3, timeframe = "", timeframe_gaps = true) Rsi_On = input.bool(true, "RSI Levels") Magnetic_Waves_On = input.bool(true, "Magnetic Waves") Extra_Lines_On = input.bool(false, "Extra Lines") Extend_Extra_Lines_On = input.bool(false, "Extend Extra Lines") Lines_Limit = input.int(defval = 31, title = "Lines Limit", minval = 5, maxval = 31) Length = input(14, "Length") Source_1 = input(hlc3, "Source 1") Source_2 = input(low , "Source 2") Tp = input.float(defval = 2.30, title = "Top Deviation" , minval = 0.0, step = 0.1) Hi = input.float(defval = 1.15, title = "High Deviation" , minval = 0.0, step = 0.1) Lo = input.float(defval = 0.00, title = "Low Deviation" , maxval = 0.0, step = 0.1) Bt = input.float(defval = -1.2, title = "Bottom Deviation", maxval = 0.0, step = 0.1) /// Magnetic Waves /// Wave_Length = 75 Magnetic_Source = hlc3 Wave_Current = ta.ema(Magnetic_Source, Wave_Length) Wave = (Wave_Current[1] * (Wave_Length - 1) + Magnetic_Source) / Wave_Length North_Pole = Wave * (104 * 0.01) Northern_Hemisphere = Wave * (102 * 0.01) Equator = Wave * (100 * 0.01) Southern_Hemisphere = Wave * (98 * 0.01) South_Pole = Wave * (96 * 0.01) /// Extra Lines Calculations /// // BB Lines Line_Deviation = ta.stdev(close, 20) Line_Split = ta.sma(close, 20) Top_Bb_Line = Line_Split + (Line_Deviation * 3) High_Bb_Line = Line_Split + (Line_Deviation * 2) Low_Bb_Line = Line_Split - (Line_Deviation * 2) Bottom_Bb_Line = Line_Split - (Line_Deviation * 3) // Top Dip Line (KAMA) Source_Sum = math.sum(math.abs(hlc3 - hlc3[1]), 5) Change_Ratio = if Source_Sum != 0 math.abs(hlc3 - hlc3[5]) / Source_Sum Ratio_Smoothing = math.pow(Change_Ratio * ((2 / (2.5 + 1)) - (2 / (20 + 1))) + (2 / (20 + 1)), 2) Previous_Ratio = 0.0 Previous_Ratio := nz(Previous_Ratio[1]) + Ratio_Smoothing * (hlc3 - nz(Previous_Ratio[1])) Ratio_Close = Previous_Ratio HAshi_Close = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, Ratio_Close) Top_Dip_Line = ta.ema(HAshi_Close, 20) // Bottom Dip Line Bottom_Dip_Line_Calculation = low - (ta.atr(20) * 5.0) Bottom_Dip_Line = ta.sma(Bottom_Dip_Line_Calculation, 75) /// ARL Bands /// ARL = ta.ema(Source_2, Length)[1] + (Source_1 - ta.ema(Source_2, Length)[1]) / (Length * math.pow(Source_1 / ta.ema(close, Length)[1], 0)) ARL_T = ARL * (1.00 + (Tp * 0.01)) ARL_H = ARL * (1.00 + (Hi * 0.01)) ARL_L = ARL * (1.00 + (Lo * 0.01)) ARL_B = ARL * (1.00 + (Bt * 0.01)) /// RSI Level /// Rsi_Level = ta.rsi(close, 14) Overbought = (Rsi_Level >= 70) Oversold = (Rsi_Level <= 30) ///////////////// ///// Plots ///// ///////////////// // Magnetic Waves NP = plot(Magnetic_Waves_On ? North_Pole : na, title = "North Pole" , color = color.rgb(129, 199, 132, 100), linewidth = 2) // North Pole NH = plot(Magnetic_Waves_On ? Northern_Hemisphere : na, title = "Northern Hemisphere", color = color.rgb(129, 199, 132, 80), linewidth = 2) // Northern Hemisphere E = plot(Magnetic_Waves_On ? Equator : na, title = "Equator" , color = color.rgb(144, 191, 249, 70), linewidth = 2) // Equator SH = plot(Magnetic_Waves_On ? Southern_Hemisphere : na, title = "Southern Hemisphere", color = color.rgb(247, 124, 128, 80), linewidth = 2) // Southern Hemisphere SP = plot(Magnetic_Waves_On ? South_Pole : na, title = "South Pole" , color = color.rgb(247, 124, 128, 100), linewidth = 2) // South Pole fill(NH, NP, color.rgb(129, 199, 132, 80), "Top Zone") fill( E, NH, color.rgb(129, 199, 132, 86), "High Zone") fill( E, SH, color.rgb(247, 124, 128, 86), "Low Zone") fill(SH, SP, color.rgb(247, 124, 128, 80), "Bottom Zone") // Extra Lines plot(Extra_Lines_On ? Top_Bb_Line : na, title = "Top BB Line" , color = color.new(color.white, 70), show_last = Extend_Extra_Lines_On ? na : Lines_Limit) plot(Extra_Lines_On ? High_Bb_Line : na, title = "High BB Line" , color = color.new(color.white, 70), show_last = Extend_Extra_Lines_On ? na : Lines_Limit) plot(Extra_Lines_On ? Low_Bb_Line : na, title = "Low BB Line" , color = color.new(color.white, 70), show_last = Extend_Extra_Lines_On ? na : Lines_Limit) plot(Extra_Lines_On ? Bottom_Bb_Line : na, title = "Bottom BB Line", color = color.new(color.white, 70), show_last = Extend_Extra_Lines_On ? na : Lines_Limit) plot(Extra_Lines_On ? Top_Dip_Line : na, title = "Top Dip Line" , color = color.new(color.yellow, 50), style = plot.style_circles, show_last = Extend_Extra_Lines_On ? na : Lines_Limit) plot(Extra_Lines_On ? Bottom_Dip_Line : na, title = "Bottom Dip Line", color = color.new(color.yellow, 50), style = plot.style_circles, show_last = Extend_Extra_Lines_On ? na : Lines_Limit) // ARLs plot(ARL_T, title = "Top ARL" , color = color.red) plot(ARL_H, title = "High ARL" , color = color.red) plot(ARL_L, title = "Low ARL" , color = color.lime) plot(ARL_B, title = "Bottom ARL", color = color.lime) // RSI Level plotshape(Rsi_On ? Overbought : na, title = "Overbought", style = shape.labeldown, location = location.abovebar, color = color.red , size = size.tiny) plotshape(Rsi_On ? Oversold : na, title = "Oversold" , style = shape.labelup , location = location.belowbar, color = color.lime, size = size.tiny)
Dealar VIX Implied Range + Retracement Levels
https://www.tradingview.com/script/mWFxSK8O-Dealar-VIX-Implied-Range-Retracement-Levels/
VolTrader005
https://www.tradingview.com/u/VolTrader005/
84
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("Dealar VIX Implied Range + Retracement Levels", overlay=true) volatilityindex = input(title="Index", type=input.string, defval="CBOE:VIX") vix = security(volatilityindex, timeframe.period, open) highTimeFrame = input("D", type=input.resolution) sessSpec = input("0830-1500", type=input.session) is_newbar(res, sess) => t = time(res, sess) na(t[1]) and not na(t) or t[1] < t newbar = is_newbar("1440", sessSpec) float s1 = na s1 := newbar ? close : nz(s1[1]) float vixclose = na vixclose := newbar ? vix : nz(vixclose[1]) float vixpercent = (vixclose / 16) * .01 float highestimate = s1 * (1 + vixpercent) float high50estimate = s1 * (1 + (vixpercent *.5)) float lowestimate = s1 * (1 - vixpercent) float low50estimate = s1 * (1 - (vixpercent * .5)) float high75estimate = s1 * (1 + (vixpercent *.75)) float low75estimate = s1 * (1 - (vixpercent * .75)) float high25estimate = s1 * (1 + (vixpercent *.25)) float low25estimate = s1 * (1 - (vixpercent * .25)) plot(highestimate, style=plot.style_circles, linewidth=1, color=color.rgb(64, 66, 75)) plot(lowestimate, style=plot.style_circles, linewidth=1, color=color.rgb(64, 66, 75)) plot(high50estimate, style=plot.style_circles, linewidth=1, color=color.red) plot(low50estimate, style=plot.style_circles, linewidth=1, color=color.red) plot(high75estimate, style=plot.style_circles, linewidth=1, color=color.gray) plot(low75estimate, style=plot.style_circles, linewidth=1, color=color.gray) plot(high25estimate, style=plot.style_circles, linewidth=1, color=color.rgb(64, 66, 75)) plot(low25estimate, style=plot.style_circles, linewidth=1, color=color.rgb(64, 66, 75))
Financial Metrics
https://www.tradingview.com/script/JMO2m0gC-Financial-Metrics/
Fin_WhizAB
https://www.tradingview.com/u/Fin_WhizAB/
165
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/ // © BasitAndrabi //@version=5 indicator("FinMet 2.0", overlay = true) // Financial Metrics (FinMet 2.0) - Fundamental Ratios and Quarterly Earnings // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | INPUTS | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // Symbol s01Col = input.color(color.rgb(49, 126, 72), title = "EPS", inline="s01Col", group="EPS & Sales bars") s01Col2 = input.color(color.rgb(124, 46, 46), title = "", inline="s01Col", group="EPS & Sales bars") s01Cols = input.color((color.rgb(33, 117, 185)), title = "Sales", inline="s01cols", group="EPS & Sales bars") Period = input.string(title="Period", defval="FQ", options=["FQ", "TTM"], group="EPS & Sales bars") // Plot Location in_plot_pos = input.string(title="Plot Location", defval= "Middle Right", options =["Top Right" , "Middle Right" , "Bottom Right" , "Top Center", "Middle Center", "Bottom Center", "Top Left" , "Middle Left" , "Bottom Left" ], group= "Plot Setting") // Bar Size barHigh = input.float(0.3, "Bar Height", minval = 0.2, step= 0.01, group = "Plot Setting") barWdth = input.float(0.8, "Bar Width" , minval = 0.2, step= 0.01, group = "Plot Setting") // Plot Color pltCol = input.color(#2a3133, title="Background", group = "Plot Setting") borCol = input.color(color.rgb(53, 64, 124), title="Border", group = "Plot Setting") txtCol = input.color(color.white, title="Text", group = "Plot Setting") // Financial Ratio limits lim_PE = input.float(15, "PE", minval = 0, step= 1, group = "Set Limits", inline = "lim_PE") lim_PEG = input.float(1, "PEG", minval = 0, step= 0.1, group = "Set Limits", inline = "lim_PE") lim_PS = input.float(2, "P/S", minval = 0, step= 0.1, group = "Set Limits", inline = "lim_PS") lim_PB = input.float(2, "P/B", minval = 0, step= 0.1, group = "Set Limits", inline = "lim_PB") lim_EVFCF = input.float(10, "EV/FCF", minval = 0, step= 1, group = "Set Limits", inline = "lim_PS") lim_OPM = input.float(15, "OPM", minval = 0, step= 1, group = "Set Limits", inline = "lim_OPM") lim_DE = input.float(1, "D/E", minval = 0, step= 0.1, group = "Set Limits", inline = "lim_OPM") lim_ROE = input.float(15, "ROE", minval = 0, step= 1, group = "Set Limits", inline = "lim_ROE") lim_DVY = input.float(2, "Div_Yield", minval = 0, step= 0.1, group = "Set Limits", inline = "lim_ROE") // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | CALCULATION | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // Calculation // Arrays initialised............................................................. sym01_arr = array.new_float(12) QOQ_arr = array.new_float(12) YOY_arr = array.new_float(12) sym01S_arr = array.new_float(12) QOQs_arr = array.new_float(12) YOYs_arr = array.new_float(12) //EPS = request.earnings(syminfo.tickerid, earnings.actual, ignore_invalid_symbol=true) EPS = request.earnings(syminfo.tickerid, earnings.standardized, ignore_invalid_symbol=true) SALES = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FQ") var earning_ticker = "ESD_FACTSET:" + syminfo.prefix + ";" + syminfo.ticker + ";EARNINGS" ResultDate = request.security(earning_ticker, "D", time, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true) //earning report date // EPSBarsNumber = ta.barssince(EPS != EPS[1]) == 0 // Actual EPS actualEPS = EPS actualEPS1 = ta.valuewhen(EPSBarsNumber, EPS, 1) // With "1" to search the previous EPS value, etc actualEPS2 = ta.valuewhen(EPSBarsNumber, EPS, 2) actualEPS3 = ta.valuewhen(EPSBarsNumber, EPS, 3) actualEPS4 = ta.valuewhen(EPSBarsNumber, EPS, 4) actualEPS5 = ta.valuewhen(EPSBarsNumber, EPS, 5) actualEPS6 = ta.valuewhen(EPSBarsNumber, EPS, 6) actualEPS7 = ta.valuewhen(EPSBarsNumber, EPS, 7) actualEPS8 = ta.valuewhen(EPSBarsNumber, EPS, 8) actualEPS9 = ta.valuewhen(EPSBarsNumber, EPS, 9) actualEPS10 = ta.valuewhen(EPSBarsNumber, EPS, 10) actualEPS11 = ta.valuewhen(EPSBarsNumber, EPS, 11) actualEPS12 = ta.valuewhen(EPSBarsNumber, EPS, 12) actualEPS13 = ta.valuewhen(EPSBarsNumber, EPS, 13) actualEPS14 = ta.valuewhen(EPSBarsNumber, EPS, 14) actualEPS15 = ta.valuewhen(EPSBarsNumber, EPS, 15) // QOQ EPS growth................................................................. QOQ0 = (actualEPS-actualEPS1)/math.abs(actualEPS1)*100 QOQ1 = (actualEPS1-actualEPS2)/math.abs(actualEPS2)*100 QOQ2 = (actualEPS2-actualEPS3)/math.abs(actualEPS3)*100 QOQ3 = (actualEPS3-actualEPS4)/math.abs(actualEPS4)*100 QOQ4 = (actualEPS4-actualEPS5)/math.abs(actualEPS5)*100 QOQ5 = (actualEPS5-actualEPS6)/math.abs(actualEPS6)*100 QOQ6 = (actualEPS6-actualEPS7)/math.abs(actualEPS7)*100 QOQ7 = (actualEPS7-actualEPS8)/math.abs(actualEPS8)*100 QOQ8 = (actualEPS8-actualEPS9)/math.abs(actualEPS9)*100 QOQ9 = (actualEPS9-actualEPS10)/math.abs(actualEPS10)*100 QOQ10 = (actualEPS10-actualEPS11)/math.abs(actualEPS11)*100 QOQ11 = (actualEPS11-actualEPS12)/math.abs(actualEPS12)*100 // YOY EPS growth................................................................. YOY0 = (actualEPS-actualEPS4)/math.abs(actualEPS4)*100 YOY1 = (actualEPS1-actualEPS5)/math.abs(actualEPS5)*100 YOY2 = (actualEPS2-actualEPS6)/math.abs(actualEPS6)*100 YOY3 = (actualEPS3-actualEPS7)/math.abs(actualEPS7)*100 YOY4 = (actualEPS4-actualEPS8)/math.abs(actualEPS8)*100 YOY5 = (actualEPS5-actualEPS9)/math.abs(actualEPS9)*100 YOY6 = (actualEPS6-actualEPS10)/math.abs(actualEPS10)*100 YOY7 = (actualEPS7-actualEPS11)/math.abs(actualEPS11)*100 YOY8 = (actualEPS8-actualEPS12)/math.abs(actualEPS12)*100 YOY9 = (actualEPS9-actualEPS13)/math.abs(actualEPS13)*100 YOY10 = (actualEPS10-actualEPS14)/math.abs(actualEPS14)*100 YOY11 = (actualEPS11-actualEPS15)/math.abs(actualEPS15)*100 // Set Array Elements.................................................................... if Period == "FQ" array.set(sym01_arr, 11, actualEPS) array.set(sym01_arr, 10, actualEPS1) array.set(sym01_arr, 9, actualEPS2) array.set(sym01_arr, 8, actualEPS3) array.set(sym01_arr, 7, actualEPS4) array.set(sym01_arr, 6, actualEPS5) array.set(sym01_arr, 5, actualEPS6) array.set(sym01_arr, 4, actualEPS7) array.set(sym01_arr, 3, actualEPS8) array.set(sym01_arr, 2, actualEPS9) array.set(sym01_arr, 1, actualEPS10) array.set(sym01_arr, 0, actualEPS11) else array.set(sym01_arr, 11, actualEPS+actualEPS1+actualEPS2+actualEPS3) array.set(sym01_arr, 10, actualEPS1+actualEPS2+actualEPS3+actualEPS4) array.set(sym01_arr, 9, actualEPS2+actualEPS3+actualEPS4+actualEPS5) array.set(sym01_arr, 8, actualEPS3+actualEPS4+actualEPS5+actualEPS6) array.set(sym01_arr, 7, actualEPS4+actualEPS5+actualEPS6+actualEPS7) array.set(sym01_arr, 6, actualEPS5+actualEPS6+actualEPS7+actualEPS8) array.set(sym01_arr, 5, actualEPS6+actualEPS7+actualEPS8+actualEPS9) array.set(sym01_arr, 4, actualEPS7+actualEPS8+actualEPS9+actualEPS10) array.set(sym01_arr, 3, actualEPS8+actualEPS9+actualEPS10+actualEPS11) array.set(sym01_arr, 2, actualEPS9+actualEPS10+actualEPS11+actualEPS12) array.set(sym01_arr, 1, actualEPS10+actualEPS11+actualEPS12+actualEPS13) array.set(sym01_arr, 0, actualEPS11+actualEPS12+actualEPS13+actualEPS14) // array.set(QOQ_arr, 11, QOQ0) array.set(QOQ_arr, 10, QOQ1) array.set(QOQ_arr, 9, QOQ2) array.set(QOQ_arr, 8, QOQ3) array.set(QOQ_arr, 7, QOQ4) array.set(QOQ_arr, 6, QOQ5) array.set(QOQ_arr, 5, QOQ6) array.set(QOQ_arr, 4, QOQ7) array.set(QOQ_arr, 3, QOQ8) array.set(QOQ_arr, 2, QOQ9) array.set(QOQ_arr, 1, QOQ10) array.set(QOQ_arr, 0, QOQ11) array.set(YOY_arr, 11, YOY0) array.set(YOY_arr, 10, YOY1) array.set(YOY_arr, 9, YOY2) array.set(YOY_arr, 8, YOY3) array.set(YOY_arr, 7, YOY4) array.set(YOY_arr, 6, YOY5) array.set(YOY_arr, 5, YOY6) array.set(YOY_arr, 4, YOY7) array.set(YOY_arr, 3, YOY8) array.set(YOY_arr, 2, YOY9) array.set(YOY_arr, 1, YOY10) array.set(YOY_arr, 0, YOY11) float QOQ = na float YOY = na SalesBarsNumber = ta.barssince(SALES != SALES[1]) == 0 // Actual SALES salesA = SALES sales1A = ta.valuewhen(SalesBarsNumber, SALES, 1) // With "1" to search the previous SALES value, etc sales2A = ta.valuewhen(SalesBarsNumber, SALES, 2) sales3A = ta.valuewhen(SalesBarsNumber, SALES, 3) sales4A = ta.valuewhen(SalesBarsNumber, SALES, 4) sales5A = ta.valuewhen(SalesBarsNumber, SALES, 5) sales6A = ta.valuewhen(SalesBarsNumber, SALES, 6) sales7A = ta.valuewhen(SalesBarsNumber, SALES, 7) sales8A = ta.valuewhen(SalesBarsNumber, SALES, 8) sales9A = ta.valuewhen(SalesBarsNumber, SALES, 9) sales10A = ta.valuewhen(SalesBarsNumber, SALES, 10) sales11A = ta.valuewhen(SalesBarsNumber, SALES, 11) sales12A = ta.valuewhen(SalesBarsNumber, SALES, 12) sales13A = ta.valuewhen(SalesBarsNumber, SALES, 13) sales14A = ta.valuewhen(SalesBarsNumber, SALES, 14) sales15A = ta.valuewhen(SalesBarsNumber, SALES, 15) // Sales in Crores sales = (salesA/10000000) sales1 = (sales1A/10000000) sales2 = (sales2A/10000000) sales3 = (sales3A/10000000) sales4 = (sales4A/10000000) sales5 = (sales5A/10000000) sales6 = (sales6A/10000000) sales7 = (sales7A/10000000) sales8 = (sales8A/10000000) sales9 = (sales9A/10000000) sales10 = (sales10A/10000000) sales11 = (sales11A/10000000) sales12 = (sales12A/10000000) sales13 = (sales13A/10000000) sales14 = (sales14A/10000000) sales15 = (sales15A/10000000) // QOQ Sales growth................................................................. QOQs0 = (sales-sales1)/math.abs(sales1)*100 QOQs1 = (sales1-sales2)/math.abs(sales2)*100 QOQs2 = (sales2-sales3)/math.abs(sales3)*100 QOQs3 = (sales3-sales4)/math.abs(sales4)*100 QOQs4 = (sales4-sales5)/math.abs(sales5)*100 QOQs5 = (sales5-sales6)/math.abs(sales6)*100 QOQs6 = (sales6-sales7)/math.abs(sales7)*100 QOQs7 = (sales7-sales8)/math.abs(sales8)*100 QOQs8 = (sales8-sales9)/math.abs(sales9)*100 QOQs9 = (sales9-sales10)/math.abs(sales10)*100 QOQs10 = (sales10-sales11)/math.abs(sales11)*100 QOQs11 = (sales11-sales12)/math.abs(sales12)*100 // YOY Sales growth................................................................. YOYs0 = (sales-sales4)/math.abs(sales4)*100 YOYs1 = (sales1-sales5)/math.abs(sales5)*100 YOYs2 = (sales2-sales6)/math.abs(sales6)*100 YOYs3 = (sales3-sales7)/math.abs(sales7)*100 YOYs4 = (sales4-sales8)/math.abs(sales8)*100 YOYs5 = (sales5-sales9)/math.abs(sales9)*100 YOYs6 = (sales6-sales10)/math.abs(sales10)*100 YOYs7 = (sales7-sales11)/math.abs(sales11)*100 YOYs8 = (sales8-sales12)/math.abs(sales12)*100 YOYs9 = (sales9-sales13)/math.abs(sales13)*100 YOYs10 = (sales10-sales14)/math.abs(sales14)*100 YOYs11 = (sales11-sales15)/math.abs(sales15)*100 // Set Array Elements if Period == "FQ" array.set(sym01S_arr, 11, sales) array.set(sym01S_arr, 10, sales1) array.set(sym01S_arr, 9, sales2) array.set(sym01S_arr, 8, sales3) array.set(sym01S_arr, 7, sales4) array.set(sym01S_arr, 6, sales5) array.set(sym01S_arr, 5, sales6) array.set(sym01S_arr, 4, sales7) array.set(sym01S_arr, 3, sales8) array.set(sym01S_arr, 2, sales9) array.set(sym01S_arr, 1, sales10) array.set(sym01S_arr, 0, sales11) else array.set(sym01S_arr, 11, sales+sales1+sales2+sales3) array.set(sym01S_arr, 10, sales1+sales2+sales3+sales4) array.set(sym01S_arr, 9, sales2+sales3+sales4+sales5) array.set(sym01S_arr, 8, sales3+sales4+sales5+sales6) array.set(sym01S_arr, 7, sales4+sales5+sales6+sales7) array.set(sym01S_arr, 6, sales5+sales6+sales7+sales8) array.set(sym01S_arr, 5, sales6+sales7+sales8+sales9) array.set(sym01S_arr, 4, sales7+sales8+sales9+sales10) array.set(sym01S_arr, 3, sales8+sales9+sales10+sales11) array.set(sym01S_arr, 2, sales9+sales10+sales11+sales12) array.set(sym01S_arr, 1, sales10+sales11+sales12+sales13) array.set(sym01S_arr, 0, sales11+sales12+sales13+sales14) // array.set(QOQs_arr, 11, QOQs0) array.set(QOQs_arr, 10, QOQs1) array.set(QOQs_arr, 9, QOQs2) array.set(QOQs_arr, 8, QOQs3) array.set(QOQs_arr, 7, QOQs4) array.set(QOQs_arr, 6, QOQs5) array.set(QOQs_arr, 5, QOQs6) array.set(QOQs_arr, 4, QOQs7) array.set(QOQs_arr, 3, QOQs8) array.set(QOQs_arr, 2, QOQs9) array.set(QOQs_arr, 1, QOQs10) array.set(QOQs_arr, 0, QOQs11) array.set(YOYs_arr, 11, YOYs0) array.set(YOYs_arr, 10, YOYs1) array.set(YOYs_arr, 9, YOYs2) array.set(YOYs_arr, 8, YOYs3) array.set(YOYs_arr, 7, YOYs4) array.set(YOYs_arr, 6, YOYs5) array.set(YOYs_arr, 5, YOYs6) array.set(YOYs_arr, 4, YOYs7) array.set(YOYs_arr, 3, YOYs8) array.set(YOYs_arr, 2, YOYs9) array.set(YOYs_arr, 1, YOYs10) array.set(YOYs_arr, 0, YOYs11) float QOQs = na float YOYs = na //Financial Ratios----------------------------------------------------------------------------------------- ROA = request.financial(syminfo.tickerid,"RETURN_ON_ASSETS", "FY") ROE = request.financial(syminfo.tickerid,"RETURN_ON_EQUITY", "FY") EPSt = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE", "TTM") TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ") TR = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "TTM") GR = request.financial(syminfo.tickerid, "REVENUE_ONE_YEAR_GROWTH", "FY") Cash = request.financial(syminfo.tickerid, "FREE_CASH_FLOW", "FY")/1000000 DY = request.financial(syminfo.tickerid, "DIVIDENDS_YIELD", "FY") DTE = request.financial(syminfo.tickerid, "DEBT_TO_EQUITY", "FY") PEGratio = request.financial(syminfo.tickerid, "PEG_RATIO", "FY") RevGrowth = request.financial(syminfo.tickerid, "REVENUE_ONE_YEAR_GROWTH", "FY")/100 EnterpriseValtoEBITDA = request.financial(syminfo.tickerid, "ENTERPRISE_VALUE_EBITDA", "FY") EBITDA = request.financial(syminfo.tickerid, "EBITDA", "FY") OPM = request.financial(syminfo.tickerid, "OPERATING_MARGIN", "FY") BV = request.financial(syminfo.tickerid, "BOOK_VALUE_PER_SHARE", "FY") //Calculation----------------------------------------------------------------------------------------- PriceEarningsRatio = close/EPSt MarketCap = TSO*close PriceSalesRatio = MarketCap/TR PriceBookValueRatio = close/BV EV = EnterpriseValtoEBITDA*EBITDA EVtoFCF = EV/(Cash*1000000) //Financial ratio Definition--------------------------------------------------------------------------- string def_PE = "The price-to-earnings (P/E) ratio is the ratio for valuing a company that measures its current share price relative to its per-share earnings." string def_PEG = "The price/earnings to growth ratio (PEG ratio) is a stock's price-to-earnings (P/E) ratio divided by the growth rate of its earnings (%) for a specified time period." string def_PS = "The price-to-sales (P/S) ratio is a valuation ratio that compares a company’s stock price to its revenues." string def_PB = "Price-to-book value (P/B) is the ratio of the market value of a company's shares (share price) over its book value of equity. The book value of equity, in turn, is the value of a company's assets expressed on the balance sheet." string def_EVFCF = "The Enterprise Value (EV) to Free Cash Flow (FCF) compares company valuation with its potential to create positive cash flow statements." string def_OPM = "Operating profit margin (OPM) is a measure of a company's operating efficiency. It is calculated by dividing operating income by net sales. " string def_DE = "Debt-to-equity (D/E) ratio is used to evaluate a company’s financial leverage and is calculated by dividing a company’s total liabilities by its shareholder equity. " string def_ROE = "Return on equity (ROE) is a measure of financial performance calculated by dividing net income by shareholders' equity. " string def_DY = "Dividend Yield represents the ratio of a company's current annual dividend compared to its current share price." //Truncate to Decimal--------------------------------------------------------------------------------- truncate(number, decimals) => factor = math.pow(10, decimals) int(number * factor) / factor Trunc_1 = truncate(ROA, 2) Trunc_2 = truncate(ROE, 2) Trunc_4 = truncate(PriceEarningsRatio, 2) Trunc_5 = truncate(PEGratio, 2) Trunc_6 = truncate(PriceSalesRatio, 2) Trunc_3 = truncate(PriceBookValueRatio, 2) Trunc_7 = truncate(Cash, 2) Trunc_8 = truncate(EVtoFCF, 2) Trunc_9 = truncate(DY, 2) Trunc_10 = truncate(DTE, 2) Trunc_11 = truncate(OPM, 2) //--------------------------------------------------------------------------------------------------------- //colors color good = color.new(#5ac573, 50) color bad = color.new(#df6464, 50) color neutral = color.new(color.blue, 50) color credits = color.new(color.blue, 50) // Find the Maximum Number for Plot scale coeff01 = math.max(math.abs(array.min(sym01_arr)), math.abs(array.max(sym01_arr))) scalCoef = 30/math.max(coeff01, 0) coeff01s = math.max(math.abs(array.min(sym01S_arr)), math.abs(array.max(sym01S_arr))) scalCoefs = 30/math.max(coeff01s, 0) // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | TABLE | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // Get Table Position table_pos(p) => switch p "Top Right" => position.top_right "Middle Right" => position.middle_right "Bottom Right" => position.bottom_right "Top Center" => position.top_center "Middle Center" => position.middle_center "Bottom Center" => position.bottom_center "Top Left" => position.top_left "Middle Left" => position.middle_left => position.bottom_left var plt = table.new(position.bottom_left, 1 , 1) // Find Number of Columns mxArr = 12 numCol = mxArr * 2 + 1 < 26 ? 25 : mxArr * 2 + 1 // Set Up Plot Table plt := table.new(table_pos(in_plot_pos), numCol+2, 81, frame_width = 0, frame_color = borCol, border_width = 0, border_color = color.new(txtCol, 100)) // Plot Cell pltCell (x, y, w, h, col, tt) => table.cell(plt, x, y, width = w, height = h, bgcolor = col) table.cell_set_tooltip(plt, x, y, tt) // Plot Columns eps pltCol (x, y, k, col) => pltCell(x, y > 0 ? 79 - k : y < 0 ? 79 + k : 79, barWdth, barHigh, color.new(col, 0), "EPS: " + str.tostring(y, "#.## \n")+ "QOQ: "+ str.tostring(QOQ, "#.#")+"%\n"+ "YOY: " + str.tostring(YOY, "#.#") + "%") // Plot Columns sales pltCol2 (x, y, k, col) => pltCell(x, y > 0 ? 43 - k : y < 0 ? 43 + k : 43, barWdth, barHigh, color.new(col, 0), "Sales: " + str.tostring(y, "#.##")+"Cr. \n"+ "QOQ: "+ str.tostring(QOQs, "#.#")+"%\n"+ "YOY: " + str.tostring(YOYs, "#.#") + "%") // Plot Financial Ratio Table table.cell(plt, 0, 0, "FinMet © Basit", width = barWdth, text_size = "small", text_color = color.white, bgcolor = borCol) table.merge_cells(plt, 0, 0, numCol+1, 0) table.cell(plt, 0, 1, "P/E: " +str.tostring(Trunc_4), width = barWdth, text_size = "normal", text_color = color.white, bgcolor = (Trunc_4 > lim_PE) or (Trunc_4 < 0) ? bad:good, tooltip = def_PE) table.merge_cells(plt, 0, 1, numCol+1, 1) table.cell(plt, 0, 2, "PEG: " +str.tostring(Trunc_5), width = barWdth, text_color = color.white, bgcolor = (Trunc_5 > lim_PEG) or (Trunc_5 < 0) ? bad:good, tooltip = def_PEG) table.merge_cells(plt, 0, 2, numCol+1, 2) table.cell(plt, 0, 3, "P/S: " +str.tostring(Trunc_6), width = barWdth, text_color = color.white, bgcolor = (Trunc_6 > lim_PS) or (Trunc_6 < 0) ? bad:good, tooltip = def_PS) table.merge_cells(plt, 0, 3, numCol+1, 3) table.cell(plt, 0, 4, "P/B: " +str.tostring(Trunc_3), width = barWdth, text_color = color.white, bgcolor = (Trunc_3 > lim_PB) or (Trunc_3 < 0) ? bad:good, tooltip = def_PB) table.merge_cells(plt, 0, 4, numCol+1, 4) table.cell(plt, 0, 5, "EV/FCF: " +str.tostring(Trunc_8), width = barWdth, text_color = color.white, bgcolor = (Trunc_8 > lim_EVFCF) or (Trunc_8 < 0) ? bad:good, tooltip = def_EVFCF) table.merge_cells(plt, 0, 5, numCol+1, 5) table.cell(plt, 0, 6, "OPM: " +str.tostring(Trunc_11) + "%", width = barWdth, text_color = color.white, bgcolor = (Trunc_11 < lim_OPM) or (Trunc_11 < 0) ? bad:good, tooltip = def_OPM) table.merge_cells(plt, 0, 6, numCol+1, 6) table.cell(plt, 0, 7, "D/E: " +str.tostring(Trunc_10), width = barWdth, text_color = color.white, bgcolor = (Trunc_10 > lim_DE) or (Trunc_10 < 0) ? bad:good, tooltip = def_DE) table.merge_cells(plt, 0, 7, numCol+1, 7) table.cell(plt, 0, 8, "ROE: " +str.tostring(Trunc_2)+ "%", width = barWdth, text_color = color.white, bgcolor = (Trunc_2 < lim_ROE) or (Trunc_2 < 0) ? bad:good, tooltip = def_ROE) table.merge_cells(plt, 0, 8, numCol+1, 8) table.cell(plt, 0, 9, "D_Yield: " +str.tostring(Trunc_9)+"%", width = barWdth, text_color = color.white, bgcolor = (Trunc_9 < lim_DVY) or (Trunc_9 < 0) ? bad:good, tooltip = def_DY) table.merge_cells(plt, 0, 9, numCol+1, 9) // Plot Sales and EPS bars if barstate.islast if mxArr > 0 // Reset Table. for i = 0 to numCol + 1 for j = 9 to 80 pltCell(i, j, 0.001, 0.001, color.new(txtCol, 100), "") // w= 0 for i = 2 to mxArr * 2 + 1 by 2 //Plot eps Columns if math.round(scalCoef * array.get(sym01_arr, w)) > 0 for k = 0 to math.round(scalCoef * array.get(sym01_arr, w)) QOQ = array.get(QOQ_arr, w) YOY = array.get(YOY_arr, w) pltCol(i, array.get(sym01_arr, w), k, s01Col) else if math.round(scalCoef * array.get(sym01_arr, w)) < 0 for k = 0 to math.round(scalCoef * array.get(sym01_arr, w)) QOQ = array.get(QOQ_arr, w) YOY = array.get(YOY_arr, w) pltCol(i, array.get(sym01_arr, w), k, s01Col2) else QOQ = array.get(QOQ_arr, w) YOY = array.get(YOY_arr, w) pltCol(i, array.get(sym01_arr, w), 0, color.new(s01Col, 0)) //plot sales columns if math.round(scalCoefs * array.get(sym01S_arr, w)) > 0 for k = 0 to math.round(scalCoefs * array.get(sym01S_arr, w)) QOQs = array.get(QOQs_arr, w) YOYs = array.get(YOYs_arr, w) pltCol2(i, array.get(sym01S_arr, w), k, s01Cols) else if math.round(scalCoefs * array.get(sym01S_arr, w)) < 0 for k = 0 to math.round(scalCoefs * array.get(sym01S_arr, w)) QOQs = array.get(QOQs_arr, w) YOYs = array.get(YOYs_arr, w) pltCol2(i, array.get(sym01S_arr, w), k, s01Col2) else QOQs = array.get(QOQs_arr, w) YOYs = array.get(YOYs_arr, w) pltCol2(i, array.get(sym01S_arr, w), 0, color.new(s01Cols, 0)) w := w + 1 // Draw X Axis Line (X==0) // for i = 2 to numCol // pltCell(i, 43, 0.4, 0.005, borCol, "") // for i = 2 to numCol // pltCell(i, 78, 0.4, 0.005, borCol, "") for i = 10 to 80 pltCell(0, i, 0.3, 0.005, borCol, "") for i = 10 to 80 pltCell(numCol+1, i, 0.3, 0.005, borCol, "") if Period == "FQ" table.cell(plt, 0, 44, "Sales (FQ)" , width = barWdth, text_size = "small", text_color = color.white, bgcolor = borCol) table.merge_cells(plt, 0, 44, numCol+1, 44) else table.cell(plt, 0, 44, "Sales (TTM)", width = barWdth, text_size = "small", text_color = color.white, bgcolor = borCol) table.merge_cells(plt, 0, 44, numCol+1, 44) if Period == "FQ" table.cell(plt, 0, 80, "EPS (FQ)" + str.format_time(ResultDate, " [dd-MM]" ), width = barWdth, text_size = "small", text_color = color.white, bgcolor = borCol) table.merge_cells(plt, 0, 80, numCol+1, 80) else table.cell(plt, 0, 80, "EPS (TTM)" + str.format_time(ResultDate, " [dd-MM]" ) , width = barWdth, text_size = "small", text_color = color.white, bgcolor = borCol) table.merge_cells(plt, 0, 80, numCol+1, 80)
RSI Trend Veracity (RSI TV)
https://www.tradingview.com/script/FmLIEQho-RSI-Trend-Veracity-RSI-TV/
More-Than-Enough
https://www.tradingview.com/u/More-Than-Enough/
54
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © More-Than-Enough //@version=5 indicator(title = "RSI Trend Veracity", shorttitle = "RSI TV", precision = 3, timeframe = "", timeframe_gaps = true) Tv_Line = 0.0 Rsi_Line = ta.rsi(close, 14) * 0.1 - 5 Ma_Line = ta.sma(Rsi_Line, 14) Low_Tsi = ta.tsi(close, 1, 54) Low_Tv_Line = ta.rsi(close, 35) * 0.1 - 5 + Low_Tsi High_Tsi = ta.tsi(close, 1, 13) High_Tv_Line = ta.rsi(close, 35) * 0.1 - 5 + High_Tsi if Rsi_Line > 0 Tv_Line := High_Tv_Line if Rsi_Line < 0 Tv_Line := Low_Tv_Line /////////////// Thresholds /////////////// High_Extremity_Color = input.color(color.new(color.lime, 50), "High Extremity Color") High_Extremity = input.float(3.0, "High Extremity", minval = 0.0, step = 0.1) High_Color = input.color(color.new(color.lime, 50), "High Color") High = input.float(2.0, "High", minval = 0.0, step = 0.1) High_Mid_Color = input.color(color.gray, "High-Mid Color") Mid = 0 Mid_Color = input.color(color.rgb(91, 156, 246, 50), "Middle Color") Low_Mid_Color = input.color(color.gray, "Low-Mid Color") Low = input.float(-2.0, "Low", maxval = 0.0, step = 0.1) Low_Color = input.color(color.new(color.red, 50), "Low Color") Low_Extremity = input.float(-3.0, "Low Extremity", maxval = 0.0, step = 0.1) Low_Extremity_Color = input.color(color.new(color.red, 50), "Low Extremity Color") /////////////// Plots /////////////// High_Extremity_Line = hline(High_Extremity, "High Extremity Line", High_Extremity_Color, linestyle = hline.style_dotted, editable = false) High_Line = hline(High, "High Line", High_Color, linestyle = hline.style_solid, editable = false) High_Mid_Line = hline(Mid + ((math.abs(High) - math.abs(Mid)) / 2), "High-Mid Line", High_Mid_Color, linestyle = hline.style_dotted, editable = false) Mid_Line = hline(Mid, "Middle Line", Mid_Color, linestyle = hline.style_solid, editable = false) Low_Mid_Line = hline(Mid - ((math.abs(Mid) + math.abs(Low)) / 2), "Low-Mid Line", Low_Mid_Color, linestyle = hline.style_dotted, editable = false) Low_Line = hline(Low, "Low Line", Low_Color, linestyle = hline.style_solid, editable = false) Low_Extremity_Line = hline(Low_Extremity, "Low Extremity Line", Low_Extremity_Color, linestyle = hline.style_dotted, editable = false) fill(Mid_Line, High_Line, color.rgb(129, 199, 132, 86), "Up Zone") fill(Mid_Line, Low_Line, color.rgb(247, 124, 128, 86), "Down Zone") plot(Tv_Line, "TV Plot", color = color.new(color.aqua, 50), style = plot.style_area) plot(Ma_Line, "MA Plot", color = color.rgb(255, 245, 157), display = display.none) plot(Rsi_Line, "RSI Plot", color = color.white)
Rate Of Change For -5 Percent Rule
https://www.tradingview.com/script/QP0bic2Q/
87468ee8f0384037b9e29d027af485
https://www.tradingview.com/u/87468ee8f0384037b9e29d027af485/
24
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © 87468ee8f0384037b9e29d027af485 //@version=5 indicator(title="Rate Of Change For -5 Percent Rule", shorttitle="ROC For -5 Percent Rule", format=format.price, precision=2, timeframe="", timeframe_gaps=true) length = input.int(1, minval=1) source1 = input(close, "Source1") source2 = input(close, "Source2") borderline = input.int(-5, "Borderline") roc = 100 * (source2 - source1[length])/source1[length] green_or_red = if roc > borderline color.green else color.red plot(roc, color = green_or_red, title = "Rate Of Change", style = plot.style_columns) hline(borderline, color = color.red, linewidth = 2, linestyle = hline.style_dotted, editable = false)
Thursday Close Bands
https://www.tradingview.com/script/6GBDxPzn-Thursday-Close-Bands/
Srinivas_SIP
https://www.tradingview.com/u/Srinivas_SIP/
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/ // © sateesh1496 //@version=5 indicator("Thursday Close Bands", overlay = true) bandsize = input.float(3,title= "Band Size") tc= ta.valuewhen(dayofweek(time('D')) == dayofweek.thursday, close, 0) upperband = tc*(1+(bandsize/100)) lowerband = tc*(1-(bandsize/100)) plot(tc,style=plot.style_stepline,linewidth=2) plot(upperband[1],title="Upper Band", color=color.red,style=plot.style_stepline,linewidth=2) plot(lowerband[1],title= "Lower Band", color=color.green,style=plot.style_stepline,linewidth=2) c = color.green bgColor = dayofweek == dayofweek.thursday ? color.new(c, 90) : color.new(color.white, 80) bgcolor(color=bgColor, transp=90)
BTC's #4 Whale Sells [TheSecretGuy]
https://www.tradingview.com/script/4Aywhbtn-BTC-s-4-Whale-Sells-TheSecretGuy/
TheSecretsOfTrading
https://www.tradingview.com/u/TheSecretsOfTrading/
78
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/ // © TheSecretsOfTrading //@version=5 indicator("Dates: BTC's #4 Whale Sells by TheSecretGuy", overlay=true) sell_color = color.rgb(255, 0, 85) var whale_sell = 0 var int[] whale_sells = array.from( timestamp("18 Nov 2022 18:17:00 EST"), //- 1000 timestamp("16 Nov 2022 18:19:00 EST"), //- 2000 timestamp("26 Oct 2022 18:16:00 EST"), //- 1000 timestamp("5 Oct 2022 18:30:00 EST"), //- 1000 timestamp("12 Sep 2022 18:34:00 EST"), // -1000 timestamp("28 Jul 2022 18:13:00 EST"), // -500 timestamp("26 Jul 2022 17:08:00 EST"), // -500 timestamp("18 Jul 2022 17:49:00 EST"), // -500 timestamp("18 Jul 2022 15:45:00 EST"), // -500 timestamp("9 Jun 2022 18:29:00 EST"), // -500 timestamp("17 May 2022 13:30:00 EST"), // -1500 timestamp("29 Apr 2022 14:46:00 EST"), // -1500 timestamp("20 Apr 2022 19:49:00 EST"), // -1500 timestamp("4 Apr 2022 18:30:00 EST"), // -3000 timestamp("1 Apr 2022 16:56:00 EST"), // -1500 timestamp("25 Mar 2022 17:03:00 EST"), // -1500 timestamp("21 Mar 2022 14:45:00 EST"), // -1500 timestamp("1 Mar 2022 16:15:00 EST"), // -1500 timestamp("9 Nov 2021 19:13:00 EST") // -1500 ) if barstate.islastconfirmedhistory i = 0 while i < array.size(whale_sells) whale_sell := array.get(whale_sells, i) line.new(x1=whale_sell, y1=high, x2=whale_sell, y2=low, extend=extend.both, color=sell_color, width=1, xloc=xloc.bar_time) i += 1
Bayesian BBSMA + nQQE Oscillator + Bank funds (whales detector)
https://www.tradingview.com/script/43zBXjjp-Bayesian-BBSMA-nQQE-Oscillator-Bank-funds-whales-detector/
tartigradia
https://www.tradingview.com/u/tartigradia/
189
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/ // // Three trend indicators in one. Fork of Gunslinger2005 indicator, with a fix to display the nQQE oscillator correctly and clearly, and converted to pinescript v5 (allowing to set a different timeframe and gaps). // How to use: Essentially, nQQE is a long term trend indicator which is more adequate in daily or weekly timeframe to indicate the current market cycle. Banker Fund seems better suited to indicate current local trend, although it is sensitive to relief rallies. Bayesian BBSMA is an awesome tool to visualize the buildup in bullish/bearish sentiment, and when it is more likely to get released, however it is unreliable, so it needs to be combined with other indicators. // // Original indicators list: // Bayesian BBSMA: https://www.tradingview.com/v/8lXcviYm/ // nQQE: https://www.tradingview.com/v/CfCuUCeE/ // L3 Banker Fund Flow Trend: https://www.tradingview.com/v/791WkWcm/ // Originally mixed together by Gunslinger2005: https://www.tradingview.com/script/Gan1g6EY-The-Bayesian-Q-Oscillator/ // Fixed nQQE plotting by Tartigradia //@version=5 indicator('Bayesian BBSMA + nQQE Oscillator + Bank funds (whales detector)', shorttitle='Bayesian/nQQE/BankFunds', precision=4, timeframe="", timeframe_gaps=true) rescale(_src, _oldMin, _oldMax, _newMin, _newMax) => // Rescales series with known min/max. // _src : series to rescale. // _oldMin, _oldMax: min/max values of series to rescale. // _newMin, _newMin: min/max values of rescaled series. _newMin + (_newMax - _newMin) * (_src - _oldMin) / math.max(_oldMax - _oldMin, 10e-10) //#################### Bayesian BBSMA bbSmaPeriod = input.int(20, title='BB SMA Period', group='═════ Bayesian BBSMA settings ═════') bbStdDevMult = input.float(2.5, title='BB Standard Deviation', maxval=50.0) bbBasis = ta.sma(close, bbSmaPeriod) bbStdDev = bbStdDevMult * ta.stdev(close, bbSmaPeriod) bbUpper = bbBasis + bbStdDev bbLower = bbBasis - bbStdDev // AO aoFast = input(5, 'AO Fast EMA Length') aoSlow = input(34, 'AO Slow EMA Length') ao = ta.sma(hl2, aoFast) - ta.sma(hl2, aoSlow) colorAo = ta.change(ao) > 0 ? color.green : color.red // AC acFast = input(5, 'AC Fast SMA Length') acSlow = input(34, 'AC Slow SMA Length') xSMA1_hl2 = ta.sma(hl2, acFast) xSMA2_hl2 = ta.sma(hl2, acSlow) xSMA1_SMA2 = xSMA1_hl2 - xSMA2_hl2 xSMA_hl2 = ta.sma(xSMA1_SMA2, acFast) ac = xSMA1_SMA2 - xSMA_hl2 cClr = ac > ac[1] ? color.blue : color.red acAo = (ac + ao) / 2 maAcAoPeriod = input(13, 'AC AO MA Period') showMaAcAo = input(false, 'Show AC AO MA?') maAcAo = ta.vwma(acAo, maAcAoPeriod) // Combine AC & AO acIsBlue = ac > ac[1] acIsRed = not(ac > ac[1]) aoIsGreen = ta.change(ao) > 0 aoIsRed = not(ta.change(ao) > 0) acAoIsBullish = acIsBlue and aoIsGreen acAoIsBearish = acIsRed and acIsRed acAoColorIndex = acAoIsBullish ? 1 : acAoIsBearish ? -1 : 0 // Alligator smma(src, length) => smma = 0.0 smma := na(smma[1]) ? ta.sma(src, length) : (smma[1] * (length - 1) + src) / length smma lipsLength = input(title='🐲 Lips Length', defval=5) teethLength = input(title='🐲 Teeth Length', defval=8) jawLength = input(title='🐲 Jaw Length', defval=13) lipsOffset = input(title='🐲 Lips Offset', defval=3) teethOffset = input(title='🐲 Teeth Offset', defval=5) jawOffset = input(title='🐲 Jaw Offset', defval=8) lips = smma(hl2, lipsLength) teeth = smma(hl2, teethLength) jaw = smma(hl2, jawLength) // SMA smaPeriod = input(20, title='SMA Period') smaValues = ta.sma(close, smaPeriod) // Bayesian Theorem Starts bayesPeriod = input(20, title='Bayesian Lookback Period') // Next candles are breaking Down probBbUpperUpSeq = close > bbUpper ? 1 : 0 probBbUpperUp = math.sum(probBbUpperUpSeq, bayesPeriod) / bayesPeriod probBbUpperDownSeq = close < bbUpper ? 1 : 0 probBbUpperDown = math.sum(probBbUpperDownSeq, bayesPeriod) / bayesPeriod probUpBbUpper = probBbUpperUp / (probBbUpperUp + probBbUpperDown) probBbBasisUpSeq = close > bbBasis ? 1 : 0 probBbBasisUp = math.sum(probBbBasisUpSeq, bayesPeriod) / bayesPeriod probBbBasisDownSeq = close < bbBasis ? 1 : 0 probBbBasisDown = math.sum(probBbBasisDownSeq, bayesPeriod) / bayesPeriod probUpBbBasis = probBbBasisUp / (probBbBasisUp + probBbBasisDown) probSmaUpSeq = close > smaValues ? 1 : 0 probSmaUp = math.sum(probSmaUpSeq, bayesPeriod) / bayesPeriod probSmaDownSeq = close < smaValues ? 1 : 0 probSmaDown = math.sum(probSmaDownSeq, bayesPeriod) / bayesPeriod probUpSma = probSmaUp / (probSmaUp + probSmaDown) sigmaProbsDown = nz(probUpBbUpper * probUpBbBasis * probUpSma / probUpBbUpper * probUpBbBasis * probUpSma + (1 - probUpBbUpper) * (1 - probUpBbBasis) * (1 - probUpSma)) // Next candles are breaking Up probDownBbUpper = probBbUpperDown / (probBbUpperDown + probBbUpperUp) probDownBbBasis = probBbBasisDown / (probBbBasisDown + probBbBasisUp) probDownSma = probSmaDown / (probSmaDown + probSmaUp) sigmaProbsUp = nz(probDownBbUpper * probDownBbBasis * probDownSma / probDownBbUpper * probDownBbBasis * probDownSma + (1 - probDownBbUpper) * (1 - probDownBbBasis) * (1 - probDownSma)) showNextCandleDown = input(true, title='Plot Next Candles Breaking Down?') plot(showNextCandleDown ? sigmaProbsDown * 100 : na, title='Next Candle Breaking Down Probs', style=plot.style_area, color=color.new(color.red, 60), linewidth=2) showNextCandleUp = input(true, title='Plot Next Candles Breaking Up?') plot(showNextCandleUp ? sigmaProbsUp * 100 : na, title='Next Candle Breaking Up Probs', style=plot.style_area, color=color.new(color.green, 60), linewidth=2) probPrime = nz(sigmaProbsDown * sigmaProbsUp / sigmaProbsDown * sigmaProbsUp + (1 - sigmaProbsDown) * (1 - sigmaProbsUp)) showPrime = input(true, title='Plot Prime Probability?') plot(showPrime ? probPrime * 100 : na, title='Prime Probability', style=plot.style_area, color=color.new(color.blue, 60), linewidth=2) lowerThreshold = input(15.0, title='Lower Threshold') sideways = probPrime < lowerThreshold / 100 and sigmaProbsUp < lowerThreshold / 100 and sigmaProbsDown < lowerThreshold / 100 longUsingProbPrime = probPrime > lowerThreshold / 100 and probPrime[1] == 0 longUsingSigmaProbsUp = sigmaProbsUp < 1 and sigmaProbsUp[1] == 1 shortUsingProbPrime = probPrime == 0 and probPrime[1] > lowerThreshold / 100 shortUsingSigmaProbsDown = sigmaProbsDown < 1 and sigmaProbsDown[1] == 1 milanIsRed = acAoColorIndex == -1 milanIsGreen = acAoColorIndex == 1 pricesAreMovingAwayUpFromAlligator = close > jaw and open > jaw pricesAreMovingAwayDownFromAlligator = close < jaw and open < jaw useBWConfirmation = input(false, title='Use Bill Williams indicators for confirmation?') bwConfirmationUp = useBWConfirmation ? milanIsGreen and pricesAreMovingAwayUpFromAlligator : true bwConfirmationDown = useBWConfirmation ? milanIsRed and pricesAreMovingAwayDownFromAlligator : true longSignal = bwConfirmationUp and (longUsingProbPrime or longUsingSigmaProbsUp) shortSignal = bwConfirmationDown and (shortUsingProbPrime or shortUsingSigmaProbsDown) barcolor(longSignal ? color.lime : na, title='Long Bars') barcolor(shortSignal ? color.maroon : na, title='Short Bars') //hzl3 = hline(lowerThreshold, color=#333333, linestyle=hline.style_solid) //hzl4 = hline(0, color=#333333, linestyle=hline.style_solid) //fill(hzl3, hzl4, title="Lower Threshold", color=sideways ? color.gray : color.maroon, transp=70) alertcondition(longSignal, title='Long!', message='Bayesian BBSMA - LONG - {{exchange}}:{{ticker}} at {{close}}') alertcondition(shortSignal, title='Short!', message='Bayesian BBSMA - SHORT - {{exchange}}:{{ticker}} at {{close}}') //#################### nQQE src = input(close) length = input.int(14, 'RSI Length', minval=1, group='═════ nQQE settings ═════') SSF = input.int(5, 'SF RSI SMoothing Factor', minval=1) showsignals = input(title='Show Crossing Signals?', defval=false) RSII = ta.ema(ta.rsi(src, length), SSF) TR = math.abs(RSII - RSII[1]) wwalpha = 1 / length WWMA = 0.0 WWMA := wwalpha * TR + (1 - wwalpha) * nz(WWMA[1]) ATRRSI = 0.0 ATRRSI := wwalpha * WWMA + (1 - wwalpha) * nz(ATRRSI[1]) QQEF = ta.ema(ta.rsi(src, length), SSF) QUP = QQEF + ATRRSI * 4.236 QDN = QQEF - ATRRSI * 4.236 QQES = 0.0 QQES := QUP < nz(QQES[1]) ? QUP : QQEF > nz(QQES[1]) and QQEF[1] < nz(QQES[1]) ? QDN : QDN > nz(QQES[1]) ? QDN : QQEF < nz(QQES[1]) and QQEF[1] > nz(QQES[1]) ? QUP : nz(QQES[1]) Colorh = QQEF > 60 ? color.lime : QQEF < 40 ? color.red : #E8E81A QQF = plot(QQEF, 'nQQE FAST', color=color.new(color.maroon, 0), linewidth=2, display=display.none) plot(QQEF, color=color.new(Colorh, 30), linewidth=2, style=plot.style_area, histbase=50) QQS = plot(QQES, 'nQQE SLOW', color=color.new(color.white, 0), linewidth=2, display=display.none) hline(60, color=color.gray, linestyle=hline.style_dashed) hline(40, color=color.gray, linestyle=hline.style_dashed) buySignalr = ta.crossover(QQEF, QQES) plotshape(buySignalr and showsignals ? QQES * 0.995 : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.black, 50), textcolor=color.new(color.white, 50)) sellSignallr = ta.crossunder(QQEF, QQES) plotshape(sellSignallr and showsignals ? QQES * 1.005 : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.black, 50), textcolor=color.new(color.white, 50)) alertcondition(ta.cross(QQEF, QQES), title='Cross Alert', message='QQE Crossing Signal!') alertcondition(ta.crossover(QQEF, QQES), title='Crossover Alarm', message='QQE BUY SIGNAL!') alertcondition(ta.crossunder(QQEF, QQES), title='Crossunder Alarm', message='QQE SELL SIGNAL!') alertcondition(ta.crossover(QQEF, 50), title='Cross 0 Up Alert', message='QQE FAST Crossing 0 UP!') alertcondition(ta.crossunder(QQEF, 50), title='Cross 0 Down Alert', message='QQE FAST Crossing 0 DOWN!') alertcondition(ta.crossover(QQEF, 60), title='Cross 10 Up Alert', message='QQE Above 10 UPTREND SIGNAL!') alertcondition(ta.crossunder(QQEF, 40), title='Cross -10 Down Alert', message='QQE Below -10 DOWNTREND SIGNAL!') alertcondition(ta.crossunder(QQEF, 60) or ta.crossover(QQEF, 40), title='SIDEWAYS', message='QQE Entering Sideways Market!') //#################### L3 Banker //functions xrf(values, length) => r_val = float(na) if length >= 1 for i = 0 to length by 1 if na(r_val) or not na(values[i]) r_val := values[i] r_val r_val xsa(src, len, wei) => sumf = 0.0 ma = 0.0 out = 0.0 sumf := nz(sumf[1]) - nz(src[len]) + src ma := na(src[len]) ? na : sumf / len out := na(out[1]) ? ma : (src * wei + out[1] * (len - wei)) / len out //set up a simple model of banker fund flow trend fundtrend = (3 * xsa((close - ta.lowest(low, 27)) / (ta.highest(high, 27) - ta.lowest(low, 27)) * 100, 5, 1) - 2 * xsa(xsa((close - ta.lowest(low, 27)) / (ta.highest(high, 27) - ta.lowest(low, 27)) * 100, 5, 1), 3, 1) - 50) * 1.032 + 50 //define typical price for banker fund typ = (2 * close + high + low + open) / 5 //lowest low with mid term fib # 34 lol = ta.lowest(low, 34) //highest high with mid term fib # 34 hoh = ta.highest(high, 34) //define banker fund flow bull bear line bullbearline = ta.ema((typ - lol) / (hoh - lol) * 100, 13) //define banker entry signal bankerentry = ta.crossover(fundtrend, bullbearline) and bullbearline < 25 //banker fund entry with yellow candle plotcandle(0, 50, 0, 50, color=bankerentry ? color.new(color.yellow, 0) : na, bordercolor=color.new(color.black, 100)) //banker increase position with green candle plotcandle(fundtrend, bullbearline, fundtrend, bullbearline, color=fundtrend > bullbearline ? color.new(color.green, 0) : na, bordercolor=color.new(color.black, 100)) //banker decrease position with white candle plotcandle(fundtrend, bullbearline, fundtrend, bullbearline, color=fundtrend < xrf(fundtrend * 0.95, 1) ? color.new(color.white, 0) : na, bordercolor=color.new(color.black, 100)) //banker fund exit/quit with red candle plotcandle(fundtrend, bullbearline, fundtrend, bullbearline, color=fundtrend < bullbearline ? color.new(color.red, 0) : na, bordercolor=color.new(color.black, 100)) //banker fund Weak rebound with blue candle plotcandle(fundtrend, bullbearline, fundtrend, bullbearline, color=fundtrend < bullbearline and fundtrend > xrf(fundtrend * 0.95, 1) ? color.new(color.blue, 0) : na, bordercolor=color.new(color.black, 100)) //overbought and oversold threshold lines //h1 = hline(80,color=color.red, linestyle=hline.style_dotted) //h2 = hline(20, color=color.yellow, linestyle=hline.style_dotted) //h3 = hline(10,color=color.lime, linestyle=hline.style_dotted) //h4 = hline(90, color=color.fuchsia, linestyle=hline.style_dotted) //fill(h2,h3,color=color.yellow,transp=70) //fill(h1,h4,color=color.fuchsia,transp=70) alertcondition(bankerentry, title='Alert on Yellow Candle', message='Yellow Candle!') alertcondition(fundtrend > bullbearline, title='Alert on Green Candle', message='Green Candle!') alertcondition(fundtrend < xrf(fundtrend * 0.95, 1), title='Alert on White Candle', message='White Candle!') alertcondition(fundtrend < bullbearline, title='Alert on Red Candle', message='Red Candle!') alertcondition(fundtrend < bullbearline and fundtrend > xrf(fundtrend * 0.95, 1), title='Alert on Blue Candle', message='Blue Candle!')
Display Momento -[0.1]-
https://www.tradingview.com/script/oBIZKM4W-Display-Momento-0-1/
DIemotion
https://www.tradingview.com/u/DIemotion/
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/ // © DI-emotion // Use for education in Discord: The Big Secret Channel //@version=5 indicator("Display Momento ", shorttitle = "Momentum Panel", overlay = true) // receive value from user sourcebar = input.source(defval = close, title = 'source') left_tab = input(defval = true , title = 'Turn on/off left tab' , group = '=======Table setting=======') Panel_header_text_size = input.string(defval = size.normal , title = 'Header size', options = [size.tiny,size.small,size.normal,size.large,size.huge], group = '=======Table setting=======') Panel_text_size = input.string(defval = size.small, title = 'Text size',options = [size.tiny,size.small,size.normal,size.large,size.huge], group = '=======Table setting=======') Panel_pos = input.session(defval = position.top_right , title = 'Panel Position' , options = [position.top_left,position.top_center,position.top_right,position.middle_left,position.middle_center,position.middle_right,position.bottom_left,position.bottom_center,position.bottom_right], group = '=======Table setting=======') indi_rsi_bool = input(defval = true,title = '', inline = 'rsi' , group = '=======RSI=======') indi_rsi = input(defval = 14, title = 'RSI' , inline = 'rsi' , group = '=======RSI=======') // indi_rsi_middle = input(defval = true, title = 'RSI seperate middle zone?') indi_stoch_bool = input(defval = true, title ='Stochastic ON/OFF ' , group = '=======Stochastic=======') indi_stoch_K = input(defval = 14, title = 'Stochastic length' , group = '=======Stochastic=======') indi_stoch_K_smooth = input.int(defval = 3 , title = 'SmoothK(Stochastic)',minval = 0 , group = '=======Stochastic=======') indi_stoch_D = input.int(defval = 3, title = 'SmoothD(Stochastic)',minval = 0 , group = '=======Stochastic=======') indi_atr_bool = input(defval = true, title ='' , inline = 'atr' , group = '=======ATR=======') indi_atr = input(defval = 14, title = 'ATR' , inline = 'atr' , group = '=======ATR=======') tf1 = input.timeframe(defval = '60' , title = 'Timeframe 1' , group = '=======Timeframe setting=======') tf2 = input.timeframe(defval = '240' , title = 'Timeframe 2' , group = '=======Timeframe setting=======') tf3 = input.timeframe(defval = '480' , title = 'Timeframe 3' , group = '=======Timeframe setting=======') tf4 = input.timeframe(defval = '720' , title = 'Timeframe 4' , group = '=======Timeframe setting=======') tf5 = input.timeframe(defval = 'D' , title = 'Timeframe 5' , group = '=======Timeframe setting=======') chart1 = input.symbol(defval = 'BTCUSDT' , title = 'Chart1' , group = '=======Chart setting=======') chart2 = input.symbol(defval = 'ETHUSDT', title = 'Chart2' , group = '=======Chart setting=======') chart3 = input.symbol(defval = 'GOLD', title = 'Chart3' , group = '=======Chart setting=======') chart4 = input.symbol(defval = 'US30', title = 'Chart4' , group = '=======Chart setting=======') note = input.string(defval = 'Note me :)' , title = 'Note') // Sad_mode = input.bool(defval = false , title = 'เปิด/ปิดไปก็เท่านั้นก็ยังโสดอยู่ดี55+') //style tab rsi_oversold = input.color(defval = color.new(#742421 , 10) , title = 'RSI oversold', group = '=======Color=======') rsi_bearzone = input.color(defval = color.new(#ec4141, 10) , title = 'RSI bearzone', group = '=======Color=======') rsi_nature = input.color(defval = color.new(#e47d38, 2) , title = 'RSI nature', group = '=======Color=======') rsi_bullzone = input.color(defval = color.new(#67f06b, 30) , title = 'RSI bullzone', group = '=======Color=======') rsi_overbought = input.color(defval = color.new(#2c812f, 30) , title = 'RSI overbought', group = '=======Color=======') stoch_oversold = input.color(defval = color.new(#742421 , 10) , title = 'STOCH oversold', group = '=======Color=======') stoch_bearzone = input.color(defval = color.new(#ec4141, 10) , title = 'STOCH bearzone', group = '=======Color=======') stoch_overbought = input.color(defval = color.new(#2c812f, 30) , title = 'STOCH overbought', group = '=======Color=======') stoch_bullzone = input.color(defval = color.new(#67f06b, 30) , title = 'STOCH bullzone', group = '=======Color=======') stoch_crossup_color = input.color(defval = color.green , title = 'STOCH crossup', group = '=======Color=======') stoch_crossdown_color = input.color(defval = color.red , title = 'STOCH crossdown', group = '=======Color=======') atr_color = input.color(defval = color.gray , title = 'ATR', group = '=======Color=======') // ta set ta_stoch_K = ta.sma(ta.stoch(sourcebar , high , low , indi_stoch_K) , indi_stoch_K_smooth) ta_stoch_D = ta.sma(ta_stoch_K , indi_stoch_D) ta_rsi = ta.rsi(sourcebar, indi_rsi) ta_atr = ta.atr(indi_atr) //rsi tf ta_rsi_1 = request.security(syminfo.tickerid , tf1 , ta_rsi) ta_rsi_2 = request.security(syminfo.tickerid , tf2 , ta_rsi) ta_rsi_3 = request.security(syminfo.tickerid , tf3 , ta_rsi) ta_rsi_4 = request.security(syminfo.tickerid , tf4 , ta_rsi) ta_rsi_5 = request.security(syminfo.tickerid , tf5 , ta_rsi) //%K stoch tf ta_stoch_1 = request.security(syminfo.tickerid , tf1 , ta_stoch_K) ta_stoch_2 = request.security(syminfo.tickerid , tf2 , ta_stoch_K) ta_stoch_3 = request.security(syminfo.tickerid , tf3 , ta_stoch_K) ta_stoch_4 = request.security(syminfo.tickerid , tf4 , ta_stoch_K) ta_stoch_5 = request.security(syminfo.tickerid , tf5 , ta_stoch_K) //%D Stoch tf ta_stoch_D_1 = request.security(syminfo.tickerid , tf1 , ta_stoch_D) ta_stoch_D_2 = request.security(syminfo.tickerid , tf2 , ta_stoch_D) ta_stoch_D_3 = request.security(syminfo.tickerid , tf3 , ta_stoch_D) ta_stoch_D_4 = request.security(syminfo.tickerid , tf4 , ta_stoch_D) ta_stoch_D_5 = request.security(syminfo.tickerid , tf5 , ta_stoch_D) //atr tf ta_atr_1 = request.security(syminfo.ticker , tf1 , ta_atr) ta_atr_2 = request.security(syminfo.ticker , tf2 , ta_atr) ta_atr_3 = request.security(syminfo.ticker , tf3 , ta_atr) ta_atr_4 = request.security(syminfo.ticker , tf4 , ta_atr) ta_atr_5 = request.security(syminfo.ticker , tf5 , ta_atr) //TF tf_list = array.new_string(112 , '') array.set(tf_list , 0 , tf1) array.set(tf_list , 1 , tf2) array.set(tf_list , 2 , tf3) array.set(tf_list , 3 , tf4) array.set(tf_list , 4 , tf5) //array chart list chart_list = array.new_string(112 , '') array.set(chart_list , 0 , chart1) array.set(chart_list , 1 , chart2) array.set(chart_list , 2 , chart3) array.set(chart_list , 3 , chart4) // symbol rsi rsi_symbol_1 = array.new_float(800 , 0) array.set(rsi_symbol_1 , 0 , request.security(chart1 , '' , ta_rsi)) array.set(rsi_symbol_1 , 1 , request.security(chart1 , tf1 , ta_rsi)) array.set(rsi_symbol_1 , 2 , request.security(chart1 , tf2 , ta_rsi)) array.set(rsi_symbol_1 , 3 , request.security(chart1 , tf3 , ta_rsi)) array.set(rsi_symbol_1 , 4 , request.security(chart1 , tf4 , ta_rsi)) array.set(rsi_symbol_1 , 5 , request.security(chart1 , tf5 , ta_rsi)) rsi_symbol_2 = array.new_float(800 , 0) array.set(rsi_symbol_2 , 0 , request.security(chart2 , '' , ta_rsi)) array.set(rsi_symbol_2 , 1 , request.security(chart2 , tf1 , ta_rsi)) array.set(rsi_symbol_2 , 2 , request.security(chart2 , tf2 , ta_rsi)) array.set(rsi_symbol_2 , 3 , request.security(chart2 , tf3 , ta_rsi)) array.set(rsi_symbol_2 , 4 , request.security(chart2 , tf4 , ta_rsi)) array.set(rsi_symbol_2 , 5 , request.security(chart2 , tf5 , ta_rsi)) rsi_symbol_3 = array.new_float(800 , 0) array.set(rsi_symbol_3 , 0 , request.security(chart3 , '' , ta_rsi)) array.set(rsi_symbol_3 , 1 , request.security(chart3 , tf1 , ta_rsi)) array.set(rsi_symbol_3 , 2 , request.security(chart3 , tf2 , ta_rsi)) array.set(rsi_symbol_3 , 3 , request.security(chart3 , tf3 , ta_rsi)) array.set(rsi_symbol_3 , 4 , request.security(chart3 , tf4 , ta_rsi)) array.set(rsi_symbol_3 , 5 , request.security(chart3 , tf5 , ta_rsi)) //limit secure request symbol 4 was close // rsi_symbol_4 = array.new_float(800 , 0) // array.set(rsi_symbol_4 , 0 , request.security(chart4 , '' , ta_rsi)) // array.set(rsi_symbol_4 , 1 , request.security(chart4 , tf1 , ta_rsi)) // array.set(rsi_symbol_4 , 2 , request.security(chart4 , tf2 , ta_rsi)) // array.set(rsi_symbol_4 , 3 , request.security(chart4 , tf3 , ta_rsi)) // array.set(rsi_symbol_4 , 4 , request.security(chart4 , tf4 , ta_rsi)) // array.set(rsi_symbol_4 , 5 , request.security(chart4 , tf5 , ta_rsi)) //rsi array set rsi_value = array.new_float(800 , 0) rsi_color = array.new_color(800 , color.black) array.set(rsi_value , 0 , ta_rsi) array.set(rsi_value , 1 , ta_rsi_1) array.set(rsi_value , 2 , ta_rsi_2) array.set(rsi_value , 3 , ta_rsi_3) array.set(rsi_value , 4 , ta_rsi_4) array.set(rsi_value , 5 , ta_rsi_5) //stoch color upto value stoch_value = array.new_float(800 , 0 ) stoch_value_d = array.new_float(800 , 0) stoch_cross = array.new_string(800 , '') stoch_color = array.new_color(800 , color.black) stoch_cross_color = array.new_color(800 , color.yellow) //%k stoch array set array.set(stoch_value , 0 , ta_stoch_K) array.set(stoch_value , 1 , ta_stoch_1) array.set(stoch_value , 2 , ta_stoch_2) array.set(stoch_value , 3 , ta_stoch_3) array.set(stoch_value , 4 , ta_stoch_4) array.set(stoch_value , 5 , ta_stoch_5) // %d stoch array set array.set(stoch_value_d , 0 , ta_stoch_D) array.set(stoch_value_d , 1 , ta_stoch_D_1) array.set(stoch_value_d , 2 , ta_stoch_D_2) array.set(stoch_value_d , 3 , ta_stoch_D_3) array.set(stoch_value_d , 4 , ta_stoch_D_4) array.set(stoch_value_d , 4 , ta_stoch_D_5) //atr array set atr_value = array.new_float(800, 0) atr_string = array.new_string(800, '') array.set(atr_value , 0 , ta_atr) array.set(atr_value , 1 , ta_atr_1) array.set(atr_value , 2 , ta_atr_2) array.set(atr_value , 3 , ta_atr_3) array.set(atr_value , 4 , ta_atr_4) array.set(atr_value , 5 , ta_atr_5) //atr filter rsi_symbol_1_color = array.new_color(800 , color.black) rsi_symbol_2_color = array.new_color(800 , color.black) rsi_symbol_3_color = array.new_color(800 , color.black) //add hr to string tf for i = 0 to 4 if str.tonumber(array.get(tf_list , i)) >= 60 array.set(tf_list , i , str.tostring(str.tonumber(array.get(tf_list , i))/60) + 'HR') //bg rsi symbol 1 for i = 0 to 5 if array.get(rsi_symbol_1 , i) < 30 array.set(rsi_symbol_1_color , i , rsi_oversold) if array.get(rsi_symbol_1 , i) < 50 and array.get(rsi_symbol_1 , i) > 30 array.set(rsi_symbol_1_color , i , rsi_bearzone) if array.get(rsi_symbol_1 , i) > 50 and array.get(rsi_symbol_1 , i) < 60 array.set(rsi_symbol_1_color , i , rsi_nature) if array.get(rsi_symbol_1 , i) > 60 and array.get(rsi_symbol_1 , i) < 70 array.set(rsi_symbol_1_color , i , rsi_bullzone) if array.get(rsi_symbol_1 , i) > 70 array.set(rsi_symbol_1_color , i , rsi_overbought) //bg rsi symbol 2 if array.get(rsi_symbol_2 , i) < 30 array.set(rsi_symbol_2_color , i , rsi_oversold) if array.get(rsi_symbol_2 , i) < 50 and array.get(rsi_symbol_2 , i) > 30 array.set(rsi_symbol_2_color , i , rsi_bearzone) if array.get(rsi_symbol_2 , i) > 50 and array.get(rsi_symbol_2 , i) < 60 array.set(rsi_symbol_2_color , i , rsi_nature) if array.get(rsi_symbol_2 , i) > 60 and array.get(rsi_symbol_2 , i) < 70 array.set(rsi_symbol_2_color , i , rsi_bullzone) if array.get(rsi_symbol_2 , i) > 70 array.set(rsi_symbol_2_color , i , rsi_overbought) //bg rsi symbol 3 if array.get(rsi_symbol_3 , i) < 30 array.set(rsi_symbol_3_color , i , rsi_oversold) if array.get(rsi_symbol_3 , i) < 50 and array.get(rsi_symbol_3 , i) > 30 array.set(rsi_symbol_3_color , i , rsi_bearzone) if array.get(rsi_symbol_3 , i) > 50 and array.get(rsi_symbol_3 , i) < 60 array.set(rsi_symbol_3_color , i , rsi_nature) if array.get(rsi_symbol_3 , i) > 60 and array.get(rsi_symbol_3 , i) < 70 array.set(rsi_symbol_3_color , i , rsi_bullzone) if array.get(rsi_symbol_3 , i) > 70 array.set(rsi_symbol_3_color , i , rsi_overbought) // for i= 0 to 5 // if array.get(atr_value , i) < 0.01 // array.set(rsi_symbol_1 , i , '#.######') //bg rsi upto value for i = 0 to 5 if array.get(rsi_value , i) < 30 array.set(rsi_color , i , rsi_oversold) if array.get(rsi_value , i)<50 and array.get(rsi_value , i) > 30 array.set(rsi_color , i , rsi_bearzone) if array.get(rsi_value , i)>50 and array.get(rsi_value , i)<60 array.set(rsi_color , i , rsi_nature) if array.get(rsi_value , i)>60 and array.get(rsi_value , i) < 70 array.set(rsi_color , i , rsi_bullzone) if array.get(rsi_value , i)>70 array.set(rsi_color , i , rsi_overbought) //bg stoch upto value for i = 0 to 5 if array.get(stoch_value , i) > 70 array.set(stoch_color , i , stoch_overbought) if array.get(stoch_value , i) > 50 and array.get(stoch_value , i) <70 array.set(stoch_color , i , stoch_bullzone) if array.get(stoch_value , i) > 30 and array.get(stoch_value , i) <50 array.set(stoch_color , i , stoch_bearzone) if array.get(stoch_value , i) < 30 array.set(stoch_color , i , stoch_oversold) //stoch cross + bg stoch cross upto value for i = 0 to 5 if array.get(stoch_value, i) > array.get(stoch_value_d, i) array.set(stoch_cross , i , 'Crossup' ) array.set(stoch_cross_color , i , stoch_crossup_color) else array.set(stoch_cross , i , 'Crossdown' ) array.set(stoch_cross_color , i , stoch_crossdown_color) //table set var table1 = table.new(Panel_pos, 30, 30, bgcolor = color.rgb(68, 68, 68, 28), border_width = 1, border_color = color.rgb(255, 255, 255)) table.set_frame_color(table1 , color.white) table.set_frame_width(table1 , 1) if left_tab == true table.cell(table1, 0 , 0 , text = '𓁹 ‿ 𓁹' , text_color = color.white , text_size = Panel_text_size ) table.cell(table1, 0 , 1 , text = 'WatchList' , text_color = color.white , text_size = Panel_text_size ) table.cell(table1, 0 , 2 , text = 'Current chart' , text_color = color.white , text_size = Panel_text_size) table.cell(table1, 0 , 3 , text = chart1 , text_color = color.white , text_size = Panel_text_size) table.cell(table1, 0 , 4 , text = chart2 , text_color = color.white , text_size = Panel_text_size) table.cell(table1, 0 , 5 , text = chart3 , text_color = color.white , text_size = Panel_text_size) table.cell(table1, 0 , 6 , text = 'Note' , text_color = color.rgb(255, 255, 255) , text_size = Panel_text_size) if indi_rsi_bool==true table.merge_cells(table1 , 1, 6 , 6, 6) table.merge_cells(table1 , 1, 0 ,6 ,0 ) //rsi symbol 1 table.cell(table1,1,3,str.tostring(array.get(rsi_symbol_1 , 0), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_1_color , 0)) table.cell(table1,2,3,str.tostring(array.get(rsi_symbol_1 , 1), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_1_color , 1)) table.cell(table1,3,3,str.tostring(array.get(rsi_symbol_1 , 2), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_1_color , 2)) table.cell(table1,4,3,str.tostring(array.get(rsi_symbol_1 , 3), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_1_color , 3)) table.cell(table1,5,3,str.tostring(array.get(rsi_symbol_1 , 4), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_1_color , 4)) table.cell(table1,6,3,str.tostring(array.get(rsi_symbol_1 , 5), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_1_color , 5)) //rsi symbol 2 , bgcolor = array.get(rsi_symbol_1_color , )) table.cell(table1,1,4,str.tostring(array.get(rsi_symbol_2 , 0), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_2_color , 0)) table.cell(table1,2,4,str.tostring(array.get(rsi_symbol_2 , 1), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_2_color , 1)) table.cell(table1,3,4,str.tostring(array.get(rsi_symbol_2 , 2), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_2_color , 2)) table.cell(table1,4,4,str.tostring(array.get(rsi_symbol_2 , 3), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_2_color , 3)) table.cell(table1,5,4,str.tostring(array.get(rsi_symbol_2 , 4), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_2_color , 4)) table.cell(table1,6,4,str.tostring(array.get(rsi_symbol_2 , 5), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_2_color , 5)) //rsi symbol 3 , bgcolor = array.get(rsi_symbol_1_color , )) table.cell(table1,1,5,str.tostring(array.get(rsi_symbol_3 , 0), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_3_color , 0)) table.cell(table1,2,5,str.tostring(array.get(rsi_symbol_3 , 1), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_3_color , 1)) table.cell(table1,3,5,str.tostring(array.get(rsi_symbol_3 , 2), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_3_color , 2)) table.cell(table1,4,5,str.tostring(array.get(rsi_symbol_3 , 3), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_3_color , 3)) table.cell(table1,5,5,str.tostring(array.get(rsi_symbol_3 , 4), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_3_color , 4)) table.cell(table1,6,5,str.tostring(array.get(rsi_symbol_3 , 5), '#.##'), text_color = color.white , text_size = Panel_text_size , bgcolor = array.get(rsi_symbol_3_color , 5)) //Interest chart table.cell(table1, 1 , 6 , text = note , text_color = color.white , text_size = Panel_text_size) //rsi symbol 4 // limit secure // table.cell(table1,1,6,str.tostring(array.get(rsi_symbol_4 , 0), '#.##'), text_color = color.white , text_size = Panel_text_size) // table.cell(table1,2,6,str.tostring(array.get(rsi_symbol_4 , 1), '#.##'), text_color = color.white , text_size = Panel_text_size) // table.cell(table1,3,6,str.tostring(array.get(rsi_symbol_4 , 2), '#.##'), text_color = color.white , text_size = Panel_text_size) // table.cell(table1,4,6,str.tostring(array.get(rsi_symbol_4 , 3), '#.##'), text_color = color.white , text_size = Panel_text_size) // table.cell(table1,5,6,str.tostring(array.get(rsi_symbol_4 , 4), '#.##'), text_color = color.white , text_size = Panel_text_size) // table.cell(table1,6,6,str.tostring(array.get(rsi_symbol_4 , 5), '#.##'), text_color = color.white , text_size = Panel_text_size) //rsi current chart table.cell(table1,1,0,text = 'RSI',text_color = color.white , text_size = Panel_header_text_size , bgcolor = color.rgb(0, 0, 0)) //header table.cell(table1,1,1,text = 'CURRENT TF',text_color = color.white , text_size = Panel_text_size) table.cell(table1,2,1,text = array.get(tf_list , 0),text_color = color.white , text_size = Panel_text_size) table.cell(table1,3,1,text = array.get(tf_list , 1),text_color = color.white , text_size = Panel_text_size) table.cell(table1,4,1,text = array.get(tf_list , 2),text_color = color.white , text_size = Panel_text_size) table.cell(table1,5,1,text = array.get(tf_list , 3),text_color = color.white , text_size = Panel_text_size) table.cell(table1,6,1,text = array.get(tf_list , 4),text_color = color.white , text_size = Panel_text_size) table.cell(table1,1,2,str.tostring(ta_rsi, '#.##'), text_color = color.white , bgcolor = (array.get(rsi_color , 0)) , text_size = Panel_text_size ) table.cell(table1,2,2,str.tostring(ta_rsi_1, '#.##'), text_color = color.white , bgcolor = (array.get(rsi_color , 1)) , text_size = Panel_text_size ) table.cell(table1,3,2,str.tostring(ta_rsi_2, '#.##'), text_color = color.white , bgcolor = (array.get(rsi_color , 2)) , text_size = Panel_text_size ) table.cell(table1,4,2,str.tostring(ta_rsi_3, '#.##'), text_color = color.white , bgcolor = (array.get(rsi_color , 3)) , text_size = Panel_text_size ) table.cell(table1,5,2,str.tostring(ta_rsi_4, '#.##'), text_color = color.white , bgcolor = (array.get(rsi_color , 4)) , text_size = Panel_text_size ) table.cell(table1,6,2,str.tostring(ta_rsi_5, '#.##'), text_color = color.white , bgcolor = (array.get(rsi_color , 5)) , text_size = Panel_text_size ) // table.cell(table1,2,1,str.tostring(ta_rsi_1hr[1], '#.##'), text_color = color.white , bgcolor = (bg_color_rsi) , text_size = Panel_text_size ) if indi_stoch_bool == true table.merge_cells(table1 , 7 , 0 , 12 , 0) table.cell(table1,7,0,text = 'STOCH', text_color = color.white , text_size = Panel_header_text_size , bgcolor = color.rgb(0, 0, 0)) //header table.cell(table1,7,1,text = 'CURRENT TF' , text_color = color.white , text_size = Panel_text_size) table.cell(table1,8,1,text = array.get(tf_list , 0), text_color = color.white , text_size = Panel_text_size) table.cell(table1,9,1,text = array.get(tf_list , 1), text_color = color.white , text_size = Panel_text_size) table.cell(table1,10,1,text = array.get(tf_list , 2), text_color = color.white , text_size = Panel_text_size) table.cell(table1,11,1,text = array.get(tf_list , 3), text_color = color.white , text_size = Panel_text_size) table.cell(table1,12,1,text = array.get(tf_list , 4), text_color = color.white , text_size = Panel_text_size) table.cell(table1,7,2,str.tostring(ta_stoch_K,'#.##'), text_color = color.white , bgcolor = array.get(stoch_color , 0) , text_size = Panel_text_size) table.cell(table1,8,2,str.tostring(ta_stoch_1,'#.##'), text_color = color.white , bgcolor = array.get(stoch_color , 1) , text_size = Panel_text_size) table.cell(table1,9,2,str.tostring(ta_stoch_2,'#.##'), text_color = color.white , bgcolor = array.get(stoch_color , 2) , text_size = Panel_text_size) table.cell(table1,10,2,str.tostring(ta_stoch_3,'#.##'), text_color = color.white , bgcolor = array.get(stoch_color , 3) , text_size = Panel_text_size) table.cell(table1,11,2,str.tostring(ta_stoch_4,'#.##'), text_color = color.white , bgcolor = array.get(stoch_color , 4) , text_size = Panel_text_size) table.cell(table1,12,2,str.tostring(ta_stoch_5,'#.##'), text_color = color.white , bgcolor = array.get(stoch_color , 5) , text_size = Panel_text_size) table.cell(table1,7,3, text = array.get(stoch_cross , 0) , text_color = color.white , bgcolor = array.get(stoch_cross_color , 0) , text_size = Panel_text_size) table.cell(table1,8,3, text = array.get(stoch_cross , 1) , text_color = color.white , bgcolor = array.get(stoch_cross_color , 1) , text_size = Panel_text_size) table.cell(table1,9,3, text = array.get(stoch_cross , 2) , text_color = color.white , bgcolor = array.get(stoch_cross_color , 2) , text_size = Panel_text_size) table.cell(table1,10,3, text = array.get(stoch_cross , 3) , text_color = color.white , bgcolor = array.get(stoch_cross_color , 3) , text_size = Panel_text_size) table.cell(table1,11,3, text = array.get(stoch_cross , 4) , text_color = color.white , bgcolor = array.get(stoch_cross_color , 4) , text_size = Panel_text_size) table.cell(table1,12,3, text = array.get(stoch_cross , 5) , text_color = color.white , bgcolor = array.get(stoch_cross_color , 5) , text_size = Panel_text_size) if indi_atr_bool == true if close < 0.001 table.merge_cells(table1 , 7 , 4 , 12 , 4) table.cell(table1,7,4,text = 'ATR', text_color = color.white , text_size = Panel_header_text_size , bgcolor = color.rgb(0, 0, 0)) //header table.cell(table1,7,5,text = 'CURRENT TF', text_color = color.white , text_size = Panel_text_size) table.cell(table1,8,5,text = array.get(tf_list , 0), text_color = color.white , text_size = Panel_text_size) table.cell(table1,9,5,text = array.get(tf_list , 1), text_color = color.white , text_size = Panel_text_size) table.cell(table1,10,5,text = array.get(tf_list , 2), text_color = color.white , text_size = Panel_text_size) table.cell(table1,11,5,text = array.get(tf_list , 3), text_color = color.white , text_size = Panel_text_size) table.cell(table1,12,5,text = array.get(tf_list , 4), text_color = color.white , text_size = Panel_text_size) table.cell(table1,7,6,str.tostring(ta_atr,'#.########'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,8,6,str.tostring(ta_atr_1,'#.########'), text_color = color.white , bgcolor = atr_color, text_size = Panel_text_size) table.cell(table1,9,6,str.tostring(ta_atr_2,'#.########'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,10,6,str.tostring(ta_atr_3,'#.########'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,11,6,str.tostring(ta_atr_4,'#.########'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,12,6,str.tostring(ta_atr_5,'#.########'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) if close < 0.01 and close > 0.001 table.merge_cells(table1 , 7 , 4 , 12 , 4) table.cell(table1,7,4,text = 'ATR', text_color = color.white , text_size = Panel_header_text_size , bgcolor = color.rgb(0, 0, 0)) //header table.cell(table1,7,5,text = 'CURRENT TF', text_color = color.white , text_size = Panel_text_size) table.cell(table1,8,5,text = array.get(tf_list , 0), text_color = color.white , text_size = Panel_text_size) table.cell(table1,9,5,text = array.get(tf_list , 1), text_color = color.white , text_size = Panel_text_size) table.cell(table1,10,5,text = array.get(tf_list , 2), text_color = color.white , text_size = Panel_text_size) table.cell(table1,11,5,text = array.get(tf_list , 3), text_color = color.white , text_size = Panel_text_size) table.cell(table1,12,5,text = array.get(tf_list , 4), text_color = color.white , text_size = Panel_text_size) table.cell(table1,7,6,str.tostring(ta_atr,'#.######'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,8,6,str.tostring(ta_atr_1,'#.######'), text_color = color.white , bgcolor = atr_color, text_size = Panel_text_size) table.cell(table1,9,6,str.tostring(ta_atr_2,'#.#######'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,10,6,str.tostring(ta_atr_3,'#.#######'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,11,6,str.tostring(ta_atr_4,'#.#######'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,12,6,str.tostring(ta_atr_5,'#.#######'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) if close < 0.1 and close > 0.01 table.merge_cells(table1 , 7 , 4 , 12 , 4) table.cell(table1,7,4,text = 'ATR', text_color = color.white , text_size = Panel_header_text_size , bgcolor = color.rgb(0, 0, 0)) //header table.cell(table1,7,5,text = 'CURRENT TF', text_color = color.white , text_size = Panel_text_size) table.cell(table1,8,5,text = array.get(tf_list , 0), text_color = color.white , text_size = Panel_text_size) table.cell(table1,9,5,text = array.get(tf_list , 1), text_color = color.white , text_size = Panel_text_size) table.cell(table1,10,5,text = array.get(tf_list , 2), text_color = color.white , text_size = Panel_text_size) table.cell(table1,11,5,text = array.get(tf_list , 3), text_color = color.white , text_size = Panel_text_size) table.cell(table1,12,5,text = array.get(tf_list , 4), text_color = color.white , text_size = Panel_text_size) table.cell(table1,7,6,str.tostring(ta_atr,'#.#####'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,8,6,str.tostring(ta_atr_1,'#.#####'), text_color = color.white , bgcolor = atr_color, text_size = Panel_text_size) table.cell(table1,9,6,str.tostring(ta_atr_2,'#.#####'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,10,6,str.tostring(ta_atr_3,'#.#####'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,11,6,str.tostring(ta_atr_4,'#.#####'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,12,6,str.tostring(ta_atr_5,'#.#####'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) if close < 10 and close > 0 table.merge_cells(table1 , 7 , 4 , 12 , 4) table.cell(table1,7,4,text = 'ATR', text_color = color.white , text_size = Panel_header_text_size , bgcolor = color.rgb(0, 0, 0)) //header table.cell(table1,7,5,text = 'CURRENT TF', text_color = color.white , text_size = Panel_text_size) table.cell(table1,8,5,text = array.get(tf_list , 0), text_color = color.white , text_size = Panel_text_size) table.cell(table1,9,5,text = array.get(tf_list , 1), text_color = color.white , text_size = Panel_text_size) table.cell(table1,10,5,text = array.get(tf_list , 2), text_color = color.white , text_size = Panel_text_size) table.cell(table1,11,5,text = array.get(tf_list , 3), text_color = color.white , text_size = Panel_text_size) table.cell(table1,12,5,text = array.get(tf_list , 4), text_color = color.white , text_size = Panel_text_size) table.cell(table1,7,6,str.tostring(ta_atr,'#.####'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,8,6,str.tostring(ta_atr_1,'#.####'), text_color = color.white , bgcolor = atr_color, text_size = Panel_text_size) table.cell(table1,9,6,str.tostring(ta_atr_2,'#.###'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,10,6,str.tostring(ta_atr_3,'#.###'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,11,6,str.tostring(ta_atr_4,'#.###'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,12,6,str.tostring(ta_atr_5,'#.###'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) else if close > 10 table.merge_cells(table1 , 7 , 4 , 12 , 4) table.cell(table1,7,4,text = 'ATR', text_color = color.white , text_size = Panel_header_text_size , bgcolor = color.rgb(0, 0, 0)) //header table.cell(table1,7,5,text = 'CURRENT TF', text_color = color.white , text_size = Panel_text_size) table.cell(table1,8,5,text = array.get(tf_list , 0), text_color = color.white , text_size = Panel_text_size) table.cell(table1,9,5,text = array.get(tf_list , 1), text_color = color.white , text_size = Panel_text_size) table.cell(table1,10,5,text = array.get(tf_list , 2), text_color = color.white , text_size = Panel_text_size) table.cell(table1,11,5,text = array.get(tf_list , 3), text_color = color.white , text_size = Panel_text_size) table.cell(table1,12,5,text = array.get(tf_list , 4), text_color = color.white , text_size = Panel_text_size) table.cell(table1,7,6,str.tostring(ta_atr,'#.##'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,8,6,str.tostring(ta_atr_1,'#.##'), text_color = color.white , bgcolor = atr_color, text_size = Panel_text_size) table.cell(table1,9,6,str.tostring(ta_atr_2,'#.##'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,10,6,str.tostring(ta_atr_3,'#.#'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,11,6,str.tostring(ta_atr_4,'#.#'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size) table.cell(table1,12,6,str.tostring(ta_atr_5,'#.#'), text_color = color.white , bgcolor = atr_color , text_size = Panel_text_size)
Recession And Bull Run Warning
https://www.tradingview.com/script/f8h1Hjzt-Recession-And-Bull-Run-Warning/
chinmaysk1
https://www.tradingview.com/u/chinmaysk1/
129
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/ // © chinmaysk1 //@version=5 indicator("Recession Warning",overlay = true) // EMA values ema1 = ta.ema(close,5) ema2 = ta.ema(close,21) // Getting moving averages from UNEMPLOY low_ema = request.security('UNEMPLOY', 'D', ema1) high_ema = request.security('UNEMPLOY', 'D', ema2) // Check When Unemploy Avgs Could Cross cross = ((102 * high_ema[1]) - (22 * low_ema[1])) / 80 // Signals and plots warning_true = low_ema[2] < high_ema[2] and low_ema >= high_ema plotshape(warning_true, "Recession Warning", style = shape.circle, location = location.abovebar, color = color.red, size = size.small) bullrun = low_ema >= high_ema and low_ema[2] > low_ema plotshape(bullrun, "Bullrun Incoming", style = shape.circle, location = location.belowbar, color = color.green, size = size.small) current_unemploy = request.security('UNEMPLOY', 'D', close) projection = label.new(bar_index + 10, close, style = label.style_label_left, color = color.rgb(15,15,15)) label.set_textcolor(projection, color.white) label.set_textalign(projection, text.align_left) label.delete(projection[1]) if low_ema < high_ema label.set_text(projection, "Current Unemployment: " + str.tostring(current_unemploy) + "\nRecession When Unemployment Reaches " + str.tostring(math.round(cross))) else label.set_text(projection, "Current Unemployment: " + str.tostring(current_unemploy) + "\nBull Run When Unemployment Drops To " + str.tostring(math.round(cross)) + "\n(Ignore If Green Dot Signalled)")
Big Money Flow & Drift Oscillator [Spiritualhealer117]
https://www.tradingview.com/script/tRxPLDfK-Big-Money-Flow-Drift-Oscillator-Spiritualhealer117/
spiritualhealer117
https://www.tradingview.com/u/spiritualhealer117/
124
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/ // © spiritualhealer117 //@version=5 indicator("BM&D Oscillator") src = input.source(close,"Source") len = input(14,"Length") ret = (src-src[1])/src[1] vol_cond = volume>ta.ema(volume, len) drift_arr = array.new<float>(len) bmf_arr = array.new<float>(len) for i = 0 to len if vol_cond[i] array.insert(bmf_arr,i,ret[i]) else array.insert(drift_arr,i,ret[i]) drift = array.avg(drift_arr) bmf = array.avg(bmf_arr) line1=plot(drift*100, "Drift", #003049) hline(0) line2=plot(bmf*100,"Big Money Flow", #003049) clr = drift>bmf?(drift>0?#eae2b7:#d62828):(bmf>0?#fcbf49:#f77f00) fill(line1,line2, clr)
HZlog
https://www.tradingview.com/script/tBSMkraL-HZlog/
RafaelZioni
https://www.tradingview.com/u/RafaelZioni/
778
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/ // © RafaelZioni //@version=5 indicator('HZlog ', overlay=true) src = input(close) tf = input(3600) len = timeframe.isintraday and timeframe.multiplier >= 1 ? tf / timeframe.multiplier * 7 : timeframe.isintraday and timeframe.multiplier < 60 ? 60 / timeframe.multiplier * 24 * 7 : 7 ma = ta.ema(src * close, len) / ta.ema(close, len) // src1 = ma z(src1, len) => n = 0.0 s = 0.0 for i = 0 to len - 1 by 1 wr = (len - i) * len n += wr s += src[i] * wr s s / n hm = 2.0 * z(src1, math.floor(len / 2)) - z(src1, len) zhma = z(hm, math.floor(math.sqrt(len))) lineColor = zhma > zhma[2] ? color.lime : color.red plot(zhma, title='ZHMA', color=lineColor, linewidth=3) hColor = true vis = true hu = hColor ? zhma > zhma[2] ? #00ff00 : #ff0000 : #ff9800 vl = zhma[0] ll = zhma[2] m1 = plot(vl, color=hu, linewidth=1, transp=60) m2 = plot(vis ? ll : na, color=hu, linewidth=2, transp=80) fill(m1, m2, color=hu, transp=70) c5 = zhma f1 = 1 f2 = 1000 // up = c5 - f1 * math.log(f2) dn = c5 + f1 * math.log(f2) // factor = input.float(title='Factor', defval=0.001, minval=0.001, maxval=5, step=0.01) hb = 0.00 hb := nz(hb[1]) hl = 0.000 hl := nz(hl[1]) lb = 0.00 lb := nz(lb[1]) l1 = 0.000 l1 := nz(l1[1]) c = 0 c := nz(c[1]) + 1 trend = 0 trend := nz(trend[1]) n = dn x = up if barstate.isfirst c := 0 lb := n hb := x l1 := c5 hl := c5 hl if c == 1 if x >= hb[1] hb := x hl := c5 trend := 1 trend else lb := n l1 := c5 trend := -1 trend if c > 1 if trend[1] > 0 hl := math.max(hl[1], c5) if x >= hb[1] hb := x hb else if n < hb[1] - hb[1] * factor lb := n l1 := c5 trend := -1 trend else l1 := math.min(l1[1], c5) if n <= lb[1] lb := n lb else if x > lb[1] + lb[1] * factor hb := x hl := c5 trend := 1 trend v = trend == 1 ? hb : trend == -1 ? lb : na //plot(v, color=trend == 1 ? color.blue : color.yellow, style=plot.style_circles, linewidth=1, title='trend', join=true, transp=0) // long = trend == 1 and trend[1] == -1 short = trend == -1 and trend[1] == 1 // last_long = 0.0 last_short = 0.0 last_long := long ? time : nz(last_long[1]) last_short := short ? time : nz(last_short[1]) buy = ta.crossover(last_long, last_short) sell = ta.crossover(last_short, last_long) /////////////// Plotting /////////////// plotshape(buy, title='buy', text='Buy', color=color.new(color.green, 0), style=shape.labelup, location=location.belowbar, size=size.small, textcolor=color.new(color.white, 0)) //plot for buy icon plotshape(sell, title='sell', text='Sell', color=color.new(color.red, 0), style=shape.labeldown, location=location.abovebar, size=size.small, textcolor=color.new(color.white, 0)) /////////////// Alerts /////////////// alertcondition(buy, title='buy', message='Buy') alertcondition(sell, title='sell', message='Sell')
FinNifty Volumes
https://www.tradingview.com/script/IWcqIJUZ-FinNifty-Volumes/
bullseyetrading_lko
https://www.tradingview.com/u/bullseyetrading_lko/
51
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/ // © carefulTortois38674 //@version=4 study("Finnifty volume",resolution="",format=format.volume) barColorsOnPrevClose = input(title="Color bars based on previous close", type=input.bool, defval=false) palette = barColorsOnPrevClose ? close[1] > close ? color.red : color.green : open > close ? color.red : color.green a= security("NSE:AXISBANK",timeframe.period,volume) b= security("NSE:BAJAJFINSV",timeframe.period,volume) c= security("NSE:BAJFINANCE",timeframe.period,volume) d= security("NSE:CHOLAFIN",timeframe.period,volume) e= security("NSE:HDFC",timeframe.period,volume) f= security("NSE:HDFCAMC",timeframe.period,volume) g= security("NSE:HDFCBANK",timeframe.period,volume) h= security("NSE:HDFCLIFE",timeframe.period,volume) i= security("NSE:ICICIBANK",timeframe.period,volume) j= security("NSE:ICICIGI",timeframe.period,volume) k= security("NSE:ICICIPRULI",timeframe.period,volume) l= security("NSE:KOTAKBANK",timeframe.period,volume) m= security("NSE:MUTHOOTFIN",timeframe.period,volume) n= security("NSE:PFC",timeframe.period,volume) o= security("NSE:RECLTD",timeframe.period,volume) p= security("NSE:SBICARD",timeframe.period,volume) q= security("NSE:SBILIFE",timeframe.period,volume) r= security("NSE:SBIN",timeframe.period,volume) s= security("NSE:SRTRANSFIN",timeframe.period,volume) Finnifty_volume=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s Finnifty_average=sma(Finnifty_volume,length=input(defval=10)) plot(Finnifty_volume, color = palette, style=plot.style_columns, title="Finnifty volume") plot(Finnifty_average,color=color.black,title="moving average") plot(close)
Chart CAGR
https://www.tradingview.com/script/xbwxRNY6-Chart-CAGR/
TradingView
https://www.tradingview.com/u/TradingView/
200
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/ // © TradingView //@version=5 indicator("Chart CAGR", overlay = true) // Chart CAGR // v1, 2022.10.09 // 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/VisibleChart/1 as chart import TradingView/ta/2 as ta //#region ———————————————————— Constants and Inputs // ————— Constants color GRAY = color.silver color NOCOLOR = #FFFFFF00 // ————— Inputs string infoBoxSizeInput = input.string("normal", "Size ", inline = "display", options = ["tiny", "small", "normal", "large", "huge", "auto"]) string infoBoxYPosInput = input.string("bottom", "↕", inline = "display", options = ["top", "middle", "bottom"]) string infoBoxXPosInput = input.string("right", "↔", inline = "display", options = ["left", "center", "right"]) color infoBoxColorInput = input.color(NOCOLOR, "", inline = "display") color infoBoxTxtColorInput = input.color(GRAY, "T", inline = "display") //#endregion //#region ———————————————————— Functions //@function Calculates the growth rate as a percent from the `exitPrice` relative to the `entryPrice`. //@param entryPrice (series float) The entry price. //@param exitPrice (series float) The exit price. //@returns (float) The percent growth rate. growthRate(series float entryPrice, series float exitPrice) => float result = (exitPrice / entryPrice - 1) * 100 //#endregion //#region ———————————————————— Calculations float firstChartBarOpen = chart.open() float lastChartBarClose = chart.close() int firstChartBarTime = chart.left_visible_bar_time int lastChartBarTime = chart.right_visible_bar_time float cagr = ta.cagr(firstChartBarTime, firstChartBarOpen, lastChartBarTime, lastChartBarClose) float gr = growthRate(firstChartBarOpen, lastChartBarClose) //#endregion //#region ———————————————————— Visuals var table infoBox = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 2, 3) if barstate.isfirst table.cell(infoBox, 0, 0, "Growth rate:", text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxColorInput) table.cell(infoBox, 0, 1, "CAGR:", text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxColorInput) table.cell(infoBox, 1, 0, "", text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxColorInput) table.cell(infoBox, 1, 1, "", text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput, bgcolor = infoBoxColorInput) else if barstate.islast table.cell_set_text(infoBox, 1, 0, str.tostring(gr, format.percent)) table.cell_set_text(infoBox, 1, 1, str.tostring(cagr, format.percent)) //#endregion
Altcoin Analyzer [Lysergik]
https://www.tradingview.com/script/fwb7gfGw-Altcoin-Analyzer-Lysergik/
lysergik
https://www.tradingview.com/u/lysergik/
28
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/ // © lysergik //@version=5 indicator("Altcoin Analyzer [Lysergik]", shorttitle='AltAnal', precision=8) // ------------ // Inputs int f_length = input.int(21, 'Fast MA Length', minval=2, group='Configs') int s_length = input.int(50, 'Slow MA Length', minval=2, group='Configs') bool use_fma = input.bool(true, 'Show Fast Moving Average', group='Settings') bool use_sma = input.bool(true, 'Show Slow Moving Average', group='Settings') bool predict_ema = input.bool(true, 'Show MA Prediction', group='Settings') bool ema = input.bool(true, 'Use EMA instead of SMA', group='Settings') bool use_candles = input.bool(true, 'Use Candles', group='Settings') bool heikin = input.bool(true, 'Heikin Candles', group='Settings') bool dark_mode = input.bool(true, 'Dark Mode', group='Swag') bool mini_display = input.bool(false, 'Mini-Display', 'Show less information in the table', group="Swag") bool col = input.bool(true, 'Color MAs to Reflect the Trend', group='Swag') // ------------ // Data float btc_open = request.security("INDEX:BTCUSD", timeframe.period, open, barmerge.gaps_off, barmerge.lookahead_off) float btc_high = request.security("INDEX:BTCUSD", timeframe.period, high, barmerge.gaps_off, barmerge.lookahead_off) float btc_low = request.security("INDEX:BTCUSD", timeframe.period, low, barmerge.gaps_off, barmerge.lookahead_off) float btc_close = request.security("INDEX:BTCUSD", timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off) float o = open/btc_open float h = high/btc_high float l = low/btc_low float c = close/btc_close float btcusd_change = ( ta.highest(btc_high, 2) ) - ( ta.lowest(btc_low, 2) ) float altusd_change = ( ta.highest(high, 2) ) - ( ta.lowest(low, 2) ) color neutral_col = dark_mode ? color.white : color.black color back_col = dark_mode ? color.black : color.white float fMA = 0.00 float sMA = 0.00 string predict_type = "EMA" bool colInvert = true string id = syminfo.basecurrency // ------------ // Pure Functions ma(_type, _src, _len) => if _type == "EMA" ta.ema(_src, _len) else if _type == "SMA" ta.sma(_src, _len) ma_prediction(_type, _src, _period, _offset) => (ma(_type, _src, _period - _offset) * (_period - _offset) + _src * _offset) / _period isBelow(_v2, _v1) => out = false if _v1 > _v2 out := true volatility(_change, _length, _close) => lowest_roc = ta.lowest(_change, _length) highest_roc = ta.highest(_change, _length) volatility = ta.ema((highest_roc - lowest_roc), 2) percent = volatility/_close*100 // ------------ // Math & Logic btc_volatility = volatility(btcusd_change, 21, btc_close) alt_volatility = volatility(altusd_change, 21, close) relative_volatility = alt_volatility - btc_volatility src(_src) => Close = not heikin ? c : math.avg(o, h, l, c) Open = float(na) Open := not heikin ? o : na(Open[1]) ? (o + c) / 2 : (nz(Open[1]) + nz(Close[1])) / 2 High = not heikin ? h : math.max(h, math.max(Open, Close)) Low = not heikin ? l : math.min(l, math.min(Open, Close)) HL2 = not heikin ? math.avg(l, h) : math.avg(High, Low) HLC3 = not heikin ? math.avg(l, h, c) : math.avg(High, Low, Close) OHLC4 = not heikin ? math.avg(o, h, l, c) : math.avg(Open, High, Low, Close) Price = _src == 'close' ? Close : _src == 'open' ? Open : _src == 'high' ? High : _src == 'low' ? Low : _src == 'hl2' ? HL2 : _src == 'hlc3' ? HLC3 : OHLC4 // PineCoders method for aligning Pine prices with chart instrument prices //Source = math.round(Price / syminfo.mintick) * syminfo.mintick if id == '' id := 'invalid' if ema fMA := ta.ema(c, f_length) sMA := ta.ema(c, s_length) predict_type := "EMA" else fMA := ta.sma(c, f_length) sMA := ta.sma(c, s_length) predict_type := "SMA" longemapredictor_1 = ma_prediction(predict_type, c, s_length, 1) longemapredictor_2 = ma_prediction(predict_type, c, s_length, 2) longemapredictor_3 = ma_prediction(predict_type, c, s_length, 3) longemapredictor_4 = ma_prediction(predict_type, c, s_length, 4) longemapredictor_5 = ma_prediction(predict_type, c, s_length, 5) shortemapredictor_1 = ma_prediction(predict_type, c, f_length, 1) shortemapredictor_2 = ma_prediction(predict_type, c, f_length, 2) shortemapredictor_3 = ma_prediction(predict_type, c, f_length, 3) shortemapredictor_4 = ma_prediction(predict_type, c, f_length, 4) shortemapredictor_5 = ma_prediction(predict_type, c, f_length, 5) isBullish = c <= fMA ? true : false slowIsBelow = sMA < fMA ? true : false color fastCol = not colInvert ? (isBullish and col ? color.rgb(0,255,0,70) : not isBullish and col ? color.rgb(255,0,0,70) : na) : (isBullish and col ? color.rgb(255,0,0,70) : not isBullish and col ? color.rgb(0,255,0,70) : na) color slowCol = not colInvert ? (slowIsBelow and col ? color.new(color.purple,75) : not slowIsBelow and col ? color.new(color.aqua,75) : na) : (slowIsBelow and col ? color.new(color.aqua,75) : not slowIsBelow and col ? color.new(color.purple,75) : na) // ------------ // Front-End f_plot = plot(use_fma ? fMA : na, 'Fast Moving Average', color=col ? color.black : color.blue, linewidth=2) s_plot = plot(use_sma ? sMA : na, 'Slow Moving Average', color=color.white, linewidth=2) main = plot(c, 'Price Line', color=use_candles ? na : neutral_col, trackprice=true) fill(main, f_plot, color=fastCol) fill(f_plot, s_plot, color=slowCol) barColor = not use_candles ? na : src('close') >= src('open') ? color.teal : color.purple plotcandle(src('open'), src('high'), src('low'), src('close'), 'Candles', color=barColor, wickcolor=not use_candles ? na : color.new(neutral_col, 50), bordercolor=na) plot(predict_ema and use_sma ? longemapredictor_1 : na, color=isBelow(shortemapredictor_1, longemapredictor_1) ? color.white : color.gray, linewidth=2, style=plot.style_cross, offset=1, show_last=1, editable=false) plot(predict_ema and use_sma ? longemapredictor_2 : na, color=isBelow(shortemapredictor_2, longemapredictor_2) ? color.white : color.gray, linewidth=2, style=plot.style_cross, offset=2, show_last=1, editable=false) plot(predict_ema and use_sma ? longemapredictor_3 : na, color=isBelow(shortemapredictor_3, longemapredictor_3) ? color.white : color.gray, linewidth=2, style=plot.style_cross, offset=3, show_last=1, editable=false) plot(predict_ema and use_sma ? longemapredictor_4 : na, color=isBelow(shortemapredictor_4, longemapredictor_4) ? color.white : color.gray, linewidth=2, style=plot.style_cross, offset=4, show_last=1, editable=false) plot(predict_ema and use_sma ? longemapredictor_5 : na, color=isBelow(shortemapredictor_5, longemapredictor_5) ? color.white : color.gray, linewidth=2, style=plot.style_cross, offset=5, show_last=1, editable=false) plot(predict_ema and use_fma ? shortemapredictor_1 : na, color=isBelow(shortemapredictor_1, longemapredictor_1) ? color.aqua : color.purple, linewidth=2, style=plot.style_cross, offset=1, show_last=1, editable=false) plot(predict_ema and use_fma ? shortemapredictor_2 : na, color=isBelow(shortemapredictor_2, longemapredictor_2) ? color.aqua : color.purple, linewidth=2, style=plot.style_cross, offset=2, show_last=1, editable=false) plot(predict_ema and use_fma ? shortemapredictor_3 : na, color=isBelow(shortemapredictor_3, longemapredictor_3) ? color.aqua : color.purple, linewidth=2, style=plot.style_cross, offset=3, show_last=1, editable=false) plot(predict_ema and use_fma ? shortemapredictor_4 : na, color=isBelow(shortemapredictor_4, longemapredictor_4) ? color.aqua : color.purple, linewidth=2, style=plot.style_cross, offset=4, show_last=1, editable=false) plot(predict_ema and use_fma ? shortemapredictor_5 : na, color=isBelow(shortemapredictor_5, longemapredictor_5) ? color.aqua : color.purple, linewidth=2, style=plot.style_cross, offset=5, show_last=1, editable=false) var line realLine = na varip lineVis = false if use_candles and ((lineVis == false and not barstate.isconfirmed) or (barstate.isrealtime and barstate.islast and not barstate.isconfirmed)) line.delete(id=realLine) realLine := line.new(x1=bar_index[1], y1=c, x2=bar_index, y2=c, width=1, extend=extend.both) line.set_color(id=realLine, color=c > o ? color.purple : c < o ? color.teal : neutral_col) line.set_style(id=realLine, style=line.style_dashed) if barstate.isconfirmed line.delete(id=realLine) lineVis := false var table disp = table.new(position.bottom_right, 710, 2) if barstate.islast if not mini_display table.cell(disp, 0, 0, str.format('{0}/BTC', id), text_color=neutral_col, text_size=size.auto, bgcolor=back_col) table.cell(disp, 1, 0, str.tostring(c, '0.00000000'), text_color=neutral_col, text_size=size.auto, bgcolor=back_col) table.cell(disp, 0, 1, str.format('{0} - BTC Volatility', id), text_color=neutral_col, text_size=size.auto, bgcolor=back_col) table.cell(disp, 1, 1, str.format('{0}%', math.round(relative_volatility, 2)), text_color=neutral_col, text_size=size.auto, bgcolor=back_col) else if mini_display table.cell(disp, 0, 0, str.tostring(c, '0.00000000'), text_color=neutral_col, text_size=size.auto, bgcolor=back_col)
Trend/Retracement - ZigZag - New way
https://www.tradingview.com/script/xfLT1Tl1-Trend-Retracement-ZigZag-New-way/
Sharad_Gaikwad
https://www.tradingview.com/u/Sharad_Gaikwad/
547
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 //import Sharad_Gaikwad/SSGLibrary/1 as lib //@version=5 indicator("Trend/Retracement - ZigZag - New way", shorttitle = 'ZigZag - Trend/Retracement', overlay = true, max_lines_count = 500) //bt_start = input.time(timestamp("01 Jan 2022")) bt_start = timestamp("01 Jan 1900") _g1 = '========== Zigzag Parameters ==========' lb_predefined = input.bool(title = 'Use predefined Lookback (See "TF based Lookback period config" section below for defaults)', defval = true, group = _g1) lb_manual = input.int(title = 'Trend lookback candles (used if predefined is unchecked)', defval = 50, group = _g1) manual_retracement_percent = input.float(title = 'Retracement % of look back candles', defval = 25, group = _g1)/100 mark_retracements = input.bool(title = 'Mark retracements', defval = true, group = _g1) plot_zigzag = input.bool(title = 'Plot zigzag', defval = true, group = _g1, inline = 'g1') trend_color = input.color(title = 'Zigzag line color', defval = color.blue, group = _g1, inline = 'g1') retrace_color = trend_color //retrace_color = input.color(title = 'Retracement line color', defval = color.yellow, group = _g1, inline = 'g1') plot_sr = input.bool(title = 'Plot support/resistance', defval = true, group = _g1, inline = 'l2') support_line_color = input.color(title = 'Color - Support', defval = color.green, group = _g1, inline = 'l2') resistance_line_color = input.color(title = 'Color - Resistance', defval = color.red, group = _g1, inline = 'l2') keep_tested = input.bool(title = 'Show support/resistance tested lines', defval = true, group = _g1) high_src = input.source(title = 'Data source - High', defval = high, group = _g1) low_src = input.source(title = 'Data source - Low', defval = low, group = _g1) _g2 = '========== TF based Lookback period config ==========' tf_min_1 = input.int(title = 'Timeframe in minute', defval = 5, minval = 1, maxval = 1440, group = _g2, inline = 'min1') tf_min_1_lb = input.int(title = 'Trend lookback candles', defval = 375, group = _g2, inline = 'min1') tf_min_2 = input.int(title = 'Timeframe in minute', defval = 15, minval = 1, maxval = 1440, group = _g2, inline ='min2') tf_min_2_lb = input.int(title = 'Trend lookback candles', defval = 250, group = _g2, inline = 'min2') tf_min_3 = input.int(title = 'Timeframe in minute', defval = 60, minval = 1, maxval = 1440, group = _g2, inline = 'min3') tf_min_3_lb = input.int(title = 'Trend lookback candles', defval = 90, group = _g2, inline = 'min3') tf_day_lb = input.int(title = "Trend lookback candles for timeframe 'D'", defval = 30, group = _g2 ) tf_week_lb = input.int(title = "Trend lookback candles for timeframe 'W'", defval = 21, group = _g2 ) tf_month_lb = input.int(title = "Trend lookback candles for timeframe 'M'", defval = 12, group = _g2 ) predefined_retracement_percent = input.float(title = 'Retracement % of look back candles', defval = 25, group = _g2)/100 //========================= // tf based lb defaults // tf ~days LB candles // data //======================== // 5m 5 375 // 15m 10 250 // 60m 15 90 // 1d 30 30 // 1w 105 21 // 1m 250 12 //======================== //switch_sr = input.bool(title = 'Switch SR lines on 1st cross', defval = true, tooltip = 'Supprt will turn resistance and resistance will turn support only on 1st cross. \n The lines would be removed on 2nd cross') var tabd = table.new(position=position.bottom_right, columns=1, rows=1) disp(msg) => table.cell(table_id=tabd, column=0, row=0, text=msg, text_color=color.yellow, text_size = size.small) tab = table.new(position=position.top_right, columns=10, 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) remove_lines(_arr , top_bottom = 'Top') => size = array.size(_arr) __arr = array.new<int>() if(size > 1) for i = 0 to size - 1 if(top_bottom == 'Top' and ((not keep_tested and high > line.get_price(array.get(_arr, i), bar_index)) or (keep_tested and close > line.get_price(array.get(_arr, i), bar_index) or keep_tested and open > line.get_price(array.get(_arr, i), bar_index)))) line.delete(array.get(_arr, i)) array.unshift(__arr, i) if(top_bottom == 'Bottom' and ((not keep_tested and low < line.get_price(array.get(_arr, i), bar_index)) or (keep_tested and close < line.get_price(array.get(_arr, i), bar_index) or keep_tested and open < line.get_price(array.get(_arr, i), bar_index)))) line.delete(array.get(_arr, i)) array.unshift(__arr, i) _size = array.size(__arr) if(_size > 1) for i = 0 to _size - 1 element = array.get(__arr, i) array.remove(_arr, element) var top_arr = array.new<line>() var bottom_arr = array.new<line>() remove_lines(top_arr, 'Top') remove_lines(bottom_arr, 'Bottom') draw(x1, y1, x2, y2, state_) => clr = state_ == 'HM' or state_ == 'LM' ? trend_color : retrace_color ln = line.new(x1, y1, x2, y2, color = clr) ln extend(ln, x2, y2, state_) => clr = state_ == 'HM' or state_ == 'LM' ? trend_color : retrace_color line.set_xy2(ln, x2, y2) line.set_color(ln, clr) process(_state, _price, _bar, dir, is_pivot) => var ln = line.new(na, na, na, na) var x1 = int(na), var y1 = float(na) var x2 = int(na), var y2 = float(na) var is_pending_extend = bool(na) var pending_x2 = int(na) var pending_y2 = float(na) var pending_state = string(na) // var dow_hip1 = float(na), var dow_lop1 = float(na) // var dow_hip2 = float(na), var dow_lop2 = float(na) // var dow_hib1 = int(na), var dow_lob1 = int(na) // var dow_hib2 = int(na), var dow_lob2 = int(na) if(plot_zigzag) new_line = na(ln) ? 1 : 0 wip_line = not na(ln) ? 1 : 0 if(is_pivot) if((_state != 'NA' and _state[1] == 'NA') or (new_line and _state == _state[1])) x1 := _bar, y1 := _price if(new_line and _state != _state[1]) // if(is_pending_extend) // extend(ln, pending_x2, pending_y2, pending_state) // is_pending_extend := false x2 := _bar, y2 := _price ln := draw(x1, y1, x2, y2, _state) if(wip_line and dir == dir[1]) x2 := _bar, y2 := _price // pending_x2 := _bar // pending_y2 := _price // pending_state := _state // is_pending_extend := true extend(ln, x2, y2, _state) if(wip_line and dir != dir[1]) // if(is_pending_extend) // extend(ln, pending_x2, pending_y2, 'HM') // is_pending_extend := false x1 := x2, y1 := y2 x2 := _bar, y2 := _price ln := draw(x1, y1, x2, y2, _state) [x1, y1, x2, y2] var wip_state = string('NA'), var wip_price = float(na), var wip_bar = int(na) var direction = int(na) var lb_candles = not lb_predefined ? lb_manual : timeframe.multiplier == tf_min_1 ? tf_min_1_lb : timeframe.multiplier == tf_min_2 ? tf_min_2_lb : timeframe.multiplier == tf_min_3 ? tf_min_3_lb : timeframe.isdaily ? tf_day_lb : timeframe.isweekly ? tf_week_lb : timeframe.ismonthly ? tf_month_lb : 50 var lb_retrace = lb_predefined ? math.max(math.floor(lb_candles * predefined_retracement_percent), 2) : math.max(math.floor(lb_candles * manual_retracement_percent), 2) if(barstate.islast) var trend_msg = str.tostring(lb_candles) +' Candles' var retrace_msg = not mark_retracements ? 'NA' : str.tostring(lb_retrace) + ' Candles' disp('Parameters: Trend:'+ trend_msg + ' Retracement:'+ retrace_msg) phm = time >= bt_start and ta.highestbars(high_src, lb_candles) == 0 ? high_src : na plm = time >= bt_start and ta.lowestbars(low_src, lb_candles) == 0 ? low_src : na phr = time >= bt_start and ta.highestbars(high_src, lb_retrace) == 0 ? mark_retracements ? high_src : na : na plr = time >= bt_start and ta.lowestbars(low_src, lb_retrace) == 0 ? mark_retracements ? low_src : na : na wip_state := phm ? 'HM' : phr ? 'HR' : plm ? 'LM' : plr ? 'LR' : wip_state wip_price := phm ? phm : phr ? phr : plm ? plm : plr ? plr : float(na) wip_bar := phm ? bar_index : phr ? bar_index : plm ? bar_index : plr ? bar_index : int(na) direction := phm or phr ? 1 : plm or plr ? -1 : direction if(phm) if(plot_sr) lnt = line.new(bar_index, high_src, bar_index+30, high_src, color = resistance_line_color, extend = extend.right) array.unshift(top_arr, lnt) if(plm) if(plot_sr) lnb = line.new(bar_index, low_src, bar_index+20, low_src, color = support_line_color, extend = extend.right) array.unshift(bottom_arr, lnb) if(phr) if(plot_sr) lnt = line.new(bar_index, high_src, bar_index+30, high_src, color = resistance_line_color, extend = extend.right) array.unshift(top_arr, lnt) if(plr) if(plot_sr) lnb = line.new(bar_index, low_src, bar_index+20, low_src, color = support_line_color, extend = extend.right) array.unshift(bottom_arr, lnb) [x1, y1, x2, y2] = process(wip_state, wip_price, wip_bar, direction, phm or plm or phr or plr) // msg(0, 0, "Data") // msg(1, 0, "wip state = "+t(wip_state)) // msg(2, 0, "wip bar = "+t(wip_bar)) // msg(3, 0, "wip price = "+t(wip_price)) // msg(4, 0, "wip state[1] = "+t(wip_state[1])) // msg(5, 0, "y1 = "+t(y1)) // msg(6, 0, "y2 = "+t(y2)) // msg(7, 0 ,'Dir / dir[1]= '+t(direction)+ ' / '+t(direction[1])) // msg(8, 0, 'phm/plm = '+t(phm) + '/ '+t(plm)) // msg(9, 0, 'phr/plr = '+t(phr) + '/ '+t(plr))
Volume Buoyancy [LucF]
https://www.tradingview.com/script/18fu8TxD-Volume-Buoyancy-LucF/
LucF
https://www.tradingview.com/u/LucF/
569
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/ // © LucF //@version=5 int MAX_BARS_BACK = 1000 indicator("Volume Buoyancy [LucF]", "Volume Buoyancy", max_bars_back = MAX_BARS_BACK, timeframe = "", timeframe_gaps = false, precision = 2) // Buoyancy [LucF] // v3, 2022.11.06 13:05 — LucF // This code was written using the recommendations from the Pine Script™ User Manual's Style Guide: // https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html import LucF/ta/2 as LucfTa //#region ———————————————————— Constants and inputs // Key levels float LEVEL_MID = 0. float LEVEL_HI = 0.3 float LEVEL_LO = -0.3 // Colors color BLUE = #3179f5 color GRAY = #434651 color GRAY_LT = #9598a1 color GREEN = #006200 color LIME = #00FF00 color MAROON = #800000 color ORANGE = #e65100 color PINK = #FF0080 color YELLOW = #fbc02d // MAs string MA01 = "Simple MA" string MA02 = "Exponential MA" string MA03 = "Wilder MA" string MA04 = "Weighted MA" string MA05 = "Volume-weighted MA" string MA06 = "Arnaud Legoux MA" string MA07 = "Hull MA" string MA08 = "Symmetrically-weighted MA" // Bar coloring modes string CB1 = "Buoyancy line" string CB2 = "MA line" string CB3 = "Channel fill" string CB4 = "MA fill" // Tooltips string TT_TARGET = "This value specifies the number of bars for which volume is added to calculate the target." string TT_LINE = "'🡑' and '🡓' indicate bull/bear conditions, which occur when the line is above/below the centerline." string TT_CHANNEL = "'🡑' and '🡓' indicate bull/bear conditions, which occur when buoyancy is above/below its MA while not also being above/below the centerline. \n\n'🡑🡑' and '🡓🡓' indicate strong bull/bear conditions, which require buoyancy to be above/below its MA, and above/below the centerline." // Inputs int periodInput = input.int(20, "Target bars", inline = "target", minval = 1, maxval = int(MAX_BARS_BACK / 4), tooltip = TT_TARGET) bool buoyancyShowInput = input.bool(true, "Buoyancy", inline = "buoyancy") color buoyancyUpColorInput = input.color(GRAY_LT, "🡑", inline = "buoyancy") color buoyancyDnColorInput = input.color(GRAY_LT, "🡓", inline = "buoyancy", tooltip = TT_LINE) bool maShowInput = input.bool(false, "MA line", inline = "ma") color maUpColorInput = input.color(YELLOW, " 🡑", inline = "ma") color maDnColorInput = input.color(ORANGE, "🡓", inline = "ma") string maTypeInput = input.string(MA06, "", inline = "ma", options = [MA01, MA02, MA03, MA04, MA05, MA06, MA07, MA08]) int maLengthInput = input.int(20, "Length", inline = "ma", minval = 2, tooltip = TT_LINE) bool channelShowInput = input.bool(true, "Channel", inline = "channel") color channelUpColorInput = input.color(GREEN, "  🡑", inline = "channel") color channelDnColorInput = input.color(MAROON, "🡓", inline = "channel") color channelUpUpColorInput = input.color(LIME, "🡑🡑", inline = "channel") color channelDnDnColorInput = input.color(PINK, "🡓🡓", inline = "channel", tooltip = TT_CHANNEL) bool maFillShowInput = input.bool(true, "MA fill", inline = "maFill") color maFillUpColorInput = input.color(GRAY, "   🡑", inline = "maFill") color maFillDnColorInput = input.color(BLUE, "🡓", inline = "maFill") bool colorBarsInput = input.bool(false, "Color chart bars using the color of", inline = "bars") string colorBarsModeInput = input.string(CB3, "", inline = "bars", options = [CB1, CB2, CB3, CB4]) //#endregion //#region ———————————————————— Calculations // Stop the indicator on charts with no volume. if barstate.islast and ta.cum(nz(volume)) == 0 runtime.error("No volume is provided by the data vendor.") // Calculate buoyancy and its MA. float buoyancy = LucfTa.buoyancy(volume, periodInput, MAX_BARS_BACK) float ma = LucfTa.ma(maTypeInput, buoyancy, maLengthInput) // States bool maIsBull = ma > LEVEL_MID bool buoyancyIsBull = buoyancy > LEVEL_MID bool channelIsBull = buoyancy > ma //#endregion //#region ———————————————————— Plots // Plotting colors color channelColor = channelIsBull ? buoyancyIsBull ? channelUpUpColorInput : channelUpColorInput : buoyancyIsBull ? channelDnColorInput : channelDnDnColorInput color buoyancyColor = buoyancyIsBull ? buoyancyUpColorInput : buoyancyDnColorInput color maColor = maIsBull ? maUpColorInput : maDnColorInput color maChannelTopColor = maIsBull ? maFillUpColorInput : color.new(maFillDnColorInput, 95) color maChannelBotColor = maIsBull ? color.new(maFillUpColorInput, 95) : maFillDnColorInput // Plots buoyancyPlot = plot(buoyancy, "Buoyancy", buoyancyShowInput ? buoyancyColor : na) maPlot = plot(ma, "MA", maShowInput ? maColor : na) zeroPlot = plot(LEVEL_MID, "Phantom Mid Level", display = display.none) // Fill the MA channel (the space between the middle level and the MA). fill(maPlot, zeroPlot, not maFillShowInput ? na : maIsBull ? LEVEL_HI : LEVEL_MID, maIsBull ? LEVEL_MID : LEVEL_LO, maChannelTopColor, maChannelBotColor) // Fill the buoyancy channel (between the buoyancy line and its MA). fill(maPlot, buoyancyPlot, ma, not channelShowInput ? na : buoyancy, color.new(channelColor, 70), channelColor) // Levels hline(LEVEL_HI, "High level", buoyancyUpColorInput, hline.style_dotted) hline(LEVEL_MID, "Mid level", color.gray, hline.style_dotted) hline(LEVEL_LO, "Low level", buoyancyDnColorInput, hline.style_dotted) // Color bars color barColor = switch colorBarsModeInput CB1 => buoyancyColor CB2 => maColor CB3 => channelColor CB4 => maIsBull ? maFillUpColorInput : maFillDnColorInput => na barcolor(colorBarsInput ? barColor : na) //#endregion
Multiple RSI One Time Frame
https://www.tradingview.com/script/o2sfa0qY-Multiple-RSI-One-Time-Frame/
SirDrBroclawEsq
https://www.tradingview.com/u/SirDrBroclawEsq/
24
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/ // © SirDrBroclawEsq //@version=4 study("Multiple RSI") rsi1length = input(defval=7, title="RSI 1 Length", minval=1, type=input.integer, group="RSI 1 Settings") rsi1source = input(defval=close, title="RSI 1 Source", type=input.source, group="RSI 1 Settings") rsi1set = rsi(rsi1source, rsi1length) rsi2length = input(defval=14, title="RSI 2 Length", minval=1, type=input.integer, group="RSI 2 Settings") rsi2source = input(defval=close, title="RSI 2 Source", type=input.source, group="RSI 2 Settings") rsi2set = rsi(rsi2source, rsi2length) rsi3length = input(defval=21, title="RSI 3 Length", minval=1, type=input.integer, group="RSI 3 Settings") rsi3source = input(defval=close, title="RSI 3 Source", type=input.source, group="RSI 3 Settings") rsi3set = rsi(rsi3source, rsi3length) rsi4length = input(defval=50, title="RSI 4 Length", minval=1, type=input.integer, group="RSI 4 Settings") rsi4source = input(defval=close, title="RSI 4 Source", type=input.source, group="RSI 4 Settings") rsi4set = rsi(rsi4source, rsi4length) rsi5length = input(defval=144, title="RSI 5 Length", minval=1, type=input.integer, group="RSI 5 Settings") rsi5source = input(defval=close, title="RSI 5 Source", type=input.source, group="RSI 5 Settings") rsi5set = rsi(rsi5source, rsi5length) //rsi1 = security(syminfo.tickerid, "5", rsi1set) //rsi2 = security(syminfo.tickerid, "15", rsi2set) //rsi3 = security(syminfo.tickerid, "30", rsi3set) //rsi4 = security(syminfo.tickerid, "60", rsi4set) //rsi5 = security(syminfo.tickerid, "240", rsi5set) plot(rsi1set, color=color.aqua) plot(rsi2set, color=color.navy) plot(rsi3set, color=color.black) plot(rsi4set, color=color.green) plot(rsi5set, color=color.yellow)
Hussarya compare DJI SPX BTC
https://www.tradingview.com/script/pmp1FYlY/
charthussars
https://www.tradingview.com/u/charthussars/
8
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/ // © hussarya //@version=5 indicator(title="Hussarya coin", overlay=true, timeframe="", timeframe_gaps=true) timeframe = timeframe.period i_sym = input.symbol("SP:SPX", "Symbol" ) i_sym2 = input.symbol("BINANCE:BTCUSD", "Symbol" ) a1c = request.security(i_sym, timeframe , close) a2c = request.security(i_sym2, timeframe , close) spx = a1c * 8 btc = a2c *1.5 plot(spx, color=#cc0000 , linewidth=1 ) plot(btc, color=#00cc00 , linewidth=1 )
Reset Strike Options-Type 1 [Loxx]
https://www.tradingview.com/script/CmozzqH5-Reset-Strike-Options-Type-1-Loxx/
loxx
https://www.tradingview.com/u/loxx/
18
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("Reset Strike Options-Type 1 [Loxx]", shorttitle ="RSIT1 [Loxx]", overlay = true, max_lines_count = 500) if not timeframe.isdaily runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.") import loxx/cnd/1 import loxx/cbnd/1 color darkGreenColor = #1B7E02 string srcAPrice = "Source Asset Price" string manAPrice = "Manual Asset Price" string callString = "Call" string putString = "Put" string Continuous = "Continuous" 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas 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.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 // Reset Strike Option Type 1 ResetOptionGrayWhaleyT1(string CallPutFlag, float S, float X, float tau, float T,float r, float b, float v)=> float ResetOptionGrayWhaleyT1 = 0 float a1 = (math.log(S / X) + (b + math.pow(v, 2) / 2) * tau) / (v * math.sqrt(tau)) float a2 = a1 - v * math.sqrt(tau) float y1 = (math.log(S / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float y2 = y1 - v * math.sqrt(T) float z1 = (b + math.pow(v, 2) / 2) * (T - tau) / (v * math.sqrt(T - tau)) float z2 = z1 - v * math.sqrt(T - tau) float rho = math.sqrt(tau / T) if CallPutFlag == callString ResetOptionGrayWhaleyT1 := math.exp((b - r) * (T - tau)) * cnd.CND1(-a2) * cnd.CND1(z1) * math.exp(-r * tau) - math.exp(-r * T) * cnd.CND1(-a2) * cnd.CND1(z2) - math.exp(-r * T) * cbnd.CBND3(a2, y2, rho) + (S / X) * math.exp((b - r) * T) * cbnd.CBND3(a1, y1, rho) else ResetOptionGrayWhaleyT1 := math.exp(-r * T) * cnd.CND1(a2) * cnd.CND1(-z2) - math.exp((b - r) * (T - tau)) * cnd.CND1(a2) * cnd.CND1(-z1) * math.exp(-r * tau) + math.exp(-r * T) * cbnd.CBND3(-a2, -y2, rho) - (S / X) * math.exp((b - r) * T) * cbnd.CBND3(-a1, -y1, rho) ResetOptionGrayWhaleyT1 EResetOptionGrayWhaleyT1(string OutPutFlag, string CallPutFlag, float S, float X, float tau, float T, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EResetOptionGrayWhaleyT1 = 0 if OutPutFlag == "p" // Value EResetOptionGrayWhaleyT1 := ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) else if OutPutFlag == "d" //Delta EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v)) / (2 * dS) * S / ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) else if OutPutFlag == "g" //Gamma EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v) - 2 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v + 0.01) - 2 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v + 0.01) + ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v - 0.01) + 2 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v - 0.01) - ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EResetOptionGrayWhaleyT1 := S / 100 * (ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v) - 2 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "dddv" //DDeltaDvol EResetOptionGrayWhaleyT1 := 1 / (4 * dS * 0.01) * (ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v - 0.01) - ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v + 0.01) + ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - 2 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) / math.pow(0.01, 2)/ 10000 else if OutPutFlag == "vp" //VegaP EResetOptionGrayWhaleyT1 := v / 0.1 * (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - 2 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if tau <= 1 / 365 EResetOptionGrayWhaleyT1 := ResetOptionGrayWhaleyT1(CallPutFlag, S, X, 0, T - 1 / 365, r, b, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) else EResetOptionGrayWhaleyT1 := ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau - 1 / 365, T - 1 / 365, r, b, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) else if OutPutFlag == "r" //Rho EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r + 0.01, b + 0.01, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" //Futures options rho EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r + 0.01, b, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" //Rho2 EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b - 0.01, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" //Carry EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b + 0.01, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" //Speed EResetOptionGrayWhaleyT1 := 1 / math.pow(dS, 3) * (ResetOptionGrayWhaleyT1(CallPutFlag, S + 2 * dS, X, tau, T, r, b, v) - 3 * ResetOptionGrayWhaleyT1(CallPutFlag, S + dS, X, tau, T, r, b, v) + 3 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S - dS, X, tau, T, r, b, v)) else if OutPutFlag == "dx" //Strike Delta EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X + dS, tau, T, r, b, v) - ResetOptionGrayWhaleyT1(CallPutFlag, S, X - dS, tau, T, r, b, v)) / (2 * dS) else if OutPutFlag == "dxdx" //Gamma EResetOptionGrayWhaleyT1 := (ResetOptionGrayWhaleyT1(CallPutFlag, S, X + dS, tau, T, r, b, v) - 2 * ResetOptionGrayWhaleyT1(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaleyT1(CallPutFlag, S, X - dS, tau, T, r, b, v)) / math.pow(dS, 2) EResetOptionGrayWhaleyT1 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 Sm = input.float(100, "Manual Asset Price", group = "Basic Settings") float Ssrc = input.source(close, "Source Asset Price", group = "Basic Settings") string assetswtich = input.string(manAPrice, "Asset Price Type", options = [srcAPrice, manAPrice], group = "Basic Settings") float K = input.float(100, "Strike Price", group = "Basic Settings") float r = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(20., "% 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") float S = assetswtich == srcAPrice ? Ssrc : Sm 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 startthruMonth = input.int(12, title = "Reset Time Start Month", minval = 1, maxval = 12, group = "Reset Date/Time") int startthruDay = input.int(31, title = "Reset Time Start Day", minval = 1, maxval = 31, group = "Reset Date/Time") int startthruYear = input.int(2022, title = "Reset Time Start Year", minval = 1970, group = "Reset Date/Time") int startmins = input.int(0, title = "Reset Time Start Minute", minval = 0, maxval = 60, group = "Reset Date/Time") int starthours = input.int(9, title = "Reset Time Start Hour", minval = 0, maxval = 24, group = "Reset Date/Time") int startsecs = input.int(0, title = "Reset Time Start Second", minval = 0, maxval = 60, group = "Reset Date/Time") int expirythruMonth = input.int(3, title = "Expiry Time Month", minval = 1, maxval = 12, group = "Time to Maturity Date/Time") int expirythruDay = input.int(31, title = "Expiry Time Day", minval = 1, maxval = 31, group = "Time to Maturity Date/Time") int expirythruYear = input.int(2023, title = "Expiry Time Year", minval = 1970, group = "Time to Maturity Date/Time") int expirymins = input.int(0, title = "Expiry Time Minute", minval = 0, maxval = 60, group = "Time to Maturity Date/Time") int expiryhours = input.int(9, title = "Expiry Time Hour", minval = 0, maxval = 24, group = "Time to Maturity Date/Time") int expirysecs = input.int(0, title = "Expiry Time Second", minval = 0, maxval = 60, group = "Time to Maturity 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 float startstart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday float startfinish = timestamp(startthruYear, startthruMonth, startthruDay, starthours, startmins, startsecs) float starttemp = (startfinish - startstart) float T1 = (startfinish - startstart) / spyr / 1000 // precision calculation miliseconds in time intreval from time equals now float expirystart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday float expiryfinish = timestamp(expirythruYear, expirythruMonth, expirythruDay, expiryhours, expirymins, expirysecs) float expirytemp = (expiryfinish - expirystart) float T2 = (expiryfinish - expirystart) / spyr / 1000 string txtsize = input.string("Auto", title = "Text Size", 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 float hvolout = switch hvoltype parkinson => parkinsonvol(histvolper) rogersatch => rogerssatchel(histvolper) c2c => closetoclose(math.log(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) float rcmpval = switch rcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 if barstate.islast float sideout = side == "Long" ? 1 : -1 float kouta = convertingToCCRate(r, rcmpval) float koutb = convertingToCCRate(b, bcmpval) float amaproxprice = EResetOptionGrayWhaleyT1("p", OpType, S, K, T1, T2, kouta, koutb, v, na) float Delta = EResetOptionGrayWhaleyT1("d", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Elasticity = EResetOptionGrayWhaleyT1("e", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Gamma = EResetOptionGrayWhaleyT1("g", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float DGammaDvol = EResetOptionGrayWhaleyT1("gv", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float GammaP = EResetOptionGrayWhaleyT1("gp", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Vega = EResetOptionGrayWhaleyT1("v", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float DvegaDvol = EResetOptionGrayWhaleyT1("dvdv", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float VegaP = EResetOptionGrayWhaleyT1("vp", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Theta = EResetOptionGrayWhaleyT1("t", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Rho = EResetOptionGrayWhaleyT1("r", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float RhoFuturesOption = EResetOptionGrayWhaleyT1("fr", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float PhiRho2 = EResetOptionGrayWhaleyT1("f", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Carry = EResetOptionGrayWhaleyT1("b", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float DDeltaDvol = EResetOptionGrayWhaleyT1("dddv", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Speed = EResetOptionGrayWhaleyT1("s", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 18, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Reset Strike Options-Type 1", 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 = "Asset Price: " + str.tostring(S) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "Asset Price Source: " + assetswtich, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, text = "Strike Price: " + str.tostring(K), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 6, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 7, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 8, 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 = 9, text = "Reset Date/Time: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", startfinish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 10, text = "Maturity Date/Time: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", expiryfinish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 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 = "Reset Strike Options-Type 1 Price: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
three bar breakout diego
https://www.tradingview.com/script/3fOEj545-three-bar-breakout-diego/
drjorge
https://www.tradingview.com/u/drjorge/
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/ // © drjorge //@version=4 study("3BB",overlay=false) threebarbreakout1 = (low > low [1] or low > low [2]) and (high < high [1] or high < high[2]) plotchar(threebarbreakout1, char= "3", location=location.bottom, size=size.tiny, color= #e91e63, transp=0, offset=0)
myBBands
https://www.tradingview.com/script/Agxg0XQf-myBBands/
Threshold
https://www.tradingview.com/u/Threshold/
28
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/ // © Threshold //@version=4 study(title="myBBands", shorttitle="myBbands", overlay=true) len_bb = input(20, minval=1, title="BB Length") mult = input(2.0, minval=0.001, maxval=50, title="StdDev") bbp = input (100, minval = 3, title ="BBand Pinch length") src = input(close, title="Source") basis = sma(src, len_bb) dev = mult * stdev(src, len_bb) upper = basis + dev lower = basis - dev bbbw = bbw(close, len_bb, mult) Lowestbbw = lowest(bbbw, bbp)[1] pinch = float(na) pinch := bbbw <= Lowestbbw ? 1 : close [1] > upper[1] ? na : close [1] < lower[1] ? na : pinch[1] plot(basis, color=#ffffff, title="BB Basis", transp=85) p1 = plot(upper, color=#ffffff, title="BB Upper", transp=85) p2 = plot(lower, color=#ffffff, title="BB Lower", transp=85) plot(pinch == 1 ? upper : na, style = plot.style_linebr, linewidth=2, color=#ff00ff, transp=10, title= 'BBand Pinch Coloru') plot(pinch == 1 ? lower : na, style = plot.style_linebr, linewidth=2, color=#ff00ff, transp=10, title= 'BBand Pinch Colord') fill(p1, p2, color=iff(pinch == 1, #9598a1, na), transp= 77, title= "Pinch Background") //
Reset Strike Options-Type 2 (Gray Whaley) [Loxx]
https://www.tradingview.com/script/yrtqazX9-Reset-Strike-Options-Type-2-Gray-Whaley-Loxx/
loxx
https://www.tradingview.com/u/loxx/
19
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("Reset Strike Options-Type 2 (Gray Whaley) [Loxx]", shorttitle ="RSOT2 [Loxx]", overlay = true, max_lines_count = 500) if not timeframe.isdaily runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.") import loxx/cnd/1 import loxx/cbnd/1 color darkGreenColor = #1B7E02 string srcAPrice = "Source Asset Price" string manAPrice = "Manual Asset Price" string callString = "Call" string putString = "Put" string Continuous = "Continuous" 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas 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.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 ResetOptionGrayWhaley(string CallPutFlag, float S, float X, float tau, float T, float r, float b, float v)=> float ResetOptionGrayWhaley = 0 float a1 = (math.log(S / X) + (b + math.pow(v, 2) / 2) * tau) / (v * math.sqrt(tau)) float a2 = a1 - v * math.sqrt(tau) float y1 = (math.log(S / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float y2 = y1 - v * math.sqrt(T) float z1 = (b + math.pow(v, 2) / 2) * (T - tau) / (v * math.sqrt(T - tau)) float z2 = z1 - v * math.sqrt(T - tau) float rho = math.sqrt(tau / T) if CallPutFlag == callString ResetOptionGrayWhaley := S * math.exp((b - r) * T) * cbnd.CBND3(a1, y1, rho) - X * math.exp(-r * T) * cbnd.CBND3(a2, y2, rho) - S * math.exp((b - r) * tau) * cnd.CND1(-a1) * cnd.CND1(z2) * math.exp(-r * (T - tau)) + S * math.exp((b - r) * T) * cnd.CND1(-a1) * cnd.CND1(z1) else ResetOptionGrayWhaley := S * math.exp((b - r) * tau) * cnd.CND1(a1) * cnd.CND1(-z2) * math.exp(-r * (T - tau)) - S * math.exp((b - r) * T) * cnd.CND1(a1) * cnd.CND1(-z1) + X * math.exp(-r * T) * cbnd.CBND3(-a2, -y2, rho) - S * math.exp((b - r) * T) * cbnd.CBND3(-a1, -y1, rho) ResetOptionGrayWhaley EResetOptionGrayWhaley(string OutPutFlag, string CallPutFlag, float S, float X, float tau, float T, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EResetOptionGrayWhaley = 0 if OutPutFlag == "p" // Value EResetOptionGrayWhaley := ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) else if OutPutFlag == "d" //Delta EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v) - ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v) - ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v)) / (2 * dS) * S / ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) else if OutPutFlag == "g" //Gamma EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v) - 2 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v + 0.01) - 2 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v + 0.01) + ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v - 0.01) + 2 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v - 0.01) - ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EResetOptionGrayWhaley := S / 100 * (ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v) - 2 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "dddv" //DDeltaDvol EResetOptionGrayWhaley := 1 / (4 * dS * 0.01) * (ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v - 0.01) - ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v + 0.01) + ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - 2 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) / math.pow(0.01, 2)/ 10000 else if OutPutFlag == "vp" //VegaP EResetOptionGrayWhaley := v / 0.1 * (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v + 0.01) - 2 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if tau <= 1 / 365 EResetOptionGrayWhaley := ResetOptionGrayWhaley(CallPutFlag, S, X, 0, T - 1 / 365, r, b, v) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) else EResetOptionGrayWhaley := ResetOptionGrayWhaley(CallPutFlag, S, X, tau - 1 / 365, T - 1 / 365, r, b, v) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) else if OutPutFlag == "r" //Rho EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r + 0.01, b + 0.01, v) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" //Futures options rho EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r + 0.01, b, v) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" //Rho2 EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b - 0.01, v) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" //Carry EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b + 0.01, v) - ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" //Speed EResetOptionGrayWhaley := 1 / math.pow(dS, 3) * (ResetOptionGrayWhaley(CallPutFlag, S + 2 * dS, X, tau, T, r, b, v) - 3 * ResetOptionGrayWhaley(CallPutFlag, S + dS, X, tau, T, r, b, v) + 3 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) - ResetOptionGrayWhaley(CallPutFlag, S - dS, X, tau, T, r, b, v)) else if OutPutFlag == "dx" //Strike Delta EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X + dS, tau, T, r, b, v) - ResetOptionGrayWhaley(CallPutFlag, S, X - dS, tau, T, r, b, v)) / (2 * dS) else if OutPutFlag == "dxdx" //Gamma EResetOptionGrayWhaley := (ResetOptionGrayWhaley(CallPutFlag, S, X + dS, tau, T, r, b, v) - 2 * ResetOptionGrayWhaley(CallPutFlag, S, X, tau, T, r, b, v) + ResetOptionGrayWhaley(CallPutFlag, S, X - dS, tau, T, r, b, v)) / math.pow(dS, 2) EResetOptionGrayWhaley 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 Sm = input.float(100, "Manual Asset Price", group = "Basic Settings") float Ssrc = input.source(close, "Source Asset Price", group = "Basic Settings") string assetswtich = input.string(manAPrice, "Asset Price Type", options = [srcAPrice, manAPrice], group = "Basic Settings") float K = input.float(100, "Strike Price", group = "Basic Settings") float r = input.float(10., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(10., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, 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") float S = assetswtich == srcAPrice ? Ssrc : Sm 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 startthruMonth = input.int(12, title = "Reset Time Month", minval = 1, maxval = 12, group = "Reset Date/Time") int startthruDay = input.int(31, title = "Reset Time Day", minval = 1, maxval = 31, group = "Reset Date/Time") int startthruYear = input.int(2022, title = "Reset Time Year", minval = 1970, group = "Reset Date/Time") int startmins = input.int(0, title = "Reset Time Minute", minval = 0, maxval = 60, group = "Reset Date/Time") int starthours = input.int(9, title = "Reset Time Hour", minval = 0, maxval = 24, group = "Reset Date/Time") int startsecs = input.int(0, title = "Reset Time Second", minval = 0, maxval = 60, group = "Reset Date/Time") int expirythruMonth = input.int(3, title = "Maturity Time Month", minval = 1, maxval = 12, group = "Time to Maturity Date/Time") int expirythruDay = input.int(31, title = "Maturity Time Day", minval = 1, maxval = 31, group = "Time to Maturity Date/Time") int expirythruYear = input.int(2023, title = "Maturity Time Year", minval = 1970, group = "Time to Maturity Date/Time") int expirymins = input.int(0, title = "Maturity Time Minute", minval = 0, maxval = 60, group = "Time to Maturity Date/Time") int expiryhours = input.int(9, title = "Maturity Time Hour", minval = 0, maxval = 24, group = "Time to Maturity Date/Time") int expirysecs = input.int(0, title = "Maturity Time Second", minval = 0, maxval = 60, group = "Time to Maturity 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 float startstart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday float startfinish = timestamp(startthruYear, startthruMonth, startthruDay, starthours, startmins, startsecs) float starttemp = (startfinish - startstart) float T1 = (startfinish - startstart) / spyr / 1000 // precision calculation miliseconds in time intreval from time equals now float expirystart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday float expiryfinish = timestamp(expirythruYear, expirythruMonth, expirythruDay, expiryhours, expirymins, expirysecs) float expirytemp = (expiryfinish - expirystart) float T2 = (expiryfinish - expirystart) / spyr / 1000 string txtsize = input.string("Auto", title = "Text Size", 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 float hvolout = switch hvoltype parkinson => parkinsonvol(histvolper) rogersatch => rogerssatchel(histvolper) c2c => closetoclose(math.log(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) float rcmpval = switch rcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 if barstate.islast float sideout = side == "Long" ? 1 : -1 float kouta = convertingToCCRate(r, rcmpval) float koutb = convertingToCCRate(b, bcmpval) float amaproxprice = EResetOptionGrayWhaley("p", OpType, S, K, T1, T2, kouta, koutb, v, na) float Delta = EResetOptionGrayWhaley("d", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Elasticity = EResetOptionGrayWhaley("e", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Gamma = EResetOptionGrayWhaley("g", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float DGammaDvol = EResetOptionGrayWhaley("gv", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float GammaP = EResetOptionGrayWhaley("gp", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Vega = EResetOptionGrayWhaley("v", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float DvegaDvol = EResetOptionGrayWhaley("dvdv", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float VegaP = EResetOptionGrayWhaley("vp", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Theta = EResetOptionGrayWhaley("t", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Rho = EResetOptionGrayWhaley("r", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float RhoFuturesOption = EResetOptionGrayWhaley("fr", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float PhiRho2 = EResetOptionGrayWhaley("f", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Carry = EResetOptionGrayWhaley("b", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float DDeltaDvol = EResetOptionGrayWhaley("dddv", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float Speed = EResetOptionGrayWhaley("s", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float StrikeDelta = EResetOptionGrayWhaley("dx", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout float StrikeGamma = EResetOptionGrayWhaley("dxdx", OpType, S, K, T1, T2, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Reset Strike Options-Type 2 (Gray Whaley)", 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 = "Asset Price: " + str.tostring(S) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "Asset Price Source: " + assetswtich, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, text = "Strike Price: " + str.tostring(K), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 6, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 7, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 8, 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 = 9, text = "Reset Date/Time: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", startfinish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 10, text = "Maturity Date/Time: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", expiryfinish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 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 = "Reset Strike Options-Type 2 (Gray Whaley) Price: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
[Floride] 4 Layers of Bollinger Shadow
https://www.tradingview.com/script/68VJWmkn/
Floride11
https://www.tradingview.com/u/Floride11/
83
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/ // © Floride //@version=5 indicator('MLBS - Multi Layers of Bollinger Shadow', 'MLBS', overlay=true) len = input.int(192, minval=1, title='주기-기간') len2 = len * 2 len3 = len * 3 len4 = len * 4 len5 = len * 5 len15 = math.round(len * 1.5) len25 = math.round(len * 2.5) len35 = math.round(len * 3.5) len45 = math.round(len * 4.5) len55 = math.round(len * 5.5) tunaon = input(true,"Tuna signal ON") lmarlinon = input(true,"Little Marlin signal ON") marlinon = input(true,"Marlin signal ON") src = input(close, title='Input Source') // m1 = input(1, minval=0.001, maxval=50) m2 = input.float(1.62, minval=0.001, maxval=50) m3 = input.float(2.62, minval=0.001, maxval=50) cl = ta.ema(src, len) // central line dev11 = m2 * ta.stdev(src, len) up11 = cl + dev11 low11 = cl - dev11 dev12 = m3 * ta.stdev(src, len) up12 = cl + dev12 low12 = cl - dev12 dev151 = m2 * ta.stdev(src, len15) up151 = cl + dev151 low151 = cl - dev151 dev152 = m3 * ta.stdev(src, len15) up152 = cl + dev152 low152 = cl - dev152 dev22 = m2 * ta.stdev(src, len2) up22 = cl + dev22 low22 = cl - dev22 dev252 = m2 * ta.stdev(src, len25) up252 = cl + dev252 low252 = cl - dev252 dev32 = m2 * ta.stdev(src, len3) up32 = cl + dev32 low32 = cl - dev32 dev352 = m2 * ta.stdev(src, len35) up352 = cl + dev352 low352 = cl - dev352 dev42 = m2 * ta.stdev(src, len4) up42 = cl + dev42 low42 = cl - dev42 dev452 = m2 * ta.stdev(src, len45) up452 = cl + dev452 low452 = cl - dev452 dev52 = m2 * ta.stdev(src, len5) up52 = cl + dev52 low52 = cl - dev52 dev53 = m3 * ta.stdev(src, len5) up53 = cl + dev53 low53 = cl - dev53 L1ON = input(true, 'L1(Basis Layer) ON') L2ON = input(true, 'L2 ON') L3ON = input(true, 'L3 ON') L4ON = input(true, 'L4 ON') PRON = input(true, 'Precedence Layer on') //precede layer 1,2 on betweenshadowon = input(true, 'Shadows between shadows ON?') shadeoff = input(false,"shade off") plot(PRON ? up11 : na, 'up11', color=color.new(#acff2f, 50), linewidth=0 ,style=plot.style_circles) plot(PRON ? low11 : na, 'low11', color=color.new(#acff2f, 55), linewidth=0,style=plot.style_circles) plot(PRON ? up151 : na, 'up151', color=color.new(#aee161, 25), linewidth=1,style=plot.style_circles) plot(PRON ? low151 : na, 'low151', color=color.new(#acdf60, 22), linewidth=1,style=plot.style_circles) pu252 = plot(L1ON and betweenshadowon? up252 : na, 'up2', color=color.new(#006400, 33), linewidth=3) pl252 = plot(L1ON and betweenshadowon? low252 : na, 'low2', color=color.new(#006400, 33), linewidth=3) pu32 = plot(L2ON ? up32 : na, 'up32', color=color.new(#414b94, 32), linewidth=3) pl32 = plot(L2ON ? low32 : na, 'low32', color=color.new(#414b94, 44), linewidth=3) pu352 = plot(L2ON and betweenshadowon? up352 : na, 'up352', color=color.new(#414b94, 55), linewidth=2) pl352 = plot(L2ON and betweenshadowon? low352 : na, 'low352', color=color.new(#414b94, 55), linewidth=2) pu42 = plot(L3ON ? up42 : na, 'up42', color=color.new(#737373, 55), linewidth=2) pl42 = plot(L3ON ? low42 : na, 'low42', color=color.new(#737373, 55), linewidth=2) pu452 = plot(L3ON and betweenshadowon? up452 : na, 'up452', color=color.new(#737373, 66), linewidth=2) pl452 = plot(L3ON and betweenshadowon? low452 : na, 'low452', color=color.new(#737373, 66), linewidth=2) pu52 = plot(L4ON ? up52 : na, 'up22', color=color.new(#FF0000, 66), linewidth=4) pl52 = plot(L4ON ? low52 : na, 'low22', color=color.new(#FF0000, 66), linewidth=4) pu53 = plot(L4ON ? up53 : na, 'up23', color=color.new(#FF0000, 33), linewidth=2) pl53 = plot(L4ON ? low53 : na, 'low23', color=color.new(#FF0000, 33), linewidth=2) CL = plot(cl, 'cl', color=color.new(color.gray, 0), linewidth=4) MP = plot(hl2,color=color.new(color.silver,99)) var tr0 = 0 var tr0s = 0 if ta.crossover(close, up22) tr0 := 1 if ta.crossunder(close, up22) tr0 := 0 if ta.crossunder(close, low22) tr0 := -1 if ta.crossover(close, low22) tr0 := 0 low3 = ta.ema(low,3) high3 = ta.ema(high,3) if ta.crossover(low3, up22) tr0s := 1 if ta.crossunder(high3, low22) tr0s := -1 var float tr0p = na float tuna = na if tr0s[1] != 1 and tr0s == 1 and tunaon tuna := close if tr0s[1] != -1 and tr0s == -1 and tunaon tuna := close tr0cu = tr0 == 1 ? color.lime : na tr0cl = tr0 == -1 ? color.lime : na plot(tunaon ? tuna : na,color=color.lime,linewidth=7,style=plot.style_cross) var tr1 = 0 if ta.crossover(close, up32) tr1 := 1 if ta.crossunder(close, up32) tr1 := 0 if ta.crossunder(close, low32) tr1 := -1 if ta.crossover(close, low32) tr1 := 0 tr1cu = tr1 == 1 ? color.rgb(255, 153, 0, 25) : na tr1cl = tr1 == -1 ? color.rgb(255, 153, 0, 33) : na float marlin = na float lmarlin = na var int tr3s = na var tr3 = 0 if ta.crossover(close, up53) tr3 := 1 if ta.crossunder(close, up53) tr3 := 0 if ta.crossunder(close, low53) tr3 := -1 if ta.crossover(close, low53) tr3 := 0 if ta.crossunder((hl2+close)/2, low52) tr3s := -1 if ta.crossover((hl2+close)/2 , up52) tr3s := 1 if tr3s[1] == -1 and tr3s == 1 lmarlin := close if tr3s[1] == 1 and tr3s == -1 lmarlin := close tr3sc = tr3s == 1 ? color.new(color.orange,96) : color.new(color.lime,77) tr0bgon = input(true,"L1 transition BGC ON") tr3bgon = input(false,"L4 transition BGC ON") bgcolor(tr0bgon and tr0s == 1 ? color.new(color.orange,99) : tr0bgon and tr0s == -1 ? color.new(color.blue,80) : na) bgcolor(tr3bgon ? tr3sc : na) if ta.crossover(low, up53) and marlinon marlin := close if ta.crossunder(high, low53) and marlinon marlin := close tr3cu = tr3 == 1 ? color.red : na tr3cl = tr3 == -1 ? color.red : na plot(marlinon ? marlin : na,style=plot.style_cross,linewidth=12,color=color.red) plot(lmarlinon ? lmarlin : na,style=plot.style_cross,linewidth=9,color=color.rgb(243, 226, 77)) pu22 = plot(L1ON ? up22 : na, 'up2' , color=color.new(#d3ff91, 55), linewidth=10) pl22 = plot(L1ON ? low22 : na, 'low2', color=color.new(#d3ff91, 55), linewidth=10) plot(L1ON and tr0s == -1 ? up22 : na, 'up2' , color=color.new(#ADFF2F, 0), linewidth=9,style= plot.style_linebr) plot(L1ON and tr0s == 1 ? low22 : na, 'low2' , color=color.new(#ADFF2F, 0), linewidth=9,style= plot.style_linebr) plot(L1ON and tr0s == -1 ? up22 : na, 'up2' , color=color.new(#7cc254, 19) , linewidth=6 ,style= plot.style_linebr) plot(L1ON and tr0s == 1 ? low22 : na, 'low2', color=color.new(#7cc254, 19), linewidth=6 ,style= plot.style_linebr) plot(L1ON and tr0s == -1 ? up22 : na, 'up2' , color=color.new(#006400, 0), linewidth=3,style= plot.style_linebr) plot(L1ON and tr0s == 1 ? low22 : na, 'low2', color=color.new(#006400, 0), linewidth=3,style= plot.style_linebr) alttrend = input(false,"alt trend") plot(alttrend == false ? up22 : na, 'up2' , color=color.new(#ADFF2F, 77), linewidth=4,style= plot.style_linebr) plot(alttrend == false ? low22 : na, 'low2' , color=color.new(#ADFF2F, 77), linewidth=4,style= plot.style_linebr) plot(alttrend == false ? up22 : na, 'up2' , color=color.new(#7cc254, 22) , linewidth=3 ,style= plot.style_linebr) plot(alttrend == false ? low22 : na, 'low2', color=color.new(#7cc254, 22), linewidth=3 ,style= plot.style_linebr) plot(alttrend == false ? up22 : na, 'up2' , color=color.new(#006400, 0), linewidth=2,style= plot.style_linebr) plot(alttrend == false ? low22 : na, 'low2', color=color.new(#006400, 0), linewidth=2,style= plot.style_linebr) fill(pu52, pl52, color=shadeoff ? na :color.new(color.red, 88)) fill(pu42, pl42, color=shadeoff ? na :color.new(#737373, 80)) fill(pu32, pl32, color=shadeoff ? na : color.new(#414b94, 80)) fill(pu22, pl22, color=shadeoff ? na : color.new(color.green, 77)) fill(MP, pu22, color=tr0cu ) fill(MP, pl22, color=tr0cl ) fill(MP, pu32, color=tr1cu ) fill(MP, pl32, color=tr1cl ) fill(MP, pu53, color=tr3cu ) fill(MP, pl53, color=tr3cl ) alertcondition(tr0 > 0 and tuna , title='ASCENDING TUNA' , message = 'ASCENDING TUNA-상승참치') alertcondition(tr0 < 0 and tuna , title='DESCENDING TUNA' , message = 'DESCENDING TUNA-하락참치') alertcondition(tr0 > 0 and lmarlin , title='ASCENDING LITTLE MARLIN-상승소새치', message = 'ASCENDING LITTLE MARLIN-상승소새치') alertcondition(tr0 < 0 and lmarlin , title='DESCENDING LITTLE MARLIN-하락소새치', message = 'DESCENDING LITTLE MARLIN-하락소새치') alertcondition(tr0 > 0 and marlin , title='ASCENDING MARLIN-상승청새치', message = 'ASCENDING MARLIN-상승청새치') alertcondition(tr0 < 0 and marlin , title='DESCENDING MARLIN-하락청새치', message = 'DESCENDING MARLIN-하락청새치') // © Floride
Writer Extendible Option [Loxx]
https://www.tradingview.com/script/4eCSgAnR-Writer-Extendible-Option-Loxx/
loxx
https://www.tradingview.com/u/loxx/
11
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("Writer Extendible Option [Loxx]", shorttitle ="WEO [Loxx]", overlay = true, max_lines_count = 500) if not timeframe.isdaily runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.") import loxx/cnd/1 import loxx/cbnd/1 color darkGreenColor = #1B7E02 string srcAPrice = "Source Asset Price" string manAPrice = "Manual Asset Price" string callString = "Call" string putString = "Put" string Continuous = "Continuous" 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas 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.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 //// Writer extendible options ExtendibleWriter(string CallPutFlag, float S, float X1, float X2, float t1, float T2, float r, float b, float v)=> float ExtendibleWriter = 0 float rho = math.sqrt(t1 / T2) float z1 = (math.log(S / X2) + (b + math.pow(v, 2) / 2) * T2) / (v * math.sqrt(T2)) float z2 = (math.log(S / X1) + (b + math.pow(v, 2) / 2) * t1) / (v * math.sqrt(t1)) if CallPutFlag == callString ExtendibleWriter := GBlackScholes(CallPutFlag, S, X1, t1, r, b, v) + S * math.exp((b - r) * T2) * cbnd.CBND3(z1, -z2, -rho) - X2 * math.exp(-r * T2) * cbnd.CBND3(z1 - math.sqrt(math.pow(v, 2) * T2), -z2 + math.sqrt(math.pow(v, 2) * t1), -rho) else ExtendibleWriter := GBlackScholes(CallPutFlag, S, X1, t1, r, b, v) + X2 * math.exp(-r * T2) * cbnd.CBND3(-z1 + math.sqrt(math.pow(v, 2) * T2), z2 - math.sqrt(math.pow(v, 2) * t1), -rho) - S * math.exp((b - r) * T2) * cbnd.CBND3(-z1, z2, -rho) ExtendibleWriter EExtendibleWriter(string OutPutFlag, string CallPutFlag, float S, float X1, float X2, float t1, float T2, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EExtendibleWriter = 0 if OutPutFlag == "p" // Value EExtendibleWriter := ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) else if OutPutFlag == "d" //Delta EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v) - ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v) - ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v)) / (2 * dS) * S / ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) else if OutPutFlag == "g" //Gamma EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v) - 2 * ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) + ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v + 0.01) - 2 * ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v + 0.01) + ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v + 0.01) - ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v - 0.01) + 2 * ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v - 0.01) - ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EExtendibleWriter := S / 100 * (ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v) - 2 * ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) + ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "dddv" //DDeltaDvol EExtendibleWriter := 1 / (4 * dS * 0.01) * (ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v + 0.01) - ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v - 0.01) - ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v + 0.01) + ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v + 0.01) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v + 0.01) - 2 * ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) + ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v - 0.01)) / math.pow(0.01, 2)/ 10000 else if OutPutFlag == "vp" //VegaP EExtendibleWriter := v / 0.1 * (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v + 0.01) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v + 0.01) - 2 * ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) + ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if t1 <= 1 / 365 EExtendibleWriter := ExtendibleWriter(CallPutFlag, S, X1, X2, 1E-05, T2 - 1 / 365, r, b, v) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) else EExtendibleWriter := ExtendibleWriter(CallPutFlag, S, X1, X2, t1 - 1 / 365, T2 - 1 / 365, r, b, v) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) else if OutPutFlag == "r" //Rho EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r + 0.01, b + 0.01, v) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" //Futures options rho EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r + 0.01, b, v) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" //Rho2 EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b - 0.01, v) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" //Carry EExtendibleWriter := (ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b + 0.01, v) - ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" //Speed EExtendibleWriter := 1 / math.pow(dS, 3) * (ExtendibleWriter(CallPutFlag, S + 2 * dS, X1, X2, t1, T2, r, b, v) - 3 * ExtendibleWriter(CallPutFlag, S + dS, X1, X2, t1, T2, r, b, v) + 3 * ExtendibleWriter(CallPutFlag, S, X1, X2, t1, T2, r, b, v) - ExtendibleWriter(CallPutFlag, S - dS, X1, X2, t1, T2, r, b, v)) EExtendibleWriter 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 Sm = input.float(100, "Manual Asset Price", group = "Basic Settings") float Ssrc = input.source(close, "Source Asset Price", group = "Basic Settings") string assetswtich = input.string(manAPrice, "Asset Price Type", options = [srcAPrice, manAPrice], group = "Basic Settings") float K1 = input.float(100, "Initial Strike Price", group = "Basic Settings") float K2 = input.float(100, "Extended Strike Price", group = "Basic Settings") float r = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(20., "% 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") float S = assetswtich == srcAPrice ? Ssrc : Sm 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 startthruMonth = input.int(12, title = "Initial Time Start Month", minval = 1, maxval = 12, group = "Initial Time to Maturity Date/Time") int startthruDay = input.int(31, title = "Initial Time Start Day", minval = 1, maxval = 31, group = "Initial Time to Maturity Date/Time") int startthruYear = input.int(2022, title = "Initial Time Start Year", minval = 1970, group = "Initial Time to Maturity Date/Time") int startmins = input.int(0, title = "Initial Time Start Minute", minval = 0, maxval = 60, group = "Initial Time to Maturity Date/Time") int starthours = input.int(9, title = "Initial Time Start Hour", minval = 0, maxval = 24, group = "Initial Time to Maturity Date/Time") int startsecs = input.int(0, title = "Initial Time Start Second", minval = 0, maxval = 60, group = "Initial Time to Maturity Date/Time") int expirythruMonth = input.int(3, title = "Extended Time Month", minval = 1, maxval = 12, group = "Extended Time to Maturity Date/Time") int expirythruDay = input.int(31, title = "Extended Time Day", minval = 1, maxval = 31, group = "Extended Time to Maturity Date/Time") int expirythruYear = input.int(2023, title = "Extended Time Year", minval = 1970, group = "Extended Time to Maturity Date/Time") int expirymins = input.int(0, title = "Extended Time Minute", minval = 0, maxval = 60, group = "Extended Time to Maturity Date/Time") int expiryhours = input.int(9, title = "Extended Time Hour", minval = 0, maxval = 24, group = "Extended Time to Maturity Date/Time") int expirysecs = input.int(0, title = "Extended Time Second", minval = 0, maxval = 60, group = "Extended Time to Maturity 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 float startstart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday float startfinish = timestamp(startthruYear, startthruMonth, startthruDay, starthours, startmins, startsecs) float starttemp = (startfinish - startstart) float T1 = (startfinish - startstart) / spyr / 1000 // precision calculation miliseconds in time intreval from time equals now float expirystart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday float expiryfinish = timestamp(expirythruYear, expirythruMonth, expirythruDay, expiryhours, expirymins, expirysecs) float expirytemp = (expiryfinish - expirystart) float T2 = (expiryfinish - expirystart) / spyr / 1000 string txtsize = input.string("Auto", title = "Text Size", 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 float hvolout = switch hvoltype parkinson => parkinsonvol(histvolper) rogersatch => rogerssatchel(histvolper) c2c => closetoclose(math.log(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) float rcmpval = switch rcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 if barstate.islast float sideout = side == "Long" ? 1 : -1 float kouta = convertingToCCRate(r, rcmpval) float koutb = convertingToCCRate(b, bcmpval) float amaproxprice = EExtendibleWriter("p", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) float Delta = EExtendibleWriter("d", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float Elasticity = EExtendibleWriter("e", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float Gamma = EExtendibleWriter("g", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float DGammaDvol = EExtendibleWriter("gv", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float GammaP = EExtendibleWriter("gp", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float Vega = EExtendibleWriter("v", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float DvegaDvol = EExtendibleWriter("dvdv", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float VegaP = EExtendibleWriter("vp", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float Theta = EExtendibleWriter("t", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float Rho = EExtendibleWriter("r", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float RhoFuturesOption = EExtendibleWriter("fr", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float PhiRho2 = EExtendibleWriter("f", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float Carry = EExtendibleWriter("b", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float DDeltaDvol = EExtendibleWriter("dddv", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout float Speed = EExtendibleWriter("s", OpType, S, K1, K2, T1, T2, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 18, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Writer Extendible Option", 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 = "Asset Price: " + str.tostring(S) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "Asset Price Source: " + assetswtich, bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, text = "Iniital Strike Price: " + str.tostring(K1), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 6, text = "Extended Strike Price: " + str.tostring(K2), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 7, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 8, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 9, 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 = 10, text = "Iniital Date/Time to Maturity: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", startfinish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 11, text = "Extended Date/Time to Maturity: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", expiryfinish), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 12, 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 = 13, 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 = 14, 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 = 15, 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 = 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 = "Writer Extendible Option Price: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Crossover Alerts for Yesterday O/H/L/C , Today Vwap [Zero54]
https://www.tradingview.com/script/wlYximf1-Crossover-Alerts-for-Yesterday-O-H-L-C-Today-Vwap-Zero54/
zero54
https://www.tradingview.com/u/zero54/
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/ // © zero54. Happy Trading! //@version=5 indicator("Crossover Alerts [Zero54]",overlay=true) _cross_over_close = ta.crossover(close,close[1]) _cross_under_close = ta.crossunder(close,close[1]) _cross_over_open = ta.crossover(close,open[1]) _cross_under_open = ta.crossunder(close,open[1]) _cross_over_high = ta.crossover(close,high[1]) _cross_under_high = ta.crossunder(close,high[1]) _cross_over_low = ta.crossover(close,low[1]) _cross_under_low = ta.crossunder(close,low[1]) _cross_over_vwap = ta.crossover(close,ta.vwap(hlc3)) _cross_under_vwap = ta.crossunder(close,ta.vwap(hlc3)) [__cross__over__close,__cross__under__close,__cross__over__open,__cross__under__open,__cross__over__high,__cross__under__high,__cross__over__low,__cross__under__low]= request.security("","D",[_cross_over_close,_cross_under_close,_cross_over_open,_cross_under_open,_cross_over_high,_cross_under_high,_cross_over_low,_cross_under_low]) [__cross__over__vwap,__cross__under__vwap]= request.security("","60",[_cross_over_vwap,_cross_under_vwap]) if __cross__over__close and (not __cross__over__close[1]) alert("Price (" + str.tostring(close) + ") crossed above yesterday's close.", alert.freq_once_per_bar) if __cross__under__close and (not __cross__under__close[1]) alert("Price (" + str.tostring(close) + ") crossed below yesterday's close.", alert.freq_once_per_bar) if __cross__over__open and (not __cross__over__open[1]) alert("Price (" + str.tostring(close) + ") crossed above yesterday's open.", alert.freq_once_per_bar) if __cross__under__open and (not __cross__under__open[1]) alert("Price (" + str.tostring(close) + ") crossed below yesterday's open.", alert.freq_once_per_bar) if __cross__over__high and (not __cross__over__high[1]) alert("Price (" + str.tostring(close) + ") crossed above yesterday's high.", alert.freq_once_per_bar) if __cross__under__high and (not __cross__under__high[1]) alert("Price (" + str.tostring(close) + ") crossed below yesterday's high.", alert.freq_once_per_bar) if __cross__over__low and (not __cross__over__low[1]) alert("Price (" + str.tostring(close) + ") crossed above yesterday's low.", alert.freq_once_per_bar) if __cross__under__low and (not __cross__under__low[1]) alert("Price (" + str.tostring(close) + ") crossed below yesterday's low.", alert.freq_once_per_bar) if __cross__over__low and (not __cross__over__low[1]) alert("Price (" + str.tostring(close) + ") crossed above yesterday's low.", alert.freq_once_per_bar) if __cross__under__low and (not __cross__under__low[1]) alert("Price (" + str.tostring(close) + ") crossed below yesterday's low.", alert.freq_once_per_bar) if __cross__over__vwap and (not __cross__over__vwap[1]) alert("Price (" + str.tostring(close) + ") crossed above Vwap.", alert.freq_once_per_bar) if __cross__under__vwap and (not __cross__under__vwap[1]) alert("Price (" + str.tostring(close) + ") crossed under Vwap.", alert.freq_once_per_bar) print_string = "Right click on me and click on 'Add Alert'. \n After you've set the alert you remove the indicator from the chart" print(txt) => // Create label on the first bar. var lbl = label.new(bar_index, na, txt, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left) // On next bars, update the label's x and y position, and the text it displays. label.set_xy(lbl, bar_index, ta.highest(10)[1]) label.set_text(lbl, txt) print(print_string)
Log Option [Loxx]
https://www.tradingview.com/script/lRJ6eRpE-Log-Option-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("Log Option [Loxx]", shorttitle ="LO [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 import loxx/combin/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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out LogOption(float S, float X, float T, float r, float b, float v)=> float d2 = (math.log(S / X) + (b - math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) LogOption = math.exp(-r * T) * ND(d2) * v * math.sqrt(T) + math.exp(-r * T) * (math.log(S / X) + (b - math.pow(v, 2) / 2) * T) * cnd.CND1(d2) LogOption ELogOption(string OutPutFlag, float S, float X, float T, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float ELogOption = 0 if OutPutFlag == "p" // Value ELogOption := LogOption(S, X, T, r, b, v) else if OutPutFlag == "d" //Delta ELogOption := (LogOption(S + dS, X, T, r, b, v) - LogOption(S - dS, X, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity ELogOption := (LogOption(S + dS, X, T, r, b, v) - LogOption(S - dS, X, T, r, b, v)) / (2 * dS) * S / LogOption(S, X, T, r, b, v) else if OutPutFlag == "g" //Gamma ELogOption := (LogOption(S + dS, X, T, r, b, v) - 2 * LogOption(S, X, T, r, b, v) + LogOption(S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol ELogOption := (LogOption(S + dS, X, T, r, b, v + 0.01) - 2 * LogOption(S, X, T, r, b, v + 0.01) + LogOption(S - dS, X, T, r, b, v + 0.01) - LogOption(S + dS, X, T, r, b, v - 0.01) + 2 * LogOption(S, X, T, r, b, v - 0.01) - LogOption(S - dS, X, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP ELogOption := S / 100 * (LogOption(S + dS, X, T, r, b, v) - 2 * LogOption(S, X, T, r, b, v) + LogOption(S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma ELogOption := (LogOption(S, X, T + 1 / 365, r, b, v) - 2 * LogOption(S, X, T, r, b, v) + LogOption(S, X, T - 1 / 365, r, b, v)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol ELogOption := 1 / (4 * dS * 0.01) * (LogOption(S + dS, X, T, r, b, v + 0.01) - LogOption(S + dS, X, T, r, b, v - 0.01) - LogOption(S - dS, X, T, r, b, v + 0.01) + LogOption(S - dS, X, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega ELogOption := (LogOption(S, X, T, r, b, v + 0.01) - LogOption(S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma ELogOption := (LogOption(S, X, T, r, b, v + 0.01) - 2 * LogOption(S, X, T, r, b, v) + LogOption(S, X, T, r, b, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP ELogOption := v / 0.1 * (LogOption(S, X, T, r, b, v + 0.01) - LogOption(S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol ELogOption := (LogOption(S, X, T, r, b, v + 0.01) - 2 * LogOption(S, X, T, r, b, v) + LogOption(S, X, T, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 ELogOption := LogOption(S, X, 1E-05, r, b, v) - LogOption(S, X, T, r, b, v) else ELogOption := LogOption(S, X, T - 1 / 365, r, b, v) - LogOption(S, X, T, r, b, v) else if OutPutFlag == "r" //Rho ELogOption := (LogOption(S, X, T, r + 0.01, b + 0.01, v) - LogOption(S, X, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" //Futures options rho ELogOption := (LogOption(S, X, T, r + 0.01, b, v) - LogOption(S, X, T, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" //Rho2 ELogOption := (LogOption(S, X, T, r, b - 0.01, v) - LogOption(S, X, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" //Carry ELogOption := (LogOption(S, X, T, r, b + 0.01, v) - LogOption(S, X, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" //Speed ELogOption := 1 / math.pow(dS, 3) * (LogOption(S + 2 * dS, X, T, r, b, v) - 3 * LogOption(S + dS, X, T, r, b, v) + 3 * LogOption(S, X, T, r, b, v) - LogOption(S - dS, X, T, r, b, v)) else if OutPutFlag == "dx" //Strike Delta ELogOption := (LogOption(S, X + dS, T, r, b, v) - LogOption(S, X - dS, T, r, b, v)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike Gamma ELogOption := (LogOption(S, X + dS, T, r, b, v) - 2 * LogOption(S, X, T, r, b, v) + LogOption(S, X - dS, T, r, b, v)) / math.pow(dS, 2) ELogOption 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(65, "Strike Price", group = "Basic Settings") string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings") float r = input.float(3.7, "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(1.84, "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(62.05, "% 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = ELogOption("p", S, K, T, kouta, koutb, v, na) Delta = ELogOption("d", S, K, T, kouta, koutb, v, na) * sideout Elasticity = ELogOption("e", S, K, T, kouta, koutb, v, na) * sideout Gamma = ELogOption("g", S, K, T, kouta, koutb, v, na) * sideout DGammaDvol = ELogOption("gv", S, K, T, kouta, koutb, v, na) * sideout GammaP = ELogOption("gp", S, K, T, kouta, koutb, v, na) * sideout Vega = ELogOption("v", S, K, T, kouta, koutb, v, na) * sideout DvegaDvol = ELogOption("dvdv", S, K, T, kouta, koutb, v, na) * sideout VegaP = ELogOption("vp", S, K, T, kouta, koutb, v, na) * sideout Theta = ELogOption("t", S, K, T, kouta, koutb, v, na) * sideout Rho = ELogOption("r", S, K, T, kouta, koutb, v, na) * sideout RhoFuturesOption = ELogOption("fr", S, K, T, kouta, koutb, v, na) * sideout PhiRho2 = ELogOption("f", S, K, T, kouta, koutb, v, na) * sideout Carry = ELogOption("b", S, K, T, kouta, koutb, v, na) * sideout DDeltaDvol = ELogOption("dddv", S, K, T, kouta, koutb, v, na) * sideout Speed = ELogOption("s", S, K, T, kouta, koutb, v, na) * sideout StrikeDelta = ELogOption("dx", S, K, T, kouta, koutb, v, na) * sideout StrikeGamma = ELogOption("dxdx", S, K, T, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Log Option", 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 = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, text = "Spot Price: " + str.tostring(S, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 3, 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 = 4, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 5, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 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 = 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 = "Log Option Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
RTI Volume Weighted Average Price
https://www.tradingview.com/script/OzbiRuR4-RTI-Volume-Weighted-Average-Price/
superkumar2020
https://www.tradingview.com/u/superkumar2020/
27
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/ // © superkumar2020 //@version=5 indicator(title="Volume Weighted Average Price", shorttitle="VWAP", overlay=true, timeframe="", timeframe_gaps=true) hideonDWM = input(false, title="Hide VWAP on 1D or Above", group="VWAP Settings") var anchor = input.string(defval = "Session", title="Anchor Period", options=["Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"], group="VWAP Settings") src = input(title = "Source", defval = hlc3, group="VWAP Settings") offset = input(0, title="Offset", group="VWAP Settings") showBand_1 = input(true, title="", group="Standard Deviation Bands Settings", inline="band_1") stdevMult_1 = input(1.0, title="Bands Multiplier #1", group="Standard Deviation Bands Settings", inline="band_1") showBand_2 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_2") stdevMult_2 = input(2.0, title="Bands Multiplier #2", group="Standard Deviation Bands Settings", inline="band_2") showBand_3 = input(false, title="", group="Standard Deviation Bands Settings", inline="band_3") stdevMult_3 = input(3.0, title="Bands Multiplier #3", group="Standard Deviation Bands Settings", inline="band_3") if barstate.islast and ta.cum(volume) == 0 runtime.error("No volume is provided by the data vendor.") new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true) new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true) new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true) isNewPeriod = switch anchor "Earnings" => not na(new_earnings) "Dividends" => not na(new_dividends) "Splits" => not na(new_split) "Session" => timeframe.change("D") "Week" => timeframe.change("W") "Month" => timeframe.change("M") "Quarter" => timeframe.change("3M") "Year" => timeframe.change("12M") "Decade" => timeframe.change("12M") and year % 10 == 0 "Century" => timeframe.change("12M") and year % 100 == 0 => false isEsdAnchor = anchor == "Earnings" or anchor == "Dividends" or anchor == "Splits" if na(src[1]) and not isEsdAnchor isNewPeriod := true float vwapValue = na float upperBandValue1 = na float lowerBandValue1 = na float upperBandValue2 = na float lowerBandValue2 = na float upperBandValue3 = na float lowerBandValue3 = na if not (hideonDWM and timeframe.isdwm) [_vwap, _stdevUpper, _] = ta.vwap(src, isNewPeriod, 1) vwapValue := _vwap stdevAbs = _stdevUpper - _vwap upperBandValue1 := _vwap + stdevAbs * stdevMult_1 lowerBandValue1 := _vwap - stdevAbs * stdevMult_1 upperBandValue2 := _vwap + stdevAbs * stdevMult_2 lowerBandValue2 := _vwap - stdevAbs * stdevMult_2 upperBandValue3 := _vwap + stdevAbs * stdevMult_3 lowerBandValue3 := _vwap - stdevAbs * stdevMult_3 plot(vwapValue, title="VWAP", color=#2962FF, offset=offset) upperBand_1 = plot(upperBandValue1, title="Upper Band #1", color=color.green, offset=offset, display = showBand_1 ? display.all : display.none) lowerBand_1 = plot(lowerBandValue1, title="Lower Band #1", color=color.green, offset=offset, display = showBand_1 ? display.all : display.none) fill(upperBand_1, lowerBand_1, title="Bands Fill #1", color= color.new(color.green, 95) , display = showBand_1 ? display.all : display.none) upperBand_2 = plot(upperBandValue2, title="Upper Band #2", color=color.olive, offset=offset, display = showBand_2 ? display.all : display.none) lowerBand_2 = plot(lowerBandValue2, title="Lower Band #2", color=color.olive, offset=offset, display = showBand_2 ? display.all : display.none) fill(upperBand_2, lowerBand_2, title="Bands Fill #2", color= color.new(color.olive, 95) , display = showBand_2 ? display.all : display.none) upperBand_3 = plot(upperBandValue3, title="Upper Band #3", color=color.teal, offset=offset, display = showBand_3 ? display.all : display.none) lowerBand_3 = plot(lowerBandValue3, title="Lower Band #3", color=color.teal, offset=offset, display = showBand_3 ? display.all : display.none) fill(upperBand_3, lowerBand_3, title="Bands Fill #3", color= color.new(color.teal, 95) , display = showBand_3 ? display.all : display.none) //indicator(shorttitle="BB", title="Bollinger Bands", overlay=true, timeframe="", timeframe_gaps=true) length = input.int(20, minval=1) src1 = input(close, title="Source") mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev") basis = ta.sma(src, length) dev = mult * ta.stdev(src, length) upper = basis + dev lower = basis - dev offset1 = 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))
Trend Dominance Multi Timeframe [Misu]
https://www.tradingview.com/script/uo2IyKkL-Trend-Dominance-Multi-Timeframe-Misu/
Fontiramisu
https://www.tradingview.com/u/Fontiramisu/
178
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("Trend Dominance MTF [Misu]", overlay = true, shorttitle="Trend Dom [Misu]") // import Fontiramisu/fontLib/86 as fontilab import Fontiramisu/fontilab/11 as fontilab // ] -------- Input --------------- [ src = input.source(close, "Source", group="Trend Settings") len = input.int(5, "Length Atr", group = "Trend Settings") mult = input.float(7.6, "Multiplier Atr", step = 0.1, group = "Trend Settings") // To Remove. colorbars = input.bool(true, "Color Bars", group = "UI Settings", inline="1") showlmidbs = input.bool(true, "Show Label", group = "UI Settings", inline="1") // Show table. show_table = input.bool(true, "Show stats", group = "Table Settings") show5min = input.bool(true, "Show 5m -------", group = "Table Settings", inline="2") show15min = input.bool(true, "Show 15m", group = "Table Settings", inline="2") show1h = input.bool(true, "Show 1h --------", group = "Table Settings", inline="3") show4h = input.bool(true, "Show 4h", group = "Table Settings", inline="3") show12h = input.bool(true, "Show 12h ------", group = "Table Settings", inline="4") showD = input.bool(true, "Show D", group = "Table Settings", inline="4") showW = input.bool(true, "Show W", group = "Table Settings", inline="5") // ] -------- Vars --------------- [ // Period. var string format = "{0,date,yyyy.MM.dd}" var sTime = str.format(format, time_close) eTime = str.format(format, time_close) // Trend. var utrendSum5m = 0, var dtrendSum5m = 0, var state5m = 99, utrendDom5m = 0. var utrendSum15m = 0, var dtrendSum15m = 0, var state15m = 99, utrendDom15m = 0. var utrendSum1h = 0, var dtrendSum1h = 0, var state1h = 99, utrendDom1h = 0. var utrendSum4h = 0, var dtrendSum4h = 0, var state4h = 99, utrendDom4h = 0. var utrendSum12h = 0, var dtrendSum12h = 0, var state12h = 99, utrendDom12h = 0. var utrendSumD = 0, var dtrendSumD = 0, var stateD = 99, utrendDomD = 0. var utrendSumW = 0, var dtrendSumW = 0, var stateW = 99, utrendDomW = 0. // ] -------- Function ----------------- [ // @function: get trend dominance. getTrendDom(midb, utrendSum, dtrendSum, state) => trendUp = nz(midb[1]) ? midb > midb[1] : false trendDown = nz(midb[1]) ? midb < midb[1] : false stateNew = trendUp ? 1 : trendDown ? -1 : state utrendSumNew = state == 1 ? utrendSum + 1 : utrendSum dtrendSumNew = state == -1 ? dtrendSum + 1 : dtrendSum [utrendSumNew, dtrendSumNew, stateNew, math.round(utrendSum / (utrendSum + dtrendSum) * 100, 1)] // ] -------- Dominance Trend Logic ----------------- [ // Get multi timeframe trend. deltaAtr = mult * ta.atr(len) // Get Trend Doms. // 5m. [midb5m, upperb5m, lowerb5m] = request.security(syminfo.tickerid, "5", fontilab.getTrendBands(src, deltaAtr), lookahead = barmerge.lookahead_on) [utrendSum5mDup, dtrendSum5mDup, state5mDup, utrendDom5mDup] = getTrendDom(midb5m, utrendSum5m, dtrendSum5m, state5m) utrendSum5m := utrendSum5mDup dtrendSum5m := dtrendSum5mDup state5m := state5mDup utrendDom5m := utrendDom5mDup // 15m. [midb15m, upperb15m, lowerb15m] = request.security(syminfo.tickerid, "15", fontilab.getTrendBands(src, deltaAtr), lookahead = barmerge.lookahead_on) [utrendSum15mDup, dtrendSum15mDup, state15mDup, utrendDom15mDup] = getTrendDom(midb15m, utrendSum15m, dtrendSum15m, state15m) utrendSum15m := utrendSum15mDup dtrendSum15m := dtrendSum15mDup state15m := state15mDup utrendDom15m := utrendDom15mDup // 1h. [midb1h, upperb1h, lowerb1h] = request.security(syminfo.tickerid, "60", fontilab.getTrendBands(src, deltaAtr), lookahead = barmerge.lookahead_on) [utrendSum1hDup, dtrendSum1hDup, state1hDup, utrendDom1hDup] = getTrendDom(midb1h, utrendSum1h, dtrendSum1h, state1h) utrendSum1h := utrendSum1hDup dtrendSum1h := dtrendSum1hDup state1h := state1hDup utrendDom1h := utrendDom1hDup // 4h. [midb4h, upperb4h, lowerb4h] = request.security(syminfo.tickerid, "240", fontilab.getTrendBands(src, deltaAtr), lookahead = barmerge.lookahead_on) [utrendSum4hDup, dtrendSum4hDup, state4hDup, utrendDom4hDup] = getTrendDom(midb4h, utrendSum4h, dtrendSum4h, state4h) utrendSum4h := utrendSum4hDup dtrendSum4h := dtrendSum4hDup state4h := state4hDup utrendDom4h := utrendDom4hDup // 12h. [midb12h, upperb12h, lowerb12h] = request.security(syminfo.tickerid, "720", fontilab.getTrendBands(src, deltaAtr), lookahead = barmerge.lookahead_on) [utrendSum12hDup, dtrendSum12hDup, state12hDup, utrendDom12hDup] = getTrendDom(midb12h, utrendSum12h, dtrendSum12h, state12h) utrendSum12h := utrendSum12hDup dtrendSum12h := dtrendSum12hDup state12h := state12hDup utrendDom12h := utrendDom12hDup // D. [midbD, upperbD, lowerbD] = request.security(syminfo.tickerid, "D", fontilab.getTrendBands(src, deltaAtr), lookahead = barmerge.lookahead_on) [utrendSumDDup, dtrendSumDDup, stateDDup, utrendDomDDup] = getTrendDom(midbD, utrendSumD, dtrendSumD, stateD) utrendSumD := utrendSumDDup dtrendSumD := dtrendSumDDup stateD := stateDDup utrendDomD := utrendDomDDup // W. [midbW, upperbW, lowerbW] = request.security(syminfo.tickerid, "W", fontilab.getTrendBands(src, deltaAtr), lookahead = barmerge.lookahead_on) [utrendSumWDup, dtrendSumWDup, stateWDup, utrendDomWDup] = getTrendDom(midbW, utrendSumW, dtrendSumW, stateW) utrendSumW := utrendSumWDup dtrendSumW := dtrendSumWDup stateW := stateWDup utrendDomW := utrendDomWDup // ] -------- Period Logic ----------------- [ // ] -------- Plot Part --------------- [ // var color colorTrend = na // colorTrend := state == -1 ? color.red : state == 1 ? color.green : state == 99 ? color.gray : nz(colorTrend[1]) // barcolor(colorbars ? colorTrend : na) // plot(upperb, "Upper Band", color = colorTrend, linewidth = 2) // plot(lowerb, "Lower Band", color = colorTrend, linewidth = 2) // ] -------- Alerts ----------------- [ // alertcondition(buyCond, title = "Long", message = "ATR Trend Bands [Misu]: Long\nSymbol: {{ticker}}\nPrice: {{close}}") // alertcondition(sellCond, title = "Short", message = "ATR Trend Bands [Misu]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") // ] -------- Show results ----------------- [ // Period color. pColor5m = not na(utrendDom5m) ? utrendDom5m >= 50 ? color.new(color.green, 20) : color.new(color.red, 20) : color.gray pColor15m = not na(utrendDom15m) ? utrendDom15m >= 50 ? color.new(color.green, 20) : color.new(color.red, 20) : color.gray pColor1h = not na(utrendDom1h) ? utrendDom1h >= 50 ? color.new(color.green, 20) : color.new(color.red, 20) : color.gray pColor4h = not na(utrendDom4h) ? utrendDom4h >= 50 ? color.new(color.green, 20) : color.new(color.red, 20) : color.gray pColor12h = not na(utrendDom12h) ? utrendDom12h >= 50 ? color.new(color.green, 20) : color.new(color.red, 20) : color.gray pColorD = not na(utrendDomD) ? utrendDomD >= 50 ? color.new(color.green, 20) : color.new(color.red, 20) : color.gray pColorW = not na(utrendDomW) ? utrendDomW >= 50 ? color.new(color.green, 20) : color.new(color.red, 20) : color.gray // Last color. lColor5m = state5m == 1 ? color.new(color.green, 20) : state5m == -1 ? color.new(color.red, 20) : color.gray lColor15m = state15m == 1 ? color.new(color.green, 20) : state15m == -1 ? color.new(color.red, 20) : color.gray lColor1h = state1h == 1 ? color.new(color.green, 20) : state1h == -1 ? color.new(color.red, 20) : color.gray lColor4h = state4h == 1 ? color.new(color.green, 20) : state4h == -1 ? color.new(color.red, 20) : color.gray lColor12h = state12h == 1 ? color.new(color.green, 20) : state12h == -1 ? color.new(color.red, 20) : color.gray lColorD = stateD == 1 ? color.new(color.green, 20) : stateD == -1 ? color.new(color.red, 20) : color.gray lColorW = stateW == 1 ? color.new(color.green, 20) : stateW == -1 ? color.new(color.red, 20) : color.gray // // Last Text. lTxt5m = state5m == 1 ? "▲" : state5m == -1 ? "▼" : "X" lTxt15m = state15m == 1 ? "▲" : state15m == -1 ? "▼" : "X" lTxt1h = state1h == 1 ? "▲" : state1h == -1 ? "▼" : "X" lTxt4h = state4h == 1 ? "▲" : state4h == -1 ? "▼" : "X" lTxt12h = state12h == 1 ? "▲" : state12h == -1 ? "▼" : "X" lTxtD = stateD == 1 ? "▲" : stateD == -1 ? "▼" : "X" lTxtW = stateW == 1 ? "▲" : stateW == -1 ? "▼" : "X" // ▼ if show_table var ATHtable = table.new(position.bottom_right, 10, 11, frame_color=#162815, frame_width=1, border_width=2, border_color=color.new(color.white, 100)) //table.new(position.top_right, 6, 41, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.white, 100)) // var table ATHtable = table.new(position.bottom_right, 10, 10, frame_color = color.gray, bgcolor = color.gray, border_width = 1, frame_width = 1, border_color = color.white) // Header table.cell(ATHtable, 0, 0, 'Period', bgcolor=color.new(color.gray, 40), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 0, str.tostring(sTime) + " - " + str.tostring(eTime), bgcolor = color.new(color.gray, 40), text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 0, "last", bgcolor = color.new(color.gray, 40), text_color=color.white, text_size=size.small) if show5min table.cell(ATHtable, 0, 1, "5m", bgcolor=color.new(color.gray, 10), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 1, str.tostring(utrendDom5m) + "% / " + str.tostring(100 - utrendDom5m) + "%", bgcolor=pColor5m, text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 1, lTxt5m, bgcolor=lColor5m, text_color=color.white, text_size=size.small) if show15min table.cell(ATHtable, 0, 2, '15m', bgcolor=color.new(color.gray, 10), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 2, str.tostring(utrendDom15m) + "% / " + str.tostring(100 - utrendDom15m) + "%", bgcolor=pColor15m, text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 2, lTxt15m, bgcolor=lColor15m, text_color=color.white, text_size=size.small) if show1h table.cell(ATHtable, 0, 3, '1h', bgcolor=color.new(color.gray, 10), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 3, str.tostring(utrendDom1h) + "% / " + str.tostring(100 - utrendDom1h) + "%", bgcolor=pColor1h, text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 3, lTxt1h, bgcolor=lColor1h, text_color=color.white, text_size=size.small) if show4h table.cell(ATHtable, 0, 4, '4h', bgcolor=color.new(color.gray, 10), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 4, str.tostring(utrendDom4h) + "% / " + str.tostring(100 - utrendDom4h) + "%", bgcolor=pColor4h, text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 4, lTxt4h, bgcolor=lColor4h, text_color=color.white, text_size=size.small) if show12h table.cell(ATHtable, 0, 5, '12h', bgcolor=color.new(color.gray, 10), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 5, str.tostring(utrendDom12h) + "% / " + str.tostring(100 - utrendDom12h) + "%", bgcolor=pColor12h, text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 5, lTxt12h, bgcolor=lColor12h, text_color=color.white, text_size=size.small) if showD table.cell(ATHtable, 0, 6, 'D', bgcolor=color.new(color.gray, 10), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 6, str.tostring(utrendDomD) + "% / " + str.tostring(100 - utrendDomD) + "%", bgcolor=pColorD, text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 6, lTxtD, bgcolor=lColorD, text_color=color.white, text_size=size.small) if showW table.cell(ATHtable, 0, 7, 'W', bgcolor=color.new(color.gray, 10), text_color=color.white, text_size=size.small) table.cell(ATHtable, 1, 7, str.tostring(utrendDomW) + "% / " + str.tostring(100 - utrendDomW) + "%", bgcolor=pColorW, text_color=color.white, text_size=size.small) table.cell(ATHtable, 2, 7, lTxtW, bgcolor=lColorW, text_color=color.white, text_size=size.small) // ]
Fade-in Options [Loxx]
https://www.tradingview.com/script/1wAKV5Q2-Fade-in-Options-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("Fade-in Options [Loxx]", shorttitle ="FIO [Loxx]", 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 import loxx/cnd/1 import loxx/cbnd/1 color darkGreenColor = #1B7E02 string callString = "Call" string putString = "Put" 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate FadeInOption(string CallPutFlag, float S, float X, float L, float H, float T, float r, float b, float v, float n)=> float dt = T / n float d1 = (math.log(S / X) + (b + v * v / 2) * T) / (v * math.sqrt(T)) float d2 = d1 - v * math.sqrt(T) float d3 = 0 float d4 = 0 float d5 = 0 float d6 = 0 float sum = 0 for i = 1 to n t1 = i * dt float rho = math.sqrt(t1) / math.sqrt(T) d3 := (math.log(S / L) + (b + v * v / 2) * t1) / (v * math.sqrt(t1)) d4 := d3 - v * math.sqrt(t1) d5 := (math.log(S / H) + (b + v * v / 2) * t1) / (v * math.sqrt(t1)) d6 := d5 - v * math.sqrt(t1) if CallPutFlag == callString sum := sum + S * math.exp((b - r) * T) * (cbnd.CBND3(-d5, d1, -rho) - cbnd.CBND3(-d3, d1, -rho)) - X * math.exp(-r * T) * (cbnd.CBND3(-d6, d2, -rho) - cbnd.CBND3(-d4, d2, -rho)) else sum := sum + X * math.exp(-r * T) * (cbnd.CBND3(-d6, -d2, rho) - cbnd.CBND3(-d4, -d2, rho)) - S * math.exp((b - r) * T) * (cbnd.CBND3(-d5, -d1, rho) - cbnd.CBND3(-d3, -d1, rho)) FadeInOption = 1 / n * sum FadeInOption smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Asset Price Settings") srcin = input.string("Close", "Asset Price", group= "Asset 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)"]) string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings") float K = input.float(100, "Strike Price", group = "Basic Settings") float L = input.float(80., "Lower Barrier", group = "Basic Settings") float H = input.float(130., "Upper Barrier", group = "Basic Settings") float n = input.float(183., "Fixings", group = "Basic Settings") float r = input.float(10., "% Risk-free Rate", group = "Rates Settings") / 100 float b = input.float(5., "% Cost of Carry", group = "Rates Settings") / 100 float v = input.float(20., "% 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 = "Time to Maturity 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 = "Text Size", 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 S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast float amaproxprice = FadeInOption(OpType, S, K, L, H, T, r, b, v, n) 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 = "Fade-in Options", 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 = "Asset Price: " + str.tostring(S, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, 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 = 3, text = "Lower Bound: " + str.tostring(L, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "Upper Bound: " + str.tostring(H, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, 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 = 6, text = "Time to Maturity: " + 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 = 7, text = "% Risk-free Rate: " + str.tostring(r * 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 = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 9, 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 = 10, text = "Fixings: " + str.tostring(n, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 15, text = "Option Ouput", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 16, text = "Fade-in Option Value: " + str.tostring(amaproxprice, "##.#############"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Log Contract Ln(S/X) [Loxx]
https://www.tradingview.com/script/jSsrlo92-Log-Contract-Ln-S-X-Loxx/
loxx
https://www.tradingview.com/u/loxx/
11
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("Log Contract Ln(S/X) [Loxx]", shorttitle ="LCSX [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 import loxx/combin/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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out LogContract_lnSX(float S, float X, float T, float r, float b, float v)=> LogContract_lnSX = math.exp(-r * T) * (math.log(S / X) + (b - math.pow(v, 2) / 2) * T) LogContract_lnSX ELogContract_lnSX(string OutPutFlag, float S, float X, float T, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float ELogContract_lnSX = 0 if OutPutFlag == "p" // Value ELogContract_lnSX := LogContract_lnSX(S, X, T, r, b, v) else if OutPutFlag == "d" //Delta ELogContract_lnSX := (LogContract_lnSX(S + dS, X, T, r, b, v) - LogContract_lnSX(S - dS, X, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity ELogContract_lnSX := (LogContract_lnSX(S + dS, X, T, r, b, v) - LogContract_lnSX(S - dS, X, T, r, b, v)) / (2 * dS) * S / LogContract_lnSX(S, X, T, r, b, v) else if OutPutFlag == "g" //Gamma ELogContract_lnSX := (LogContract_lnSX(S + dS, X, T, r, b, v) - 2 * LogContract_lnSX(S, X, T, r, b, v) + LogContract_lnSX(S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol ELogContract_lnSX := (LogContract_lnSX(S + dS, X, T, r, b, v + 0.01) - 2 * LogContract_lnSX(S, X, T, r, b, v + 0.01) + LogContract_lnSX(S - dS, X, T, r, b, v + 0.01) - LogContract_lnSX(S + dS, X, T, r, b, v - 0.01) + 2 * LogContract_lnSX(S, X, T, r, b, v - 0.01) - LogContract_lnSX(S - dS, X, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP ELogContract_lnSX := S / 100 * (LogContract_lnSX(S + dS, X, T, r, b, v) - 2 * LogContract_lnSX(S, X, T, r, b, v) + LogContract_lnSX(S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma ELogContract_lnSX := (LogContract_lnSX(S, X, T + 1 / 365, r, b, v) - 2 * LogContract_lnSX(S, X, T, r, b, v) + LogContract_lnSX(S, X, T - 1 / 365, r, b, v)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol ELogContract_lnSX := 1 / (4 * dS * 0.01) * (LogContract_lnSX(S + dS, X, T, r, b, v + 0.01) - LogContract_lnSX(S + dS, X, T, r, b, v - 0.01) - LogContract_lnSX(S - dS, X, T, r, b, v + 0.01) + LogContract_lnSX(S - dS, X, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega ELogContract_lnSX := (LogContract_lnSX(S, X, T, r, b, v + 0.01) - LogContract_lnSX(S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma ELogContract_lnSX := (LogContract_lnSX(S, X, T, r, b, v + 0.01) - 2 * LogContract_lnSX(S, X, T, r, b, v) + LogContract_lnSX(S, X, T, r, b, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP ELogContract_lnSX := v / 0.1 * (LogContract_lnSX(S, X, T, r, b, v + 0.01) - LogContract_lnSX(S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol ELogContract_lnSX := (LogContract_lnSX(S, X, T, r, b, v + 0.01) - 2 * LogContract_lnSX(S, X, T, r, b, v) + LogContract_lnSX(S, X, T, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 ELogContract_lnSX := LogContract_lnSX(S, X, 1E-05, r, b, v) - LogContract_lnSX(S, X, T, r, b, v) else ELogContract_lnSX := LogContract_lnSX(S, X, T - 1 / 365, r, b, v) - LogContract_lnSX(S, X, T, r, b, v) else if OutPutFlag == "r" //Rho ELogContract_lnSX := (LogContract_lnSX(S, X, T, r + 0.01, b + 0.01, v) - LogContract_lnSX(S, X, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" //Futures options rho ELogContract_lnSX := (LogContract_lnSX(S, X, T, r + 0.01, b, v) - LogContract_lnSX(S, X, T, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" //Rho2 ELogContract_lnSX := (LogContract_lnSX(S, X, T, r, b - 0.01, v) - LogContract_lnSX(S, X, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" //Carry ELogContract_lnSX := (LogContract_lnSX(S, X, T, r, b + 0.01, v) - LogContract_lnSX(S, X, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" //Speed ELogContract_lnSX := 1 / math.pow(dS, 3) * (LogContract_lnSX(S + 2 * dS, X, T, r, b, v) - 3 * LogContract_lnSX(S + dS, X, T, r, b, v) + 3 * LogContract_lnSX(S, X, T, r, b, v) - LogContract_lnSX(S - dS, X, T, r, b, v)) else if OutPutFlag == "dx" //Strike Delta ELogContract_lnSX := (LogContract_lnSX(S, X + dS, T, r, b, v) - LogContract_lnSX(S, X - dS, T, r, b, v)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike Gamma ELogContract_lnSX := (LogContract_lnSX(S, X + dS, T, r, b, v) - 2 * LogContract_lnSX(S, X, T, r, b, v) + LogContract_lnSX(S, X - dS, T, r, b, v)) / math.pow(dS, 2) ELogContract_lnSX 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(80, "Strike Price", group = "Basic Settings") string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings") float r = input.float(8., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(8., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(35., "% 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = ELogContract_lnSX("p", S, K, T, kouta, koutb, v, na) Delta = ELogContract_lnSX("d", S, K, T, kouta, koutb, v, na) * sideout Elasticity = ELogContract_lnSX("e", S, K, T, kouta, koutb, v, na) * sideout Gamma = ELogContract_lnSX("g", S, K, T, kouta, koutb, v, na) * sideout DGammaDvol = ELogContract_lnSX("gv", S, K, T, kouta, koutb, v, na) * sideout GammaP = ELogContract_lnSX("gp", S, K, T, kouta, koutb, v, na) * sideout Vega = ELogContract_lnSX("v", S, K, T, kouta, koutb, v, na) * sideout DvegaDvol = ELogContract_lnSX("dvdv", S, K, T, kouta, koutb, v, na) * sideout VegaP = ELogContract_lnSX("vp", S, K, T, kouta, koutb, v, na) * sideout Theta = ELogContract_lnSX("t", S, K, T, kouta, koutb, v, na) * sideout Rho = ELogContract_lnSX("r", S, K, T, kouta, koutb, v, na) * sideout RhoFuturesOption = ELogContract_lnSX("fr", S, K, T, kouta, koutb, v, na) * sideout PhiRho2 = ELogContract_lnSX("f", S, K, T, kouta, koutb, v, na) * sideout Carry = ELogContract_lnSX("b", S, K, T, kouta, koutb, v, na) * sideout DDeltaDvol = ELogContract_lnSX("dddv", S, K, T, kouta, koutb, v, na) * sideout Speed = ELogContract_lnSX("s", S, K, T, kouta, koutb, v, na) * sideout StrikeDelta = ELogContract_lnSX("dx", S, K, T, kouta, koutb, v, na) * sideout StrikeGamma = ELogContract_lnSX("dxdx", S, K, T, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Log Contract Ln(S/X)", 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 = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, text = "Spot Price: " + str.tostring(S, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 3, 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 = 4, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 5, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 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 = 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 = "Log Contract Ln(S/X) Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Pro Trading Art - Candlestick Patterns with alert
https://www.tradingview.com/script/Lpsn1af1-Pro-Trading-Art-Candlestick-Patterns-with-alert/
protradingart
https://www.tradingview.com/u/protradingart/
370
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/ // © protradingart //@version=5 indicator("Pro Trading Art - Candlestick Patterns with alert", "PTA - Candlestick Patterns", overlay=true) emaLen = input.int(21, "EMA Length") ema = ta.ema(close, emaLen) distance = math.abs((open - close)/close*100) var candleRange = array.new_float(na) array.push(candleRange, distance) avgRange = array.avg(candleRange) //#region Hammer shadowGroup = "=========== Shadow ===========" isHammer = input.bool(true, "Hammer", group=shadowGroup, inline = "Hammer") hammerMult = input.float(defval=2.0, title="Multiplier", step=0.1, group=shadowGroup, inline = "Hammer") hammer = (open-low) > (close-open)*hammerMult and (close-open) > (high-close) and isHammer and close < ema plotshape(hammer ? low : na, title="Hammer", text = "Hammer", style=shape.labelup, color=color.lime, size=size.normal, location=location.absolute, textcolor = color.black) if hammer alert("Hammer in : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Hanging Man isHanging = input.bool(true, "Hanging Man", group=shadowGroup, inline = "Hanging Man") hangingMult = input.float(defval=3.0, title="Multiplier", step=0.1, group=shadowGroup, inline = "Hanging Man") hanging = (open-low) > (close-open)*hangingMult and (close-open) > (high-close) and isHanging and close > ema plotshape(hanging ? high : na, title="Hanging Man", text = "Hanging Man", style=shape.labeldown, color=color.rgb(240, 116, 116), size=size.normal, location=location.absolute, textcolor = color.white) if hanging alert("Hanging Man In : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Inverted Hammer isInvertedHammer = input.bool(true, "Inverted Hammer", group=shadowGroup, inline = "Inverted Hammer") invertedHammerMult = input.float(defval=2.0, title="Multiplier", step=0.1, group=shadowGroup, inline = "Inverted Hammer") invertedHammer = (high-open) > (open-close)*invertedHammerMult and (open-close) > (close-low) and isInvertedHammer and close < ema plotshape(invertedHammer ? low : na, title=" Inverted Hammer", text = "Inverted Hammer", style=shape.labelup, color=color.rgb(60, 231, 148), size=size.normal, location=location.absolute, textcolor = color.black) if invertedHammer alert("Inverted Hammer : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Shooting Star starGroup = "=========== Star ===========" isShootingStar = input.bool(true, "Shooting Star", group=starGroup, inline = "Shooting Star") shootingStarMult = input.float(defval=2.0, title="Multiplier", step=0.1, group=starGroup, inline = "Shooting Star") shootingStar = (high-open) > (open-close)*shootingStarMult and (open-close) > (close-low) and isShootingStar and close > ema plotshape(shootingStar ? high : na, title="Shooting Star", text = "Shooting Star", style=shape.labeldown, color=color.red, size=size.normal, location=location.absolute, textcolor = color.white) if shootingStar alert("Shooting Star : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Morning Star isMorningStar = input.bool(true, "Morning Star", group=starGroup) morningStar(Open, Close, High, Low)=> Close > Open and Close > Close[1] and Open > Open[1] and Open > Close [1] and Open[1] < Open[2] and Open[1] < Close[2] and Close[1] < Open[2] and Close[1] < Close[2] and Close < ta.sma(Close, 50) and High > Low[2] and Close > Low[2] morningstar = morningStar(open, close, high, low) and isMorningStar and close < ema plotshape(morningstar ? low : na, title="Morning Star", style=shape.labelup, color=color.rgb(54, 167, 58), location=location.absolute, text="Morning Star", textcolor=color.black, size=size.normal) if morningstar alert("Morning Star : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Evening Star isEveningStar = input.bool(true, "Evening Star", group=starGroup) eveningStar(Open, Close, High, Low)=> Close < Open and Close < Close[1] and Open < Open[1] and Open < Close [1] and Open[1] > Open[2] and Open[1] > Close[2] and Close[1] > Open[2] and Close[1] > Close[2] and Close > ta.sma(Close, 50) and Low < High[2] and Close < High[2] eveningstar = eveningStar(open, close, high, low) and isEveningStar and close > ema plotshape(eveningstar ? high : na, title="Evening Star", style=shape.labeldown, color=color.rgb(230, 47, 47, 7), location=location.absolute, text="Evening Star", textcolor=color.white, size=size.normal) if eveningstar alert("Evening Star : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Bullish Engulfing engulfingGroup = "=========== Engulfing ===========" isBulllishEngulfing = input.bool(true, "Bullish Engulfing", group=engulfingGroup) bullishEngulfing = close > open[1] and close > close[1] and open < open[1] and open < close[1] and close < ema and distance > avgRange and isBulllishEngulfing plotshape(bullishEngulfing ? low : na, title="Bullish Engulfing", text = "Bullish Engulfing", style=shape.labelup, color=color.rgb(1, 189, 98), size=size.normal, location=location.absolute, textcolor = color.black) if bullishEngulfing alert("Bullish Engulfing in : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Bearish Engulfing isBearishEngulfing = input.bool(true, "Bearish Engulfing", group=engulfingGroup) bearishEngulfing = close < open[1] and close < close[1] and open > open[1] and open > close[1] and close > ema and distance > avgRange and isBearishEngulfing plotshape(bearishEngulfing ? high : na, title="Bearish Engulfing", text = "Bearish Engulfing", style=shape.labeldown, color=color.rgb(250, 64, 64), size=size.normal, location=location.absolute, textcolor = color.white) if bearishEngulfing alert("Bearish Engulfing in : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Dark Cloud Cover cloudGroup = "=========== Cloud ===========" isDarkCloudCover = input.bool(true, "Dark - Cloud Cover", group = cloudGroup) darkCloud = close[1] > open[1] and close < open and open > high[1] and close < close[1] - (high[1] - low[1])/4 and close > open[1] and close > ema plotshape(darkCloud ? high : na, title="Dark - Cloud Cover", text = "Dark - Cloud Cover", style=shape.labeldown, color=color.rgb(250, 64, 64), size=size.normal, location=location.absolute, textcolor = color.white) if darkCloud alert("Dark - Cloud Cover in : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion //#region Piercing Pattern isPiercingPattern = input.bool(true, "Piercing Pattern", group = cloudGroup) piercing = close[1] < open[1] and close > open and close > close[1] + (open[1] - close[1])/2 and open < low[1] and close < open[1] and close < ema plotshape(piercing ? low : na, title="Piercing Pattern", text = "Piercing Pattern", style=shape.labelup, color=color.rgb(1, 189, 98), size=size.normal, location=location.absolute, textcolor = color.black) if piercing alert("Piercing Pattern in : "+syminfo.ticker, alert.freq_once_per_bar_close) //#endregion
Golden Gate
https://www.tradingview.com/script/SJauXAU1-Golden-Gate/
vaibhavpatil216
https://www.tradingview.com/u/vaibhavpatil216/
18
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/ // © vaibhavpatil216 //@version=5 indicator(title="Golden Gate", shorttitle="EMA", overlay=true, timeframe="", timeframe_gaps=true) len20 = input.int(20, minval=1, title="Length") src20 = input(close, title="Source") offset20 = input.int(title="Offset", defval=0, minval=-500, maxval=500) out20 = ta.ema(src20, len20) plot(out20, title="EMA", color=color.blue, offset=offset20) ma(source, length, type) => switch type "EMA" => ta.ema(source, length) typeMA20 = input.string(title = "Method", defval = "EMA", options=["EMA"]) len50 = input.int(50, minval=1, title="Length") src50 = input(close, title="Source") offset50 = input.int(title="Offset", defval=0, minval=-500, maxval=500) out50 = ta.ema(src50, len50) plot(out50, title="EMA", color=color.red, offset=offset50) ma50(source, length, type) => switch type "EMA" => ta.ema(source, length) typeMA50 = input.string(title = "Method", defval = "EMA", options=["EMA"]) len200 = input.int(200, minval=1, title="Length") src200 = input(close, title="Source") offset200 = input.int(title="Offset", defval=0, minval=-500, maxval=500) out200 = ta.ema(src200, len200) plot(out200, title="EMA", color=color.lime, offset=offset200) ma200(source, length, type) => switch type "EMA" => ta.ema(source, length) typeMA200 = input.string(title = "Method", defval = "EMA", options=["EMA"]) len100 = input.int(100, minval=1, title="Length") src100 = input(close, title="Source") offset100 = input.int(title="Offset", defval=0, minval=-500, maxval=500) out100 = ta.ema(src100, len100) plot(out100, title="EMA", color=color.rgb(226, 230, 0), offset=offset100) ma100(source, length, type) => switch type "EMA" => ta.ema(source, length) typeMA100 = input.string(title = "Method", defval = "EMA", options=["EMA"])
FREE PVT 2 [BELES]
https://www.tradingview.com/script/D7bIcKXi/
CoinFix
https://www.tradingview.com/u/CoinFix/
129
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/ // © BELESCOIN //@version=5 indicator("FREE PVT 2 [BELES]",overlay=true,max_bars_back=500,max_lines_count=500) length = input.int(50,minval=2,maxval=500) max_color = input.color(color.rgb(255, 255, 255, 100),'Trailing Maximum Color',group='Style') min_color = input.color(color.rgb(255, 255, 255, 100),'Trailing Minimum Color',group='Style') avg_color = input.color(#00ff15,'Trailing Maximum Color',group='Style') bull_fill = input.color(color.new(color.teal,80),'Uptrend Area',group='Style') bear_fill = input.color(color.new(color.red,80),'Downtrend Area',group='Style') //---- var max = 0. var min = 0. ph = ta.pivothigh(length,length) pl = ta.pivotlow(length,length) if ph or pl max := high[length] min := low[length] max := math.max(high[length],max) min := math.min(low[length],min) avg = math.avg(max,min) //---- plot1 = plot(max,'Trailing Maximum',ph or pl ? na : max_color,1,plot.style_linebr,offset=-length) plot2 = plot(min,'Trailing Minimum',ph or pl ? na : min_color,1,plot.style_linebr,offset=-length) fill_css = fixnan(ph ? bear_fill : pl ? bull_fill : na) fill(plot1,plot2,ph or pl ? na : fill_css) plot(avg,'Average',ph or pl ? na : avg_color,1,plot.style_linebr,offset=-length) plotshape(pl ? pl : na,"Pivot High",shape.labelup,location.absolute,max_color,-length,text="▲",textcolor=color.rgb(74, 255, 128),size=size.large) plotshape(ph ? ph : na,"Pivot Low",shape.labeldown,location.absolute,min_color,-length,text="▼",textcolor=color.rgb(255, 72, 72),size=size.large) //---- n = bar_index max_prev = max min_prev = min avg_prev = avg max2 = max min2 = min if barstate.islast for line_object in line.all line.delete(line_object) for i = 0 to length-1 max2 := math.max(high[length-1-i],max_prev) min2 := math.min(low[length-1-i],min_prev) avg2 = math.avg(max2,min2) line1 = line.new(n-(length-i),max_prev,n-(length-1-i),max2,color=max_color) line2 = line.new(n-(length-i),min_prev,n-(length-1-i),min2,color=min_color) linefill.new(line1,line2,color.new(fill_css,80)) line.new(n-(length-i),avg_prev,n-(length-1-i),avg2,color=avg_color) max_prev := max2 min_prev := min2 avg_prev := avg2
AI-EngulfingCandle
https://www.tradingview.com/script/58m8mjwG-AI-EngulfingCandle/
ahmedirshad419
https://www.tradingview.com/u/ahmedirshad419/
1,913
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/ // © ahmedirshad419 //@version=4 study("EngulfingCandle", overlay=true ) bullishCandle=close >= open[1] and close[1] < open[1] //and high >= high[1] and low <= low[1] bearishCandle=close <= open[1] and close[1] >open[1] //and high > high[1] and low < low[1] // RSI integration rsiSource=input(title="rsiSource", defval=close, type=input.source) rsiLenghth=input(title="rsi length", type=input.integer, defval=14) rsiOverBought=input(title="rsi overbought level", type=input.integer, defval=70) rsiOverSold=input(title="rsi over sold level", type=input.integer, defval=30) //rsiOverBoughtThreshold=input(title="rsiOBThreshold level", type=input.integer, defval=97) //rsiOverSoldThreshold=input(title="rsiOSThreshold level", type=input.integer, defval=18) //get RSI value rsiValue=rsi(rsiSource,rsiLenghth) isRSIOB=rsiValue >= rsiOverBought and rsiValue isRSIOS=rsiValue <= rsiOverSold and rsiValue tradeSignal=((isRSIOS or isRSIOS[1] or isRSIOS[2]) and bullishCandle ) or ((isRSIOB or isRSIOB[1] or isRSIOB[2]) and bearishCandle) //plot on chart plotshape(tradeSignal and bullishCandle,title="bullish", location=location.belowbar, color=color.green,style=shape.triangleup, text="buy MIT") plotshape(tradeSignal and bearishCandle,title="bearish", location=location.abovebar, color=color.red,style=shape.triangledown, text="sell MIT")
Volatility Elvis
https://www.tradingview.com/script/UEsBQg8j-Volatility-Elvis/
mwangielvis49
https://www.tradingview.com/u/mwangielvis49/
21
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/ // © hajixde //@version=5 indicator("Volatility Screener", overlay = false) coin1 = input.string("WINUSDT", group = "Coins" , inline = "coins_") coin2 = input.string("DODOUSDT", group = "Coins" , inline = "coins_") coin3 = input.string("AUCTIONUSDT", group = "Coins" , inline = "coins_") coin4 = input.string("MBOXUSDT", group = "Coins" , inline = "coins_") coin5 = input.string("ETHUSDT", group = "Coins" , inline = "coins_") coin6 = input.string("BTCUSDT", group = "Coins" , inline = "coins_") coin7 = input.string("IMXUSDT", group = "Coins" , inline = "coins_") coin8 = input.string("VIDYUSDT", group = "Coins" , inline = "coins_") coin9 = input.string("ALICEUSDT", group = "Coins" , inline = "coins_") coin10 = input.string("VGXUSDT", group = "Coins" , inline = "coins_") coin11 = input.string("CTKUSDT", group = "Coins" , inline = "coins_") coin12 = input.string("BORINGUSDT", group = "Coins" , inline = "coins_") length = input.int(100, minval=1) minVolatility = input.float(10, title = "Minimum Volatility Percentage") volatility(src, len) => dev = ta.stdev(src, len) s = ta.sma(src, len) v = 100*dev / s v var table statTable = table.new(position.middle_center, 4, 36, bgcolor = color.black, frame_width = 1, frame_color = color.black, border_color = color.black, border_width = 1) table.cell(statTable, 0, 0, " Ticker ", text_color = color.white, bgcolor = #336688) table.cell(statTable, 1, 0, " Volatility", text_color = color.white, bgcolor = #336688) table.cell(statTable, 2, 0, " Ticker ", text_color = color.white, bgcolor = #336688) table.cell(statTable, 3, 0, " Volatility", text_color = color.white, bgcolor = #336688) table.cell(statTable, 0, 1, coin1, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 0, 2, coin2, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 0, 3, coin3, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 0, 4, coin4, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 0, 5, coin5, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 0, 6, coin6, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 2, 1, coin7, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 2, 2, coin8, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 2, 3, coin9, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 2, 4, coin10, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 2, 5, coin11, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 2, 6, coin12, text_color = color.white, bgcolor = #9999EE) table.cell(statTable, 1, 1, str.tostring(volatility(request.security(coin1, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin1, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 1, 2, str.tostring(volatility(request.security(coin2, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin2, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 1, 3, str.tostring(volatility(request.security(coin3, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin3, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 1, 4, str.tostring(volatility(request.security(coin4, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin4, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 1, 5, str.tostring(volatility(request.security(coin5, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin5, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 1, 6, str.tostring(volatility(request.security(coin6, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin6, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 3, 1, str.tostring(volatility(request.security(coin7, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin7, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 3, 2, str.tostring(volatility(request.security(coin8, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin8, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 3, 3, str.tostring(volatility(request.security(coin9, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin9, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 3, 4, str.tostring(volatility(request.security(coin10, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin10, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 3, 5, str.tostring(volatility(request.security(coin11, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin11, timeframe.period, close), length) > minVolatility ? #992266 : #998833) table.cell(statTable, 3, 6, str.tostring(volatility(request.security(coin12, timeframe.period, close), length), "#.##") + " %", text_color = color.white, bgcolor = volatility(request.security(coin12, timeframe.period, close), length) > minVolatility ? #992266 : #998833)
MA 6 Ribbon-Bollinger Band
https://www.tradingview.com/script/EUaLW4ip-MA-6-Ribbon-Bollinger-Band/
sarojinideviperumalla
https://www.tradingview.com/u/sarojinideviperumalla/
4
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © sarojinideviperumalla //@version=5 indicator("MA 6 Ribbon", shorttitle="MA Ribbon", overlay=true, timeframe="", timeframe_gaps=true) ma(source, length, type) => 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 show_ma1 = input(true , "MA №1", inline="MA #1") ma1_type = input.string("SMA" , "" , inline="MA #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"]) ma1_source = input(close , "" , inline="MA #1") ma1_length = input.int(20 , "" , inline="MA #1", minval=1) ma1_color = input(#f6c309, "" , inline="MA #1") ma1 = ma(ma1_source, ma1_length, ma1_type) plot(show_ma1 ? ma1 : na, color = ma1_color, title="MA №1") show_ma2 = input(true , "MA №2", inline="MA #2") ma2_type = input.string("SMA" , "" , inline="MA #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"]) ma2_source = input(close , "" , inline="MA #2") ma2_length = input.int(50 , "" , inline="MA #2", minval=1) ma2_color = input(#fb9800, "" , inline="MA #2") ma2 = ma(ma2_source, ma2_length, ma2_type) plot(show_ma2 ? ma2 : na, color = ma2_color, title="MA №2") show_ma3 = input(true , "MA №3", inline="MA #3") ma3_type = input.string("SMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"]) ma3_source = input(close , "" , inline="MA #3") ma3_length = input.int(100 , "" , inline="MA #3", minval=1) ma3_color = input(#fb6500, "" , inline="MA #3") ma3 = ma(ma3_source, ma3_length, ma3_type) plot(show_ma3 ? ma3 : na, color = ma3_color, title="MA №3") show_ma4 = input(true , "MA №4", inline="MA #4") ma4_type = input.string("SMA" , "" , inline="MA #4", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"]) ma4_source = input(close , "" , inline="MA #4") ma4_length = input.int(200 , "" , inline="MA #4", minval=1) ma4_color = input(#f60c0c, "" , inline="MA #4") ma4 = ma(ma4_source, ma4_length, ma4_type) plot(show_ma4 ? ma4 : na, color = ma4_color, title="MA №4") show_ma5 = input(true , "MA №5", inline="MA #5") ma5_type = input.string("SMA" , "" , inline="MA #5", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"]) ma5_source = input(close , "" , inline="MA #5") ma5_length = input.int(200 , "" , inline="MA #5", minval=1) ma5_color = input(#f60c0c, "" , inline="MA #5") ma5 = ma(ma5_source, ma5_length, ma5_type) plot(show_ma5 ? ma5 : na, color = ma5_color, title="MA №5") show_ma6 = input(true , "MA №6", inline="MA #6") ma6_type = input.string("SMA" , "" , inline="MA #6", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"]) ma6_source = input(close , "" , inline="MA #6") ma6_length = input.int(200 , "" , inline="MA #6", minval=1) ma6_color = input(#f60c0c, "" , inline="MA #6") ma6 = ma(ma6_source, ma6_length, ma6_type) plot(show_ma6 ? ma6 : na, color = ma6_color, title="MA №6") length = input.int(20, minval=1) src = input(close, title="Source") mult = input.float(2.0, 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))
Volume/Market Profile
https://www.tradingview.com/script/WWqoUu7e-Volume-Market-Profile/
SamRecio
https://www.tradingview.com/u/SamRecio/
1,462
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © SamRecio //@version=5 indicator("Volume/Market Profile", shorttitle = "VMP", overlay = true, max_lines_count = 500, max_boxes_count = 500) //Profile Settings tf = input.timeframe("D", title = "Timeframe", inline = "0", group = "PROFILE SETTINGS") lb_calc = input.bool(false, title = "Use Lookback Calc?", inline = "0", group = "PROFILE SETTINGS", tooltip = "Lookback Calculation Historically compiles a profile to display the data from the requested timeframe amount of time.\nProgressive Calculation (Default) restarts the profile calculation on each change of the requested timeframe(New Bar).\n\nExamples:\nLookback = '1D' will display a profile based on 1 Day of historical data.\nProgressive = '1D' will display a profile base on data since the start of the Day.\n\nTip: There is a manual control for lookback bars at the bottom if you prefer to see a specific number.") vap = input.float(70, title = "Value Area %", inline = "1_1", group = "PROFILE SETTINGS")/100 mp = input.bool(false, title = "Calculate As Market Profile", inline = "2", group = "PROFILE SETTINGS", tooltip = "Calculations will distribue a 1 instead of the candle's volume.") //Display Settings disp_size = input.int(-50, minval = -500,maxval = 500,title = "Display Size   ", inline = "3", group = "DISPLAY SETTINGS", tooltip = "The entire range of your profile will scale to fit inside this range.\nNotes:\n-This value is # bars away from your profile's axis.\n-The larger this value is, the more granular your (horizontal) view will be. This does not change the Profiles' value; because of this, sometimes the POC looks tied with other values widely different. The POC CAN be tied to values close to it, but if the value is far away it is likely to just be a visual constraint.\n-This Value CAN be negative") prof_offset = input.int(50, minval = -500,maxval = 500, title = "Display Offset", inline = "4", group = "DISPLAY SETTINGS", tooltip = "Offset your profile's axis (Left/Right) to customize your display to fit your style.\nNotes:\n-Zero = Current Bar\n-This Value CAN be negative") //Additional Data Displays extend_day = input.bool(false, title = "Extend POC/VAH/VAL", inline = "1", group = "Additional Data Displays") lab_tog = input.bool(true, title = "Label POC/VAH/VAL", inline = "2", group = "Additional Data Displays") dev_poc = input.bool(false, title = "Rolling POC/TPO", inline = "3", group = "Additional Data Displays", tooltip = "Displays Value as it Develops!\nNote: Will Cause Longer Load Time. If not needed, it is reccomended to turn these off.") dev_va = input.bool(false, title = "Rolling VAH/VAL", inline = "4", group = "Additional Data Displays") //High/Low Volume Nodes node_tog = input.bool(true, title = "Highlight Nodes", group = "High/Low Volume Nodes") hi_width = input.int(10, maxval = 100, minval = 1,title = "[HVN] Analysis Width %      ↕", group = "High/Low Volume Nodes", tooltip = "[HVN] = High Volume Node\nAnalysis Width % = % of profile to take into account when determining what is a High Volume Node and what is Not.")*0.01 lo_width = input.int(10, maxval = 100, minval = 1, title = "[LVN]  Analysis Width %      ↕", group = "High/Low Volume Nodes", tooltip = "[LVN] = Low Volume Node\nAnalysis Width % = % of profile to take into account when determining what is a Low Volume Node and what is Not.")*0.01 //Colors poc_color = input.color(#ff033e, title = "POC/TPO Color", group = "Colors") var_color = input.color(color.white, title = "Value High/Low Color", group = "Colors") vaz_color = input.color(color.new(#555555,50), title = "Value Zone Color", group = "Colors") ov_color = input.color(#555555, title = "Profile Color", group = "Colors") lv_color = input.color(#801922, title = "Low Volume Color", group = "Colors") hv_color = input.color(#2295BF, title = "High Volume Color", group = "Colors") //⭕Manual Lookback Override⭕ lb_override = input.bool(false, title = "[Check to Enable]", group = "⭕Manual Lookback Override⭕", inline = "1") lb_over_bars = input.int(500, title = "   Lookback", group = "⭕Manual Lookback Override⭕", inline = "1", tooltip = "Lookback Calc must be enabled for this feature.") ///_________________________________________ ///Misc Stuff ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ decimal_places = str.contains(str.tostring(syminfo.mintick),".")?str.length(array.get(str.split(str.tostring(syminfo.mintick),"."),1)):0 round_to(_round,_to) => math.round(_round/_to)*_to ///_________________________________________ ///Setup for Length ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ tf_change = timeframe.change(tf) var int bi_nd = na // BI_ND = Bar Index _ New Day var int bi_lnd = na //BI_LND = Bar Index Last New Day bi_lnd := tf_change?bi_nd:bi_lnd bi_nd := tf_change?bar_index:bi_nd tf_len = (bi_nd - bi_lnd)+1 bs_newtf = (bar_index - bi_nd)+1 id_lb_bars = timeframe.in_seconds(tf)/timeframe.in_seconds(timeframe.period) dwm_lb_bars = (math.max(tf_len,bs_newtf)>1?math.max(tf_len,bs_newtf)-1:1) auto_lb_bars = timeframe.in_seconds(tf) >= timeframe.in_seconds("D")?dwm_lb_bars:id_lb_bars lb_bars = (lb_calc?(na(tf_len)?bar_index:(lb_override?lb_over_bars:auto_lb_bars)):na(bs_newtf)?bar_index:bs_newtf) ///_________________________________________ ///Warning for Large Timeframe ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ var d = dayofmonth var m = switch month == 1 => "Jan" month == 2 => "Feb" month == 3 => "Mar" month == 4 => "Apr" month == 5 => "May" month == 6 => "Jun" month == 7 => "Jul" month == 8 => "Aug" month == 9 => "Sep" month == 10 => "Oct" month == 11 => "Nov" month == 12 => "Dec" var y = year - (int(year/100)*100) send_warning = (lb_calc and na(tf_len)) or (not lb_calc and na(bs_newtf)) warning = "[WARNING ⚠]"+" ["+tf+"]"+"\nData Start: " + str.tostring(d,"00")+" "+m + " '" + str.tostring(y) + "\n\n" if na(volume) and (mp == false) runtime.error("No Volume Data. Please Use a Ticker with Volume Data or Switch to Market Profile Calculation.") ///_________________________________________ ///Start Data Accumulation ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ //By storing the data, I can use it later without the need for historical reference. //Additionally, I can control the amount of data kept in memory to only hold the lookback amount of bars. //This is all of the advantages of lookback calcs, with all the advantages of progressive calculations. src_high = math.round_to_mintick(high) src_low = math.round_to_mintick(low) var highs = array.new_float(na) var lows = array.new_float(na) var vol = array.new_float(na) highs.push(src_high) lows.push(src_low) vol.push(volume) if highs.size() >= lb_bars for i = highs.size()-1 to lb_bars if highs.size() == lb_bars break else highs.shift() lows.shift() vol.shift() //Granularity Gets more corse farther from current bar for speed. Replay mode can get a full gran profile if needed. v_gran = bar_index>=(last_bar_index-1000)?999: bar_index>=(last_bar_index-2000)?249: bar_index>=(last_bar_index-4000)?124:64 tick_size = math.max(syminfo.mintick,(highs.max()-lows.min())/v_gran) full_hist_calc = (dev_poc or dev_va) ///_________________________________________ ///Profile Calcs ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ data_map = map.new<float,float>() if full_hist_calc and highs.size() > 0 for i = 0 to array.size(highs)-1 hi = round_to(highs.get(i),tick_size) lo = round_to(lows.get(i),tick_size) candle_index = ((hi-lo)/tick_size) tick_vol = mp?1:math.round((vol.get(i)/(candle_index+1)),3) for e = 0 to candle_index val = round_to(lo+(e*tick_size),tick_size) data_map.put(val, math.round(nz(data_map.get(val)),3)+tick_vol) if (full_hist_calc == false) and barstate.islast for i = 0 to array.size(highs)-1 hi = round_to(highs.get(i),tick_size) lo = round_to(lows.get(i),tick_size) candle_index = ((hi-lo)/tick_size) tick_vol = mp?1:math.round((vol.get(i)/(candle_index+1)),3) for e = 0 to candle_index val = round_to(lo+(e*tick_size),tick_size) data_map.put(val, math.round(nz(data_map.get(val)),3)+tick_vol) ///_________________________________________ ////Other Profile Values ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ keys = map.keys(data_map) values = map.values(data_map) array.sort(keys, order.ascending) ///_________________________________________ ///AQUIRE POC ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ //POC = Largest Volume Closest to Price Average of Profile // float poc = 0 float poc_vol = 0 prof_avg = array.avg(keys) for [key, value] in data_map if (value > poc_vol) or (value == poc_vol and math.abs(key-prof_avg)<math.abs(poc-prof_avg)) poc := key poc_vol := value ///_________________________________________ ///VALUE ZONES ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ max_vol = array.sum(values)*vap max_index = poc vol_count = poc_vol up_count = max_index down_count = max_index for i = 0 to array.size(keys) if vol_count >= max_vol break upper_vol = nz(data_map.get(round_to(up_count+tick_size,tick_size))) + nz(data_map.get(round_to(up_count+(tick_size*2),tick_size))) lower_vol = nz(data_map.get(round_to(down_count-tick_size,tick_size))) + nz(data_map.get(round_to(down_count-(tick_size*2),tick_size))) if (((upper_vol >= lower_vol) and upper_vol > 0) or (lower_vol>0 == false)) and up_count < array.max(keys)-tick_size vol_count += upper_vol up_count := round_to(up_count+(tick_size*2),tick_size) else if down_count > array.min(keys)+tick_size vol_count += lower_vol down_count := round_to(down_count-(tick_size*2),tick_size) val = down_count vah = up_count //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //END PROFILE CALCs// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Cluster ID for Volume Nodes// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Cluster ID analyzes a local group (cluster) of volume profile indexes (rows) to determine if the current index is higher(or lower) than those around it. // The Analysis width is a % of the entire # of rows in the profile to pull into a cluster, by increasing or decreasing this value, we can tune the profile to our individual preference. vgroup_pull(_var,_array,_num1,_num2) => _var == 1 and _num1>=_num2?data_map.get(array.get(_array,_num1-_num2)): //Pulls Index Value from Below _var == 2 and array.size(_array)-1 >= (_num1 + _num2)?data_map.get(array.get(_array,_num1+_num2)) //Pulls Index Value from Above :0 var hvn_points = array.new_int(na) if array.size(keys) > 0 and barstate.islast and node_tog array.clear(hvn_points) for i = 0 to array.size(keys)-1 _val = data_map.get(array.get(keys,i)) ary = array.new_float(na) for e = 0 to int(array.size(keys)*hi_width) array.push(ary,vgroup_pull(1,keys,i,e)) array.push(ary,vgroup_pull(2,keys,i,e)) max = array.max(ary) avg = array.avg(ary) if _val >= math.avg(max,avg) array.push(hvn_points,i) var lvn_points = array.new_int(na) if array.size(keys) > 0 and barstate.islast and node_tog array.clear(lvn_points) for i = 0 to array.size(keys)-1 _val = data_map.get(array.get(keys,i)) ary = array.new_float(na) for e = 0 to int(array.size(keys)*lo_width) array.push(ary,vgroup_pull(1,keys,i,e)) array.push(ary,vgroup_pull(2,keys,i,e)) min = array.min(ary) avg = array.avg(ary) if _val <= math.avg(min,avg) array.push(lvn_points,i) ///_________________________________________ ///Cluster Merging ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ merge_clusters(_array) => if array.size(_array)>0 for i = 0 to array.size(_array)-1 hi_found = false lo_found = false _val = array.get(_array,i) for e = int(array.size(keys)*0.02) to 0 if hi_found array.push(_array,_val+e) else if array.includes(_array,_val+e) hi_found := true if lo_found array.push(_array,_val-e) else if array.includes(_array,_val-e) lo_found := true dummy = "This is here to make the loop return 'void'. " // run it if barstate.islast and node_tog merge_clusters(hvn_points) merge_clusters(lvn_points) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //END Cluster ID Calcs// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Display// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var profile = array.new_line(na) var box_profile = array.new_box(na) if barstate.islast and array.size(profile) > 0 for [index,line] in profile line.delete(line) array.clear(profile) if barstate.islast and array.size(box_profile) > 0 for [index,box] in box_profile box.delete(box) array.clear(box_profile) prof_color(_num,_key) => //Function for determining what color each profile index gets switch _key==poc => poc_color //If its the max Value, give it poc color (_key==up_count or _key==down_count) => var_color //If its the value high or low, give it those colors array.includes(hvn_points,_num) and array.includes(lvn_points,_num) => ((_key>up_count or _key<down_count)?ov_color:vaz_color) /// If its BOTH a HVN and LVN only display color based on valuezone (in value or out) I plan to imporove this in the future. array.includes(lvn_points,_num) => lv_color //If it is < lv% of the max volume, give it the low volume color array.includes(hvn_points,_num) => hv_color //If its > hv% of the max volume, give it the high volume color (_key>up_count or _key<down_count) => ov_color //If its above or below our value zone, give it the out of value color => vaz_color // Everything else is inside the value zone so it gets the value zone color dash(_i) => (_i/2 - math.floor(_i/2)) > 0 //only true when the number is odd, Making it oscillate on/off, I can make use of this to evenly distribute boxes and lines throughout the display to make it cleaner. roof = keys.max() ///_________________________________________ ///Drawing the Profile ///‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ if barstate.islast and array.size(keys) > 0 for [i,get_key] in keys scale = disp_size/array.max(values) get_vol = data_map.get(get_key) scaled = math.round(get_vol*scale) too_far_back = (lb_calc?bar_index-lb_bars:bi_nd)<bar_index-4999 p1 = extend_day ? (too_far_back?bar_index-4999:(lb_calc?bar_index-lb_bars:bi_nd)) : (bar_index+prof_offset) p2 = extend_day ? (disp_size<0?(bar_index+prof_offset):((bar_index+scaled)+prof_offset)) : ((bar_index+scaled)+prof_offset) if get_key == poc array.push(box_profile,box.new(p1,poc,p2,poc, border_color = poc_color, border_style = line.style_solid, border_width = 1, extend = (extend_day and too_far_back?extend.left:extend.none))) else if get_key == vah array.push(box_profile,box.new(p1,vah,p2,vah, border_color = var_color, border_style = line.style_solid, border_width = 1, extend = (extend_day and too_far_back?extend.left:extend.none))) else if get_key == val array.push(box_profile,box.new(p1,val,p2,val, border_color = var_color, border_style = line.style_solid, border_width = 1, extend = (extend_day and too_far_back?extend.left:extend.none))) else if dash(i) and (array.size(profile) <= 499) and (math.abs(scaled)>=1) array.push(profile,line.new(bar_index+prof_offset,get_key,(bar_index+scaled)+prof_offset,get_key, color = prof_color(i,get_key), style = (get_key<down_count or get_key>up_count?line.style_dotted:line.style_solid),width = 1)) else if (array.size(box_profile) <= 499) and (math.abs(scaled)>=1) array.push(box_profile,box.new(bar_index+prof_offset,get_key,(bar_index+scaled)+prof_offset,get_key, border_color = prof_color(i,get_key), border_style = (get_key<down_count or get_key>up_count?line.style_dotted:line.style_solid), border_width = 1)) //Drawing labels for the profile lab = label.new(bar_index+prof_offset,roof, text = (send_warning?warning:"")+(mp?"Market Profile [":"Volume Profile [") + (send_warning?"MAX":(lb_override?"Manual":tf)) + "] " + (lb_calc?"\nLookback [" + str.tostring(lb_bars) + " Bars]":"") + "\nGranularity: " + str.tostring(math.round(tick_size,decimal_places),"$#.################"), style = (disp_size<0?label.style_label_lower_right:label.style_label_lower_left), color = color.rgb(0,0,0,100), textcolor = send_warning?color.rgb(255, 136, 0):chart.fg_color, textalign = (disp_size<0?text.align_left:text.align_right), text_font_family = font.family_monospace) label.delete(lab[1]) if lab_tog poc_lab = label.new(bar_index+prof_offset,poc, text = mp?"TPO":"POC", tooltip = (mp?"TPO: ":"POC: ") + str.tostring(math.round(poc,decimal_places),"$#.################"),size = size.small, style = (disp_size<0?label.style_label_left:label.style_label_right), color = color.rgb(0,0,0,100), textcolor = poc_color, textalign = (disp_size<0?text.align_right:text.align_left), text_font_family = font.family_monospace) vah_lab = label.new(bar_index+prof_offset,vah, text = "VAH",size = size.small,tooltip = "VAH: " + str.tostring(math.round(vah,decimal_places),"$#.################"), style = (disp_size<0?label.style_label_left:label.style_label_right), color = color.rgb(0,0,0,100), textcolor = var_color, textalign = (disp_size<0?text.align_right:text.align_left), text_font_family = font.family_monospace) val_lab = label.new(bar_index+prof_offset,val, text = "VAL",size = size.small,tooltip = "VAL: " + str.tostring(math.round(val,decimal_places),"$#.################"), style = (disp_size<0?label.style_label_left:label.style_label_right), color = color.rgb(0,0,0,100), textcolor = var_color, textalign = (disp_size<0?text.align_right:text.align_left), text_font_family = font.family_monospace) label.delete(poc_lab[1]) label.delete(vah_lab[1]) label.delete(val_lab[1]) // Alerts alertcondition(ta.crossover(close,poc), "Cross-Over Point of Control") alertcondition(ta.crossunder(close,poc), "Cross-Under Point of Control") alertcondition(ta.crossover(close,vah), "Cross-Over Value High") alertcondition(ta.crossunder(close,vah), "Cross-Under Value High") alertcondition(ta.crossover(close,val), "Cross-Over Value Low") alertcondition(ta.crossunder(close,val),"Cross-Under Value Low") //Plotting Developing Lines plot(dev_poc?(poc==0?na:poc):na, color = poc_color, title = "Developing POC/TOP") plot(dev_va?vah:na, color = var_color, title = "Developing VAH") plot(dev_va?val:na, color = var_color, title = "Developing VAL")
Power Contract [Loxx]
https://www.tradingview.com/script/Lo0kSwww-Power-Contract-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("Power Contract [Loxx]", shorttitle ="PC [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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out PowerContract(float S, float X, float T, float r, float b, float v, float i)=> PowerContract = math.pow(S / X, i) * math.exp(((b - v * v / 2) * i - r + math.pow(i, 2) * v * v / 2) * T) PowerContract EPowerContract(string OutPutFlag, float S, float X, float T, float r, float b, float v, float i, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EPowerContract = 0 if OutPutFlag == "p" // Value EPowerContract := PowerContract(S, X, T, r, b, v, i) else if OutPutFlag == "d" //Delta EPowerContract := (PowerContract(S + dS, X, T, r, b, v, i) - PowerContract(S - dS, X, T, r, b, v, i)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EPowerContract := (PowerContract(S + dS, X, T, r, b, v, i) - PowerContract(S - dS, X, T, r, b, v, i)) / (2 * dS) * S / PowerContract(S, X, T, r, b, v, i) else if OutPutFlag == "g" //Gamma EPowerContract := (PowerContract(S + dS, X, T, r, b, v, i) - 2 * PowerContract(S, X, T, r, b, v, i) + PowerContract(S - dS, X, T, r, b, v, i)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EPowerContract := (PowerContract(S + dS, X, T, r, b, v + 0.01, i) - 2 * PowerContract(S, X, T, r, b, v + 0.01, i) + PowerContract(S - dS, X, T, r, b, v + 0.01, i) - PowerContract(S + dS, X, T, r, b, v - 0.01, i) + 2 * PowerContract(S, X, T, r, b, v - 0.01, i) - PowerContract(S - dS, X, T, r, b, v - 0.01, i)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EPowerContract := S / 100 * (PowerContract(S + dS, X, T, r, b, v, i) - 2 * PowerContract(S, X, T, r, b, v, i) + PowerContract(S - dS, X, T, r, b, v, i)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma EPowerContract := (PowerContract(S, X, T + 1 / 365, r, b, v, i) - 2 * PowerContract(S, X, T, r, b, v, i) + PowerContract(S, X, T - 1 / 365, r, b, v, i)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol EPowerContract := 1 / (4 * dS * 0.01) * (PowerContract(S + dS, X, T, r, b, v + 0.01, i) - PowerContract(S + dS, X, T, r, b, v - 0.01, i) - PowerContract(S - dS, X, T, r, b, v + 0.01, i) + PowerContract(S - dS, X, T, r, b, v - 0.01, i)) / 100 else if OutPutFlag == "v" //Vega EPowerContract := (PowerContract(S, X, T, r, b, v + 0.01, i) - PowerContract(S, X, T, r, b, v - 0.01, i)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EPowerContract := (PowerContract(S, X, T, r, b, v + 0.01, i) - 2 * PowerContract(S, X, T, r, b, v, i) + PowerContract(S, X, T, r, b, v - 0.01, i)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP EPowerContract := v / 0.1 * (PowerContract(S, X, T, r, b, v + 0.01, i) - PowerContract(S, X, T, r, b, v - 0.01, i)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EPowerContract := (PowerContract(S, X, T, r, b, v + 0.01, i) - 2 * PowerContract(S, X, T, r, b, v, i) + PowerContract(S, X, T, r, b, v - 0.01, i)) else if OutPutFlag == "t" //Theta if T <= (1 / 365) EPowerContract := PowerContract(S, X, 1E-05, r, b, v, i) - PowerContract(S, X, T, r, b, v, i) else EPowerContract := PowerContract(S, X, T - 1 / 365, r, b, v, i) - PowerContract(S, X, T, r, b, v, i) else if OutPutFlag == "r" //Rho EPowerContract := (PowerContract(S, X, T, r + 0.01, b + 0.01, v, i) - PowerContract(S, X, T, r - 0.01, b - 0.01, v, i)) / 2 else if OutPutFlag == "fr" //Futures options rho EPowerContract := (PowerContract(S, X, T, r + 0.01, b, v, i) - PowerContract(S, X, T, r - 0.01, b, v, i)) / 2 else if OutPutFlag == "f" //Rho2 EPowerContract := (PowerContract(S, X, T, r, b - 0.01, v, i) - PowerContract(S, X, T, r, b + 0.01, v, i)) / 2 else if OutPutFlag == "b" //Carry EPowerContract := (PowerContract(S, X, T, r, b + 0.01, v, i) - PowerContract(S, X, T, r, b - 0.01, v, i)) / 2 else if OutPutFlag == "s" //Speed EPowerContract := 1 / math.pow(dS, 3) * (PowerContract(S + 2 * dS, X, T, r, b, v, i) - 3 * PowerContract(S + dS, X, T, r, b, v, i) + 3 * PowerContract(S, X, T, r, b, v, i) - PowerContract(S - dS, X, T, r, b, v, i)) else if OutPutFlag == "dx" //Strike Delta EPowerContract := (PowerContract(S, X + dS, T, r, b, v, i) - PowerContract(S, X - dS, T, r, b, v, i)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike Gamma EPowerContract := (PowerContract(S, X + dS, T, r, b, v, i) - 2 * PowerContract(S, X, T, r, b, v, i) + PowerContract(S, X - dS, T, r, b, v, i)) / math.pow(dS, 2) EPowerContract 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(450, "Strike Price", group = "Basic Settings") string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings") float r = input.float(8., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(25., "% Volatility", group = "Rates Settings") / 100 float i = input.float(2, "Power", group = "Rates Settings") 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = PowerContract(S, K, T, kouta, koutb, v, i) Delta = EPowerContract("d", S, K, T, kouta, koutb, v, i, na) * sideout Elasticity = EPowerContract("e", S, K, T, kouta, koutb, v, i, na) * sideout Gamma = EPowerContract("g", S, K, T, kouta, koutb, v, i, na) * sideout DGammaDvol = EPowerContract("gv", S, K, T, kouta, koutb, v, i, na) * sideout GammaP = EPowerContract("gp", S, K, T, kouta, koutb, v, i, na) * sideout Vega = EPowerContract("v", S, K, T, kouta, koutb, v, i, na) * sideout DvegaDvol = EPowerContract("dvdv", S, K, T, kouta, koutb, v, i, na) * sideout VegaP = EPowerContract("vp", S, K, T, kouta, koutb, v, i, na) * sideout Theta = EPowerContract("t", S, K, T, kouta, koutb, v, i, na) * sideout Rho = EPowerContract("r", S, K, T, kouta, koutb, v, i, na) * sideout RhoFuturesOption = EPowerContract("fr", S, K, T, kouta, koutb, v, i, na) * sideout PhiRho2 = EPowerContract("f", S, K, T, kouta, koutb, v, i, na) * sideout Carry = EPowerContract("b", S, K, T, kouta, koutb, v, i, na) * sideout DDeltaDvol = EPowerContract("dddv", S, K, T, kouta, koutb, v, i, na) * sideout Speed = EPowerContract("s", S, K, T, kouta, koutb, v, i, na) * sideout StrikeDelta = EPowerContract("dx", S, K, T, kouta, koutb, v, i, na) * sideout StrikeGamma = EPowerContract("dxdx", S, K, T, kouta, koutb, v, i, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Power Contract", 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 = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, text = "Spot Price: " + str.tostring(S, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 3, 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 = 4, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 5, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 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 = "Power: " + str.tostring(i, "##.##"), 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 = 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 = "Power Contract Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Triple SuperTrend
https://www.tradingview.com/script/4XFdaIrL/
DebbyLe1487
https://www.tradingview.com/u/DebbyLe1487/
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/ // © DebbyLe1487 //@version=5 indicator("Triple supertrend", overlay = true, format=format.price, precision=2) Periods_1 = input.int(title="ATR Period 1", defval=10) Multiplier_1 = input.float(title="ATR Multiplier 1", step=0.1, defval=1.0) Periods_2 = input.int(title="ATR Period 2", defval=11) Multiplier_2 = input.float(title="ATR Multiplier 2", step=0.1, defval=2.0) Periods_3 = input.int(title="ATR Period 3", defval=12) Multiplier_3 = input.float(title="ATR Multiplier 3", step=0.1, defval=3.0) src = input(hl2, title="Source") changeATR= input.bool(title="Change ATR Calculation Method ?", defval=true) showsignals = input.bool(title="Show Buy/Sell Signals ?", defval=true) highlighting = input.bool(title="Highlighter Trend lines On/Off ?", defval=true) highlightingBG = input.bool(title="Highlighter BackGround Buy/Sell On/Off ?", defval=true) //common mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0) //Line 1 atr2_1 = ta.sma(ta.tr, Periods_1) atr_1= changeATR ? ta.atr(Periods_1) : atr2_1 up_1=src-(Multiplier_1*atr_1) up1_1 = nz(up_1[1],up_1) up_1 := close[1] > up1_1 ? math.max(up_1,up1_1) : up_1 dn_1=src+(Multiplier_1*atr_1) dn1_1 = nz(dn_1[1], dn_1) dn_1 := close[1] < dn1_1 ? math.min(dn_1, dn1_1) : dn_1 trend_1 = 1 trend_1 := nz(trend_1[1], trend_1) trend_1 := trend_1 == -1 and close > dn1_1 ? 1 : trend_1 == 1 and close < up1_1 ? -1 : trend_1 upPlot_1 = plot(trend_1 == 1 ? up_1 : na, title="Up Trend 1", style=plot.style_linebr, linewidth=2, color=color.new(color.green,0)) buySignal_1 = trend_1 == 1 and trend_1[1] == -1 plotshape(buySignal_1 ? up_1 : na, title="UpTrend Begins 1", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green) //plotshape(buySignal_1 and showsignals ? up_1 : na, title="Buy_1", text="Buy_1", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green,75), textcolor=color.new(color.white,75)) dnPlot_1 = plot(trend_1 == 1 ? na : dn_1, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red) sellSignal_1 = trend_1 == -1 and trend_1[1] == 1 plotshape(sellSignal_1 ? dn_1 : na, title="DownTrend Begins 1", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red) //plotshape(sellSignal_1 and showsignals ? dn_1 : na, title="Sell_1", text="Sell_1", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red,75), textcolor=color.new(color.white,75)) longFillColor_1 = highlighting ? (trend_1 == 1 ? color.new(color.green,95) : color.new(color.white,100)) : color.new(color.white,100) shortFillColor_1 = highlighting ? (trend_1 == -1 ? color.new(color.red,95) : color.new(color.white,100)) : color.new(color.white,100) fill(mPlot, upPlot_1, title="UpTrend Highligter", color=longFillColor_1) fill(mPlot, dnPlot_1, title="DownTrend Highligter", color=shortFillColor_1) //alertcondition(buySignal_1, title="SuperTrend Buy", message="SuperTrend Buy!") //alertcondition(sellSignal_1, title="SuperTrend Sell", message="SuperTrend Sell!") changeCond_1 = trend_1 != trend_1[1] //alertcondition(changeCond_1, title="SuperTrend Direction Change", message="SuperTrend has changed direction!") //Line 2 atr2_2 = ta.sma(ta.tr, Periods_2) atr_2= changeATR ? ta.atr(Periods_2) : atr2_2 up_2=src-(Multiplier_2*atr_2) up1_2 = nz(up_2[1],up_2) up_2 := close[1] > up1_2 ? math.max(up_2,up1_2) : up_2 dn_2=src+(Multiplier_2*atr_2) dn1_2 = nz(dn_2[1], dn_2) dn_2 := close[1] < dn1_2 ? math.min(dn_2, dn1_2) : dn_2 trend_2 = 1 trend_2 := nz(trend_2[1], trend_2) trend_2 := trend_2 == -1 and close > dn1_2 ? 1 : trend_2 == 1 and close < up1_2 ? -1 : trend_2 upPlot_2 = plot(trend_2 == 1 ? up_2 : na, title="Up Trend 1", style=plot.style_linebr, linewidth=2, color=color.new(color.green,0)) buySignal_2 = trend_2 == 1 and trend_2[1] == -1 plotshape(buySignal_2 ? up_2 : na, title="UpTrend Begins 1", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green) //plotshape(buySignal_2 and showsignals ? up_2 : na, title="Buy_2", text="Buy_2", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green,75), textcolor=color.new(color.white,75)) dnPlot_2 = plot(trend_2 == 1 ? na : dn_2, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red) sellSignal_2 = trend_2 == -1 and trend_2[1] == 1 plotshape(sellSignal_2 ? dn_2 : na, title="DownTrend Begins 1", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red) //plotshape(sellSignal_2 and showsignals ? dn_2 : na, title="Sell_2", text="Sell_2", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red,75), textcolor=color.new(color.white,75)) longFillColor_2 = highlighting ? (trend_2 == 1 ? color.new(color.green,95) : color.new(color.white,100)) : color.new(color.white,100) shortFillColor_2 = highlighting ? (trend_2 == -1 ? color.new(color.red,95) : color.new(color.white,100)) : color.new(color.white,100) fill(mPlot, upPlot_2, title="UpTrend Highligter", color=longFillColor_2) fill(mPlot, dnPlot_2, title="DownTrend Highligter", color=shortFillColor_2) //alertcondition(buySignal_2, title="SuperTrend Buy", message="SuperTrend Buy!") //alertcondition(sellSignal_2, title="SuperTrend Sell", message="SuperTrend Sell!") changeCond_2 = trend_2 != trend_2[1] //alertcondition(changeCond_2, title="SuperTrend Direction Change", message="SuperTrend has changed direction!") //Line 3 atr2_3 = ta.sma(ta.tr, Periods_3) atr_3= changeATR ? ta.atr(Periods_3) : atr2_3 up_3=src-(Multiplier_3*atr_3) up1_3 = nz(up_3[1],up_3) up_3 := close[1] > up1_3 ? math.max(up_3,up1_3) : up_3 dn_3=src+(Multiplier_3*atr_3) dn1_3 = nz(dn_3[1], dn_3) dn_3 := close[1] < dn1_3 ? math.min(dn_3, dn1_3) : dn_3 trend_3 = 1 trend_3 := nz(trend_3[1], trend_3) trend_3 := trend_3 == -1 and close > dn1_3 ? 1 : trend_3 == 1 and close < up1_3 ? -1 : trend_3 upPlot_3 = plot(trend_3 == 1 ? up_3 : na, title="Up Trend 1", style=plot.style_linebr, linewidth=2, color=color.new(color.green,0)) buySignal_3 = trend_3 == 1 and trend_3[1] == -1 plotshape(buySignal_3 ? up_3 : na, title="UpTrend Begins 1", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green) //plotshape(buySignal_3 and showsignals ? up_3 : na, title="Buy_3", text="Buy_3", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green,75), textcolor=color.new(color.white,75)) dnPlot_3 = plot(trend_3 == 1 ? na : dn_3, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red) sellSignal_3 = trend_3 == -1 and trend_3[1] == 1 plotshape(sellSignal_3 ? dn_3 : na, title="DownTrend Begins 1", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red) //plotshape(sellSignal_3 and showsignals ? dn_3 : na, title="Sell_3", text="Sell_3", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red,75), textcolor=color.new(color.white,75)) longFillColor_3 = highlighting ? (trend_3 == 1 ? color.new(color.green,95) : color.new(color.white,100)) : color.new(color.white,100) shortFillColor_3 = highlighting ? (trend_3 == -1 ? color.new(color.red,95) : color.new(color.white,100)) : color.new(color.white,100) fill(mPlot, upPlot_3, title="UpTrend Highligter", color=longFillColor_3) fill(mPlot, dnPlot_3, title="DownTrend Highligter", color=shortFillColor_3) //alertcondition(buySignal_3, title="SuperTrend Buy", message="SuperTrend Buy!") //alertcondition(sellSignal_3, title="SuperTrend Sell", message="SuperTrend Sell!") changeCond_3 = trend_3 != trend_3[1] //alertcondition(changeCond_3, title="SuperTrend Direction Change", message="SuperTrend has changed direction!") //General Buy buy = (buySignal_1 or buySignal_2 or buySignal_3) and trend_1 == 1 and trend_2 == 1 and trend_3 == 1 plotshape(buy and showsignals ? up_3 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green,60), textcolor=color.new(color.white,40)) //General Sell sell = (sellSignal_1 or sellSignal_2 or sellSignal_3) and trend_1 == -1 and trend_2 == -1 and trend_3 == -1 plotshape(sell and showsignals ? dn_3 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red,60), textcolor=color.new(color.white,40)) longCondition = trend_1 == 1 and trend_2 == 1 and trend_3 == 1 shortCondition = trend_1 == -1 and trend_2 == -1 and trend_3 == -1 bgcolor(longCondition and highlightingBG ? color.new(color.blue,90) : shortCondition and highlightingBG ? color.new(color.purple,90) : color.new(color.blue,100))
Powered Option [Loxx]
https://www.tradingview.com/script/UXFRaYFF-Powered-Option-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("Powered Option [Loxx]", shorttitle ="PO [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 import loxx/combin/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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out PoweredOption(string CallPutFlag, float S, float X, float T, float r, float b, float v, float i)=> float d1 = 0 float PoweredOption = 0 if CallPutFlag == callString float sum = 0 for j = 0 to i d1 := (math.log(S / X) + (b + (i - j - 0.5) * v * v) * T) / (v * math.sqrt(T)) sum := sum + combin.combin(int(i), j) * math.pow(S, (i - j)) * math.pow(-X, j) * math.exp((i - j - 1) * (r + (i - j) * v * v / 2) * T - (i - j) * (r - b) * T) * cnd.CND1(d1) PoweredOption := sum else float sum = 0 for j = 0 to i d1 := (math.log(S / X) + (b + (i - j - 0.5) * v * v) * T) / (v * math.sqrt(T)) sum := sum + combin.combin(int(i), j) * math.pow(-S, (i - j)) * math.pow(X, j) * math.exp((i - j - 1) * (r + (i - j) * v * v / 2) * T - (i - j) * (r - b) * T) * cnd.CND1(-d1) PoweredOption := sum PoweredOption EPoweredOption(string OutPutFlag, string CallPutFlag, float S, float X, float T, float r, float b, float v, float i, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EPoweredOption = 0 if OutPutFlag == "p" // Value EPoweredOption := PoweredOption(CallPutFlag, S, X, T, r, b, v, i) else if OutPutFlag == "d" //Delta EPoweredOption := (PoweredOption(CallPutFlag, S + dS, X, T, r, b, v, i) - PoweredOption(CallPutFlag, S - dS, X, T, r, b, v, i)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EPoweredOption := (PoweredOption(CallPutFlag, S + dS, X, T, r, b, v, i) - PoweredOption(CallPutFlag, S - dS, X, T, r, b, v, i)) / (2 * dS) * S / PoweredOption(CallPutFlag, S, X, T, r, b, v, i) else if OutPutFlag == "g" //Gamma EPoweredOption := (PoweredOption(CallPutFlag, S + dS, X, T, r, b, v, i) - 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v, i) + PoweredOption(CallPutFlag, S - dS, X, T, r, b, v, i)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EPoweredOption := (PoweredOption(CallPutFlag, S + dS, X, T, r, b, v + 0.01, i) - 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v + 0.01, i) + PoweredOption(CallPutFlag, S - dS, X, T, r, b, v + 0.01, i) - PoweredOption(CallPutFlag, S + dS, X, T, r, b, v - 0.01, i) + 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v - 0.01, i) - PoweredOption(CallPutFlag, S - dS, X, T, r, b, v - 0.01, i)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EPoweredOption := S / 100 * (PoweredOption(CallPutFlag, S + dS, X, T, r, b, v, i) - 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v, i) + PoweredOption(CallPutFlag, S - dS, X, T, r, b, v, i)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma EPoweredOption := (PoweredOption(CallPutFlag, S, X, T + 1 / 365, r, b, v, i) - 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v, i) + PoweredOption(CallPutFlag, S, X, T - 1 / 365, r, b, v, i)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol EPoweredOption := 1 / (4 * dS * 0.01) * (PoweredOption(CallPutFlag, S + dS, X, T, r, b, v + 0.01, i) - PoweredOption(CallPutFlag, S + dS, X, T, r, b, v - 0.01, i) - PoweredOption(CallPutFlag, S - dS, X, T, r, b, v + 0.01, i) + PoweredOption(CallPutFlag, S - dS, X, T, r, b, v - 0.01, i)) / 100 else if OutPutFlag == "v" //Vega EPoweredOption := (PoweredOption(CallPutFlag, S, X, T, r, b, v + 0.01, i) - PoweredOption(CallPutFlag, S, X, T, r, b, v - 0.01, i)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EPoweredOption := (PoweredOption(CallPutFlag, S, X, T, r, b, v + 0.01, i) - 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v, i) + PoweredOption(CallPutFlag, S, X, T, r, b, v - 0.01, i)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP EPoweredOption := v / 0.1 * (PoweredOption(CallPutFlag, S, X, T, r, b, v + 0.01, i) - PoweredOption(CallPutFlag, S, X, T, r, b, v - 0.01, i)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EPoweredOption := (PoweredOption(CallPutFlag, S, X, T, r, b, v + 0.01, i) - 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v, i) + PoweredOption(CallPutFlag, S, X, T, r, b, v - 0.01, i)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 EPoweredOption := PoweredOption(CallPutFlag, S, X, 1E-05, r, b, v, i) - PoweredOption(CallPutFlag, S, X, T, r, b, v, i) else EPoweredOption := PoweredOption(CallPutFlag, S, X, T - 1 / 365, r, b, v, i) - PoweredOption(CallPutFlag, S, X, T, r, b, v, i) else if OutPutFlag == "r" //Rho EPoweredOption := (PoweredOption(CallPutFlag, S, X, T, r + 0.01, b + 0.01, v, i) - PoweredOption(CallPutFlag, S, X, T, r - 0.01, b - 0.01, v, i)) / 2 else if OutPutFlag == "fr" //Futures options rho EPoweredOption := (PoweredOption(CallPutFlag, S, X, T, r + 0.01, b, v, i) - PoweredOption(CallPutFlag, S, X, T, r - 0.01, b, v, i)) / 2 else if OutPutFlag == "f" //Rho2 EPoweredOption := (PoweredOption(CallPutFlag, S, X, T, r, b - 0.01, v, i) - PoweredOption(CallPutFlag, S, X, T, r, b + 0.01, v, i)) / 2 else if OutPutFlag == "b" //Carry EPoweredOption := (PoweredOption(CallPutFlag, S, X, T, r, b + 0.01, v, i) - PoweredOption(CallPutFlag, S, X, T, r, b - 0.01, v, i)) / (2) else if OutPutFlag == "s" //Speed EPoweredOption := 1 / math.pow(dS, 3) * (PoweredOption(CallPutFlag, S + 2 * dS, X, T, r, b, v, i) - 3 * PoweredOption(CallPutFlag, S + dS, X, T, r, b, v, i) + 3 * PoweredOption(CallPutFlag, S, X, T, r, b, v, i) - PoweredOption(CallPutFlag, S - dS, X, T, r, b, v, i)) else if OutPutFlag == "dx" //Strike Delta EPoweredOption := (PoweredOption(CallPutFlag, S, X + dS, T, r, b, v, i) - PoweredOption(CallPutFlag, S, X - dS, T, r, b, v, i)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike Gamma EPoweredOption := (PoweredOption(CallPutFlag, S, X + dS, T, r, b, v, i) - 2 * PoweredOption(CallPutFlag, S, X, T, r, b, v, i) + PoweredOption(CallPutFlag, S, X - dS, T, r, b, v, i)) / math.pow(dS, 2) EPoweredOption 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(100, "Strike Price", group = "Basic Settings") string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings") string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings") float r = input.float(0., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(2., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(42., "% Volatility", group = "Rates Settings") / 100 float i = input.float(2, "Power", group = "PO Settings") 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = EPoweredOption("p", OpType, S, K, T, kouta, koutb, v, i, na) Delta = EPoweredOption("d", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Elasticity = EPoweredOption("e", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Gamma = EPoweredOption("g", OpType, S,K, T, kouta, koutb, v, i, na) * sideout DGammaDvol = EPoweredOption("gv", OpType, S,K, T, kouta, koutb, v, i, na) * sideout GammaP = EPoweredOption("gp", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Vega = EPoweredOption("v", OpType, S,K, T, kouta, koutb, v, i, na) * sideout DvegaDvol = EPoweredOption("dvdv", OpType, S,K, T, kouta, koutb, v, i, na) * sideout VegaP = EPoweredOption("vp", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Theta = EPoweredOption("t", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Rho = EPoweredOption("r", OpType, S,K, T, kouta, koutb, v, i, na) * sideout RhoFuturesOption = EPoweredOption("fr", OpType, S,K, T, kouta, koutb, v, i, na) * sideout PhiRho2 = EPoweredOption("f", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Carry = EPoweredOption("b", OpType, S,K, T, kouta, koutb, v, i, na) * sideout DDeltaDvol = EPoweredOption("dddv", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Speed = EPoweredOption("s", OpType, S,K, T, kouta, koutb, v, i, na) * sideout StrikeDelta = EPoweredOption("dx", OpType, S,K, T, kouta, koutb, v, i, na) * sideout StrikeGamma = EPoweredOption("dxdx", OpType, S,K, T, kouta, koutb, v, i, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Powered Option", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = "Power: " + str.tostring(i, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 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 = "Powered Option Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Log Contract Ln(S) [Loxx]
https://www.tradingview.com/script/BCL36aZI-Log-Contract-Ln-S-Loxx/
loxx
https://www.tradingview.com/u/loxx/
10
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("Log Contract Ln(S) [Loxx]", shorttitle ="LC [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 import loxx/combin/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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out LogContract_LnS(float S, float T, float r, float b, float v)=> LogContract_LnS = math.exp(-r * T) * (math.log(S) + (b - math.pow(v, 2) / 2) * T) LogContract_LnS ELogContract_LnS(string OutPutFlag, float S, float T, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float ELogContract_LnS = 0 if OutPutFlag == "p" // Value ELogContract_LnS := LogContract_LnS(S, T, r, b, v) else if OutPutFlag == "d" //Delta ELogContract_LnS := (LogContract_LnS(S + dS, T, r, b, v) - LogContract_LnS(S - dS, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity ELogContract_LnS := (LogContract_LnS(S + dS, T, r, b, v) - LogContract_LnS(S - dS, T, r, b, v)) / (2 * dS) * S / LogContract_LnS(S, T, r, b, v) else if OutPutFlag == "g" //Gamma ELogContract_LnS := (LogContract_LnS(S + dS, T, r, b, v) - 2 * LogContract_LnS(S, T, r, b, v) + LogContract_LnS(S - dS, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol ELogContract_LnS := (LogContract_LnS(S + dS, T, r, b, v + 0.01) - 2 * LogContract_LnS(S, T, r, b, v + 0.01) + LogContract_LnS(S - dS, T, r, b, v + 0.01) - LogContract_LnS(S + dS, T, r, b, v - 0.01) + 2 * LogContract_LnS(S, T, r, b, v - 0.01) - LogContract_LnS(S - dS, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP ELogContract_LnS := S / 100 * (LogContract_LnS(S + dS, T, r, b, v) - 2 * LogContract_LnS(S, T, r, b, v) + LogContract_LnS(S - dS, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma ELogContract_LnS := (LogContract_LnS(S, T + 1 / 365, r, b, v) - 2 * LogContract_LnS(S, T, r, b, v) + LogContract_LnS(S, T - 1 / 365, r, b, v)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol ELogContract_LnS := 1 / (4 * dS * 0.01) * (LogContract_LnS(S + dS, T, r, b, v + 0.01) - LogContract_LnS(S + dS, T, r, b, v - 0.01) - LogContract_LnS(S - dS, T, r, b, v + 0.01) + LogContract_LnS(S - dS, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega ELogContract_LnS := (LogContract_LnS(S, T, r, b, v + 0.01) - LogContract_LnS(S, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma ELogContract_LnS := (LogContract_LnS(S, T, r, b, v + 0.01) - 2 * LogContract_LnS(S, T, r, b, v) + LogContract_LnS(S, T, r, b, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP ELogContract_LnS := v / 0.1 * (LogContract_LnS(S, T, r, b, v + 0.01) - LogContract_LnS(S, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol ELogContract_LnS := (LogContract_LnS(S, T, r, b, v + 0.01) - 2 * LogContract_LnS(S, T, r, b, v) + LogContract_LnS(S, T, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 ELogContract_LnS := LogContract_LnS(S, 1E-05, r, b, v) - LogContract_LnS(S, T, r, b, v) else ELogContract_LnS := LogContract_LnS(S, T - 1 / 365, r, b, v) - LogContract_LnS(S, T, r, b, v) else if OutPutFlag == "r" //Rho ELogContract_LnS := (LogContract_LnS(S, T, r + 0.01, b + 0.01, v) - LogContract_LnS(S, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" //Futures options rho ELogContract_LnS := (LogContract_LnS(S, T, r + 0.01, b, v) - LogContract_LnS(S, T, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" //Rho2 ELogContract_LnS := (LogContract_LnS(S, T, r, b - 0.01, v) - LogContract_LnS(S, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" //Carry ELogContract_LnS := (LogContract_LnS(S, T, r, b + 0.01, v) - LogContract_LnS(S, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" //Speed ELogContract_LnS := 1 / math.pow(dS, 3) * (LogContract_LnS(S + 2 * dS, T, r, b, v) - 3 * LogContract_LnS(S + dS, T, r, b, v) + 3 * LogContract_LnS(S, T, r, b, v) - LogContract_LnS(S - dS, T, r, b, v)) ELogContract_LnS 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)"]) string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings") float r = input.float(8., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(8., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(35., "% 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = ELogContract_LnS("p", S, T, kouta, koutb, v, na) Delta = ELogContract_LnS("d", S, T, kouta, koutb, v, na) * sideout Elasticity = ELogContract_LnS("e", S, T, kouta, koutb, v, na) * sideout Gamma = ELogContract_LnS("g", S, T, kouta, koutb, v, na) * sideout DGammaDvol = ELogContract_LnS("gv", S, T, kouta, koutb, v, na) * sideout GammaP = ELogContract_LnS("gp", S, T, kouta, koutb, v, na) * sideout Vega = ELogContract_LnS("v", S, T, kouta, koutb, v, na) * sideout DvegaDvol = ELogContract_LnS("dvdv", S, T, kouta, koutb, v, na) * sideout VegaP = ELogContract_LnS("vp", S, T, kouta, koutb, v, na) * sideout Theta = ELogContract_LnS("t", S, T, kouta, koutb, v, na) * sideout Rho = ELogContract_LnS("r", S, T, kouta, koutb, v, na) * sideout RhoFuturesOption = ELogContract_LnS("fr", S, T, kouta, koutb, v, na) * sideout PhiRho2 = ELogContract_LnS("f", S, T, kouta, koutb, v, na) * sideout Carry = ELogContract_LnS("b", S, T, kouta, koutb, v, na) * sideout DDeltaDvol = ELogContract_LnS("dddv", S, T, kouta, koutb, v, na) * sideout Speed = ELogContract_LnS("s", S, T, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Log Contract Ln(S)", 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 = "Side: " + side , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, text = "Spot Price: " + str.tostring(S, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 3, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 4, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 5, 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 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 = "Log Contract Ln(S) Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Standard Power Option [Loxx]
https://www.tradingview.com/script/E5CvlhCe-Standard-Power-Option-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("Standard Power Option [Loxx]", shorttitle ="SPO [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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out PowerOptionAsymmetric(string CallPutFlag, float S, float X, float T, float r, float b, float v, float i)=> float PowerOptionAsymmetric = 0 float d1 = (math.log(S / math.pow(X, (1 / i))) + (b + (i - 1 / 2) * v * v) * T) / (v * math.sqrt(T)) float d2 = d1 - i * v * math.sqrt(T) if CallPutFlag == callString PowerOptionAsymmetric := math.pow(S, i) * math.exp(((i - 1) * (r + i * v * v / 2) - i * (r - b)) * T) * cnd.CND1(d1) - X * math.exp(-r * T) * cnd.CND1(d2) else PowerOptionAsymmetric := X * math.exp(-r * T) * cnd.CND1(-d2) - math.pow(S, i) * math.exp(((i - 1) * (r + i * v * v / 2) - i * (r - b)) * T) * cnd.CND1(-d1) PowerOptionAsymmetric EPowerOptionAsymmetric(string OutPutFlag, string CallPutFlag, float S, float X, float T, float r, float b, float v, float i, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EPowerOptionAsymmetric = 0 if OutPutFlag == "p" // Value EPowerOptionAsymmetric := PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) else if OutPutFlag == "d" //Delta EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v, i) - PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v, i)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v, i) - PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v, i)) / (2 * dS) * S / PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) else if OutPutFlag == "g" //Gamma EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v, i) - 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) + PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v, i)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v + 0.01, i) - 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v + 0.01, i) + PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v + 0.01, i) - PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v - 0.01, i) + 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v - 0.01, i) - PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v - 0.01, i)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EPowerOptionAsymmetric := S / 100 * (PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v, i) - 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) + PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v, i)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T + 1 / 365, r, b, v, i) - 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) + PowerOptionAsymmetric(CallPutFlag, S, X, T - 1 / 365, r, b, v, i)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol EPowerOptionAsymmetric := 1 / (4 * dS * 0.01) * (PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v + 0.01, i) - PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v - 0.01, i) - PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v + 0.01, i) + PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v - 0.01, i)) / 100 else if OutPutFlag == "v" //Vega EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v + 0.01, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v - 0.01, i)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v + 0.01, i) - 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) + PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v - 0.01, i)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP EPowerOptionAsymmetric := v / 0.1 * (PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v + 0.01, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v - 0.01, i)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v + 0.01, i) - 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) + PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v - 0.01, i)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 EPowerOptionAsymmetric := PowerOptionAsymmetric(CallPutFlag, S, X, 1E-05, r, b, v, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) else EPowerOptionAsymmetric := PowerOptionAsymmetric(CallPutFlag, S, X, T - 1 / 365, r, b, v, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) else if OutPutFlag == "r" //Rho EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T, r + 0.01, b + 0.01, v, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r - 0.01, b - 0.01, v, i)) / 2 else if OutPutFlag == "fr" //Futures options rho EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T, r + 0.01, b, v, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r - 0.01, b, v, i)) / 2 else if OutPutFlag == "f" //Rho2 EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b - 0.01, v, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b + 0.01, v, i)) / 2 else if OutPutFlag == "b" //Carry EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b + 0.01, v, i) - PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b - 0.01, v, i)) / 2 else if OutPutFlag == "s" //Speed EPowerOptionAsymmetric := 1 / math.pow(dS, 3) * (PowerOptionAsymmetric(CallPutFlag, S + 2 * dS, X, T, r, b, v, i) - 3 * PowerOptionAsymmetric(CallPutFlag, S + dS, X, T, r, b, v, i) + 3 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) - PowerOptionAsymmetric(CallPutFlag, S - dS, X, T, r, b, v, i)) else if OutPutFlag == "dx" //Strike Delta EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X + dS, T, r, b, v, i) - PowerOptionAsymmetric(CallPutFlag, S, X - dS, T, r, b, v, i)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike Gamma EPowerOptionAsymmetric := (PowerOptionAsymmetric(CallPutFlag, S, X + dS, T, r, b, v, i) - 2 * PowerOptionAsymmetric(CallPutFlag, S, X, T, r, b, v, i) + PowerOptionAsymmetric(CallPutFlag, S, X - dS, T, r, b, v, i)) / math.pow(dS, 2) EPowerOptionAsymmetric 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(450, "Strike Price", group = "Basic Settings") string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings") string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings") float r = input.float(8., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(25., "% Volatility", group = "Rates Settings") / 100 float i = input.float(2, "Power", group = "Rates Settings") 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = EPowerOptionAsymmetric("p", OpType, S, K, T, kouta, koutb, v, i, na) Delta = EPowerOptionAsymmetric("d", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Elasticity = EPowerOptionAsymmetric("e", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Gamma = EPowerOptionAsymmetric("g", OpType, S,K, T, kouta, koutb, v, i, na) * sideout DGammaDvol = EPowerOptionAsymmetric("gv", OpType, S,K, T, kouta, koutb, v, i, na) * sideout GammaP = EPowerOptionAsymmetric("gp", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Vega = EPowerOptionAsymmetric("v", OpType, S,K, T, kouta, koutb, v, i, na) * sideout DvegaDvol = EPowerOptionAsymmetric("dvdv", OpType, S,K, T, kouta, koutb, v, i, na) * sideout VegaP = EPowerOptionAsymmetric("vp", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Theta = EPowerOptionAsymmetric("t", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Rho = EPowerOptionAsymmetric("r", OpType, S,K, T, kouta, koutb, v, i, na) * sideout RhoFuturesOption = EPowerOptionAsymmetric("fr", OpType, S,K, T, kouta, koutb, v, i, na) * sideout PhiRho2 = EPowerOptionAsymmetric("f", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Carry = EPowerOptionAsymmetric("b", OpType, S,K, T, kouta, koutb, v, i, na) * sideout DDeltaDvol = EPowerOptionAsymmetric("dddv", OpType, S,K, T, kouta, koutb, v, i, na) * sideout Speed = EPowerOptionAsymmetric("s", OpType, S,K, T, kouta, koutb, v, i, na) * sideout StrikeDelta = EPowerOptionAsymmetric("dx", OpType, S,K, T, kouta, koutb, v, i, na) * sideout StrikeGamma = EPowerOptionAsymmetric("dxdx", OpType, S,K, T, kouta, koutb, v, i, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Standard Power Option", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = "Power: " + str.tostring(i, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 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 = "Power Contract Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Capped Standard Power Option [Loxx]
https://www.tradingview.com/script/ndzulKRE-Capped-Standard-Power-Option-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("Capped Standard Power Option [Loxx]", shorttitle ="CSPO [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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out CappedPowerOption(string CallPutFlag, float S, float X, float T, float r, float b, float v, float i, float c)=> float e1 = (math.log(S / math.pow(X, (1 / i))) + (b + (i - 1 / 2) * v * v) * T) / (v * math.sqrt(T)) float e2 = e1 - i * v * math.sqrt(T) float e3 = 0 float e4 = 0 float CappedPowerOption = 0 if CallPutFlag == callString e3 := (math.log(S / math.pow(X + c, (1 / i))) + (b + (i - 1 / 2) * v * v) * T) / (v * math.sqrt(T)) e4 := e3 - i * v * math.sqrt(T) CappedPowerOption := math.pow(S, i) * math.exp((i - 1) * (r + i * v * v / 2) * T - i * (r - b) * T) * (cnd.CND1(e1) - cnd.CND1(e3)) - math.exp(-r * T) * (X * cnd.CND1(e2) - (c + X) * cnd.CND1(e4)) else e3 := (math.log(S / math.pow(X - c, (1 / i))) + (b + (i - 1 / 2) * v * v) * T) / (v * math.sqrt(T)) e4 := e3 - i * v * math.sqrt(T) CappedPowerOption := math.exp(-r * T) * (X * cnd.CND1(-e2) - (X - c) * cnd.CND1(-e4)) - math.pow(S, i) * math.exp((i - 1) * (r + i * v * v / 2) * T - i * (r - b) * T) * (cnd.CND1(-e1) - cnd.CND1(-e3)) CappedPowerOption ECappedPowerOption(string OutPutFlag, string CallPutFlag, float S, float X, float T, float r, float b, float v, float i, float c, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float ECappedPowerOption = 0 if OutPutFlag == "p" // Value ECappedPowerOption := CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) else if OutPutFlag == "d" //Delta ECappedPowerOption := (CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v, i, c) - CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v, i, c)) / (2 * dS) else if OutPutFlag == "e" //Elasticity ECappedPowerOption := (CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v, i, c) - CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v, i, c)) / (2 * dS) * S / CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) else if OutPutFlag == "g" //Gamma ECappedPowerOption := (CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v, i, c) - 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) + CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v, i, c)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol ECappedPowerOption := (CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v + 0.01, i, c) - 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v + 0.01, i, c) + CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v + 0.01, i, c) - CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v - 0.01, i, c) + 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v - 0.01, i, c) - CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v - 0.01, i, c)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP ECappedPowerOption := S / 100 * (CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v, i, c) - 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) + CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v, i, c)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T + 1 / 365, r, b, v, i, c) - 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) + CappedPowerOption(CallPutFlag, S, X, T - 1 / 365, r, b, v, i, c)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol ECappedPowerOption := 1 / (4 * dS * 0.01) * (CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v + 0.01, i, c) - CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v - 0.01, i, c) - CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v + 0.01, i, c) + CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v - 0.01, i, c)) / 100 else if OutPutFlag == "v" //Vega ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T, r, b, v + 0.01, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r, b, v - 0.01, i, c)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T, r, b, v + 0.01, i, c) - 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) + CappedPowerOption(CallPutFlag, S, X, T, r, b, v - 0.01, i, c)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP ECappedPowerOption := v / 0.1 * (CappedPowerOption(CallPutFlag, S, X, T, r, b, v + 0.01, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r, b, v - 0.01, i, c)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T, r, b, v + 0.01, i, c) - 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) + CappedPowerOption(CallPutFlag, S, X, T, r, b, v - 0.01, i, c)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 ECappedPowerOption := CappedPowerOption(CallPutFlag, S, X, 1E-05, r, b, v, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) else ECappedPowerOption := CappedPowerOption(CallPutFlag, S, X, T - 1 / 365, r, b, v, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) else if OutPutFlag == "r" //Rho ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T, r + 0.01, b + 0.01, v, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r - 0.01, b - 0.01, v, i, c)) / 2 else if OutPutFlag == "fr" //Futures options rho ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T, r + 0.01, b, v, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r - 0.01, b, v, i, c)) / 2 else if OutPutFlag == "f" //Rho2 ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T, r, b - 0.01, v, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r, b + 0.01, v, i, c)) / 2 else if OutPutFlag == "b" //Carry ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X, T, r, b + 0.01, v, i, c) - CappedPowerOption(CallPutFlag, S, X, T, r, b - 0.01, v, i, c)) / 2 else if OutPutFlag == "s" //Speed ECappedPowerOption := 1 / math.pow(dS, 3) * (CappedPowerOption(CallPutFlag, S + 2 * dS, X, T, r, b, v, i, c) - 3 * CappedPowerOption(CallPutFlag, S + dS, X, T, r, b, v, i, c) + 3 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) - CappedPowerOption(CallPutFlag, S - dS, X, T, r, b, v, i, c)) else if OutPutFlag == "dx" //Strike Delta ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X + dS, T, r, b, v, i, c) - CappedPowerOption(CallPutFlag, S, X - dS, T, r, b, v, i, c)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike Gamma ECappedPowerOption := (CappedPowerOption(CallPutFlag, S, X + dS, T, r, b, v, i, c) - 2 * CappedPowerOption(CallPutFlag, S, X, T, r, b, v, i, c) + CappedPowerOption(CallPutFlag, S, X - dS, T, r, b, v, i, c)) / math.pow(dS, 2) ECappedPowerOption 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(100, "Strike Price", group = "Basic Settings") string side = input.string("Long", "Side", options = ["Long", "Short"], group = "Basic Settings") string OpType = input.string(callString, "Option type", options = [callString, putString], group = "Basic Settings") float r = input.float(10., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(5., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float i = input.float(2, "Power", group = "CSPO Settings") float c = input.float(5, "Capped on Pay Off", group = "CSPO 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = ECappedPowerOption("p", OpType, S, K, T, kouta, koutb, v, i, c, na) Delta = ECappedPowerOption("d", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout Elasticity = ECappedPowerOption("e", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout Gamma = ECappedPowerOption("g", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout DGammaDvol = ECappedPowerOption("gv", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout GammaP = ECappedPowerOption("gp", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout Vega = ECappedPowerOption("v", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout DvegaDvol = ECappedPowerOption("dvdv", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout VegaP = ECappedPowerOption("vp", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout Theta = ECappedPowerOption("t", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout Rho = ECappedPowerOption("r", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout RhoFuturesOption = ECappedPowerOption("fr", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout PhiRho2 = ECappedPowerOption("f", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout Carry = ECappedPowerOption("b", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout DDeltaDvol = ECappedPowerOption("dddv", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout Speed = ECappedPowerOption("s", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout StrikeDelta = ECappedPowerOption("dx", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout StrikeGamma = ECappedPowerOption("dxdx", OpType, S,K, T, kouta, koutb, v, i, c, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Capped Standard Power Option", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = "Power: " + str.tostring(i, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 9, text = "Capped on Pay Off: " + str.tostring(c, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 15, 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 = 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 = "Capped Standard Power Option Value: " + str.tostring(amaproxprice, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 2, text = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Firestorm Trend Chaser
https://www.tradingview.com/script/aEba9Qc0-Firestorm-Trend-Chaser/
firestormtd
https://www.tradingview.com/u/firestormtd/
210
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/ // © firestormtd //@version=5 indicator('Firestorm Trend Chaser', overlay=true, format=format.price, precision=2, timeframe='') Periods = input(title='ATR Period', defval=10) src = input(hl2, title='Source') Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0) changeATR = input(title='Change ATR Calculation Method ?', defval=true) showsignals = input(title='Show Buy/Sell Signals ?', defval=true) highlighting = input(title='Highlighter On/Off ?', 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 upPlot = plot(trend == 1 ? up : na, title='Up Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0)) buySignal = trend == 1 and trend[1] == -1 plotshape(buySignal ? up : na, title='UpTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.green, 0)) plotshape(buySignal and showsignals ? up : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0)) dnPlot = plot(trend == 1 ? na : dn, title='Down Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0)) sellSignal = trend == -1 and trend[1] == 1 plotshape(sellSignal ? dn : na, title='DownTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.red, 0)) plotshape(sellSignal and showsignals ? dn : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0)) mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0) longFillColor = highlighting ? trend == 1 ? color.green : color.white : color.white shortFillColor = highlighting ? trend == -1 ? color.red : color.white : color.white fill(mPlot, upPlot, title='UpTrend Highligter', color=longFillColor, transp=90) fill(mPlot, dnPlot, title='DownTrend Highligter', color=shortFillColor, transp=90) alertcondition(buySignal, title='SuperTrend Buy', message='SuperTrend Buy!') alertcondition(sellSignal, title='SuperTrend Sell', message='SuperTrend Sell!') changeCond = trend != trend[1] alertcondition(changeCond, title='SuperTrend Direction Change', message='SuperTrend has changed direction!') //Inputs avg_type = input.string("EMA", "Average Type", options=["EMA","SMA"]) annual_avg = input(252, "Annual Moving Avg Length") month_step_down = input(21, "Monthly Step Down") annual_ribbon = input.color(color.rgb(255, 255, 255, 88), "Annual Ribbon") bull_ribbon = input.color(color.rgb(83, 224, 88, 68), "Bull Ribbon") bear_ribbon = input.color(color.rgb(255, 82, 82, 73), "Bear Ribbon") bull_fill = input.color(color.new(#62df66, 80), "Bull Fill") bear_fill = input.color(color.new(#f76c6c, 88), "Bear Fill") //Ribbion Colors ribbon_color1 = annual_ribbon ribbon_color2 = bull_ribbon ribbon_color3 = bull_ribbon ribbon_color4 = bull_ribbon ribbon_color5 = bull_ribbon ribbon_color6 = bull_ribbon ribbon_color7 = bull_ribbon ribbon_color8 = bull_ribbon ribbon_color9 = bull_ribbon ribbon_color10 = bull_ribbon ribbon_color11 = bull_ribbon ribbon_color12 = bull_ribbon //Fill Color fill_color1 = bull_fill fill_color2 = bull_fill fill_color3 = bull_fill fill_color4 = bull_fill fill_color5 = bull_fill fill_color6 = bull_fill fill_color7 = bull_fill fill_color8 = bull_fill fill_color9 = bull_fill fill_color10 = bull_fill fill_color11 = bull_fill //Step Values month_step_down1 = month_step_down month_step_down2 = month_step_down*2 month_step_down3 = month_step_down*3 month_step_down4 = month_step_down*4 month_step_down5 = month_step_down*5 month_step_down6 = month_step_down*6 month_step_down7 = month_step_down*7 month_step_down8 = month_step_down*8 month_step_down9 = month_step_down*9 month_step_down10 = month_step_down*10 month_step_down11 = month_step_down*11 //Inital Avg plot values avg1 = 0.0 avg2 = 0.0 avg3 = 0.0 avg4 = 0.0 avg5 = 0.0 avg6 = 0.0 avg7 = 0.0 avg8 = 0.0 avg9 = 0.0 avg10 = 0.0 avg11 = 0.0 avg12 = 0.0 // MA Values if avg_type == "EMA" avg1 := ta.ema(close, annual_avg) if ta.ema(close,annual_avg-month_step_down1) < ta.ema(close,annual_avg) ribbon_color2 := bear_ribbon avg2 := ta.ema(close,annual_avg-month_step_down1) if ta.ema(close,annual_avg-month_step_down2) < ta.ema(close,annual_avg) ribbon_color3 := bear_ribbon avg3 := ta.ema(close,annual_avg-month_step_down2) if ta.ema(close,annual_avg-month_step_down3) < ta.ema(close,annual_avg) ribbon_color4 := bear_ribbon avg4 := ta.ema(close,annual_avg-month_step_down3) if ta.ema(close,annual_avg-month_step_down4) < ta.ema(close,annual_avg) ribbon_color5 := bear_ribbon avg5 := ta.ema(close,annual_avg-month_step_down4) if ta.ema(close,annual_avg-month_step_down5) < ta.ema(close,annual_avg) ribbon_color6 := bear_ribbon avg6 := ta.ema(close,annual_avg-month_step_down5) if ta.ema(close,annual_avg-month_step_down6) < ta.ema(close,annual_avg) ribbon_color7 := bear_ribbon avg7 := ta.ema(close,annual_avg-month_step_down6) if ta.ema(close,annual_avg-month_step_down7) < ta.ema(close,annual_avg) ribbon_color8 := bear_ribbon avg8 := ta.ema(close,annual_avg-month_step_down7) if ta.ema(close,annual_avg-month_step_down8) < ta.ema(close,annual_avg) ribbon_color9 := bear_ribbon avg9 := ta.ema(close,annual_avg-month_step_down8) if ta.ema(close,annual_avg-month_step_down9) < ta.ema(close,annual_avg) ribbon_color10 := bear_ribbon avg10 := ta.ema(close,annual_avg-month_step_down9) if ta.ema(close,annual_avg-month_step_down10) < ta.ema(close,annual_avg) ribbon_color11 := bear_ribbon avg11 := ta.ema(close,annual_avg-month_step_down10) if ta.ema(close,annual_avg-month_step_down11) < ta.ema(close,annual_avg) ribbon_color12 := bear_ribbon avg12 := ta.ema(close,annual_avg-month_step_down11) else avg1 := ta.sma(close, annual_avg) if ta.sma(close,annual_avg-month_step_down1) < ta.sma(close,annual_avg) ribbon_color2 := bear_ribbon avg2 := ta.sma(close,annual_avg-month_step_down1) if ta.sma(close,annual_avg-month_step_down2) < ta.sma(close,annual_avg) ribbon_color3 := bear_ribbon avg3 := ta.sma(close,annual_avg-month_step_down2) if ta.sma(close,annual_avg-month_step_down3) < ta.sma(close,annual_avg) ribbon_color4 := bear_ribbon avg4 := ta.sma(close,annual_avg-month_step_down3) if ta.sma(close,annual_avg-month_step_down4) < ta.sma(close,annual_avg) ribbon_color5 := bear_ribbon avg5 := ta.sma(close,annual_avg-month_step_down4) if ta.sma(close,annual_avg-month_step_down5) < ta.sma(close,annual_avg) ribbon_color6 := bear_ribbon avg6 := ta.sma(close,annual_avg-month_step_down5) if ta.sma(close,annual_avg-month_step_down6) < ta.sma(close,annual_avg) ribbon_color7 := bear_ribbon avg7 := ta.sma(close,annual_avg-month_step_down6) if ta.sma(close,annual_avg-month_step_down7) < ta.sma(close,annual_avg) ribbon_color8 := bear_ribbon avg8 := ta.sma(close,annual_avg-month_step_down7) if ta.sma(close,annual_avg-month_step_down8) < ta.sma(close,annual_avg) ribbon_color9 := bear_ribbon avg9 := ta.sma(close,annual_avg-month_step_down8) if ta.sma(close,annual_avg-month_step_down9) < ta.sma(close,annual_avg) ribbon_color10 := bear_ribbon avg10 := ta.sma(close,annual_avg-month_step_down9) if ta.sma(close,annual_avg-month_step_down10) < ta.sma(close,annual_avg) ribbon_color11 := bear_ribbon avg11 := ta.sma(close,annual_avg-month_step_down10) if ta.sma(close,annual_avg-month_step_down11) < ta.sma(close,annual_avg) ribbon_color12 := bear_ribbon avg12 := ta.sma(close,annual_avg-month_step_down11) //Fill Colors if avg2 < avg1 fill_color1 := bear_fill if avg3 < avg2 fill_color2 := bear_fill if avg4 < avg3 fill_color3 := bear_fill if avg5 < avg4 fill_color4 := bear_fill if avg6 < avg5 fill_color5 := bear_fill if avg7 < avg6 fill_color6 := bear_fill if avg8 < avg7 fill_color7 := bear_fill if avg9 < avg8 fill_color8 := bear_fill if avg10 < avg9 fill_color9 := bear_fill if avg11 < avg10 fill_color10 := bear_fill if avg12 < avg11 fill_color11 := bear_fill //Plots p1 = plot(avg1, linewidth = 3, title="Annual Avg", color = ribbon_color1) p2 = plot(avg2, title="Monthly Step Down 1", color = ribbon_color2) p3 = plot(avg3, title="Monthly Step Down 2", color = ribbon_color3) p4 = plot(avg4, title="Monthly Step Down 3", color = ribbon_color4) p5 = plot(avg5, title="Monthly Step Down 4", color = ribbon_color5) p6 = plot(avg6, title="Monthly Step Down 5", color = ribbon_color6) p7 = plot(avg7, title="Monthly Step Down 6", color = ribbon_color7) p8 = plot(avg8, title="Monthly Step Down 7", color = ribbon_color8) p9 = plot(avg9, title="Monthly Step Down 8", color = ribbon_color9) p10 = plot(avg10, title="Monthly Step Down 9", color = ribbon_color10) p11 = plot(avg11, title="Monthly Step Down 10", color = ribbon_color11) p12 = plot(avg12, linewidth = 3, title="Monthly Step Down 11", color = ribbon_color12) fill(p1, p2, color=fill_color1, title = "Gap Slow Avg Step Down 1") fill(p2, p3, color=fill_color2, title = "Step Down 1 Step Down 2") fill(p3, p4, color=fill_color3, title = "Step Down 2 Step Down 3") fill(p4, p5, color=fill_color4, title = "Step Down 3 Step Down 4") fill(p5, p6, color=fill_color5, title = "Step Down 4 Step Down 5") fill(p6, p7, color=fill_color6, title = "Step Down 5 Step Down 6") fill(p7, p8, color=fill_color7, title = "Step Down 6 Step Down 7") fill(p8, p9, color=fill_color8, title = "Step Down 7 Step Down 8") fill(p9, p10, color=fill_color9, title = "Step Down 8 Step Down 9") fill(p10, p11, color=fill_color10, title = "Step Down 9 Step Down 10") fill(p11, p12, color=fill_color11, title = "Step Down 10 Step Down 11")
Bollinger Bands Width and Bollinger Bands %B
https://www.tradingview.com/script/VzwzkmnX-Bollinger-Bands-Width-and-Bollinger-Bands-B/
polarbearking
https://www.tradingview.com/u/polarbearking/
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/ // © polarbearking //@version=5 indicator(title="Bollinger Bands Width and Bollinger Bands %B", shorttitle="BBW & %B", format=format.price, precision=2, timeframe="", timeframe_gaps=true) // Bollinger Bands Width (BBW): Color = (Default: Green [#138484]) // Bollinger Bands %B (%B): Color = (Default: Blue [#62b6ee]) length = input.int(20, minval=1) src = input(close, title="Source") mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev") basis = ta.sma(src, length) stdev = ta.stdev(src, length) dev = mult * stdev upper = basis + dev lower = basis - dev bbw = ((upper-lower)/basis) * 10 bbr = (src - lower)/(upper - lower) * 10 hline(mult * 4) hline(mult * 3) hline(mult * 2) hline(mult) hline(1) hline(10) plot(bbr, "Bollinger Bands %B", color=#62b6ee) plot(bbw, "Bollinger Bands Width", color=#138484)
Swing Top / Bottom Finder
https://www.tradingview.com/script/xWqqt8HN-Swing-Top-Bottom-Finder/
UnknownUnicorn36161431
https://www.tradingview.com/u/UnknownUnicorn36161431/
454
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/ // © zathruswriter //@version=5 indicator("Swing Top / Bottom Finder", overlay = true, max_bars_back = 4900, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500) GROUP_GENERAL = "General Settings" GROUP_ADVANCED = "Advanced Settings" GROUP_VISUAL = "Visual Settings" search_threshold = input.float( 0.04, "Search Threshold %", step = 0.01, group = GROUP_GENERAL, tooltip = "How many % around our currently checked high/low should we consider when checking for similar swing highs and lows in the past." ) lookback_bars = input.int( 500, "Lookback length (bars)", group = GROUP_GENERAL, tooltip = "Number of bars in the past up to where highs and lows are being checked for similarities with the current high/low." ) min_prev_bottoms = input.int( 3, "Min previous horizontals with same high/low", group = GROUP_GENERAL, tooltip = "A swing top/bottom must be confirmed by at least this many times in the past to be considered valid.") min_diff_between_highs_lows = input.float( 0.17, "Min difference between two highs/lows %", step = 0.01, group = GROUP_GENERAL, tooltip = "This setting will tell us how much apart will two similar highs/lows be in order to be counted and displayed as different highs/lows." ) bars_wait_before_next_swing = input.int( 17, "Pause after a high/low is found (bars)", group = GROUP_GENERAL, tooltip = "Sometimes, there could be many highs/lows with a very simmilar price tag around the same area. This setting allows waiting for X amount of bars before searching for the next one, eliminating this crowd effect." ) bars_wait_before_next_swing_potential = input.int( 3, "Pause after a potential high/low is found (bars)", group = GROUP_ADVANCED ) check_only_current_swing_candles = input.bool( true, "Perform checks on current swing high/low candles ONLY", group = GROUP_ADVANCED, tooltip = "When ticked, only candles that are actually swing highs/lows will be checked for validity (e.g. against other similar previous highs/lows). Otherwise, all candles will be checked." ) show_potential_swings = input.bool( true, "Show potential swing highs/lows", group = GROUP_ADVANCED, tooltip = "When ticked, potential swing highs/lows will be shown even when no previous high/low exists in the history for that price level yet." ) show_lines = input.bool( true, "Show high/low lines", group = GROUP_VISUAL, tooltip = "High/low lines serve the purpose of showing you the last unbroken swing high/low. This could be used to observe a potential TP level during scalping." ) i_trend_line_color = input.color( color.black, "Trend Line Color", group = GROUP_VISUAL, inline = "tl" ) i_trend_line_width = input.int( 2, "width", group = GROUP_VISUAL, inline = "tl" ) i_trend_line_style = input.string( line.style_solid, "style", options = [line.style_solid, line.style_dashed, line.style_dotted], group = GROUP_VISUAL, inline = "tl" ) // VARIABLES transparentcolor = color.new(color.white,100) var last_low_point = -1.0 var last_high_point = -1.0 var last_low_point_potential = -1.0 var last_high_point_potential = -1.0 var paused_highs = false var paused_lows = false var paused_highs_potential = false var paused_lows_potential = false var pause_counter_highs = 0 var pause_counter_lows = 0 var pause_counter_highs_potential = 0 var pause_counter_lows_potential = 0 var swing_high_line = line.new( bar_index, 0, bar_index, 0, color = transparentcolor, width = i_trend_line_width, style = i_trend_line_style ) var swing_low_line = line.new( bar_index, 0, bar_index, 0, color = transparentcolor, width = i_trend_line_width, style = i_trend_line_style ) // FUNCTIONS s_( txt ) => str.tostring( txt ) f_debug_label( txt ) => label.new(bar_index, high, str.tostring( txt ), color = color.lime, textcolor = color.black) f_debug_label_down( txt ) => label.new(bar_index, low, str.tostring( txt ), color = color.lime, textcolor = color.black, style = label.style_label_up) f_set_swing_line_to_current_bar( which, offset ) => if show_lines //f_debug_label_down( which + " / " + s_( bar_index ) + " / " + s_( offset ) ) // f_debug_label( s_( bar_index[ offset ] ) + " / " + s_( bar_index - offset ) ) //f_debug_label( s_( bar_index - offset) + " / " + s_( which == "high" ? last_high_point > last_high_point_potential ? last_high_point : last_high_point_potential : last_low_point > last_low_point_potential ? last_low_point : last_low_point_potential ) ) //f_debug_label( s_( last_low_point ) + " / " + s_( last_low_point_potential ) ) swing_line = which == "high" ? swing_high_line : swing_low_line line.set_x1( swing_line, bar_index - offset ) line.set_x2( swing_line, bar_index - offset ) line.set_y1( swing_line, which == "high" ? last_high_point > last_high_point_potential ? last_high_point : last_high_point_potential : last_low_point > last_low_point_potential ? last_low_point : last_low_point_potential ) line.set_y2( swing_line, which == "high" ? last_high_point > last_high_point_potential ? last_high_point : last_high_point_potential : last_low_point > last_low_point_potential ? last_low_point : last_low_point_potential ) line.set_color( swing_line, i_trend_line_color ) f_extend_swing_line_to_current_bar( which ) => if show_lines swing_line = which == "high" ? swing_high_line : swing_low_line line.set_x2( swing_line, bar_index ) f_reset_swing_line( which ) => if show_lines swing_line = which == "high" ? swing_high_line : swing_low_line line.set_x1( swing_line, bar_index ) line.set_x2( swing_line, bar_index ) line.set_y1( swing_line, 0 ) line.set_y2( swing_line, 0 ) line.set_color( swing_line, transparentcolor ) f_is_swing_line_reset( which ) => swing_line = which == "high" ? swing_high_line : swing_low_line line.get_y1( swing_line ) == 0 // LOGIC num_bottoms = 0 num_tops = 0 // if we enabled checking of swing candles only, activate offset here last_candle_was_swing = check_only_current_swing_candles ? false : true last_candle_swing_type = "" check_offset = check_only_current_swing_candles ? 1 : 0 is_unmarked_swing_top = false is_unmarked_swing_bot = false // also, check for last candle as swing candle if check_only_current_swing_candles if high < high[ check_offset ] and high[ check_offset + 1] < high[ check_offset ] last_candle_was_swing := true last_candle_swing_type := "high" if low > low[ check_offset ] and low[ check_offset + 1] > low[ check_offset ] last_candle_was_swing := true last_candle_swing_type := "low" // even if swing candles checking is disabled, this variable will still be set to true if last_candle_was_swing if ( paused_lows == false or ( check_only_current_swing_candles and paused_lows_potential == false ) ) and ( check_only_current_swing_candles == false or last_candle_swing_type == "low" ) // find swing bottoms if this low is not too close to the previous swing low found if last_low_point == -1.0 or math.abs( ( ( low[ check_offset ] - last_low_point ) / last_low_point ) * 100 ) >= min_diff_between_highs_lows //f_debug_label( str.tostring( low ) + " / " + str.tostring( last_low_point ) + "\n" + str.tostring( math.abs( ( ( low - last_low_point ) / last_low_point ) * 100 ) ) + " / " + s_( min_diff_between_highs_lows ) ) for i = 0 to lookback_bars low_with_threshold = ( ( low[ i + check_offset ] / 100 ) * search_threshold ) point_was_swing_low = false if i > 0 point_was_swing_low := low[ i + check_offset - 1 ] > low[ i + check_offset ] and low[ i + check_offset + 1 ] > low[ i + check_offset ] if paused_lows == false and point_was_swing_low and low[ check_offset ] < low[ i + check_offset ] + low_with_threshold and low[ check_offset ] > low[ i + check_offset ] - low_with_threshold num_bottoms := num_bottoms + 1 if num_bottoms >= min_prev_bottoms last_low_point := low[ check_offset ] else if paused_lows_potential == false and low > low[ check_offset ] and low[ check_offset + 1] > low[ check_offset ] is_unmarked_swing_bot := true last_low_point_potential := low[ check_offset ] else f_extend_swing_line_to_current_bar( "low" ) if pause_counter_lows >= bars_wait_before_next_swing pause_counter_lows := 0 paused_lows := false else pause_counter_lows := pause_counter_lows + 1 if pause_counter_lows_potential >= bars_wait_before_next_swing_potential pause_counter_lows_potential := 0 paused_lows_potential := false else pause_counter_lows_potential := pause_counter_lows_potential + 1 if ( paused_highs == false or ( check_only_current_swing_candles and paused_highs_potential == false ) ) and ( check_only_current_swing_candles == false or last_candle_swing_type == "high" ) // find swing tops if this high is not too close to the previous swing high found if last_high_point == -1.0 or math.abs( ( ( high[ check_offset ] - last_high_point ) / last_high_point ) * 100 ) >= min_diff_between_highs_lows for i = 0 to lookback_bars high_with_threshold = ( ( high[ i + check_offset ] / 100 ) * search_threshold ) point_was_swing_high = false if i > 0 point_was_swing_high := high[ i + check_offset - 1 ] < high[ i + check_offset ] and high[ i + check_offset + 1 ] < high[ i + check_offset ] if paused_highs == false and point_was_swing_high and high[ check_offset ] < high[ i + check_offset ] + high_with_threshold and high[ check_offset ] > high[ i + check_offset ] - high_with_threshold num_tops := num_tops + 1 if num_tops >= min_prev_bottoms last_high_point := high[ check_offset ] else if paused_highs_potential == false and high < high[ check_offset ] and high[ check_offset + 1] < high[ check_offset ] is_unmarked_swing_top := true last_high_point_potential := high[ check_offset ] else f_extend_swing_line_to_current_bar( "high" ) if pause_counter_highs >= bars_wait_before_next_swing pause_counter_highs := 0 paused_highs := false else pause_counter_highs := pause_counter_highs + 1 if pause_counter_highs_potential >= bars_wait_before_next_swing_potential pause_counter_highs_potential := 0 paused_highs_potential := false else pause_counter_highs_potential := pause_counter_highs_potential + 1 if num_bottoms >= min_prev_bottoms // pause until the number of new bars is reached paused_lows := true last_low_point_potential := -1 // also activate the low point line if f_is_swing_line_reset( "low" ) f_set_swing_line_to_current_bar( "low", check_offset ) f_extend_swing_line_to_current_bar( "low" ) if is_unmarked_swing_bot // pause until the number of new bars is reached paused_lows_potential := true last_low_point := -1 // also activate the low point line if f_is_swing_line_reset( "low" ) f_set_swing_line_to_current_bar( "low", check_offset ) f_extend_swing_line_to_current_bar( "low" ) if num_tops >= min_prev_bottoms // pause until the number of new bars is reached paused_highs := true // also activate the high point line if f_is_swing_line_reset( "high" ) f_set_swing_line_to_current_bar( "high", check_offset ) f_extend_swing_line_to_current_bar( "high" ) if is_unmarked_swing_top // pause until the number of new bars is reached paused_highs_potential := true // also activate the high point line if f_is_swing_line_reset( "high" ) f_set_swing_line_to_current_bar( "high", check_offset ) f_extend_swing_line_to_current_bar( "high" ) // PLOTTING plotshape( num_bottoms >= min_prev_bottoms ? 1 : na, "Swing Low", shape.triangleup, location.belowbar, color.green, size = size.small, offset = -check_offset ) plotshape( num_tops >= min_prev_bottoms ? 1 : na, "Swing High", shape.triangledown, location.abovebar, color.red, size = size.small, offset = -check_offset ) plotshape( show_potential_swings and is_unmarked_swing_bot ? 1 : na, "Potential Swing Low", shape.triangleup, location.belowbar, color.aqua, size = size.tiny, offset = -check_offset ) plotshape( show_potential_swings and is_unmarked_swing_top ? 1 : na, "Potential Swing High", shape.triangledown, location.abovebar, color.fuchsia, size = size.tiny, offset = -check_offset ) // reset or update swing lines high_line_was_reset = false low_line_was_reset = false if ( last_high_point > last_high_point_potential and high < last_high_point ) or ( last_high_point < last_high_point_potential and high < last_high_point_potential ) f_extend_swing_line_to_current_bar( "high" ) else if ( last_high_point > last_high_point_potential and high >= last_high_point ) or ( last_high_point < last_high_point_potential and high >= last_high_point_potential ) if f_is_swing_line_reset( "high" ) == false f_reset_swing_line( "high" ) high_line_was_reset := true if ( last_low_point > last_low_point_potential and low > last_low_point ) or ( last_low_point < last_low_point_potential and low > last_low_point_potential ) f_extend_swing_line_to_current_bar( "low" ) else if ( last_low_point > last_low_point_potential and low <= last_low_point ) or ( last_low_point < last_low_point_potential and low <= last_low_point_potential ) if f_is_swing_line_reset( "low" ) == false f_reset_swing_line( "low" ) low_line_was_reset := true // ALERTS alertcondition( num_bottoms >= min_prev_bottoms, "Swing Low Found", "Swing Low Found" ) alertcondition( num_tops >= min_prev_bottoms, "Swing High Found", "Swing High Found" ) alertcondition( show_potential_swings and is_unmarked_swing_bot, "Potential Swing Low Found", "Potential Swing Low Found" ) alertcondition( show_potential_swings and is_unmarked_swing_top, "Potential Swing High Found", "Potential Swing High Found" ) alertcondition( high_line_was_reset, "Swing High Level Broken", "Swing High Level Broken" ) alertcondition( low_line_was_reset, "Swing Low Level Broken", "Swing High Level Broken" ) // provide a one to serve them all option as well if num_bottoms >= min_prev_bottoms alert( "Swing Low Found", alert.freq_once_per_bar ) if num_tops >= min_prev_bottoms alert( "Swing High Found", alert.freq_once_per_bar ) if show_potential_swings and is_unmarked_swing_bot alert( "Potential Swing Low Found", alert.freq_once_per_bar ) if show_potential_swings and is_unmarked_swing_top alert( "Potential Swing High Found", alert.freq_once_per_bar ) if show_lines and high_line_was_reset alert( "Swing High Level Broken", alert.freq_once_per_bar ) if show_lines and low_line_was_reset alert( "Swing Low Level Broken", alert.freq_once_per_bar )
Variable Purchase Options [Loxx]
https://www.tradingview.com/script/0xhjnrFz-Variable-Purchase-Options-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("Variable Purchase Options [Loxx]", shorttitle ="VPO [Loxx]", 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 import loxx/cnd/1 import loxx/cbnd/1 color darkGreenColor = #1B7E02 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate VPO(float S, float X, float L, float U, float D, float T, float r, float b, float v)=> float NMin = X / (U * (1 - D)) float NMax = X / (L * (1 - D)) float d1 = (math.log(S / U) + (b + v * v / 2) * T) / (v * math.sqrt(T)) float d2 = d1 - v * math.sqrt(T) float d3 = (math.log(S / L) + (b + v * v / 2) * T) / (v * math.sqrt(T)) float d4 = d3 - v * math.sqrt(T) float d5 = (math.log(S / (L * (1 - D))) + (b + v * v / 2) * T) / (v * math.sqrt(T)) float d6 = d5 - v * math.sqrt(T) VPO = X * D / (1 - D) * math.exp(-r * T) + NMin * (S * math.exp((b - r) * T) *cnd.CND1(d1) - U * math.exp(-r * T) *cnd.CND1(d2)) - NMax * (L * math.exp(-r * T) *cnd.CND1(-d4) - S * math.exp((b - r) * T) *cnd.CND1(-d3)) + NMax * (L * (1 - D) * math.exp(-r * T) *cnd.CND1(-d6) - S * math.exp((b - r) * T) *cnd.CND1(-d5)) VPO smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Asset Price Settings") srcin = input.string("Close", "Asset Price", group= "Asset 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") float L = input.float(90., "Lower Bound", group = "Basic Settings") float U = input.float(200., "Upper Bound", group = "Basic Settings") float discount = input.float(20., "% Discount Rate", group = "Rates Settings") / 100 float r = input.float(5., "% Risk-free Rate", group = "Rates Settings") / 100 float b = input.float(5., "% Cost of Carry", group = "Rates Settings") / 100 float v = input.float(20., "% 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 = "Time to Maturity 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 = "Text Size", 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 S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast float amaproxprice = VPO(S, K, L, U, discount, T, r, b, v) var testTable = table.new(position = position.middle_right, columns = 2, rows = 21, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Variable Purchase Options", 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 = "Asset Price: " + str.tostring(S, format.mintick) , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, 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 = 3, text = "% Discount Rate: " + str.tostring(discount * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "Lower Bound: " + str.tostring(L, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, text = "Upper Bound: " + str.tostring(U, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 6, 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 = 7, text = "Time to Maturity: " + 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 = 8, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 9, text = "% Cost of Carry: " + str.tostring(b * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 15, text = "Option Ouput", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 16, text = "Value: " + str.tostring(amaproxprice, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Executive Stock Options [Loxx]
https://www.tradingview.com/script/qfDoaFEi-Executive-Stock-Options-Loxx/
loxx
https://www.tradingview.com/u/loxx/
8
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("Executive Stock Options [Loxx]", shorttitle ="ESO [Loxx]", 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 import loxx/cnd/1 import loxx/cbnd/1 string Continuous = "Continuous" string PeriodRate = "Period Rate" string Annual = "Annual" string SemiAnnual = "Semi-Annual" string Quaterly = "Quaterly" string Monthly = "Monthly" color darkGreenColor = #1B7E02 string callString = "Call" string putString = "Put" 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas 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.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 //// Executive stock options Executive(string CallPutFlag, float S, float X, float T, float r, float b, float v, float lambda)=> float EExecutive = math.exp(-lambda * T) * GBlackScholes(CallPutFlag, S, X, T, r, b, v) EExecutive EExecutive(string OutPutFlag, string CallPutFlag, float S, float X, float T,float r, float b, float v, float lambda, float dSin)=> float dS = 0 if na(dSin) dS := 0.01 float EExecutive = 0 if OutPutFlag == "p" // Value EExecutive := Executive(CallPutFlag, S, X, T, r, b, v, lambda) else if OutPutFlag == "d" //Delta EExecutive := (Executive(CallPutFlag, S + dS, X, T, r, b, v, lambda) - Executive(CallPutFlag, S - dS, X, T, r, b, v, lambda)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EExecutive := (Executive(CallPutFlag, S + dS, X, T, r, b, v, lambda) - Executive(CallPutFlag, S - dS, X, T, r, b, v, lambda)) / (2 * dS) * S / Executive(CallPutFlag, S, X, T, r, b, v, lambda) else if OutPutFlag == "g" //Gamma EExecutive := (Executive(CallPutFlag, S + dS, X, T, r, b, v, lambda) - 2 * Executive(CallPutFlag, S, X, T, r, b, v, lambda) + Executive(CallPutFlag, S - dS, X, T, r, b, v, lambda)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EExecutive := (Executive(CallPutFlag, S + dS, X, T, r, b, v + 0.01, lambda) - 2 * Executive(CallPutFlag, S, X, T, r, b, v + 0.01, lambda) + Executive(CallPutFlag, S - dS, X, T, r, b, v + 0.01, lambda) - Executive(CallPutFlag, S + dS, X, T, r, b, v - 0.01, lambda) + 2 * Executive(CallPutFlag, S, X, T, r, b, v - 0.01, lambda) - Executive(CallPutFlag, S - dS, X, T, r, b, v - 0.01, lambda)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EExecutive := S / 100 * (Executive(CallPutFlag, S + dS, X, T, r, b, v, lambda) - 2 * Executive(CallPutFlag, S, X, T, r, b, v, lambda) + Executive(CallPutFlag, S - dS, X, T, r, b, v, lambda)) / math.pow(dS, 2) else if OutPutFlag == "dddv" //DDeltaDvol EExecutive := 1 / (4 * dS * 0.01) * (Executive(CallPutFlag, S + dS, X, T, r, b, v + 0.01, lambda) - Executive(CallPutFlag, S + dS, X, T, r, b, v - 0.01, lambda) - Executive(CallPutFlag, S - dS, X, T, r, b, v + 0.01, lambda) + Executive(CallPutFlag, S - dS, X, T, r, b, v - 0.01, lambda)) / 100 else if OutPutFlag == "v" //Vega EExecutive := (Executive(CallPutFlag, S, X, T, r, b, v + 0.01, lambda) - Executive(CallPutFlag, S, X, T, r, b, v - 0.01, lambda)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EExecutive := (Executive(CallPutFlag, S, X, T, r, b, v + 0.01, lambda) - 2 * Executive(CallPutFlag, S, X, T, r, b, v, lambda) + Executive(CallPutFlag, S, X, T, r, b, v - 0.01, lambda)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP EExecutive := v / 0.1 * (Executive(CallPutFlag, S, X, T, r, b, v + 0.01, lambda) - Executive(CallPutFlag, S, X, T, r, b, v - 0.01, lambda)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EExecutive := (Executive(CallPutFlag, S, X, T, r, b, v + 0.01, lambda) - 2 * Executive(CallPutFlag, S, X, T, r, b, v, lambda) + Executive(CallPutFlag, S, X, T, r, b, v - 0.01, lambda)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 EExecutive := Executive(CallPutFlag, S, X, 1E-05, r, b, v, lambda) - Executive(CallPutFlag, S, X, T, r, b, v, lambda) else EExecutive := Executive(CallPutFlag, S, X, T - 1 / 365, r, b, v, lambda) - Executive(CallPutFlag, S, X, T, r, b, v, lambda) else if OutPutFlag == "r" //Rho EExecutive := (Executive(CallPutFlag, S, X, T, r + 0.01, b + 0.01, v, lambda) - Executive(CallPutFlag, S, X, T, r - 0.01, b - 0.01, v, lambda)) / 2 else if OutPutFlag == "fr" //Futures options rho EExecutive := (Executive(CallPutFlag, S, X, T, r + 0.01, b, v, lambda) - Executive(CallPutFlag, S, X, T, r - 0.01, b, v, lambda)) / 2 else if OutPutFlag == "f" //Rho2 EExecutive := (Executive(CallPutFlag, S, X, T, r, b - 0.01, v, lambda) - Executive(CallPutFlag, S, X, T, r, b + 0.01, v, lambda)) / 2 else if OutPutFlag == "b" //Carry EExecutive := (Executive(CallPutFlag, S, X, T, r, b + 0.01, v, lambda) - Executive(CallPutFlag, S, X, T, r, b - 0.01, v, lambda)) / 2 else if OutPutFlag == "s" //Speed EExecutive := 1 / math.pow(dS, 3) * (Executive(CallPutFlag, S + 2 * dS, X, T, r, b, v, lambda) - 3 * Executive(CallPutFlag, S + dS, X, T, r, b, v, lambda) + 3 * Executive(CallPutFlag, S, X, T, r, b, v, lambda) - Executive(CallPutFlag, S - dS, X, T, r, b, v, lambda)) else if OutPutFlag == "dx" //StrikeDelta EExecutive := (Executive(CallPutFlag, S, X + dS, T, r, b, v, lambda) - Executive(CallPutFlag, S, X - dS, T, r, b, v, lambda)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike gamma EExecutive := (Executive(CallPutFlag, S, X + dS, T, r, b, v, lambda) - 2 * Executive(CallPutFlag, S, X, T, r, b, v, lambda) + Executive(CallPutFlag, S, X - dS, T, r, b, v, lambda)) / math.pow(dS, 2) else if OutPutFlag == "j" //Sensitivity to jump EExecutive := (Executive(CallPutFlag, S, X + dS, T, r, b, v, lambda + 0.01) - Executive(CallPutFlag, S, X - dS, T, r, b, v, lambda - 0.01)) / (2) EExecutive smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Asset Price Settings") srcin = input.string("Close", "Asset Price", group= "Asset 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(100, "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 r = input.float(10., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(5., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = 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 float lambda = input.float(18., "% Jump Rate per Year", 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 = "Text Size", 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 S = 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float hvolout = switch hvoltype parkinson => parkinsonvol(histvolper) rogersatch => rogerssatchel(histvolper) c2c => closetoclose(math.log(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) bsmprice = GBlackScholes(OpType, S, K, T, kouta, koutb, v) amaproxprice = EExecutive("p", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Delta = EExecutive("d", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Elasticity = EExecutive("e", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Gamma = EExecutive("g", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout DGammaDvol = EExecutive("gv", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout GammaP = EExecutive("gp", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Vega = EExecutive("v", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout DvegaDvol = EExecutive("dvdv", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout VegaP = EExecutive("vp", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Theta = EExecutive("t", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Rho = EExecutive("r", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout RhoFuturesOption = EExecutive("fr", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout PhiRho2 = EExecutive("f", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Carry = EExecutive("b", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout DDeltaDvol = EExecutive("dddv", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout Speed = EExecutive("s", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout StrikeDelta = EExecutive("dx", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout StrikeGamma = EExecutive("dxdx", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout JumpRateSense = EExecutive("j", OpType, S, K, T, kouta, koutb, v, lambda, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 21, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Executive Stock Options", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = "% Jump Rate (annual): " + str.tostring(lambda * 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 = "% 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 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 = "Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 19, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 20, text = "Jump Rate Sensitivity 1%: " + str.tostring(JumpRateSense, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Outside Bar + PFR - x Cash Investing
https://www.tradingview.com/script/qUVS3vop/
Phillipowisk
https://www.tradingview.com/u/Phillipowisk/
13
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/ // © Phillipowisk //@version=4 study("x Cash", shorttitle="x Cash Investing", overlay=true) candle_OutsideBar1 = high > high[1] and low < low[1] and close > open candle_OutsideBar2 = high > high[1] and low < low[1] and close < open outsidebar_compra = candle_OutsideBar1 ? color.rgb(63, 231, 231) : na outsidebar_venda = candle_OutsideBar2 ? color.rgb(240, 62, 195) : na // plots barcolor(outsidebar_compra) // plots barcolor(outsidebar_venda) // inputs stoch_length = input(8, "Slow Stoch Length", type=input.integer, minval=2) stock_smooth = input(3, "Slow Stoch Smooth", type=input.integer, minval=2) stoch_use = input(false, "Use o filtro para PFR") stoch_overbought = input(80, "Slow Stoch Overbought", minval=0, type=input.integer) stoch_oversold = input(20, "Slow Stoch Oversold", minval=0, type=input.integer) //calcs stoch_value = sma(stoch(close, high, low, stoch_length), stock_smooth) candle_bottom = close > close[1] and lowest(2) < lowest(2)[1] and (not stoch_use or stoch_value < stoch_oversold) candle_top = close < close[1] and highest(2) > highest(2)[1] and (not stoch_use or stoch_value > stoch_overbought) PFR = candle_bottom ? color.navy : candle_top ? color.yellow : na // plots barcolor(PFR)
Performance Table
https://www.tradingview.com/script/A6cTKjVR-Performance-Table/
tv94067
https://www.tradingview.com/u/tv94067/
48
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/ // © tv94067 //@version=5 indicator('Performance Table', overlay=true) TablePos = input.string(title='Tabel Position', defval='Bottom Center', options=['Top Right', 'Middle Right', 'Bottom Right', 'Top Center', 'Middle Center', 'Bottom Center', 'Top Left', 'Middle Left', 'Bottom Left'], inline='tabp', group = '') tableColumnsInput = input.int(9, 'Columns', minval=1, maxval=9, step=1, inline='tabp', group = '') _tablePos = TablePos == 'Top Right' ? position.top_right : TablePos == 'Middle Right' ? position.middle_right : TablePos == 'Bottom Right' ? position.bottom_right : TablePos == 'Top Center' ? position.top_center : TablePos == 'Middle Center'? position.middle_center : TablePos == 'Bottom Center'? position.bottom_center : TablePos == 'Top Left' ? position.top_left : TablePos == 'Middle Left' ? position.middle_left : position.bottom_left //tooltipText = 'Custom timeframes can be added via the chart's Timeframe dropdown. Until added, custom timeframes show up as 'Chart' instead.' showTF1 = input.bool(true, '1-D', inline = 'TF1', group = '') showTF2 = input.bool(true, '5-D', inline = 'TF1', group = '') showTF3 = input.bool(true, '1-W', inline = 'TF1', group = '') showTF4 = input.bool(true, '4-W', inline = 'TF1', group = '') showTF5 = input.bool(true, '1-M', inline = 'TF2', group = '') showTF6 = input.bool(true, '3-M', inline = 'TF2', group = '') showTF7 = input.bool(true, '6-M', inline = 'TF2', group = '') showTF8 = input.bool(true, '12-M', inline = 'TF2', group = '') showTF9 = input.bool(true, '52-W', inline = 'TF2', group = '') showTFArray = array.from(showTF1, showTF2, showTF3, showTF4, showTF5, showTF6, showTF7, showTF8, showTF9) timeframeArray = array.from('1D', '5D', '1W', '4W', '1M', '3M', '6M', '12M', '52W') var table perfTable = table.new(position = _tablePos, columns = tableColumnsInput, rows = array.size(timeframeArray), bgcolor = na, frame_color = na , frame_width = 0, border_color = na, border_width = 1) lightTransp = 90 avgTransp = 80 heavyTransp = 70 // === USER INPUTS === i_posColor = input(color.rgb(38, 166, 154), title='Positive Color', inline='col') i_negColor = input(color.rgb(240, 83, 80), title='Negative Color', inline='col') i_volColor = input(color.new(#999999, 0), title='Neutral Color', inline='col') f_rateOfreturn(current_close, previous_close) => (current_close - previous_close) * 100 / math.abs(previous_close) f_performance(_security, _timeframe, _barsBack) => request.security(_security, _timeframe, f_rateOfreturn(close, close[_barsBack]), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) f_fillCell(_table, _column, _row, _value, _timeframe) => _c_color = _value >= 0 ? i_posColor : i_negColor _transp = math.abs(_value) > 10 ? heavyTransp : math.abs(_value) > 5 ? avgTransp : lightTransp _cellText = str.tostring(_value, '0.00') + '%\n' + _timeframe table.cell(_table, _column, _row, _cellText, bgcolor=color.new(_c_color, _transp), text_color=_c_color, width=6) performanceArray = array.from(f_performance(syminfo.tickerid, '1D', 1), f_performance(syminfo.tickerid, '1D', 5), f_performance(syminfo.tickerid, '1W', 1), f_performance(syminfo.tickerid, '1W', 4), f_performance(syminfo.tickerid, '1M', 1), f_performance(syminfo.tickerid, '1M', 3), f_performance(syminfo.tickerid, '1M', 6), f_performance(syminfo.tickerid, '1M', 12), f_performance(syminfo.tickerid, '1W', 52)) if barstate.islast filled = 0 for i = 0 to array.size(showTFArray) - 1 if array.get(showTFArray, i) f_fillCell(perfTable, filled % tableColumnsInput, filled / tableColumnsInput, array.get(performanceArray, i), array.get(timeframeArray, i)) filled += 1
Forward Start Options [Loxx]
https://www.tradingview.com/script/H6Xp8bKa-Forward-Start-Options-Loxx/
loxx
https://www.tradingview.com/u/loxx/
11
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("Forward Start Options [Loxx]", shorttitle ="FSO [Loxx]", 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 import loxx/cnd/1 import loxx/cbnd/1 string Continuous = "Continuous" string PeriodRate = "Period Rate" string Annual = "Annual" string SemiAnnual = "Semi-Annual" string Quaterly = "Quaterly" string Monthly = "Monthly" color darkGreenColor = #1B7E02 string callString = "Call" string putString = "Put" 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas 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.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 //// Forward start options ForwardStartOption(string CallPutFlag, float S, float Alpha, float t1, float T, float r, float b, float v)=> float ForwardStartOption = S * math.exp((b - r) * t1) * GBlackScholes(CallPutFlag, 1, Alpha, T - t1, r, b, v) ForwardStartOption EForwardStartOption(string OutPutFlag, string CallPutFlag, float S, float Alpha, float t1, float T, float r, float b, float v, float dSin)=> float dS = 0 if na(dSin) dS := 0.01 float EForwardStartOption = 0 if OutPutFlag == "p" // Value EForwardStartOption := ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v) else if OutPutFlag == "d" //Delta EForwardStartOption := (ForwardStartOption(CallPutFlag, S + dS, Alpha, t1, T, r, b, v) - ForwardStartOption(CallPutFlag, S - dS, Alpha, t1, T, r, b, v)) / (2 * dS) else if OutPutFlag == "g" //Gamma EForwardStartOption := (ForwardStartOption(CallPutFlag, S + dS, Alpha, t1, T, r, b, v) - 2 * ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v) + ForwardStartOption(CallPutFlag, S - dS, Alpha, t1, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EForwardStartOption := (ForwardStartOption(CallPutFlag, S + dS, Alpha, t1, T, r, b, v + 0.01) - 2 * ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v + 0.01) + ForwardStartOption(CallPutFlag, S - dS, Alpha, t1, T, r, b, v + 0.01) - ForwardStartOption(CallPutFlag, S + dS, Alpha, t1, T, r, b, v - 0.01) + 2 * ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v - 0.01) - ForwardStartOption(CallPutFlag, S - dS, Alpha, t1, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "dddv" //DDeltaDvol EForwardStartOption := 1 / (4 * dS * 0.01) * (ForwardStartOption(CallPutFlag, S + dS, Alpha, t1, T, r, b, v + 0.01) - ForwardStartOption(CallPutFlag, S + dS, Alpha, t1, T, r, b, v - 0.01) - ForwardStartOption(CallPutFlag, S - dS, Alpha, t1, T, r, b, v + 0.01) + ForwardStartOption(CallPutFlag, S - dS, Alpha, t1, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega EForwardStartOption := (ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v + 0.01) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vp" //VegaP EForwardStartOption := v / 0.1 * (ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v + 0.01) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EForwardStartOption := (ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v + 0.01) - 2 * ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v) + ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 EForwardStartOption := ForwardStartOption(CallPutFlag, S, Alpha, t1, 1E-05, r, b, v) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v) else EForwardStartOption := ForwardStartOption(CallPutFlag, S, Alpha, t1, T - 1 / 365, r, b, v) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v) else if OutPutFlag == "r" //Rho EForwardStartOption := (ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r + 0.01, b + 0.01, v) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" //Futures Rho EForwardStartOption := (ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r + 0.01, b, v) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" //Rho2 EForwardStartOption := (ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b - 0.01, v) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" //Carry EForwardStartOption := (ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b + 0.01, v) - ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" //Speed EForwardStartOption := 1 / math.pow(dS, 3) * (ForwardStartOption(CallPutFlag, S + 2 * dS, Alpha, t1, T, r, b, v) - 3 * ForwardStartOption(CallPutFlag, S + dS, Alpha, t1, T, r, b, v) + 3 * ForwardStartOption(CallPutFlag, S, Alpha, t1, T, r, b, v) - ForwardStartOption(CallPutFlag, S - dS, Alpha, t1, T, r, b, v)) EForwardStartOption smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Asset Price Settings") srcin = input.string("Close", "Asset Price", group= "Asset 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)"]) 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 a = input.float(100., "% Alpha", group = "Basic Settings") / 100 float r = input.float(13., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(2., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(23., "% 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 startthruMonth = input.int(12, title = "Forward Start Month", minval = 1, maxval = 12, group = "Forward Start Date/Time") int startthruDay = input.int(31, title = "Forward Start Day", minval = 1, maxval = 31, group = "Forward Start Date/Time") int startthruYear = input.int(2022, title = "Forward Start Year", minval = 1970, group = "Forward Start Date/Time") int startmins = input.int(0, title = "Forward Start Minute", minval = 0, maxval = 60, group = "Forward Start Date/Time") int starthours = input.int(9, title = "Forward Start Hour", minval = 0, maxval = 24, group = "Forward Start Date/Time") int startsecs = input.int(0, title = "Forward Start Second", minval = 0, maxval = 60, group = "Forward Start Date/Time") int expirythruMonth = input.int(3, title = "Expiry Month", minval = 1, maxval = 12, group = "Expiry Date/Time") int expirythruDay = input.int(31, title = "Expiry Day", minval = 1, maxval = 31, group = "Expiry Date/Time") int expirythruYear = input.int(2023, title = "Expiry Year", minval = 1970, group = "Expiry Date/Time") int expirymins = input.int(0, title = "Expiry Minute", minval = 0, maxval = 60, group = "Expiry Date/Time") int expiryhours = input.int(9, title = "Expiry Hour", minval = 0, maxval = 24, group = "Expiry Date/Time") int expirysecs = 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 startstart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday startfinish = timestamp(startthruYear, startthruMonth, startthruDay, starthours, startmins, startsecs) starttemp = (startfinish - startstart) float T1 = (startfinish - startstart) / spyr / 1000 // precision calculation miliseconds in time intreval from time equals now expirystart = timein == "Time Now" ? timenow : timein == "Time Bar" ? time : time_tradingday expiryfinish = timestamp(expirythruYear, expirythruMonth, expirythruDay, expiryhours, expirymins, expirysecs) expirytemp = (expiryfinish - expirystart) float T = (expiryfinish - expirystart) / spyr / 1000 string txtsize = input.string("Auto", title = "Text Size", 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 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 S = 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float hvolout = switch hvoltype parkinson => parkinsonvol(histvolper) rogersatch => rogerssatchel(histvolper) c2c => closetoclose(math.log(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) bsmprice = EForwardStartOption("p", OpType, S, a, T1, T, kouta, koutb, v, na) amaproxprice = EForwardStartOption("p", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Delta = EForwardStartOption("d", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Elasticity = Delta * S / bsmprice DDeltaDvol = EForwardStartOption("dddv", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Gamma = EForwardStartOption("g", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout DGammaDvol = EForwardStartOption("gv", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Vega = EForwardStartOption("v", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout VegaP = EForwardStartOption("vp", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout DvegaDvol = EForwardStartOption("dvdv", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Theta = EForwardStartOption("t", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Rho = EForwardStartOption("r", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout RhoFuturesOption = EForwardStartOption("fr", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout PhiRho2 = EForwardStartOption("f", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Carry = EForwardStartOption("b", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout Speed = EForwardStartOption("s", OpType, S, a, T1, T, kouta, koutb, v, na) * sideout 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 = "Forward Start Options", 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(S, 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 = "% Alpha: " + str.tostring(a * 100, "##.##") + "%", 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = "Forward Start Date/Time: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", startfinish), 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/Time: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", expiryfinish), 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 = 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 = "Value: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 = "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 = 6, 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 = 7, 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 = 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 = "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 = 10, 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 = 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Moving Grid Trader - With Alerts
https://www.tradingview.com/script/n3SwWgno-Moving-Grid-Trader-With-Alerts/
starlord_xrp
https://www.tradingview.com/u/starlord_xrp/
262
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/ // © activedutyjosh //@version=5 indicator("Moving Grid Trader - Alerts", "Moving Grid Trader - Alerts", overlay=true) //direction check x=color.orange plotwidth= input(2), title="Width of EMA signel lines" len = input(21, title="short Term EMA - Default 21") src = input(close, title="Source") offset = input(0, title="Offset") out = ta.ema(src, len) if(out[1] > out[5]) //check to see if the trend is up x:=color.green else x:=color.red //plot(out, color=x, linewidth=plotwidth, title="Long MA", offset=offset) y=color.orange len2 = input(100, title="long Term EMA - Default 100") out2 = ta.ema(src, len2) if(out2[1] > out2[5]) //check to see if the trend is up y:=color.green else y:=color.red //plot(out2, color=y, linewidth=plotwidth, title="Long MA", offset=offse //macd portion fast_length = input(title="Fast Length", defval=12) slow_length = input(title="Slow Length", defval=26) src2 = 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"]) // 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(#12FF05, "Above   Grow", group="Histogram", inline="Above") col_fall_above = input(#E30909, "Fall", group="Histogram", inline="Above") col_grow_below = input(#12FF05, "Below Grow", group="Histogram", inline="Below") col_fall_below = input(#E30909, "Fall", group="Histogram", inline="Below") // Calculating fast_ma = sma_source == "SMA" ? ta.sma(src2, fast_length) : ta.ema(src2, fast_length) slow_ma = sma_source == "SMA" ? ta.sma(src2, slow_length) : ta.ema(src2, slow_length) macd = fast_ma - slow_ma MACDsignal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length) hist = macd - MACDsignal //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))) //generate variable with the color of the histogram colorCheck=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)) var openorder = false var buyposition=1000.23 minline = buyposition+(buyposition*0.00005) //0.5 cent for each 100 dollars invested line1 = buyposition+(buyposition*0.0001) //1 cent for each 100 dollars invested line2 = buyposition+(buyposition*0.0003) // 3 cent line3 = buyposition+(buyposition*0.0005) // 5 cent line4 = buyposition+(buyposition*0.0007) // 7 cent line5 = buyposition+(buyposition*0.0009) // 9 cent line6 = buyposition+(buyposition*0.0011) // 11 cent line7 = buyposition+(buyposition*0.0013) // 13 line8 = buyposition+(buyposition*0.0015) //15 line9 = buyposition+(buyposition*0.0017) line10 = buyposition+(buyposition*0.0019) line11 = buyposition+(buyposition*0.0021) //21 line12 = buyposition+(buyposition*0.0023) line13 = buyposition+(buyposition*0.0025) line14 = buyposition+(buyposition*0.0027) line15 = buyposition+(buyposition*0.0029) line16 = buyposition+(buyposition*0.0031) line17 = buyposition+(buyposition*0.0033) line18 = buyposition+(buyposition*0.0035) line19 = buyposition+(buyposition*0.0037) line20 = buyposition+(buyposition*0.0039) line21 = buyposition+(buyposition*0.0041) line22 = buyposition+(buyposition*0.0043) line23 = buyposition+(buyposition*0.0045) line24 = buyposition+(buyposition*0.0047) line25 = buyposition+(buyposition*0.0049) line26 = buyposition+(buyposition*0.0051) line27 = buyposition+(buyposition*0.0053) line28 = buyposition+(buyposition*0.0055) //55 line29 = buyposition+(buyposition*0.0057) line30 = buyposition+(buyposition*0.0059) line31 = buyposition+(buyposition*0.0061) line32 = buyposition+(buyposition*0.0063) line33 = buyposition+(buyposition*0.0065) line34 = buyposition+(buyposition*0.0067) line35 = buyposition+(buyposition*0.0069) line36 = buyposition+(buyposition*0.0071) line37 = buyposition+(buyposition*0.0071) line38 = buyposition+(buyposition*0.0073) line39 = buyposition+(buyposition*0.0075) line40 = buyposition+(buyposition*0.0077) line41 = buyposition+(buyposition*0.0079) line42 = buyposition+(buyposition*0.0081) line43 = buyposition+(buyposition*0.0083) line44 = buyposition+(buyposition*0.0085) line45 = buyposition+(buyposition*0.0087) line46 = buyposition+(buyposition*0.0089) line47 = buyposition+(buyposition*0.0091) line48 = buyposition+(buyposition*0.0093) line49 = buyposition+(buyposition*0.0095) line50 = buyposition+(buyposition*0.0097) // 97 cents line01 = buyposition+(buyposition*0.01) // 1 dollar stoploss = (buyposition-(buyposition*0.02)) //2 percent stop loss sell1 = (ta.crossunder (low, line1)) sell2 = (ta.crossunder(low, line2)) sell3 = (ta.crossunder(low, line3)) sell4 = (ta.crossunder(low, line4)) sell5 = (ta.crossunder(low, line5)) sell6 = (ta.crossunder(low, line6)) sell7 = (ta.crossunder(low, line7)) sell8 = (ta.crossunder(low, line8)) sell9 = (ta.crossunder(low, line9)) sell10 = (ta.crossunder(low, line10)) sell11 = (ta.crossunder(low, line11)) sell12 = (ta.crossunder(low, line12)) sell13 = (ta.crossunder(low, line13)) sell14 = (ta.crossunder(low, line14)) sell15 = (ta.crossunder(low, line15)) sell16 = (ta.crossunder(low, line16)) sell17 = (ta.crossunder(low, line17)) sell18 = (ta.crossunder(low, line18)) sell19 = (ta.crossunder(low, line19)) sell20 = (ta.crossunder(low, line20)) sell21 = (ta.crossunder(low, line21)) sell22 = (ta.crossunder(low, line22)) sell23 = (ta.crossunder(low, line23)) sell24 = (ta.crossunder(low, line24)) sell25 = (ta.crossunder(low, line25)) sell26 = (ta.crossunder(low, line26)) sell27 = (ta.crossunder(low, line27)) sell28 = (ta.crossunder(low, line28)) sell29 = (ta.crossunder(low, line29)) sell30 = (ta.crossunder(low, line30)) sell31 = (ta.crossunder(low, line31)) sell32 = (ta.crossunder(low, line32)) sell33 = (ta.crossunder(low, line33)) sell34 = (ta.crossunder(low, line34)) sell35 = (ta.crossunder(low, line35)) sell36 = (ta.crossunder(low, line36)) sell37 = (ta.crossunder(low, line37)) sell38 = (ta.crossunder(low, line38)) sell39 = (ta.crossunder(low, line39)) sell40 = (ta.crossunder(low, line40)) sell41 = (ta.crossunder(low, line41)) sell42 = (ta.crossunder(low, line42)) sell43 = (ta.crossunder(low, line43)) sell44 = (ta.crossunder(low, line44)) sell45 = (ta.crossunder(low, line45)) sell46 = (ta.crossunder(low, line46)) sell47 = (ta.crossunder(low, line47)) sell48 = (ta.crossunder(low, line48)) sell49 = (ta.crossunder(low, line49)) sell50 = (ta.crossunder(low, line50)) sell01 = (ta.crossunder (low, line01)) sellminline = (ta.crossunder(low, minline)) sellstoploss = (ta.crossunder(low, stoploss)) //move grid up if the price keeps climbing if (close > line50) buyposition := low-(low*0.00007) //buy and sell conditions buy=(close>open and openorder==false and (colorCheck==col_grow_below or colorCheck==col_grow_above)) sell = ((sellminline or sell01 or sell1 or sell2 or sell3 or sell4 or sell5 or sell6 or sell7 or sell8 or sell9 or sell10 or sell11 or sell12 or sell13 or sell14 or sell15 or sell16 or sell17 or sell18 or sell19 or sell20 or sell21 or sell22 or sell23 or sell24 or sell25 or sell26 or sell27 or sell28 or sell29 or sell30 or sell31 or sell32 or sell33 or sell34 or sell35 or sell36 or sell37 or sell37 or sell39 or sell40 or sell41 or sell42 or sell43 or sell44 or sell45 or sell46 or sell47 or sell48 or sell49 or sell50) and close<open and openorder) soldstop=(sellstoploss and openorder==true) eject= (low < stoploss and openorder==true) sellalert = (sell or soldstop or eject) //set buy persistant values if (buy) openorder := true buyposition := high //close order if sell alert detected if (sellalert) openorder := false //Alert conditions alertcondition(buy, title='Buy Signal', message='{ "message_type": "bot", "bot_id": 9614178, "email_token": "73f54f38-a92b-4a8d-bce8-2e16cf28922b", "delay_seconds": 0}') alertcondition(sellalert, title='Sell Signal', message='{ "action": "close_at_market_price", "message_type": "bot", "bot_id": 9614178, "email_token": "73f54f38-a92b-4a8d-bce8-2e16cf28922b", "delay_seconds": 0 }') //Plotting plot(minline, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line1, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line2, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line3, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line4, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line5, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line6, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line7, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line8, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line9, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line10, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line10, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line12, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line13, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line14, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line15, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line16, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line17, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line18, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line19, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line20, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line21, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line22, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line23, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line24, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line25, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line26, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line27, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line28, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line29, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line30, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line31, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line32, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line33, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line34, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line35, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line36, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line37, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line38, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line39, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line40, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line41, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line42, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line43, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line44, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line44, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line45, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line46, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line47, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line48, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line49, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) //plot(line50, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) plot(stoploss, color=color.red, linewidth=plotwidth, title="Stoploss", offset=offset) plot(line01, color=color.green, linewidth=plotwidth, title="Long MA", offset=offset) plotshape(buy, style=shape.labelup, title="BUY", location=location.belowbar, color=color.white, text="BUY", size=size.auto) plotshape(sell, style=shape.labeldown, location=location.abovebar, color=color.green, text="MONEY", size=size.auto) plotshape(soldstop, style=shape.labelup, location = location.belowbar, color=color.red, text="Stopploss", size=size.auto)
Moneyness Options [Loxx]
https://www.tradingview.com/script/9DHV0M0k-Moneyness-Options-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("Moneyness Options [Loxx]", shorttitle ="MO [Loxx]", overlay = true, max_lines_count = 500) if not timeframe.isdaily runtime.error("Error: Invald timeframe. Indicator only works on daily timeframe.") import loxx/cnd/1 import loxx/cbnd/1 string Continuous = "Continuous" string PeriodRate = "Period Rate" string Annual = "Annual" string SemiAnnual = "Semi-Annual" string Quaterly = "Quaterly" string Monthly = "Monthly" color darkGreenColor = #1B7E02 string callString = "Call" string putString = "Put" 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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas 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.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 MoneynessOption(float Moneyness, float T, float r, float v)=> float d1 = (-math.log(Moneyness) + v * v / 2 * T) / (v * math.sqrt(T)) float d2 = d1 - v * math.sqrt(T) float MoneynessOption = math.exp(-r * T) * (cnd.CND1(d1) - Moneyness * cnd.CND1(d2)) MoneynessOption EMoneynessOption(string OutPutFlag, float S, float T, float r, float v, float dSin)=> float dS = 0 if na(dSin) dS := 0.01 float EMoneynessOption = 0 if OutPutFlag == "p" // Value EMoneynessOption := MoneynessOption(S, T, r, v) else if OutPutFlag == "d" //Delta EMoneynessOption := (MoneynessOption(S + dS, T, r, v) - MoneynessOption(S - dS, T, r, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EMoneynessOption := (MoneynessOption(S + dS, T, r, v) - MoneynessOption(S - dS, T, r, v)) / (2 * dS) * S / MoneynessOption(S, T, r, v) else if OutPutFlag == "g" //Gamma EMoneynessOption := (MoneynessOption(S + dS, T, r, v) - 2 * MoneynessOption(S, T, r, v) + MoneynessOption(S - dS, T, r, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EMoneynessOption := (MoneynessOption(S + dS, T, r, v + 0.01) - 2 * MoneynessOption(S, T, r, v + 0.01) + MoneynessOption(S - dS, T, r, v + 0.01) - MoneynessOption(S + dS, T, r, v - 0.01) + 2 * MoneynessOption(S, T, r, v - 0.01) - MoneynessOption(S - dS, T, r, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EMoneynessOption := S / 100 * (MoneynessOption(S + dS, T, r, v) - 2 * MoneynessOption(S, T, r, v) + MoneynessOption(S - dS, T, r, v)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma EMoneynessOption := (MoneynessOption(S, T + 1 / 365, r, v) - 2 * MoneynessOption(S, T, r, v) + MoneynessOption(S, T - 1 / 365, r, v)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol EMoneynessOption := 1 / (4 * dS * 0.01) * (MoneynessOption(S + dS, T, r, v + 0.01) - MoneynessOption(S + dS, T, r, v - 0.01) - MoneynessOption(S - dS, T, r, v + 0.01) + MoneynessOption(S - dS, T, r, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega EMoneynessOption := (MoneynessOption(S, T, r, v + 0.01) - MoneynessOption(S, T, r, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EMoneynessOption := (MoneynessOption(S, T, r, v + 0.01) - 2 * MoneynessOption(S, T, r, v) + MoneynessOption(S, T, r, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP EMoneynessOption := v / 0.1 * (MoneynessOption(S, T, r, v + 0.01) - MoneynessOption(S, T, r, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EMoneynessOption := (MoneynessOption(S, T, r, v + 0.01) - 2 * MoneynessOption(S, T, r, v) + MoneynessOption(S, T, r, v - 0.01)) else if OutPutFlag == "t" //Theta if T <= 1 / 365 EMoneynessOption := MoneynessOption(S, 1E-05, r, v) - MoneynessOption(S, T, r, v) else EMoneynessOption := MoneynessOption(S, T - 1 / 365, r, v) - MoneynessOption(S, T, r, v) else if OutPutFlag == "r" //Rho EMoneynessOption := (MoneynessOption(S, T, r + 0.01, v) - MoneynessOption(S, T, r - 0.01, v)) / (2) else if OutPutFlag == "fr" //Futures options rho EMoneynessOption := (MoneynessOption(S, T, r + 0.01, v) - MoneynessOption(S, T, r - 0.01, v)) / (2) else if OutPutFlag == "s" //Speed EMoneynessOption := 1 / math.pow(dS, 3) * (MoneynessOption(S + 2 * dS, T, r, v) - 3 * MoneynessOption(S + dS, T, r, v) + 3 * MoneynessOption(S, T, r, v) - MoneynessOption(S - dS, T, r, v)) EMoneynessOption float S = input.float(120, "% Moneyness", group = "Rates Settings") / 100 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 r = input.float(8., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(30., "% 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 = "Text Size", 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 float rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float hvolout = switch hvoltype parkinson => parkinsonvol(histvolper) rogersatch => rogerssatchel(histvolper) c2c => closetoclose(math.log(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) price = EMoneynessOption("p", S, T, kouta, v, na) Delta = EMoneynessOption("d", S, T, kouta, v, na) * sideout Elasticity = EMoneynessOption("e", S, T, kouta, v, na) * sideout Gamma = EMoneynessOption("g", S, T, kouta, v, na) * sideout DGammaDvol = EMoneynessOption("gv", S, T, kouta, v, na) * sideout GammaP = EMoneynessOption("gp", S, T, kouta, v, na) * sideout Vega = EMoneynessOption("v", S, T, kouta, v, na) * sideout DvegaDvol = EMoneynessOption("dvdv", S, T, kouta, v, na) * sideout VegaP = EMoneynessOption("vp", S, T, kouta, v, na) * sideout Theta = EMoneynessOption("t", S, T, kouta, v, na) * sideout Rho = EMoneynessOption("r", S, T, kouta, v, na) * sideout RhoFuturesOption = EMoneynessOption("fr", S, T, kouta, v, na) * sideout DDeltaDvol = EMoneynessOption("dddv", S, T, kouta, v, na) * sideout Speed = EMoneynessOption("s", S, T, kouta, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 16, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Moneyness Options", 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 = "% Moneyness: " + str.tostring(S * 100, "##.##") + "%" , bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "% Risk-free Rate: " + str.tostring(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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 = 5, 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 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 = "Value: " + str.tostring(price, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 2, text = "Option Sensitivities", 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, 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 = 15, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Balanced Price Range (BPR)
https://www.tradingview.com/script/856oabwc-Balanced-Price-Range-BPR/
tradeforopp
https://www.tradingview.com/u/tradeforopp/
2,610
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("Balanced Price Range - BPR [TFO]", "BPR [TFO]", overlay = true, max_bars_back = 500, max_boxes_count = 500) bpr_threshold = input.float(0, step = 0.25, title = "BPR Threshold", tooltip = "Valid BPR's must have a range greater than this number") bars_since = input(10, "Bars to Look Back for BPR", tooltip = "Only look for BPR's when a sequence of bearish and bullish FVG's are within this many bars of each other") only_clean_bpr = input(false, "Only Clean BPR", tooltip = "Only show BPR's when price does not interfere with the range prior to its completion") delete_old_bpr = input(false, "Delete Old BPR", tooltip = "Delete all BPR's that have been invalidated or overwritten. Only show current/active BPR's") bearish_bpr_color = input.color(color.new(color.red, 70)) bullish_bpr_color = input.color(color.new(color.green, 70)) float box_high = na float box_low = na int box_left = 0 int box_right = 0 var box box_bearish = na var box box_bullish = na new_fvg_bearish = low[2] - high > 0 new_fvg_bullish = low - high[2] > 0 valid_high = high[1] > high[2] and high[1] > high[0] valid_low = low[1] < low[2] and low[1] < low[0] midline = (high - low) / 2 + low valid_hammer = open > midline and close > midline valid_shooter = open < midline and close < midline // Bullish BPR bull_num_since = ta.barssince(new_fvg_bearish) bull_bpr_cond_1 = new_fvg_bullish and bull_num_since <= bars_since bull_bpr_cond_2 = bull_bpr_cond_1 ? high[bull_num_since] + low[bull_num_since + 2] + high[2] + low > math.max(low[bull_num_since + 2], low) - math.min(high[bull_num_since], high[2]) : na bull_combined_low = bull_bpr_cond_2 ? math.max(high[bull_num_since], high[2]) : na bull_combined_high = bull_bpr_cond_2 ? math.min(low[bull_num_since + 2], low) : na bull_bpr_cond_3 = true if only_clean_bpr for h = 2 to (bull_num_since) if high[h] > bull_combined_low bull_bpr_cond_3 := false bull_result = bull_bpr_cond_1 and bull_bpr_cond_2 and bull_bpr_cond_3 and (bull_combined_high - bull_combined_low >= bpr_threshold) if bull_result[1] if delete_old_bpr and not na(box_bullish) box.delete(box_bullish) box_bullish := box.new(bar_index - bull_num_since - 1, bull_combined_high[1], bar_index + 1, bull_combined_low[1], border_color = bullish_bpr_color, border_width = 1, bgcolor = bullish_bpr_color) alertcondition(bull_result[1], "Bullish Alert", "New Bullish BPR") if not na(box_bullish) and low > box.get_bottom(box_bullish) box.set_right(box_bullish, bar_index + 1) else if not na(box_bullish) and low < box.get_bottom(box_bullish) if delete_old_bpr box.delete(box_bullish) else box_bullish := na // Bearish BPR bear_num_since = ta.barssince(new_fvg_bullish) bear_bpr_cond_1 = new_fvg_bearish and bear_num_since <= bars_since bear_bpr_cond_2 = bear_bpr_cond_1 ? high[bear_num_since] + low[bear_num_since + 2] + high[2] + low > math.max(low[bear_num_since + 2], low) - math.min(high[bear_num_since], high[2]) : na bear_combined_low = bear_bpr_cond_2 ? math.max(high[bear_num_since + 2], high) : na bear_combined_high = bear_bpr_cond_2 ? math.min(low[bear_num_since], low[2]) : na bear_bpr_cond_3 = true if only_clean_bpr for h = 2 to (bear_num_since) if low[h] < bear_combined_high bear_bpr_cond_3 := false bear_result = bear_bpr_cond_1 and bear_bpr_cond_2 and bear_bpr_cond_3 and (bear_combined_high - bear_combined_low >= bpr_threshold) if bear_result[1] if delete_old_bpr and not na(box_bearish) box.delete(box_bearish) box_bearish := box.new(bar_index - bear_num_since - 1, bear_combined_high[1], bar_index + 1, bear_combined_low[1], border_color = bearish_bpr_color, border_width = 1, bgcolor = bearish_bpr_color) alertcondition(bear_result[1], "Bearish Alert", "New Bearish BPR") if not na(box_bearish) and high < box.get_top(box_bearish) box.set_right(box_bearish, bar_index + 1) else if not na(box_bearish) and high > box.get_top(box_bearish) if delete_old_bpr box.delete(box_bearish) else box_bearish := na
American Approximation: Barone-Adesi and Whaley [Loxx]
https://www.tradingview.com/script/2NDydZJQ-American-Approximation-Barone-Adesi-and-Whaley-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("American Approximation: Barone-Adesi and Whaley [Loxx]", shorttitle ="AABAW [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 import loxx/cbnd/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 convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out GBlackScholes(string CallPutFlag, float S, float x, float T, float r, float b, float v)=> float gBlackScholes = 0 float d1 = (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float 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 // Newton Raphson algorithm to solve for the critical commodity price for a Put Kp(float X, float T, float r, float b, float v)=> // Calculation of seed value, Si float N = 2 * b / math.pow(v, 2) float m = 2 * r / math.pow(v, 2) float q1u = (-(N - 1) - math.sqrt(math.pow(N - 1, 2) + 4 * m)) / 2 float su = X / (1 - 1 / q1u) float h1 = (b * T - 2 * v * math.sqrt(T)) * X / (X - su) float Si = su + (X - su) * math.exp(h1) float k = 2 * r / (math.pow(v, 2) * (1 - math.exp(-r * T))) float d1 = (math.log(Si / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float Q1 = (-(N - 1) - math.sqrt(math.pow(N - 1, 2) + 4 * k)) / 2 float LHS = X - Si float RHS = GBlackScholes(putString, Si, X, T, r, b, v) - (1 - math.exp((b - r) * T) * cnd.CND1(-d1)) * Si / Q1 float bi = -math.exp((b - r) * T) * cnd.CND1(-d1) * (1 - 1 / Q1) - (1 + math.exp((b - r) * T) * ND(-d1) / (v * math.sqrt(T))) / Q1 float E = 1E-06 float Kp = 0 // Newton Raphson algorithm for finding critical price Si while math.abs(LHS - RHS) / X > E Si := (X - RHS + bi * Si) / (1 + bi) d1 := (math.log(Si / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) LHS := X - Si RHS := GBlackScholes(putString, Si, X, T, r, b, v) - (1 - math.exp((b - r) * T) * cnd.CND1(-d1)) * Si / Q1 bi := -math.exp((b - r) * T) * cnd.CND1(-d1) * (1 - 1 / Q1) - (1 + math.exp((b - r) * T) * cnd.CND1(-d1) / (v * math.sqrt(T))) / Q1 Kp := Si Kp // Newton Raphson algorithm to solve for the critical commodity price for a Call Kc(float X, float T, float r, float b, float v)=> // Calculation of seed value, Si float N = 2 * b / math.pow(v, 2) float m = 2 * r / math.pow(v, 2) float q2u = (-(N - 1) + math.sqrt(math.pow(N - 1, 2) + 4 * m)) / 2 float su = X / (1 - 1 / q2u) float h2 = -(b * T + 2 * v * math.sqrt(T)) * X / (su - X) float Si = X + (su - X) * (1 - math.exp(h2)) float k = 2 * r / (math.pow(v, 2) * (1 - math.exp(-r * T))) float d1 = (math.log(Si / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float Q2 = (-(N - 1) + math.sqrt(math.pow(N - 1, 2) + 4 * k)) / 2 float LHS = Si - X float RHS = GBlackScholes(callString, Si, X, T, r, b, v) + (1 - math.exp((b - r) * T) * cnd.CND1(d1)) * Si / Q2 float bi = math.exp((b - r) * T) * cnd.CND1(d1) * (1 - 1 / Q2) + (1 - math.exp((b - r) * T) * cnd.CND1(d1) / (v * math.sqrt(T))) / Q2 float E = 1E-06 float Kc = 0 // Newton Raphson algorithm for finding critical price Si while math.abs(LHS - RHS) / X > E Si := (X + RHS - bi * Si) / (1 - bi) d1 := (math.log(Si / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) LHS := Si - X RHS := GBlackScholes(callString, Si, X, T, r, b, v) + (1 - math.exp((b - r) * T) * cnd.CND1(d1)) * Si / Q2 bi := math.exp((b - r) * T) * cnd.CND1(d1) * (1 - 1 / Q2) + (1 - math.exp((b - r) * T) * ND(d1) / (v * math.sqrt(T))) / Q2 Kc := Si Kc // American call BAWAmericanCallApprox(float S, float X, float T, float r, float b, float v)=> float Sk = 0 float BAWAmericanCallApprox = 0 if b >= r BAWAmericanCallApprox := GBlackScholes(callString, S, X, T, r, b, v) else Sk := Kc(X, T, r, b, v) float N = 2 * b / math.pow(v, 2) float k = 2 * r / (math.pow(v, 2) * (1 - math.exp(-r * T))) float d1 = (math.log(Sk / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float Q2 = (-(N - 1) + math.sqrt(math.pow(N - 1, 2) + 4 * k)) / 2 float a2 = (Sk / Q2) * (1 - math.exp((b - r) * T) * cnd.CND1(d1)) if S < Sk BAWAmericanCallApprox := GBlackScholes(callString, S, X, T, r, b, v) + a2 * math.pow(S / Sk, Q2) else BAWAmericanCallApprox := S - X BAWAmericanCallApprox // American put BAWAmericanPutApprox(float S, float X, float T, float r, float b, float v)=> float Sk = Kp(X, T, r, b, v) float N = 2 * b / math.pow(v, 2) float k = 2 * r / (math.pow(v, 2) * (1 - math.exp(-r * T))) float d1 = (math.log(Sk / X) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float Q1 = (-(N - 1) - math.sqrt(math.pow(N - 1, 2) + 4 * k)) / 2 float a1 = -(Sk / Q1) * (1 - math.exp((b - r) * T) * cnd.CND1(-d1)) float BAWAmericanPutApprox = 0 if S > Sk BAWAmericanPutApprox := GBlackScholes(putString, S, X, T, r, b, v) + a1 * math.pow(S / Sk, Q1) else BAWAmericanPutApprox := X - S BAWAmericanPutApprox // The Barone-Adesi and Whaley (1987) American approximation BAWAmericanApprox(string CallPutFlag, float S, float X, float T, float r, float b, float v)=> float BAWAmericanApprox = 0 if CallPutFlag == callString BAWAmericanApprox := BAWAmericanCallApprox(S, X, T, r, b, v) else BAWAmericanApprox := BAWAmericanPutApprox(S, X, T, r, b, v) BAWAmericanApprox EBAWAmericanApprox(string OutPutFlag, string CallPutFlag, float S, float X, float T, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EBAWAmericanApprox = 0 if OutPutFlag =="p" // ' Value EBAWAmericanApprox := BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "d" // 'Delta EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / (2 * dS) else if OutPutFlag =="e" // 'Elasticity EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / (2 * dS) * S / BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag =="g" // 'Gamma EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag =="gv" // 'DGammaDVol EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v + 0.01) - 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) + BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v + 0.01) - BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v - 0.01) + 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01) - BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag =="gp" // 'GammaP EBAWAmericanApprox := S / 100 * (BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag =="tg" // 'time Gamma EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T + 1 / 365, r, b, v) - 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BAWAmericanApprox(CallPutFlag, S, X, T - 1 / 365, r, b, v)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" // 'DDeltaDvol EBAWAmericanApprox := 1 / (4 * dS * 0.01) * (BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v + 0.01) - BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v - 0.01) - BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v + 0.01) + BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" // 'Vega EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" // 'DvegaDvol/vomma EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" // 'VegaP EBAWAmericanApprox := v / 0.1 * (BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" // 'DvegaDvol EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) else if OutPutFlag == "t" // 'Theta if T <= (1 / 365) EBAWAmericanApprox := BAWAmericanApprox(CallPutFlag, S, X, 1E-05, r, b, v) - BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) else EBAWAmericanApprox := BAWAmericanApprox(CallPutFlag, S, X, T - 1 / 365, r, b, v) - BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag =="r" // 'Rho EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T, r + 0.01, b + 0.01, v) - BAWAmericanApprox(CallPutFlag, S, X, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag =="fr" // 'Futures options rho EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T, r + 0.01, b, v) - BAWAmericanApprox(CallPutFlag, S, X, T, r - 0.01, b, v)) / 2 else if OutPutFlag =="f" // 'Rho2 EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T, r, b - 0.01, v) - BAWAmericanApprox(CallPutFlag, S, X, T, r, b + 0.01, v)) / 2 else if OutPutFlag =="b" // 'Carry EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X, T, r, b + 0.01, v) - BAWAmericanApprox(CallPutFlag, S, X, T, r, b - 0.01, v)) / 2 else if OutPutFlag =="s" // 'Speed EBAWAmericanApprox := 1 / math.pow(dS, 3) * (BAWAmericanApprox(CallPutFlag, S + 2 * dS, X, T, r, b, v) - 3 * BAWAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) + 3 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) - BAWAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) else if OutPutFlag =="dx" // 'Strike Delta EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X + dS, T, r, b, v) - BAWAmericanApprox(CallPutFlag, S, X - dS, T, r, b, v)) / (2 * dS) else if OutPutFlag =="dxdx" // 'Strike Gamma EBAWAmericanApprox := (BAWAmericanApprox(CallPutFlag, S, X + dS, T, r, b, v) - 2 * BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BAWAmericanApprox(CallPutFlag, S, X - dS, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag =="di" // 'Difference in value between BS Approx and Black-Scholes Merton value EBAWAmericanApprox := BAWAmericanApprox(CallPutFlag, S, X, T, r, b, v) - GBlackScholes(CallPutFlag, S, X, T, r, b, v) EBAWAmericanApprox 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 r = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) bsmprice = GBlackScholes(OpType, S, K, T, kouta, koutb, v) amaproxprice = EBAWAmericanApprox("p", OpType, S, K, T, kouta, koutb, v, na) * sideout Delta = EBAWAmericanApprox("d", OpType, S, K, T, kouta, koutb, v, na) * sideout Elasticity = EBAWAmericanApprox("e", OpType, S, K, T, kouta, koutb, v, na) * sideout Gamma = EBAWAmericanApprox("g", OpType, S, K, T, kouta, koutb, v, na) * sideout DGammaDvol = EBAWAmericanApprox("gv", OpType, S, K, T, kouta, koutb, v, na) * sideout GammaP = EBAWAmericanApprox("gp", OpType, S, K, T, kouta, koutb, v, na) * sideout Vega = EBAWAmericanApprox("v", OpType, S, K, T, kouta, koutb, v, na) * sideout DvegaDvol = EBAWAmericanApprox("dvdv", OpType, S, K, T, kouta, koutb, v, na) * sideout VegaP = EBAWAmericanApprox("vp", OpType, S, K, T, kouta, koutb, v, na) * sideout Theta = EBAWAmericanApprox("t", OpType, S, K, T, kouta, koutb, v, na) * sideout Rho = EBAWAmericanApprox("r", OpType, S, K, T, kouta, koutb, v, na) * sideout RhoFuturesOption = EBAWAmericanApprox("fr", OpType, S, K, T, kouta, koutb, v, na) * sideout PhiRho2 = EBAWAmericanApprox("f", OpType, S, K, T, kouta, koutb, v, na) * sideout Carry = EBAWAmericanApprox("b", OpType, S, K, T, kouta, koutb, v, na) * sideout DDeltaDvol = EBAWAmericanApprox("dddv", OpType, S, K, T, kouta, koutb, v, na) * sideout Speed = EBAWAmericanApprox("s", OpType, S, K, T, kouta, koutb, v, na) * sideout StrikeDelta = EBAWAmericanApprox("dx", OpType, S, K, T, kouta, koutb, v, na) * sideout StrikeGamma = EBAWAmericanApprox("dxdx", OpType, S, K, T, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 21, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "American Approximation: Barone-Adesi and Whaley", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 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 = "American Approximation Price: " + str.tostring(amaproxprice, 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 = "Black-Scholes-Merton Value: " + str.tostring(bsmprice, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 3, text = "Option Sensitivities", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 4, 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 = 5, 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 1, row = 14, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 16, 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 = 1, row = 17, 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 = 18, 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 = 19, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 20, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
[FriZz]Watermark
https://www.tradingview.com/script/K83leyVY-FriZz-Watermark/
FFriZz
https://www.tradingview.com/u/FFriZz/
147
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('[FFriZz]Watermark', '', true) string ypos = input.string('top', 'Position', inline='pos', options=['top', 'middle', 'bottom']) int UTC = input.int(-5,'UTC',minval=-18,maxval = 18,group = 'Time Adjust') string xpos = input.string('right', '', inline='pos', options=['left', 'right', 'center']) string tok = input.session('1900-0400','Tokyo',group='Sessions',inline='') string lon = input.session('0200-1100','London',group='Sessions',inline='') string ny = input.session('0800-1700','New York',group='Sessions',inline='') string sesclosed = input.session('1600-1900','Sessions Closed',group='Sessions',inline='') string tva1 = input.string(text.align_center,'Textbox #1',group = 'Text align/Size',inline = 'tb1',options = [text.align_top, text.align_center, text.align_bottom]) string tha1 = input.string(text.align_center,'',group = 'Text align/Size',inline = 'tb1',options = [text.align_left, text.align_center, text.align_right]) string tva12 = input.string(text.align_center,'Textbox #2',group = 'Text align/Size',inline = 'tb2',options = [text.align_top, text.align_center, text.align_bottom]) string tha12 = input.string(text.align_center,'',group = 'Text align/Size',inline = 'tb2',options = [text.align_left, text.align_center, text.align_right]) string textsize1 = input.string('normal', '',inline = 'tb1',group = 'Text align/Size', options=['tiny', 'small', 'normal', 'large', 'huge', 'auto']) string textsize2 = input.string('normal', '',inline = 'tb2',group = 'Text align/Size', options=['tiny', 'small', 'normal', 'large', 'huge', 'auto']) color color = input(color.new(#000000, transp=0),'TextBox 1',group = 'Text Colors') color color2 = input(color.new(#000000, transp=0),'TextBox 2',group = 'Text Colors') //[ string ticker2 = input.symbol('BTCUSDTPERP','Ticker2',group = 'Extra Ticker') string t2 = array.get(str.split(ticker2,':'),1) string exampleBox = input.text_area('EXAMPLES USE BOXES BELOW\nBy: [FrizLabz] | Options▼▼▼ Can use TextBox 1 or 2 all boxes can have different color text\nUse the words at the bottom of this box Case matched and Spelled correctly it will only replace the word so you can use whatever else youd like as long the word is correct\nSpecial Chars. @ Bottom\n\nOptions\n----------------\nTF\nTicker\nTicker2\nVolume\nOpen\nClose\nHigh\nLow\nDay\nDate\nTime\nSession\nSessionTime','EXAMPLES/INTRUCTIONS',group = '') string textbox1 = input.text_area('@FFriZz | FrizLabz','TextBox 1',group = '') string textbox2 = input.text_area('Date\nTicker | TF\nSession | Time','TextBox 2',group = '') string texttt = input.text_area( '𝓪𝓫𝓬𝓭𝓮𝓯𝓰𝓱𝓲𝓳𝓴𝓵𝓶𝓷𝓸𝓹𝓺𝓻𝓼𝓽𝓾𝓿𝔀𝔁𝔂𝔃'+ 'abcdefghijklmnopqrstuvwxyz'+ '🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿'+ '🅐🅑🅒🅓🅔🅕🅖🅗🅘🅙🅚🅛🅜🅝🅞🅟🅠🅡🅢🅣🅤🅥🅦🅧🅨🅩'+ 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'+ '𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵'+ '𝓐𝓑𝓒𝓓𝓔𝓕𝓖𝓗𝓘𝓙𝓚𝓛𝓜𝓝𝓞𝓟𝓠𝓡𝓢𝓣𝓤𝓥𝓦𝓧𝓨𝓩'+ '𝓪𝓫𝓬𝓭𝓮𝓯𝓰𝓱𝓲𝓳𝓴𝓵𝓶𝓷𝓸𝓹𝓺𝓻𝓽𝓾𝓿𝔀𝔁𝔂𝔃'+ '𝐚𝐛𝐜𝐝𝐞𝐟𝐠𝐡𝐢𝐣𝐤𝐥𝐦𝐧𝐨𝐩𝐪𝐫𝐬𝐭𝐮𝐯𝐰𝐱𝐲𝐳'+ '𝕒𝕓𝕔𝕕𝕖𝕗𝕘𝕙𝕚𝕛𝕜𝕝𝕞𝕟𝕠𝕡𝕢𝕣𝕤𝕥𝕦𝕧𝕨𝕩𝕪𝕫'+ 'ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ'+ '𝕬𝕭𝕮𝕯𝕰𝕱𝕲𝕳𝕴𝕵𝕶𝕷𝕸𝕹𝕺𝕻𝕼𝕽𝕾𝕿𝖀𝖁𝖂𝖃𝖄𝖅'+ '↦↧↨↩↪↫↬↭↮↯↰↱↲↳↴↶↷↸↹↺↻⟳↼↽↾↿⇀⇁⇂⇃⇄⇅⇆⇇㊊㊋㊌㊍㊎㊏㊐㊑㊒㊓㊔㊕㊖㊗㊘㊙㊚㊛㊜㊝㊞㊟㊠㊡㊢㊣㊤㊥㊦㊧㊨㊩㊪㊫㊬㊭㊮㊯㊰☠⚰☤☥☦☧☨☩☪☫☬☮☭☯☸☽☾✙✚✛✜✝▒▓░'+ '▁▂▄▅▆▇██▇▆▅▄▂▁'+ '•·∙⊙⊚⊛◉○◌◍◎●◘◦。☉⦾⦿⁃⁌⁍◆◇◈★☆■□☐☑☒✓✔❖'+ 'ϟ☽☾ϟ☽☾〔〕︽︾〖〗〘〙〚〛《》♔♕♖♗♘♙♚♛♜♝♞♟♤♠♧♣♡♥♢♦↕↖↗↘↙↚↛↜↝↞↟↠↡↢↣↤↥↦↧↨↩↪↫↬↭↮↯↰↱↲↳↴↶↷↸↹↺↻↼↽↾↿⇀⇁⇂⇃⇄⇅⇆⇇⇈⇉⇊⇋⇌⇍⇎⇏⇕⇖⇗⇘⇙⇚⇛⇜⇝⇞⇟⇠⇡⇢⇣⇤⇥⇦⇧⇨⇩⇪⌅⌆⌤⏎▶☇☈☊☋☌☍➔➘➙➚➛➜➝➞➟➠➡➢➣➤➥➦'+ '➧➨➩➪➫➬➭➮➯➱➲➳➴➵➶➷➸➹➺➻➼➽➾⤴⤵↵↓↔←→↑⌦⌫⌧⇰⇫⇬⇭⇳⇮⇯⇱⇲⇴⇵⇷⇸⇹⇺⇑⇓⇽⇾⇿⬳⟿⤉⤈⇻⇼⬴⤀⬵⤁⬹⤔⬺⤕⬶⤅⬻⤖⬷⤐⬼⤗⬽⤘⤝⤞⤟⤠⤡⤢⤣⤤⤥⤦⤪⤨⤧⤩⤭⤮⤯⤰⤱⤲⤫⤬⬐⬎⬑⬏⤶⤷⥂⥃⥄⭀⥱⥶⥸⭂⭈⭊⥵⭁⭇⭉⥲⭋⭌⥳⥴⥆⥅⥹⥻⬰⥈⬾⥇⬲⟴⥷⭃⥺⭄⥉⥰⬿⤳⥊⥋⥌⥍⥎⥏⥐⥑⥒⥓⥔⥕⥖⥗⥘⥙⥚⥛⥜⥝⥞⥟⥠⥡⥢⥤⥣'+ '⥥⥦⥨⥧⥩⥮⥯⥪⥬⥫⥭⤌⤍⤎⤏⬸⤑⬱⟸⟹⟺⤂⤃⤄⤆⤇⤊⤋⭅⭆⟰⟱⇐⇒⇔⇶⟵⟶⟷⬄⬀⬁⬂⬃⬅⬆⬇⬈⬉⬊⬋⬌⬍⟻⟼⤒⤓⤙⤚⤛⤜⥼⥽⥾⥿⤼⤽⤾⤿⤸⤺⤹⤻⥀⥁⟲⟳☮☸♈♉☪♊♋♌♍♎♏♐♑♒♓☤☥☧☨☩☫☬☭☯☽☾✙✚✛✜✝✞✟†⊹‡♁♆❖♅✠✡✢〷☠☢☣☦π∞Σ√∛∜∫∬∭∮∯∰∱∲∳∀∁∂∃∄∅∆∇∈∉∊∋∌∍∎∏∐∑−∓∔∕∖∗∘∙∝∟∠∡∢∣∤∥∦∧∨∩∪∴∵∶∷∸∹∺∻∼∽∾∿≀≁≂≃≄≅≆≇≈≉≊≋≌≍≎≏≐≑≒≓'+ '≔≕≖≗≘≙≚≛≜≝≞≟≠≡≢≣≤≥≦≧≨≩≪≫≬≭≮≯≰≱≲≳≴≵≶≷≸≹≺≻≼≽≾≿⊀⊁⊂⊃⊄⊅⊆⊇⊈⊉⊊⊋⊌⊍⊎⊏⊐⊑⊒⊓⊔⊕⊖⊗⊘⊙⊚⊛⊜⊝⊞⊟⊠⊡⊢⊣⊤⊥⊦⊧⊨⊩⊪⊫⊬⊭⊮⊯⊰⊱⊲⊳⊴⊵⊶⊷⊸⊹⊺⊻⊼⊽⊾⊿⋀⋁⋂⋃⋄⋅⋆⋇⋈⋉⋊⋋⋌⋍⋎⋏⋐⋑⋒⋓⋔⋕⋖⋗⋘⋙⋚⋛⋜⋝⋞⋟⋠⋡⋢⋣⋤⋥⋦⋧⋨⋩⋪⋫⋬⋭⋮⋯⋰⋱⁺⁻⁼⁽⁾ⁿ₊₋₌₍₎✖﹢﹣+-/=÷±×ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿↀↁↂ➀➁➂➃➄➅➆➇➈➉➊➋➌➍➎➏➐➑➒➓⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾⓿❶❷❸❹❺❻❼❽❾❿⁰¹²³⁴⁵⁶⁷⁸⁹₀'+ '₁₂₃₄₅₆₇₈₉⓪①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩㊀㊁㊂㊃㊄㊅㊆㊇㊈㊉01234'+ '56789ⁱₐₑₒₓₔ❏❐❑❒▀▁▂▃▄▅▆▇▉▊▋█▌▐▍▎▏▕░▒▓▔▬▢▣▤▥▦▧▨▩▪▫▭▮▯☰☲☱☴☵☶☳☷▰▱◧◨◩◪◫∎■□⊞⊟⊠⊡❘❙❚〓◊◈◇◆⎔⎚☖☗◄▲▼►◀◣◥◤◢▶◂'+ '▴▾▸◁△▽▷∆∇⊳⊲⊴⊵◅▻▵▿◃▹◭◮⫷⫸⋖⋗⋪⋫⋬⋭⊿◬≜⑅│┃╽'+ '╿╏║╎┇︱┊︳┋┆╵〡〢╹╻╷〣☰☱☲☳☴☵☶☷≡✕═━─╍┅┉┄┈╌╴╶╸╺╼╾﹉﹍﹊﹎︲⑆'+ '⑇⑈⑉⑊⑄⑀︴﹏﹌﹋╳╲╱︶︵〵〴〳〆`ᐟ‐⁃⎯〄﹄﹃﹂﹁┕┓└┐┖┒┗┑┍┙┏┛┎┚┌┘「」『』˩˥├┝┞┟┠┡┢┣┤┥┦'+ '┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╒╕╓╖╔╗╘╛╙╜╚╝╞╡╟╢╠╣╥╨╧╤╦╩╪╫╬〒⊢⊣⊤⊥╭╮╯╰⊦⊧⊨⊩⊪⊫⊬⊭⊮⊯⊺〦〧〨˦˧˨⑁⑂⑃∟◉○◌◍◎●◐◑◒◓◔◕◖◗❂☢⊗⊙◘◙◚◛◜◝◞◟◠◡◯〇〶⚫⬤◦∅∘⊕⊖⊘⊚⊛⊜⊝❍⦿😂😄😃😀😊😉😍😘😚'+ '😗😙😜😝😛😳😁😔😌😒😞😣😢😭😪😥😰😅😓😩😫😨😱😠😡😤😖😆😋😷😎😴😵😲😟😦😧😈👿😮😬😐😕😯😶😇☺️😏😑🙃🙄☹️🤐🤑🤒🤓🤔🤕🙁🙂🤗🤣🤠🤥🤤🤢🤧🤡🤖🖤💛💙💜💚🧡❤️️💔💗💓💕💖💞💘💝❣️💌💋😺😸😻😽😼🙀😿😹😾🙈🙉🙊💀👽👹👺🤩🤨🥺️🤯🤪🤬🤮🤫🤭🧐🥰️🥵️🥶️🥴️♾️♀️♂️⚧️⚕️➰➿💲💱©️®️™️〰️🔠🔡🔤ℹ️🆗🆕🆙🆒🆓🆖📶🎦🚻🚹🚺🚼🚾🚮🅿️♿️Ⓜ️🛂🛄🛅🛃🆑🆘🆚🚫🚭🔞📵🚯🚱🚳🚷🚸⛔️⚠️🛑🚧✳️❇️❎✅✴️💟📳📴🅰️🅱️🆎🅾️💠♻️🏧🚰💹〽️❌⭕️❗️❓❕❔🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕖🕗🕘🕙🕚🕡🕢🕣🕤🕥🕦🔟🔢#️⃣🔣⏭⏮⏯*️⃣⏸⏹⏺⏏️☢️☣️➕➖✖️➗♥️♦️♣️♠️💮💯💫💥💢💦💤💨✔️☑️🔘🔗🔱🔲🔳⬜️⬛️◼️◻️◾️◽️▪️▫️🔺⚫️⚪️🔴🔵🔻🔶🔷🔸🔹⁉️‼️🔰🆔*️⃣🛗☮️🛐🕎✝'+ '️✡️☦️☪️☯️☸️⚛️♈️♉️♊️♋️♌️♍️♎️♏️♐️♑️♒️♓️⛎🔯🈁🈯️🈳🈵🈴🈲🉐🈹🈺🈶🈚️🈷️🈸🈂️🉑㊙️㊗️☕️🍵🍶🍺🍻🍸🍹🍷🍴🍕🍔🍟🍗🍖🍝🍛🍤🍱🍣🍥🍙🍘🍚🍜🍲🍢🍡🍳🍞🍩🍮🍦🍨🍧🎂🍰🍪🍫🍬🍭🍯🍎🍏🍊🍋🍒🍇🍉🍓🍑🍈🍌🍐🍍🍠🍆🍅🌽🌶🌭🌮🌯🍾🍿🥝🥑🥔🥕🥒🥜🥐🥖🥞🥓🥙🥚🥘🥗🥛🥥🥦🥨🥩🥪🥣🥫🥟🥠🥡🥧🥤🥢🥭️🥬️🥯️🧂️🥮️🦞️🧁️👍👎👌👊✊✌️👋✋👐👆👇👉👈🙌🙏💪🖖🖐☝️👏✍️🤘🖕🤞🤙🤛🤜🤚🤝🤟🤲🏴󠁧󠁢󠁥󠁮󠁧󠁿🏴󠁧󠁢󠁳󠁣󠁴󠁿🏴󠁧󠁢󠁷󠁬󠁳󠁿🇺🇳🚩🏳🏴🏳️‍🌈🏴‍☠️️🎲🎯'+ '🏈🏀️⚽️⚾️🎾🎱🏉🎳️⛳️🏁🏇🏆⛷⛸🏏🏐🏑🏒🏓🏸🏹🏂🏍🏎🤺🥅🥇🥈🥉🥊🥋🤼🤼‍♂️🎣🥌🐶🐺🐱🐭🐹🐰🐸🐯🐨🐻🐷🐽🐮🐗🐵🐒🐴🐑🐘🐼🐧🐦🐤🐥🐣🐔🐍🐢🐛🐝🐜🐿🐞🐌🐙🐚🐠🐟🐬🐳🐋🐄🐏🐀🐃🐅🐇🐉🐎🐐🐓🐕🐖🐁🐂🐲🐡🐊🐫🐪🐆🐈🐩🐾🦀🦁🦂🕷🦃🦄🦐🦑🦋🦍🦊🦌🦏🦇🦅🦆🦉🦎🦈🦓🦒🦔🦕🦖🦝️🦙️🦛️🦘️🦡️🦢️🦚️🦜️🦟️🐻‍❄️🦭🐃🪱🦬🪳🦣🦤🐈‍⬛' ,'Special Chars.',group='')//] string fDay = input.string('E', 'Formatting | Day:',inline = 'f',group = 'Formatting',tooltip = 'You can google Java Date Formatting for Examples\n 12h clock use hh \n24h clock use HH') string fDate = input.string('MM/dd/yy', 'Date:',inline = 'f',group = 'Formatting') string fTime = input.string('hh:mm:ssa', 'Time:',inline = 'f',group = 'Formatting') //////////////////////////////////////////////////////////////////////////////// timeSes(ses,int = 1) => str = '' if int == 1 str := str.substring(ses,0,4) if int == 2 str := str.substring(ses,4,9) str Time(Unix, format) => str.format("{0,time," + format + "}", int(Unix)) string tfm = '' tfs = timeframe.in_seconds() if tfs < 60 tfm := str.tostring(tfs) + 's' if tfs >= 60 tfm := timeframe.period + 'm' if timeframe.isminutes if tfs >= (60 * 60) tfm := str.tostring(str.tonumber(timeframe.period) / 60) + 'h' if timeframe.isdwm tfm := timeframe.period //////////////////////////////////////////////////////////////////////////////// string utcStr = '' if UTC > 0 utcStr := 'UTC+' + str.tostring(UTC) if UTC <= 0 utcStr := 'UTC' + str.tostring(UTC) int Tok = time('', tok,utcStr) int Lon = time('', lon,utcStr) int Ny = time('', ny,utcStr) int Sesclosed = time('', sesclosed,utcStr) var Session = '' var session = '' var sessionTime = '' if Tok Session := 'Tokyo | ' + tok session := 'Tokyo' sessionTime := tok if Lon Session := 'London | ' + lon session := 'London' sessionTime := lon if Ny Session := 'New York | ' + ny session := 'New York' sessionTime := ny if Tok and Lon Session := 'Tokyo/London OverLap | ' + timeSes(tok) + timeSes(lon,2) session := 'Tokyo/London' sessionTime := timeSes(lon) + timeSes(tok,2) if Lon and Ny Session := 'London/New York OverLap | ' + timeSes(lon) + timeSes(ny,2) session := 'London/New York' sessionTime := timeSes(ny) + timeSes(lon,2) if Sesclosed Session := 'SessionsClosed | ' + sesclosed session := 'Closed' sessionTime := sesclosed //////////////////////////////////////////////////////////////////////////////// close2 = request.security(ticker2,'',close) UTC := UTC * 3600000 strReplace(textbox) => str = textbox str := str.replace_all(str,'Volume',str.tostring(volume)) str := str.replace_all(str,'Open',str.tostring(open)) str := str.replace_all(str,'Close',str.tostring(close)) str := str.replace_all(str,'High',str.tostring(high)) str := str.replace_all(str,'Low',str.tostring(low)) str := str.replace_all(str,'Ticker2',t2 + ': ' +str.tostring(close2)) str := str.replace_all(str,'Ticker',syminfo.ticker) str := str.replace_all(str,'TF',str.tostring(tfm)) str := str.replace_all(str,'Day',Time(timenow + UTC,fDay)) str := str.replace_all(str,'Date',Time(timenow + UTC,fDate)) str := str.replace_all(str,'Time',Time(timenow + UTC,fTime)) str := str.replace_all(str,'Session',session) str := str.replace_all(str,'SessionTime',sessionTime) str //////////////////////////////////////////////////////////////////////////////// tn = Time(timenow + UTC,'HH:mm:ssa') + '\nCurrent Session: ' + Session var table Table = table.new(ypos + '_' + xpos, 2, 1) if barstate.islast table.cell(Table, 0, 0,strReplace(textbox1), 0, 0, color, text_size = textsize1 ,text_valign = tva1,text_halign = tha1) table.cell(Table, 1, 0,strReplace(textbox2), 0, 0,text_color = color2,text_halign = tha12,text_valign = tva12,text_size = textsize2, tooltip = '------------------- Sessions🕧 -----------------\n' + '-- Tokyo: '+ tok + '\n-- Tokyo/London overlap: '+ timeSes(lon) + timeSes(tok,2) + '\n-- London: '+ lon + '\n-- NY/London overlap: '+ timeSes(ny) + timeSes(lon,2) + '\n-- New York: '+ ny + '\n-- Sessions Closed: '+ sesclosed + '\n------------------------------------\nTime: ' + tn + '\n------------------------------------')
Perpetual American Options [Loxx]
https://www.tradingview.com/script/cW7TWLlK-Perpetual-American-Options-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("Perpetual American Options [Loxx]", shorttitle ="PMO [Loxx]", 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 import loxx/cnd/1 import loxx/cbnd/1 color darkGreenColor = #1B7E02 string callString = "Call" string putString = "Put" string Continuous = "Continuous" string Annual = "Annual" string SemiAnnual = "Semi-Annual" string Quaterly = "Quaterly" string Monthly = "Monthly" // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out PerpetualOption(string CallPutFlag, float S, float X, float r, float b, float v)=> float PerpetualOption = 0 float y1 = 1 / 2 - b / math.pow(v, 2) + math.sqrt(math.pow((b / math.pow(v, 2) - 1 / 2), 2) + 2 * r / math.pow(v, 2)) float y2 = 1 / 2 - b / math.pow(v, 2) - math.sqrt(math.pow((b / math.pow(v, 2) - 1 / 2), 2) + 2 * r / math.pow(v, 2)) if CallPutFlag == callString PerpetualOption := X / (y1 - 1) * math.pow((y1 - 1) / y1 * S / X, y1) else PerpetualOption := X / (1 - y2) * math.pow((y2 - 1) / y2 * S / X, y2) PerpetualOption EPerpetualOption(string OutPutFlag, string CallPutFlag, float S, float X, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EPerpetualOption = 0 if OutPutFlag == "p" // Value EPerpetualOption := PerpetualOption(CallPutFlag, S, X, r, b, v) else if OutPutFlag == "d" // 'Delta EPerpetualOption := (PerpetualOption(CallPutFlag, S + dS, X, r, b, v) - PerpetualOption(CallPutFlag, S - dS, X, r, b, v)) / (2 * dS) else if OutPutFlag == "e" // 'Elasticity EPerpetualOption := (PerpetualOption(CallPutFlag, S + dS, X, r, b, v) - PerpetualOption(CallPutFlag, S - dS, X, r, b, v)) / (2 * dS) * S / PerpetualOption(CallPutFlag, S, X, r, b, v) else if OutPutFlag =="g" // 'Gamma EPerpetualOption := (PerpetualOption(CallPutFlag, S + dS, X, r, b, v) - 2 * PerpetualOption(CallPutFlag, S, X, r, b, v) + PerpetualOption(CallPutFlag, S - dS, X, r, b, v)) / math.pow(dS, 2) else if OutPutFlag =="gv" // 'DGammaDVol EPerpetualOption := (PerpetualOption(CallPutFlag, S + dS, X, r, b, v + 0.01) - 2 * PerpetualOption(CallPutFlag, S, X, r, b, v + 0.01) + PerpetualOption(CallPutFlag, S - dS, X, r, b, v + 0.01) - PerpetualOption(CallPutFlag, S + dS, X, r, b, v - 0.01) + 2 * PerpetualOption(CallPutFlag, S, X, r, b, v - 0.01) - PerpetualOption(CallPutFlag, S - dS, X, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag =="gp" // 'GammaP EPerpetualOption := S / 100 * (PerpetualOption(CallPutFlag, S + dS, X, r, b, v) - 2 * PerpetualOption(CallPutFlag, S, X, r, b, v) + PerpetualOption(CallPutFlag, S - dS, X, r, b, v)) / math.pow(dS, 2) else if OutPutFlag =="dddv" // 'DDeltaDvol EPerpetualOption := 1 / (4 * dS * 0.01) * (PerpetualOption(CallPutFlag, S + dS, X, r, b, v + 0.01) - PerpetualOption(CallPutFlag, S + dS, X, r, b, v - 0.01) - PerpetualOption(CallPutFlag, S - dS, X, r, b, v + 0.01) + PerpetualOption(CallPutFlag, S - dS, X, r, b, v - 0.01)) / 100 else if OutPutFlag =="v" // 'Vega EPerpetualOption := (PerpetualOption(CallPutFlag, S, X, r, b, v + 0.01) - PerpetualOption(CallPutFlag, S, X, r, b, v - 0.01)) / 2 else if OutPutFlag =="vv" // 'DvegaDvol/vomma EPerpetualOption := (PerpetualOption(CallPutFlag, S, X, r, b, v + 0.01) - 2 * PerpetualOption(CallPutFlag, S, X, r, b, v) + PerpetualOption(CallPutFlag, S, X, r, b, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag =="vp" // 'VegaP EPerpetualOption := v / 0.1 * (PerpetualOption(CallPutFlag, S, X, r, b, v + 0.01) - PerpetualOption(CallPutFlag, S, X, r, b, v - 0.01)) / 2 else if OutPutFlag =="dvdv" // 'DvegaDvol EPerpetualOption := (PerpetualOption(CallPutFlag, S, X, r, b, v + 0.01) - 2 * PerpetualOption(CallPutFlag, S, X, r, b, v) + PerpetualOption(CallPutFlag, S, X, r, b, v - 0.01)) else if OutPutFlag =="r" // 'Rho EPerpetualOption := (PerpetualOption(CallPutFlag, S, X, r + 0.01, b + 0.01, v) - PerpetualOption(CallPutFlag, S, X, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag =="fr" // 'Futures options rho EPerpetualOption := (PerpetualOption(CallPutFlag, S, X, r + 0.01, b, v) - PerpetualOption(CallPutFlag, S, X, r - 0.01, b, v)) / 2 else if OutPutFlag =="f" // 'Rho2 EPerpetualOption := (PerpetualOption(CallPutFlag, S, X, r, b - 0.01, v) - PerpetualOption(CallPutFlag, S, X, r, b + 0.01, v)) / 2 else if OutPutFlag =="b" // 'Carry EPerpetualOption := (PerpetualOption(CallPutFlag, S, X, r, b + 0.01, v) - PerpetualOption(CallPutFlag, S, X, r, b - 0.01, v)) / 2 else if OutPutFlag =="s" // 'Speed EPerpetualOption := 1 / math.pow(dS, 3) * (PerpetualOption(CallPutFlag, S + 2 * dS, X, r, b, v) - 3 * PerpetualOption(CallPutFlag, S + dS, X, r, b, v) + 3 * PerpetualOption(CallPutFlag, S, X, r, b, v) - PerpetualOption(CallPutFlag, S - dS, X, r, b, v)) else if OutPutFlag =="dx" // 'Strike Delta EPerpetualOption := (PerpetualOption(CallPutFlag, S, X + dS, r, b, v) - PerpetualOption(CallPutFlag, S, X - dS, r, b, v)) / (2 * dS) else if OutPutFlag =="dxdx" // 'Strike Gamma EPerpetualOption := (PerpetualOption(CallPutFlag, S, X + dS, r, b, v) - 2 * PerpetualOption(CallPutFlag, S, X, r, b, v) + PerpetualOption(CallPutFlag, S, X - dS, r, b, v)) / math.pow(dS, 2) EPerpetualOption 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 r = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(40., "% Volatility", group = "Rates Settings") / 100 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 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 rcmpval = switch rcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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 if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) amaproxprice = EPerpetualOption("p", OpType, S, K, kouta, koutb, v, na) * sideout Delta = EPerpetualOption("d", OpType, S, K, kouta, koutb, v, na) * sideout Elasticity = EPerpetualOption("e", OpType, S, K, kouta, koutb, v, na) * sideout Gamma = EPerpetualOption("g", OpType, S, K, kouta, koutb, v, na) * sideout DGammaDvol = EPerpetualOption("gv", OpType, S, K, kouta, koutb, v, na) * sideout GammaP = EPerpetualOption("gp", OpType, S, K, kouta, koutb, v, na) * sideout Vega = EPerpetualOption("v", OpType, S, K, kouta, koutb, v, na) * sideout DvegaDvol = EPerpetualOption("dvdv", OpType, S, K, kouta, koutb, v, na) * sideout VegaP = EPerpetualOption("vp", OpType, S, K, kouta, koutb, v, na) * sideout Rho = EPerpetualOption("r", OpType, S, K, kouta, koutb, v, na) * sideout RhoFuturesOption = EPerpetualOption("fr", OpType, S, K, kouta, koutb, v, na) * sideout PhiRho2 = EPerpetualOption("f", OpType, S, K, kouta, koutb, v, na) * sideout Carry = EPerpetualOption("b", OpType, S, K, kouta, koutb, v, na) * sideout DDeltaDvol = EPerpetualOption("dddv", OpType, S, K, kouta, koutb, v, na) * sideout Speed = EPerpetualOption("s", OpType, S, K, kouta, koutb, v, na) * sideout StrikeDelta = EPerpetualOption("dx", OpType, S, K, kouta, koutb, v, na) * sideout StrikeGamma = EPerpetualOption("dxdx", OpType, S, K, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 21, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Perpetual American Options", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 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 = "Perpetual American Price: " + str.tostring(amaproxprice, 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 = "Option Sensitivities", 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 = "Rho ρ: " + str.tostring(Rho, "##.########"), 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(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, 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 = 1, row = 15, 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 = 16, 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 = 17, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 18, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
American Approximation Bjerksund & Stensland 1993 [Loxx]
https://www.tradingview.com/script/EGAr7TMG-American-Approximation-Bjerksund-Stensland-1993-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("American Approximation Bjerksund & Stensland 1993 [Loxx]", shorttitle ="AABS1993 [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 import loxx/cbnd/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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out phi(float S, float T, float gamma, float h, float i, float r, float b, float v)=> float lambda = (-r + gamma * b + 0.5 * gamma * (gamma - 1) * math.pow(v, 2)) * T float d = -(math.log(S / h) + (b + (gamma - 0.5) * math.pow(v, 2)) * T) / (v * math.sqrt(T)) float kappa = 2 * b / math.pow(v, 2) + 2 * gamma - 1 float phi = math.exp(lambda) * math.pow(S, gamma) * (cnd.CND1(d) - math.pow(i / S, kappa) * cnd.CND1(d - 2 * math.log(i / S) / (v * math.sqrt(T)))) phi GBlackScholes(string CallPutFlag, float S, float x, float T, float r, float b, float v)=> float gBlackScholes = 0 float d1 = (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float 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 BSAmericanCallApprox(float S, float X, float T, float r, float b, float v)=> float BInfinity = 0 float B0 = 0 float ht = 0, float i = 0 float Alpha = 0 float Beta = 0 float BSAmericanCallApprox = 0 if b >= r // Never optimal to exersice before maturity BSAmericanCallApprox := GBlackScholes(callString, S, X, T, r, b, v) else Beta := (1 / 2 - b / math.pow(v, 2)) + math.sqrt(math.pow(b / math.pow(v, 2) - 1 / 2, 2) + 2 * r / math.pow(v, 2)) BInfinity := Beta / (Beta - 1) * X B0 := math.max(X, r / (r - b) * X) ht := -(b * T + 2 * v * math.sqrt(T)) * B0 / (BInfinity - B0) i := B0 + (BInfinity - B0) * (1 - math.exp(ht)) Alpha := (i - X) * math.pow(i, (-Beta)) if S >= i BSAmericanCallApprox := S - X else BSAmericanCallApprox := Alpha * math.pow(S, Beta) - Alpha * phi(S, T, Beta, i, i, r, b, v) + phi(S, T, 1, i, i, r, b, v) - phi(S, T, 1, X, i, r, b, v) - X * phi(S, T, 0, i, i, r, b, v) + X * phi(S, T, 0, X, i, r, b, v) BSAmericanCallApprox // The Bjerksund and Stensland (1993) American approximation BSAmericanApprox(string CallPutFlag, float S, float X, float T, float r, float b, float v)=> float BSAmericanApprox = 0 if CallPutFlag == callString BSAmericanApprox := BSAmericanCallApprox(S, X, T, r, b, v) else // Use the Bjerksund and Stensland put-call transformation BSAmericanApprox := BSAmericanCallApprox(X, S, T, r - b, -b, v) BSAmericanApprox ImpliedVolGBlackScholes(string CallPutFlag, float S, float X, float T, float r, float b, float cm)=> float vLow = 0.005 float vHigh = 4 float epsilon = 1E-08 float cLow = GBlackScholes(CallPutFlag, S, X, T, r, b, vLow) float cHigh = GBlackScholes(CallPutFlag, S, X, T, r, b, vHigh) int N = 0 float vi = vLow + (cm - cLow) * (vHigh - vLow) / (cHigh - cLow) float ImpliedVolGBlackScholes = 0 while math.abs(cm - GBlackScholes(CallPutFlag, S, X, T, r, b, vi)) > epsilon N := N + 1 if N > 20 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) ImpliedVolGBlackScholes := vi ImpliedVolGBlackScholes EBSAmericanApprox(string OutPutFlag, string CallPutFlag, float S, float X, float T, float r, float b, float v, float dSin)=> float dS = dSin if na(dS) dS := 0.01 float EBSAmericanApprox = 0 if OutPutFlag == "p" // ' Value EBSAmericanApprox := BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "d" // 'Delta EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" // 'Elasticity EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / (2 * dS) * S / BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "g" // 'Gamma EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" // 'DGammaDVol EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v + 0.01) - 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) + BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v + 0.01) - BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v - 0.01) + 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01) - BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" // 'GammaP EBSAmericanApprox := S / 100 * (BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) - 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "tg" // 'time Gamma EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T + 1 / 365, r, b, v) - 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox(CallPutFlag, S, X, T - 1 / 365, r, b, v)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" // 'DDeltaDvol EBSAmericanApprox := 1 / (4 * dS * 0.01) * (BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v + 0.01) - BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v - 0.01) - BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v + 0.01) + BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" // 'Vega EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - BSAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" // 'DvegaDvol/vomma EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" // 'VegaP EBSAmericanApprox := v / 0.1 * (BSAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - BSAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" // 'DvegaDvol EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T, r, b, v + 0.01) - 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox(CallPutFlag, S, X, T, r, b, v - 0.01)) else if OutPutFlag == "t" // 'Theta if T <= 1 / 365 EBSAmericanApprox := BSAmericanApprox(CallPutFlag, S, X, 1E-05, r, b, v) - BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) else EBSAmericanApprox := BSAmericanApprox(CallPutFlag, S, X, T - 1 / 365, r, b, v) - BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "r" // 'Rho EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T, r + 0.01, b + 0.01, v) - BSAmericanApprox(CallPutFlag, S, X, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" // 'Futures options rho EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T, r + 0.01, b, v) - BSAmericanApprox(CallPutFlag, S, X, T, r - 0.01, b, v)) / 2 else if OutPutFlag == "f" // 'Rho2 EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T, r, b - 0.01, v) - BSAmericanApprox(CallPutFlag, S, X, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" // 'Carry EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X, T, r, b + 0.01, v) - BSAmericanApprox(CallPutFlag, S, X, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" // 'Speed EBSAmericanApprox := 1 / math.pow(dS, 3) * (BSAmericanApprox(CallPutFlag, S + 2 * dS, X, T, r, b, v) - 3 * BSAmericanApprox(CallPutFlag, S + dS, X, T, r, b, v) + 3 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) - BSAmericanApprox(CallPutFlag, S - dS, X, T, r, b, v)) else if OutPutFlag == "dx" // 'Strike Delta EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X + dS, T, r, b, v) - BSAmericanApprox(CallPutFlag, S, X - dS, T, r, b, v)) / (2 * dS) else if OutPutFlag == "dxdx" // 'Strike Gamma EBSAmericanApprox := (BSAmericanApprox(CallPutFlag, S, X + dS, T, r, b, v) - 2 * BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox(CallPutFlag, S, X - dS, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "di" // 'Difference in value between BS Approx and Black-Scholes Merton value EBSAmericanApprox := BSAmericanApprox(CallPutFlag, S, X, T, r, b, v) - GBlackScholes(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "BSIVol" // 'Equivalent Black-Scholes-Merton implied volatility string CallPutFlagff = putString if S >= S * math.exp(b * T) CallPutFlagff := callString EBSAmericanApprox := ImpliedVolGBlackScholes(CallPutFlagff, S, X, T, r, b, BSAmericanApprox(CallPutFlagff, S, X, T, r, b, v)) EBSAmericanApprox 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 r = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) bsmprice = GBlackScholes(OpType, S, K, T, kouta, koutb, v) amaproxprice = EBSAmericanApprox("p", OpType, S, K, T, kouta, koutb, v, na) * sideout Delta = EBSAmericanApprox("d", OpType, S, K, T, kouta, koutb, v, na) * sideout Elasticity = EBSAmericanApprox("e", OpType, S, K, T, kouta, koutb, v, na) * sideout Gamma = EBSAmericanApprox("g", OpType, S, K, T, kouta, koutb, v, na) * sideout DGammaDvol = EBSAmericanApprox("gv", OpType, S, K, T, kouta, koutb, v, na) * sideout GammaP = EBSAmericanApprox("gp", OpType, S, K, T, kouta, koutb, v, na) * sideout Vega = EBSAmericanApprox("v", OpType, S, K, T, kouta, koutb, v, na) * sideout DvegaDvol = EBSAmericanApprox("dvdv", OpType, S, K, T, kouta, koutb, v, na) * sideout VegaP = EBSAmericanApprox("vp", OpType, S, K, T, kouta, koutb, v, na) * sideout Theta = EBSAmericanApprox("t", OpType, S, K, T, kouta, koutb, v, na) * sideout Rho = EBSAmericanApprox("r", OpType, S, K, T, kouta, koutb, v, na) * sideout RhoFuturesOption = EBSAmericanApprox("fr", OpType, S, K, T, kouta, koutb, v, na) * sideout PhiRho2 = EBSAmericanApprox("f", OpType, S, K, T, kouta, koutb, v, na) * sideout Carry = EBSAmericanApprox("b", OpType, S, K, T, kouta, koutb, v, na) * sideout DDeltaDvol = EBSAmericanApprox("dddv", OpType, S, K, T, kouta, koutb, v, na) * sideout Speed = EBSAmericanApprox("s", OpType, S, K, T, kouta, koutb, v, na) * sideout StrikeDelta = EBSAmericanApprox("dx", OpType, S, K, T, kouta, koutb, v, na) * sideout StrikeGamma = EBSAmericanApprox("dxdx", OpType, S, K, T, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 21, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "American Approximation Bjerksund & Stensland 1993", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 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 = "American Approximation Price: " + str.tostring(amaproxprice, 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 = "Black-Scholes-Merton Value: " + str.tostring(bsmprice, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 3, text = "Option Sensitivities", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 4, 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 = 5, 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 1, row = 14, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 16, 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 = 1, row = 17, 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 = 18, 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 = 19, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 20, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
big shadow
https://www.tradingview.com/script/V3Nu7kWe-big-shadow/
farzam00248
https://www.tradingview.com/u/farzam00248/
3
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/ // © farzam00248 //@version=5 indicator("big shadow", overlay = true) highshadow_length = input(15) lowhshadow_length = input(15) big_shadow = false high_percentage = ((high - math.max(open,close))/math.max(open,close))*100 low_percentage = ((math.min(open,close) - low)/low)*100 if high_percentage > highshadow_length or low_percentage > lowhshadow_length big_shadow := true alertcondition(big_shadow, title='big_shadow', message='big_shadow') barcolor(big_shadow ? color.white : na) //plot(close)
American Approximation Bjerksund & Stensland 2002 [Loxx]
https://www.tradingview.com/script/rpVhNN5g-American-Approximation-Bjerksund-Stensland-2002-Loxx/
loxx
https://www.tradingview.com/u/loxx/
13
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("American Approximation Bjerksund & Stensland 2002 [Loxx]", shorttitle ="AABS2002 [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 import loxx/cbnd/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 // via Espen Gaarder Haug; The Complete Guide to Option Pricing Formulas convertingToCCRate(float r, float Compoundings)=> float ConvertingToCCRate = 0 if Compoundings == 0 ConvertingToCCRate := r else ConvertingToCCRate := Compoundings * math.log(1 + r / Compoundings) ConvertingToCCRate ND(float x)=> float out = math.exp(-x * x * 0.5) / math.sqrt(2 * math.pi) out GBlackScholes(string CallPutFlag, float S, float x, float T, float r, float b, float v)=> float gBlackScholes = 0 float d1 = (math.log(S / x) + (b + math.pow(v, 2) / 2) * T) / (v * math.sqrt(T)) float 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 phi(float S, float T, float gamma, float h, float i, float r, float b, float v)=> float lambda = (-r + gamma * b + 0.5 * gamma * (gamma - 1) * math.pow(v, 2)) * T float d = -(math.log(S / h) + (b + (gamma - 0.5) * math.pow(v, 2)) * T) / (v * math.sqrt(T)) float kappa = 2 * b / math.pow(v, 2) + 2 * gamma - 1 float phi = math.exp(lambda) * math.pow(S, gamma) * (cnd.CND1(d) - math.pow(i / S, kappa) * cnd.CND1(d - 2 * math.log(i / S) / (v * math.sqrt(T)))) phi ksi(float S, float T2, float gamma, float h, float I2, float I1, float t1, float r, float b, float v)=> float e1 = (math.log(S / I1) + (b + (gamma - 0.5) * v * v) * t1) / (v * math.sqrt(t1)) float e2 = (math.log(math.pow(I2, 2) / (S * I1)) + (b + (gamma - 0.5) * math.pow(v, 2)) * t1) / (v * math.sqrt(t1)) float e3 = (math.log(S / I1) - (b + (gamma - 0.5) * math.pow(v, 2)) * t1) / (v * math.sqrt(t1)) float e4 = (math.log(math.pow(I2, 2) / (S * I1)) - (b + (gamma - 0.5) * math.pow(v, 2)) * t1) / (v * math.sqrt(t1)) float f1 = (math.log(S / h) + (b + (gamma - 0.5) * math.pow(v, 2)) * T2) / (v * math.sqrt(T2)) float f2 = (math.log(math.pow(I2, 2) / (S * h)) + (b + (gamma - 0.5) * math.pow(v, 2)) * T2) / (v * math.sqrt(T2)) float f3 = (math.log(math.pow(I1, 2) / (S * h)) + (b + (gamma - 0.5) * math.pow(v, 2)) * T2) / (v * math.sqrt(T2)) float f4 = (math.log(S * math.pow(I1, 2) / (h * math.pow(I2, 2))) + (b + (gamma - 0.5) * math.pow(v, 2)) * T2) / (v * math.sqrt(T2)) float rho = math.sqrt(t1 / T2) float lambda = -r + gamma * b + 0.5 * gamma * (gamma - 1) * math.pow(v, 2) float kappa = 2 * b / (math.pow(v, 2)) + (2 * gamma - 1) float ksi = math.exp(lambda * T2) * math.pow(S, gamma) * (cbnd.CBND3(-e1, -f1, rho) - math.pow(I2 / S, kappa) * cbnd.CBND3(-e2, -f2, rho) - math.pow(I1 / S, kappa) * cbnd.CBND3(-e3, -f3, -rho) + math.pow(I1 / I2, kappa) * cbnd.CBND3(-e4, -f4, -rho)) ksi BSAmericanCallApprox2002(float S, float X, float T, float r, float b, float v)=> float BInfinity = 0 float B0 = 0 float ht1 = 0 float ht2 = 0 float I1 = 0 float I2 = 0 float alfa1 = 0 float alfa2 = 0 float Beta = 0 float t1 = 0 float BSAmericanCallApprox2002 = 0 t1 := 1 / 2 * (math.sqrt(5) - 1) * T if b >= r // Never optimal to exersice before maturity BSAmericanCallApprox2002 := GBlackScholes(callString, S, X, T, r, b, v) else Beta := (1 / 2 - b / math.pow(v, 2)) + math.sqrt(math.pow(b / math.pow(v, 2) - 1 / 2, 2) + 2 * r / math.pow(v, 2)) BInfinity := Beta / (Beta - 1) * X B0 := math.max(X, r / (r - b) * X) ht1 := -(b * t1 + 2 * v * math.sqrt(t1)) * math.pow(X, 2) / ((BInfinity - B0) * B0) ht2 := -(b * T + 2 * v * math.sqrt(T)) * math.pow(X, 2) / ((BInfinity - B0) * B0) I1 := B0 + (BInfinity - B0) * (1 - math.exp(ht1)) I2 := B0 + (BInfinity - B0) * (1 - math.exp(ht2)) alfa1 := (I1 - X) * math.pow(I1, (-Beta)) alfa2 := (I2 - X) * math.pow(I2, (-Beta)) if S >= I2 BSAmericanCallApprox2002 := S - X else BSAmericanCallApprox2002 := alfa2 * math.pow(S, Beta) - alfa2 * phi(S, t1, Beta, I2, I2, r, b, v) + phi(S, t1, 1, I2, I2, r, b, v) - phi(S, t1, 1, I1, I2, r, b, v) - X * phi(S, t1, 0, I2, I2, r, b, v) + X * phi(S, t1, 0, I1, I2, r, b, v) + alfa1 * phi(S, t1, Beta, I1, I2, r, b, v) - alfa1 * ksi(S, T, Beta, I1, I2, I1, t1, r, b, v) + ksi(S, T, 1, I1, I2, I1, t1, r, b, v) - ksi(S, T, 1, X, I2, I1, t1, r, b, v) - X * ksi(S, T, 0, I1, I2, I1, t1, r, b, v) + X * ksi(S, T, 0, X, I2, I1, t1, r, b, v) BSAmericanCallApprox2002 // The Bjerksund and Stensland (2002) American approximation BSAmericanApprox2002(string CallPutFlag, float S, float X, float T, float r, float b, float v)=> float BSAmericanApprox2002 = 0 if CallPutFlag == callString BSAmericanApprox2002 := BSAmericanCallApprox2002(S, X, T, r, b, v) else // Use the Bjerksund and Stensland put-call transformation BSAmericanApprox2002 := BSAmericanCallApprox2002(X, S, T, r - b, -b, v) BSAmericanApprox2002 EBSAmericanApprox2002(string OutPutFlag, string CallPutFlag, float S, float X, float T, float r, float b, float v, float dSin)=> float dS = 0 if na(dSin) dS := 0.01 float EBSAmericanApprox2002 = 0 if OutPutFlag == "p" //Value EBSAmericanApprox2002 := BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "d" //Delta EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v) - BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" //Elasticity EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v) - BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v)) / (2 * dS) * S / BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "g" //Gamma EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v) - 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" //DGammaDVol EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v + 0.01) - 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v + 0.01) + BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v + 0.01) - BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v - 0.01) + 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v - 0.01) - BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" //GammaP EBSAmericanApprox2002 := S / 100 * (BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v) - 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "tg" //time Gamma EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T + 1 / 365, r, b, v) - 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox2002(CallPutFlag, S, X, T - 1 / 365, r, b, v)) / math.pow(1 / 365, 2) else if OutPutFlag == "dddv" //DDeltaDvol EBSAmericanApprox2002 := 1 / (4 * dS * 0.01) * (BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v + 0.01) - BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v - 0.01) - BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v + 0.01) + BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" //Vega EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v + 0.01) - BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vv" //DvegaDvol/vomma EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v + 0.01) - 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v - 0.01)) / math.pow(0.01, 2) / 10000 else if OutPutFlag == "vp" //VegaP EBSAmericanApprox2002 := v / 0.1 * (BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v + 0.01) - BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" //DvegaDvol EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v + 0.01) - 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v - 0.01)) else if OutPutFlag == "t" //Theta if T <= (1 / 365) EBSAmericanApprox2002 := BSAmericanApprox2002(CallPutFlag, S, X, 1E-05, r, b, v) - BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) else EBSAmericanApprox2002 := BSAmericanApprox2002(CallPutFlag, S, X, T - 1 / 365, r, b, v) - BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) else if OutPutFlag == "r" //Rho EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T, r + 0.01, b + 0.01, v) - BSAmericanApprox2002(CallPutFlag, S, X, T, r - 0.01, b - 0.01, v)) / (2) else if OutPutFlag == "fr" //Futures options rho EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T, r + 0.01, b, v) - BSAmericanApprox2002(CallPutFlag, S, X, T, r - 0.01, b, v)) / (2) else if OutPutFlag == "f" //Rho2 EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T, r, b - 0.01, v) - BSAmericanApprox2002(CallPutFlag, S, X, T, r, b + 0.01, v)) / (2) else if OutPutFlag == "b" //Carry EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X, T, r, b + 0.01, v) - BSAmericanApprox2002(CallPutFlag, S, X, T, r, b - 0.01, v)) / (2) else if OutPutFlag == "s" //Speed EBSAmericanApprox2002 := 1 / math.pow(dS, 3) * (BSAmericanApprox2002(CallPutFlag, S + 2 * dS, X, T, r, b, v) - 3 * BSAmericanApprox2002(CallPutFlag, S + dS, X, T, r, b, v) + 3 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) - BSAmericanApprox2002(CallPutFlag, S - dS, X, T, r, b, v)) else if OutPutFlag == "dx" //Strike Delta EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X + dS, T, r, b, v) - BSAmericanApprox2002(CallPutFlag, S, X - dS, T, r, b, v)) / (2 * dS) else if OutPutFlag == "dxdx" //Strike Gamma EBSAmericanApprox2002 := (BSAmericanApprox2002(CallPutFlag, S, X + dS, T, r, b, v) - 2 * BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) + BSAmericanApprox2002(CallPutFlag, S, X - dS, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "di" //Difference in value between BS Approx and Black-Scholes Merton value EBSAmericanApprox2002 := BSAmericanApprox2002(CallPutFlag, S, X, T, r, b, v) - GBlackScholes(CallPutFlag, S, X, T, r, b, v) EBSAmericanApprox2002 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 r = input.float(6., "% Risk-free Rate", group = "Rates Settings") / 100 string rcmp = input.string(Continuous, "% Risk-free Rate Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float b = input.float(6., "% Cost of Carry", group = "Rates Settings") / 100 string bcmp = 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 rcmpval = switch rcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float bcmpval = switch bcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float S = 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(S / nz(S[1])), histvolper) gkvol => garmanKlass(histvolper) gkzhvol => gkyzvol(histvolper) ewmavolstr => ewmavol(math.log(S / nz(S[1])), histvolper) if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(r, rcmpval) koutb = convertingToCCRate(b, bcmpval) bsmprice = GBlackScholes(OpType, S, K, T, kouta, koutb, v) amaproxprice = EBSAmericanApprox2002("p", OpType, S, K, T, kouta, koutb, v, na) * sideout Delta = EBSAmericanApprox2002("d", OpType, S, K, T, kouta, koutb, v, na) * sideout Elasticity = EBSAmericanApprox2002("e", OpType, S, K, T, kouta, koutb, v, na) * sideout Gamma = EBSAmericanApprox2002("g", OpType, S, K, T, kouta, koutb, v, na) * sideout DGammaDvol = EBSAmericanApprox2002("gv", OpType, S, K, T, kouta, koutb, v, na) * sideout GammaP = EBSAmericanApprox2002("gp", OpType, S, K, T, kouta, koutb, v, na) * sideout Vega = EBSAmericanApprox2002("v", OpType, S, K, T, kouta, koutb, v, na) * sideout DvegaDvol = EBSAmericanApprox2002("dvdv", OpType, S, K, T, kouta, koutb, v, na) * sideout VegaP = EBSAmericanApprox2002("vp", OpType, S, K, T, kouta, koutb, v, na) * sideout Theta = EBSAmericanApprox2002("t", OpType, S, K, T, kouta, koutb, v, na) * sideout Rho = EBSAmericanApprox2002("r", OpType, S, K, T, kouta, koutb, v, na) * sideout RhoFuturesOption = EBSAmericanApprox2002("fr", OpType, S, K, T, kouta, koutb, v, na) * sideout PhiRho2 = EBSAmericanApprox2002("f", OpType, S, K, T, kouta, koutb, v, na) * sideout Carry = EBSAmericanApprox2002("b", OpType, S, K, T, kouta, koutb, v, na) * sideout DDeltaDvol = EBSAmericanApprox2002("dddv", OpType, S, K, T, kouta, koutb, v, na) * sideout Speed = EBSAmericanApprox2002("s", OpType, S, K, T, kouta, koutb, v, na) * sideout StrikeDelta = EBSAmericanApprox2002("dx", OpType, S, K, T, kouta, koutb, v, na) * sideout StrikeGamma = EBSAmericanApprox2002("dxdx", OpType, S, K, T, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 21, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "American Approximation Bjerksund & Stensland 2002", 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(S, 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(r * 100, "##.##") + "%\n" + "Compounding Type: " + rcmp + "\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(b * 100, "##.##") + "%\n" + "Compounding Type: " + bcmp + "\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 = 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 = "American Approximation Price: " + str.tostring(amaproxprice, 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 = "Black-Scholes-Merton Value: " + str.tostring(bsmprice, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 3, text = "Option Sensitivities", bgcolor=color.yellow, text_color = color.black, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 4, 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 = 5, 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 1, row = 14, text = "Rho Futures 0ption ρ: " + str.tostring(RhoFuturesOption, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, text = "Phi/Rho2: " + str.tostring(PhiRho2, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 16, 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 = 1, row = 17, 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 = 18, 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 = 19, text = "Strike Delta: " + str.tostring(StrikeDelta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 20, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
big shadow
https://www.tradingview.com/script/cDBX4NCD-big-shadow/
farzam00248
https://www.tradingview.com/u/farzam00248/
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/ // © farzam00248 //@version=5 indicator("big shadow", overlay = true) highshadow_length = input(15) lowhshadow_length = input(15) big_shadow = false high_percentage = ((high - math.max(open,close))/math.max(open,close))*100 low_percentage = ((math.min(open,close) - low)/low)*100 if high_percentage > highshadow_length or low_percentage > lowhshadow_length big_shadow := true alertcondition(big_shadow, title='big_shadow', message='big_shadow') barcolor(big_shadow ? color.white : na) //plot(close)
SPX Fair Value Bands
https://www.tradingview.com/script/Q3uMZHHU-SPX-Fair-Value-Bands/
dharmatech
https://www.tradingview.com/u/dharmatech/
722
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/ // © dharmatech //@version=5 indicator("SPX Fair Value Bands", overlay = true) line_a = request.security("(WALCL - WTREGEN - RRPONTSYD)/1000/1000/1000/1.1 - 1625 + 350", "D", close) plot(series=line_a, title = 'Upper Band', color = color.orange) line_b = request.security("(WALCL - WTREGEN - RRPONTSYD)/1000/1000/1000/1.1 - 1625 - 150", "D", close) plot(series=line_b, title = 'Lower Band', color=color.aqua) fv = request.security("(WALCL - WTREGEN - RRPONTSYD)/1000/1000/1000/1.1 - 1625", "D", close) plot(series=fv, title = 'Fair Value', color=color.purple)
MTF MA Ribbon and Bands + BB, Gaussian F. and R. VWAP with StDev
https://www.tradingview.com/script/I6v2DNQ9-MTF-MA-Ribbon-and-Bands-BB-Gaussian-F-and-R-VWAP-with-StDev/
Yatagarasu_
https://www.tradingview.com/u/Yatagarasu_/
162
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("MA • Yata", overlay = true) // ------------------------------ groupMA = "Moving Average Ribbon" // ------------------------------ ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) "LSMA" => ta.linreg(source, length, offset=0) "HMA" => ta.hma(source, length) "ALMA" => ta.alma(source, length, 0.85, 6.0) // ------------------------------ trend_flip = input.int (2, minval=0 , title="Flip Trend Periods" , inline="MA01", group=groupMA) src = input (close , title="Source" , inline="MA01", group=groupMA) ribbon_colorup = input.color (color.new(#00FEEF, 95) , title="Ribbon Colors: Bullish", inline="MA02", group=groupMA) ribbon_colordn = input.color (color.new(#E21B22, 95) , title="Bearish" , inline="MA02", group=groupMA) only_fill = input.bool (false , title="Hide MA Lines" , inline="MA02", group=groupMA) price = plot(close, title="Price", color=color.silver, display=display.none) // ------------------------------ visible1 = input.bool(true , title="MA 1:" , inline="MA1" , group=groupMA) visiblefill1 = input.bool(false, title="Show MA Fill", inline="MA1A" , group=groupMA) visible2 = input.bool(true , title="MA 2:" , inline="MA2" , group=groupMA) visiblefill2 = input.bool(false, title="Show MA Fill", inline="MA2A" , group=groupMA) visible3 = input.bool(true , title="MA 3:" , inline="MA3" , group=groupMA) visiblefill3 = input.bool(false, title="Show MA Fill", inline="MA3A" , group=groupMA) visible4 = input.bool(true , title="MA 4:" , inline="MA4" , group=groupMA) visiblefill4 = input.bool(false, title="Show MA Fill", inline="MA4A" , group=groupMA) visible5 = input.bool(true , title="MA 5:" , inline="MA5" , group=groupMA) visiblefill5 = input.bool(false, title="Show MA Fill", inline="MA5A" , group=groupMA) visible6 = input.bool(true , title="MA 6:" , inline="MA6" , group=groupMA) visiblefill6 = input.bool(false, title="Show MA Fill", inline="MA6A" , group=groupMA) visible7 = input.bool(false, title="MA 7:" , inline="MA7" , group=groupMA) visiblefill7 = input.bool(false, title="Show MA Fill", inline="MA7A" , group=groupMA) visible8 = input.bool(false, title="MA 8:" , inline="MA8" , group=groupMA) visiblefill8 = input.bool(false, title="Show MA Fill", inline="MA8A" , group=groupMA) visible9 = input.bool(false, title="MA 9:" , inline="MA9" , group=groupMA) visiblefill9 = input.bool(false, title="Show MA Fill", inline="MA9A" , group=groupMA) //visible10 = input.bool(false, title="MA A:" , inline="MA10" , group=groupMA) //visiblefill10 = input.bool(false, title="Show MA Fill", inline="MA10A", group=groupMA) //visible11 = input.bool(false, title="MA B:" , inline="MA11" , group=groupMA) //visiblefill11 = input.bool(false, title="Show MA Fill", inline="MA11A", group=groupMA) //visible12 = input.bool(false, title="MA C:" , inline="MA12" , group=groupMA) //visiblefill12 = input.bool(false, title="Show MA Fill", inline="MA12A", group=groupMA) //visible13 = input.bool(false, title="MA D:" , inline="MA13" , group=groupMA) //visiblefill13 = input.bool(false, title="Show MA Fill", inline="MA13A", group=groupMA) //visible14 = input.bool(false, title="MA E:" , inline="MA14" , group=groupMA) //visiblefill14 = input.bool(false, title="Show MA Fill", inline="MA14A", group=groupMA) //visible15 = input.bool(false, title="MA F:" , inline="MA15" , group=groupMA) //visiblefill15 = input.bool(false, title="Show MA Fill", inline="MA15A", group=groupMA) // ------------------------------ len1 = input.int(9 , minval=1, title="", inline="MA1", group=groupMA) len2 = input.int(21 , minval=1, title="", inline="MA2", group=groupMA) len3 = input.int(34 , minval=1, title="", inline="MA3", group=groupMA) len4 = input.int(55 , minval=1, title="", inline="MA4", group=groupMA) len5 = input.int(100 , minval=1, title="", inline="MA5", group=groupMA) len6 = input.int(200 , minval=1, title="", inline="MA6", group=groupMA) len7 = input.int(400 , minval=1, title="", inline="MA7", group=groupMA) len8 = input.int(800 , minval=1, title="", inline="MA8", group=groupMA) len9 = input.int(1600 , minval=1, title="", inline="MA9", group=groupMA) //len10 = input.int(9 , minval=1, title="", inline="MA10", group=groupMA) //len11 = input.int(21 , minval=1, title="", inline="MA11", group=groupMA) //len12 = input.int(34 , minval=1, title="", inline="MA12", group=groupMA) //len13 = input.int(55 , minval=1, title="", inline="MA13", group=groupMA) //len14 = input.int(100 , minval=1, title="", inline="MA14", group=groupMA) //len15 = input.int(200 , minval=1, title="", inline="MA15", group=groupMA) // ------------------------------ maType1 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA1", group=groupMA) maType2 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA2", group=groupMA) maType3 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA3", group=groupMA) maType4 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA4", group=groupMA) maType5 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA5", group=groupMA) maType6 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA6", group=groupMA) maType7 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA7", group=groupMA) maType8 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA8", group=groupMA) maType9 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA9", group=groupMA) //maType10 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA10", group=groupMA) //maType11 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA11", group=groupMA) //maType12 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA12", group=groupMA) //maType13 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA13", group=groupMA) //maType14 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA14", group=groupMA) //maType15 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA15", group=groupMA) // ------------------------------ line_width1 = input.int(1, minval=0, title="| Line Width", inline="MA1A", group=groupMA) line_width2 = input.int(1, minval=0, title="| Line Width", inline="MA2A", group=groupMA) line_width3 = input.int(1, minval=0, title="| Line Width", inline="MA3A", group=groupMA) line_width4 = input.int(1, minval=0, title="| Line Width", inline="MA4A", group=groupMA) line_width5 = input.int(1, minval=0, title="| Line Width", inline="MA5A", group=groupMA) line_width6 = input.int(1, minval=0, title="| Line Width", inline="MA6A", group=groupMA) line_width7 = input.int(1, minval=0, title="| Line Width", inline="MA7A", group=groupMA) line_width8 = input.int(1, minval=0, title="| Line Width", inline="MA8A", group=groupMA) line_width9 = input.int(1, minval=0, title="| Line Width", inline="MA9A", group=groupMA) //line_width10 = input.int(1, minval=0, title="| Line Width", inline="MA10A", group=groupMA) //line_width11 = input.int(1, minval=0, title="| Line Width", inline="MA11A", group=groupMA) //line_width12 = input.int(1, minval=0, title="| Line Width", inline="MA12A", group=groupMA) //line_width13 = input.int(1, minval=0, title="| Line Width", inline="MA13A", group=groupMA) //line_width14 = input.int(1, minval=0, title="| Line Width", inline="MA14A", group=groupMA) //line_width15 = input.int(1, minval=0, title="| Line Width", inline="MA15A", group=groupMA) // ------------------------------ up_color1 = input.color(color.new(#E12D7B, 25), title="", inline="MA1A", group=groupMA) up_color2 = input.color(color.new(#F67B52, 25), title="", inline="MA2A", group=groupMA) up_color3 = input.color(color.new(#EDCD3B, 25), title="", inline="MA3A", group=groupMA) up_color4 = input.color(color.new(#3BBC54, 25), title="", inline="MA4A", group=groupMA) up_color5 = input.color(color.new(#2665BD, 25), title="", inline="MA5A", group=groupMA) up_color6 = input.color(color.new(#481899, 25), title="", inline="MA6A", group=groupMA) up_color7 = input.color(color.new(#B2B5BE, 50), title="", inline="MA7A", group=groupMA) up_color8 = input.color(color.new(#B2B5BE, 50), title="", inline="MA8A", group=groupMA) up_color9 = input.color(color.new(#B2B5BE, 50), title="", inline="MA9A", group=groupMA) //up_color10 = input.color(color.new(#B2B5BE, 50), title="", inline="MA10A", group=groupMA) //up_color11 = input.color(color.new(#B2B5BE, 50), title="", inline="MA11A", group=groupMA) //up_color12 = input.color(color.new(#B2B5BE, 50), title="", inline="MA12A", group=groupMA) //up_color13 = input.color(color.new(#B2B5BE, 50), title="", inline="MA13A", group=groupMA) //up_color14 = input.color(color.new(#B2B5BE, 50), title="", inline="MA14A", group=groupMA) //up_color15 = input.color(color.new(#B2B5BE, 50), title="", inline="MA15A", group=groupMA) down_color1 = input.color(color.new(#F19A9C, 50), title="", inline="MA1A", group=groupMA) down_color2 = input.color(color.new(#FFC29F, 50), title="", inline="MA2A", group=groupMA) down_color3 = input.color(color.new(#FFFAAE, 50), title="", inline="MA3A", group=groupMA) down_color4 = input.color(color.new(#CDECAD, 50), title="", inline="MA4A", group=groupMA) down_color5 = input.color(color.new(#A0CDED, 50), title="", inline="MA5A", group=groupMA) down_color6 = input.color(color.new(#AF8FC1, 50), title="", inline="MA6A", group=groupMA) down_color7 = input.color(color.new(#B2B5BE, 75), title="", inline="MA7A", group=groupMA) down_color8 = input.color(color.new(#B2B5BE, 75), title="", inline="MA8A", group=groupMA) down_color9 = input.color(color.new(#B2B5BE, 75), title="", inline="MA9A", group=groupMA) //down_color10 = input.color(color.new(#B2B5BE, 75), title="", inline="MA10A", group=groupMA) //down_color11 = input.color(color.new(#B2B5BE, 75), title="", inline="MA11A", group=groupMA) //down_color12 = input.color(color.new(#B2B5BE, 75), title="", inline="MA12A", group=groupMA) //down_color13 = input.color(color.new(#B2B5BE, 75), title="", inline="MA13A", group=groupMA) //down_color14 = input.color(color.new(#B2B5BE, 75), title="", inline="MA14A", group=groupMA) //down_color15 = input.color(color.new(#B2B5BE, 75), title="", inline="MA15A", group=groupMA) // ------------------------------ ma1 = ma(src, len1, maType1) ma2 = ma(src, len2, maType2) ma3 = ma(src, len3, maType3) ma4 = ma(src, len4, maType4) ma5 = ma(src, len5, maType5) ma6 = ma(src, len6, maType6) ma7 = ma(src, len7, maType7) ma8 = ma(src, len8, maType8) ma9 = ma(src, len9, maType9) //ma10 = ma(src, len10, maType10) //ma11 = ma(src, len11, maType11) //ma12 = ma(src, len12, maType12) //ma13 = ma(src, len13, maType13) //ma14 = ma(src, len14, maType14) //ma15 = ma(src, len15, maType15) // ------------------------------ res1 = input.timeframe("", title="", inline="MA1", group=groupMA) res2 = input.timeframe("", title="", inline="MA2", group=groupMA) res3 = input.timeframe("", title="", inline="MA3", group=groupMA) res4 = input.timeframe("", title="", inline="MA4", group=groupMA) res5 = input.timeframe("", title="", inline="MA5", group=groupMA) res6 = input.timeframe("", title="", inline="MA6", group=groupMA) res7 = input.timeframe("", title="", inline="MA7", group=groupMA) res8 = input.timeframe("", title="", inline="MA8", group=groupMA) res9 = input.timeframe("", title="", inline="MA9", group=groupMA) //res10 = input.timeframe("", title="", inline="MA10", group=groupMA) //res11 = input.timeframe("", title="", inline="MA11", group=groupMA) //res12 = input.timeframe("", title="", inline="MA12", group=groupMA) //res13 = input.timeframe("", title="", inline="MA13", group=groupMA) //res14 = input.timeframe("", title="", inline="MA14", group=groupMA) //res15 = input.timeframe("", title="", inline="MA15", group=groupMA) maT1 = request.security(syminfo.tickerid, res1, ma1, gaps=barmerge.gaps_off) maT2 = request.security(syminfo.tickerid, res2, ma2, gaps=barmerge.gaps_off) maT3 = request.security(syminfo.tickerid, res3, ma3, gaps=barmerge.gaps_off) maT4 = request.security(syminfo.tickerid, res4, ma4, gaps=barmerge.gaps_off) maT5 = request.security(syminfo.tickerid, res5, ma5, gaps=barmerge.gaps_off) maT6 = request.security(syminfo.tickerid, res6, ma6, gaps=barmerge.gaps_off) maT7 = request.security(syminfo.tickerid, res7, ma7, gaps=barmerge.gaps_off) maT8 = request.security(syminfo.tickerid, res8, ma8, gaps=barmerge.gaps_off) maT9 = request.security(syminfo.tickerid, res9, ma9, gaps=barmerge.gaps_off) //maT10 = request.security(syminfo.tickerid, res10, ma10, gaps=barmerge.gaps_off) //maT11 = request.security(syminfo.tickerid, res11, ma11, gaps=barmerge.gaps_off) //maT12 = request.security(syminfo.tickerid, res12, ma12, gaps=barmerge.gaps_off) //maT13 = request.security(syminfo.tickerid, res13, ma13, gaps=barmerge.gaps_off) //maT14 = request.security(syminfo.tickerid, res14, ma14, gaps=barmerge.gaps_off) //maT15 = request.security(syminfo.tickerid, res15, ma15, gaps=barmerge.gaps_off) // ------------------------------ plot_color1 = visible1 ? maT1 >= maT1[trend_flip] ? up_color1 : down_color1 : na plot_color2 = visible2 ? maT2 >= maT2[trend_flip] ? up_color2 : down_color2 : na plot_color3 = visible3 ? maT3 >= maT3[trend_flip] ? up_color3 : down_color3 : na plot_color4 = visible4 ? maT4 >= maT4[trend_flip] ? up_color4 : down_color4 : na plot_color5 = visible5 ? maT5 >= maT5[trend_flip] ? up_color5 : down_color5 : na plot_color6 = visible6 ? maT6 >= maT6[trend_flip] ? up_color6 : down_color6 : na plot_color7 = visible7 ? maT7 >= maT7[trend_flip] ? up_color7 : down_color7 : na plot_color8 = visible8 ? maT8 >= maT8[trend_flip] ? up_color8 : down_color8 : na plot_color9 = visible9 ? maT9 >= maT9[trend_flip] ? up_color9 : down_color9 : na //plot_color10 = visible10 ? maT10 >= maT10[trend_flip] ? up_color10 : down_color10 : na //plot_color11 = visible11 ? maT11 >= maT11[trend_flip] ? up_color11 : down_color11 : na //plot_color12 = visible12 ? maT12 >= maT12[trend_flip] ? up_color12 : down_color12 : na //plot_color13 = visible13 ? maT13 >= maT13[trend_flip] ? up_color13 : down_color13 : na //plot_color14 = visible14 ? maT14 >= maT14[trend_flip] ? up_color14 : down_color14 : na //plot_color15 = visible15 ? maT15 >= maT15[trend_flip] ? up_color15 : down_color15 : na map1 = plot(maT1, title="MA 1", style=plot.style_line, color= only_fill ? na : plot_color1, linewidth=line_width1) map2 = plot(maT2, title="MA 2", style=plot.style_line, color= only_fill ? na : plot_color2, linewidth=line_width2) map3 = plot(maT3, title="MA 3", style=plot.style_line, color= only_fill ? na : plot_color3, linewidth=line_width3) map4 = plot(maT4, title="MA 4", style=plot.style_line, color= only_fill ? na : plot_color4, linewidth=line_width4) map5 = plot(maT5, title="MA 5", style=plot.style_line, color= only_fill ? na : plot_color5, linewidth=line_width5) map6 = plot(maT6, title="MA 6", style=plot.style_line, color= only_fill ? na : plot_color6, linewidth=line_width6) map7 = plot(maT7, title="MA 7", style=plot.style_line, color= only_fill ? na : plot_color7, linewidth=line_width7) map8 = plot(maT8, title="MA 8", style=plot.style_line, color= only_fill ? na : plot_color8, linewidth=line_width8) map9 = plot(maT9, title="MA 9", style=plot.style_line, color= only_fill ? na : plot_color9, linewidth=line_width9) //map10 = plot(maT10, title="MA 10", style=plot.style_line, color= only_fill ? na : plot_color10, linewidth=line_width9) //map11 = plot(maT11, title="MA 11", style=plot.style_line, color= only_fill ? na : plot_color11, linewidth=line_width9) //map12 = plot(maT12, title="MA 12", style=plot.style_line, color= only_fill ? na : plot_color12, linewidth=line_width9) //map13 = plot(maT13, title="MA 13", style=plot.style_line, color= only_fill ? na : plot_color13, linewidth=line_width9) //map14 = plot(maT14, title="MA 14", style=plot.style_line, color= only_fill ? na : plot_color14, linewidth=line_width9) //map15 = plot(maT15, title="MA 15", style=plot.style_line, color= only_fill ? na : plot_color15, linewidth=line_width9) // ------------------------------ ma1color = (close > maT1 ? ribbon_colorup : ribbon_colordn) ma2color = (close > maT2 ? ribbon_colorup : ribbon_colordn) ma3color = (close > maT3 ? ribbon_colorup : ribbon_colordn) ma4color = (close > maT4 ? ribbon_colorup : ribbon_colordn) ma5color = (close > maT5 ? ribbon_colorup : ribbon_colordn) ma6color = (close > maT6 ? ribbon_colorup : ribbon_colordn) ma7color = (close > maT7 ? ribbon_colorup : ribbon_colordn) ma8color = (close > maT8 ? ribbon_colorup : ribbon_colordn) ma9color = (close > maT9 ? ribbon_colorup : ribbon_colordn) //ma10color = (close > maT10 ? ribbon_colorup : ribbon_colordn) //ma11color = (close > maT11 ? ribbon_colorup : ribbon_colordn) //ma12color = (close > maT12 ? ribbon_colorup : ribbon_colordn) //ma13color = (close > maT13 ? ribbon_colorup : ribbon_colordn) //ma14color = (close > maT14 ? ribbon_colorup : ribbon_colordn) //ma15color = (close > maT15 ? ribbon_colorup : ribbon_colordn) fill(price, map1, visible1 and visiblefill1 ? ma1color : na, title="MA Fill 1") fill(price, map2, visible2 and visiblefill2 ? ma2color : na, title="MA Fill 2") fill(price, map3, visible3 and visiblefill3 ? ma3color : na, title="MA Fill 3") fill(price, map4, visible4 and visiblefill4 ? ma4color : na, title="MA Fill 4") fill(price, map5, visible5 and visiblefill5 ? ma5color : na, title="MA Fill 5") fill(price, map6, visible6 and visiblefill6 ? ma6color : na, title="MA Fill 6") fill(price, map7, visible7 and visiblefill7 ? ma7color : na, title="MA Fill 7") fill(price, map8, visible8 and visiblefill8 ? ma8color : na, title="MA Fill 8") fill(price, map9, visible9 and visiblefill9 ? ma9color : na, title="MA Fill 9") //fill(price, map10, visible10 and visiblefill10 ? ma9color : na, title="MA Fill 10") //fill(price, map11, visible11 and visiblefill11 ? ma9color : na, title="MA Fill 11") //fill(price, map12, visible12 and visiblefill12 ? ma9color : na, title="MA Fill 12") //fill(price, map13, visible13 and visiblefill13 ? ma9color : na, title="MA Fill 13") //fill(price, map14, visible14 and visiblefill14 ? ma9color : na, title="MA Fill 14") //fill(price, map15, visible15 and visiblefill15 ? ma9color : na, title="MA Fill 15") // ---------------------------- groupB = "Moving Average Bands" // ---------------------------- showMAb = input.bool (false , title="MA b:", inline="MAB1", group=groupB) lengthMAb = input.int (34, minval=1 , title="", inline="MAB1", group=groupB) maTypeMAb = input.string ("EMA" , title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MAB1", group=groupB) resMAb = input.timeframe ("" , title="", inline="MAB1", group=groupB) h_MA = ma(high, lengthMAb, maTypeMAb) l_MA = ma(low, lengthMAb, maTypeMAb) MA_b = ma(close, lengthMAb, maTypeMAb) h_MAmtf = request.security(syminfo.tickerid, resMAb, h_MA) l_MAmtf = request.security(syminfo.tickerid, resMAb, l_MA) MA_bmtf = request.security(syminfo.tickerid, resMAb, MA_b) b_High = ((h_MAmtf - MA_bmtf) * math.phi) * math.pi + MA_bmtf b_Low = (-(MA_bmtf - l_MAmtf) * math.phi) * math.pi + MA_bmtf b_High_S = ta.wma(b_High, 8) b_Low_S = ta.wma(b_Low, 8) phi_High = ((h_MAmtf - MA_bmtf) * math.phi) * (math.phi + 4) + MA_bmtf phi_Low = (-(MA_bmtf - l_MAmtf) * math.phi) * (math.phi + 4) + MA_bmtf phi_High_S = ta.wma(phi_High, 8) phi_Low_S = ta.wma(phi_Low, 8) hi_color = input.color(color.new(color.red, 95) , title="Fill Colors: Upper", inline="MAB2", group=groupB) mi_color = input.color(color.new(color.silver, 95) , title="Middle" , inline="MAB2", group=groupB) lo_color = input.color(color.new(color.blue, 95) , title="Lower" , inline="MAB2", group=groupB) highP1 = plot(showMAb ? h_MAmtf : na , color=color.new(color.silver, 95), title = "Bands - Middle Top" , display=display.none) lowP1 = plot(showMAb ? l_MAmtf : na , color=color.new(color.silver, 95), title = "Bands - Middle Bottom", display=display.none) highP3 = plot(showMAb ? b_High_S : na , color=color.new(color.silver, 95), title = "Bands - Upper Bottom" , display=display.none) lowP3 = plot(showMAb ? b_Low_S : na , color=color.new(color.silver, 95), title = "Bands - Lower Top" , display=display.none) phiPlotHigh = plot(showMAb ? phi_High_S : na , color=color.new(color.silver, 95), title = "Bands - Upper Top" , display=display.none) phiPlotLow = plot(showMAb ? phi_Low_S : na , color=color.new(color.silver, 95), title = "Bands - Lower Bottom" , display=display.none) fill(phiPlotHigh, highP3, hi_color, title = "Bands - Sell Zone") fill(lowP3, phiPlotLow , lo_color, title = "Bands - Buy Zone") fill(highP1, lowP1 , mi_color, title = "Bands - Median Zone") // ------------------------ groupBB = "Bollinger Bands" // ------------------------ visibleBB = input.bool (false , title="B.B.:" , inline="BB1", group=groupBB) lengthBB = input.int (20, minval=1 , title="" , inline="BB1", group=groupBB) srcBB = input (close , title="" , inline="BB1", group=groupBB) resBB = input.timeframe ("" , title="" , inline="BB1", group=groupBB) mult = input.float (2.0 , title="StDev" , inline="BB2", group=groupBB) basis = ta.sma(srcBB, lengthBB) dev = mult * ta.stdev(srcBB, lengthBB) offset = input.int(0, minval=-500, maxval=500, title="Offset", inline="BB2", group=groupBB) BB_color = input.color(color.new(color.silver, 97), title="Fill Color", inline="BB2", group=groupBB) upper = basis + dev lower = basis - dev MTFbasis = request.security(syminfo.tickerid, resBB, basis) MTFupper = request.security(syminfo.tickerid, resBB, upper) MTFlower = request.security(syminfo.tickerid, resBB, lower) plot(visibleBB ? MTFbasis : na , color=color.new(color.silver, 95), offset=offset, display=display.none, title="BB - Basis") p1 = plot(visibleBB ? MTFupper : na , color=color.new(color.silver, 95), offset=offset, display=display.none, title="BB - Upper") p2 = plot(visibleBB ? MTFlower : na , color=color.new(color.silver, 95), offset=offset, display=display.none, title="BB - Lower") fill(p1, p2, color=BB_color, title="BB - Background") // ------------------------ groupGF = "Gaussian Filter" // ------------------------ fact(int n)=> float a = 1 for i = 1 to n a *= i a _alpha(int period, int poles)=> w = 2.0 * math.pi / period float b = (1.0 - math.cos(w)) / (math.pow(1.414, 2.0 / poles) - 1.0) float a = - b + math.sqrt(b * b + 2.0 * b) a _npolegf(float src, int period, int order)=> coeffs = matrix.new<float>(order + 1, 3, 0.) float a = _alpha(period, order) for r = 0 to order out = nz(fact(order) / (fact(order - r) * fact(r)), 1) matrix.set(coeffs, r, 0, out) matrix.set(coeffs, r, 1, math.pow(a, r)) matrix.set(coeffs, r, 2, math.pow(1.0 - a, r)) float filt = src * matrix.get(coeffs, order, 1) int sign = 1 for r = 1 to order filt += sign * matrix.get(coeffs, r, 0) * matrix.get(coeffs, r, 2) * nz(filt[r]) sign *= -1 filt // ------------------------ showGF = input (false , title="G.F.:" , inline="GF1", group=groupGF) periodGF = input.int (144 , title="" , inline="GF1", group=groupGF) orderGF = input.int (4, minval = 1 , title="Poles" , inline="GF2", group=groupGF) srcGF = input (close , title="" , inline="GF1", group=groupGF) LwidthGF = input.int (2, minval=0 , title="Line Width", inline="GF2", group=groupGF) colorGF1 = input.color(color.new(#00FEEF, 25), title="" , inline="GF2", group=groupGF) colorGF2 = input.color(color.new(#E21B22, 25), title="" , inline="GF2", group=groupGF) out = _npolegf(srcGF, periodGF, orderGF) resGF = input.timeframe("", title="", inline="GF1", group=groupGF) mtfGF = request.security(syminfo.tickerid, resGF, out, gaps=barmerge.gaps_off) colorGF = mtfGF > mtfGF[1] ? colorGF1 : mtfGF < mtfGF[1] ? colorGF2 : color.silver plot(showGF ? mtfGF : na, color=colorGF, linewidth=LwidthGF, title="Gaussian Filter") // ------------------------------------- groupRV = "Rolling VWAP & StDev Bands" // ------------------------------------- show_rVWAP = input(false, title="VWAP:" , inline="RV1", group=groupRV) showSTDEV = input(false, title="StDev Bands |", inline="RV2", group=groupRV) rolling_period = input(200, title="", inline="RV1", group=groupRV) src_rVWAP = input(hlc3, title="", inline="RV1", group=groupRV) fillSTDEV = input(true , title="Fill |", inline="RV2", group=groupRV) showrL = input(false , title="Lines:", inline="RV2", group=groupRV) Lwidth_rVWAP = input.int(1, minval=0 , title="Width" , inline="RV2", group=groupRV) showrLC = showrL ? display.all : display.none stDevMultiplier_1 = input.float(0.618 , step=0.1, title="StDev 0.5", inline="StDev1", group=groupRV) stDevMultiplier_2 = input.float(1.0 , step=0.1, title="StDev 1.0", inline="StDev1", group=groupRV) stDevMultiplier_3 = input.float(1.618 , step=0.1, title="StDev 1.5", inline="StDev2", group=groupRV) stDevMultiplier_4 = input.float(2.0 , step=0.1, title="StDev 2.0", inline="StDev2", group=groupRV) stDevMultiplier_5 = input.float(2.618 , step=0.1, title="StDev 2.5", inline="StDev3", group=groupRV) //stDevMultiplier_6 = input.float(3.0 , step=0.1, title="StDev 3.0", inline="StDev6", group=groupRV) rVWAP_color = input.color(color.new(color.silver, 50) , title="Colors: VWAP" , inline="RV3", group=groupRV) up_color = input.color(color.red , title="Upper" , inline="RV3", group=groupRV) lw_color = input.color(color.blue , title="Lower" , inline="RV3", group=groupRV) Vstyle = input(false, title="Circles Line", inline="RV3", group=groupRV) VstyleC = Vstyle ? plot.style_circles : plot.style_line // ------------------------------------- rVWAP(length) => float p = na float vol = na float sn = na p_ = src_rVWAP * volume p := nz(p[1]) + p_ - nz(p_[length]) vol := nz(vol[1]) + volume - nz(volume[length]) v = p / vol sn_ = volume * (src_rVWAP - nz(v[1])) * (src_rVWAP - v) sn := nz(sn[1]) + sn_ - nz(sn_[length]) std = math.sqrt(sn / vol) [v, std] [vwap_r, std_r] = rVWAP(rolling_period) // ------------------------------------- resrVWAP = input.timeframe("", title="", inline="RV1", group=groupRV) mtfrVWAP = request.security(syminfo.tickerid, resrVWAP, vwap_r, gaps=barmerge.gaps_off) mtfSTD = request.security(syminfo.tickerid, resrVWAP, std_r, gaps=barmerge.gaps_off) plot(show_rVWAP ? mtfrVWAP : na, title = "VWAP - Rolling", color=rVWAP_color, linewidth=Lwidth_rVWAP, style=VstyleC) // ------------------------------------- fb_transp = input.float(100, minval=0, maxval=100, title="Transparency", inline="RV4", group=groupRV) fb_step = input.float(5, minval=0, maxval=100, title="Step", inline="RV4", group=groupRV) //fill_col_up5 = color.new(up_color, fb_transp - fb_step * 5) fill_col_up4 = color.new(up_color, fb_transp - fb_step * 4) fill_col_up3 = color.new(up_color, fb_transp - fb_step * 3) fill_col_up2 = color.new(up_color, fb_transp - fb_step * 2) fill_col_up = color.new(up_color, fb_transp - fb_step * 1) //fill_col_mid = color.new(color.silver, fb_transp) fill_col_down = color.new(lw_color, fb_transp - fb_step * 1) fill_col_down2 = color.new(lw_color, fb_transp - fb_step * 2) fill_col_down3 = color.new(lw_color, fb_transp - fb_step * 3) fill_col_down4 = color.new(lw_color, fb_transp - fb_step * 4) //fill_col_down5 = color.new(lw_color, fb_transp - fb_step * 5) // ------------------------------------- rV_stdevU1 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_1 * mtfSTD : na, title="rVWAP - STDEV +1", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevU2 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_2 * mtfSTD : na, title="rVWAP - STDEV +2", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevU3 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_3 * mtfSTD : na, title="rVWAP - STDEV +3", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevU4 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_4 * mtfSTD : na, title="rVWAP - STDEV +4", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevU5 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_5 * mtfSTD : na, title="rVWAP - STDEV +5", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) //rV_stdevU6 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_6 * mtfSTD : na, title="rVWAP - STDEV +6", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevD1 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_1 * mtfSTD : na, title="rVWAP - STDEV -1", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevD2 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_2 * mtfSTD : na, title="rVWAP - STDEV -2", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevD3 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_3 * mtfSTD : na, title="rVWAP - STDEV -3", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevD4 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_4 * mtfSTD : na, title="rVWAP - STDEV -4", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) rV_stdevD5 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_5 * mtfSTD : na, title="rVWAP - STDEV -5", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) //rV_stdevD6 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_6 * mtfSTD : na, title="rVWAP - STDEV -6", color=color.new(color.silver, 75), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC) // ------------------------------------- fill(rV_stdevU1, rV_stdevD1, title="rVWAP - STDEV +-1", color=color.new(color.silver, 95), display=display.none) fill(rV_stdevU2, rV_stdevU1, title="rVWAP - STDEV +2", color= fillSTDEV ? fill_col_up : na) fill(rV_stdevU3, rV_stdevU2, title="rVWAP - STDEV +3", color= fillSTDEV ? fill_col_up2 : na) fill(rV_stdevU4, rV_stdevU3, title="rVWAP - STDEV +4", color= fillSTDEV ? fill_col_up3 : na) fill(rV_stdevU5, rV_stdevU4, title="rVWAP - STDEV +5", color= fillSTDEV ? fill_col_up4 : na) //fill(rV_stdevU6, rV_stdevU5, title="rVWAP - STDEV +6", color= fillSTDEV ? fill_col_up5 : na) fill(rV_stdevD2, rV_stdevD1, title="rVWAP - STDEV -2", color= fillSTDEV ? fill_col_down : na) fill(rV_stdevD3, rV_stdevD2, title="rVWAP - STDEV -3", color= fillSTDEV ? fill_col_down2 : na) fill(rV_stdevD4, rV_stdevD3, title="rVWAP - STDEV -4", color= fillSTDEV ? fill_col_down3 : na) fill(rV_stdevD5, rV_stdevD4, title="rVWAP - STDEV -5", color= fillSTDEV ? fill_col_down4 : na) //fill(rV_stdevD6, rV_stdevD5, title="rVWAP - STDEV -6", color= fillSTDEV ? fill_col_down5 : na)
Distance from Avg + avgs
https://www.tradingview.com/script/JaO79ADU-Distance-from-Avg-avgs/
ta96ninja
https://www.tradingview.com/u/ta96ninja/
9
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/ // © ta96ninja //@version=4 study("Distance from Avg + avgs", overlay=false) len = input(200) smaC = sma(close,len) smaH = sma(high,len) smaL = sma(low,len) smaO = sma(open,len) o = (((open/smaC)-1)*100) h = (((high/smaC)-1)*100) l = (((low/smaC)-1)*100) c = (((close/smaC)-1)*100) plotbar(o,h,l,c) plot(c) plot(c) len1 = input(200) smalen1 = sma((((close/smaC)-1)*100),len1) plot(smalen1, color=color.red) len2 = input(50) smalen2 = sma((((close/smaC)-1)*100),len2) plot(smalen2, color=color.aqua) len3 = input(8) emalen3 = sma((((close/smaC)-1)*100),len3) plot(emalen3, color=color.black) band1 = hline(0,title = "zero line", color=color.black)
Tri-MayerMultiple by USCG_Vet
https://www.tradingview.com/script/kLdWowDo-Tri-MayerMultiple-by-USCG-Vet/
USCG_Vet
https://www.tradingview.com/u/USCG_Vet/
49
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/ // © Written by USCG_Vet; All credit to Trace Mayer. Notice, this indicator is for educational purposes only and is not financial advice. //@version=4 study(title="Tri-MayerMultiple by USCG_Vet", overlay=false) HiOrLow = input(title="high vs low vs avg", type=input.string, defval = "high") n1 = high if HiOrLow == "high" n1 = high else if HiOrLow == "low" n1 = low else n1 = high + low / 2 smavema = input(title="SMA vs EMA", type=input.integer, defval=1, minval=1, maxval=2, step=1) d1 = input(title="Long MA", type=input.integer, defval=150, minval=1, maxval=99999, step=1) ma200d = 0.0 ma21d = 0.0 ma75d = 0.0 if smavema == 2 ma200d := ema(close, d1) else ma200d := sma(close, d1) d2 = input(title="Short MA", type=input.integer, defval=5, minval=1, maxval=99999, step=1) if smavema == 2 ma21d := ema(close, d2) else ma21d := sma(close, d2) d3 = input(title="Med MA", type=input.integer, defval=75, minval=1, maxval=99999, step=1) if smavema == 2 ma75d := ema(close, d3) else ma75d := sma(close, d3) MyerMultiple = n1 / ma200d // Risk is between 0 and n MyerMultipleb = n1 / ma75d // Risk is between 0 and n MyerMultiple2 = n1 / ma21d // Risk is between 0 and n topCol = color.orange plot(MyerMultiple, color=topCol, linewidth=1) bottCol = color.yellow plot(MyerMultipleb, color=bottCol, linewidth=1) plot(MyerMultiple2, color=color.red, linewidth=1)
Crypto-DX Crypto Directional Index [chhslai]
https://www.tradingview.com/script/zteGOrCd-Crypto-DX-Crypto-Directional-Index-chhslai/
chhslai
https://www.tradingview.com/u/chhslai/
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/ // © chhslai // Latest update: 3, Oct, 2022 - GMT+8 23:xx //@version=5 indicator(title="Crypto-DX Crypto Directional Index [chhslai]", shorttitle="Crypto-DX @chhslai") // -------------- // INPUT SETTINGS // -------------- plotAverage = input.bool(true, title="Plot crypto index") plotEach = input.bool(false, title="Plot 5 custom crypto") plotAll = input.bool(false, title="Plot top 30 crypto") rocLength = 21 //input(21, title="ROC length") smoothingLength = 13 //input(13, title="EMA length") labelArrow = input.string("⬅") invisible = color.new(color.black, 100) ticker1 = input.symbol("BINANCE:BTCUSDT", inline="1") color1 = input.color(color.blue,title="", inline="1") ticker2 = input.symbol("BINANCE:ETHUSDT", inline="2") color2 = input.color(color.red, title="", inline="2") ticker3 = input.symbol("BINANCE:BNBUSDT", inline="3") color3 = input.color(color.yellow, title="", inline="3") ticker4 = input.symbol("BINANCE:XRPUSDT", inline="4") color4 = input.color(color.green, title="", inline="4") ticker5 = input.symbol("BINANCE:ADAUSDT", inline="5") color5 = input.color(color.teal, title="", inline="5") // -------------- // MAIN FUNCTIONS // -------------- calc_sroc(_ticker) => src = close ema = ta.ema(src, smoothingLength) sroc = 100 * (ema - ema[rocLength])/ema[rocLength] [sroc] plotEachlabel(_text, _loc, _color)=> var label la = na var counter = 0 counter := counter + 1 label.delete(la) la := plotEach ? label.new( x=timenow, y=_loc, text="                                        " + labelArrow + " " + _text, xloc=xloc.bar_time, yloc=yloc.price, color=invisible, style=label.style_none, textcolor=_color, size=size.small, textalign=text.align_left) : na plotAlllabel(_text, _loc, _color)=> var label la = na var counter = 0 counter := counter + 1 label.delete(la) la := plotAll ? label.new( x=timenow, y=_loc, text="                              " + labelArrow + " " + _text, xloc=xloc.bar_time, yloc=yloc.price, color=invisible, style=label.style_none, textcolor=_color, size=size.small, textalign=text.align_left) : na plotAveragelabel(_text, _loc, _color)=> var label la = na var counter = 0 counter := counter + 1 label.delete(la) la := plotAverage ? label.new( x=timenow, y=_loc, text="                                " + labelArrow + " " + _text, xloc=xloc.bar_time, yloc=yloc.price, color=invisible, style=label.style_none, textcolor=_color, size=size.small, textalign=text.align_left) : na // ----------- // PLOT TOP 30 // ----------- // Crypto Index is consist of TOP 30 cryptocurrencies Market Cap (2022.08.04) // BTC, ETH, BNB, XRP, ADA, SOL, DOT, DOGE, MATIC, AVAX // UNI, SHIB, TRX, ETC, LTC, FTT, CRO, LINK, NEAR // ATOM, XMR, XLM, BCH, ALGO, APE, VET, FIL, ICP, FLOW, MANA [BTC] = request.security("BINANCE:BTCUSDT", "", calc_sroc("BINANCE:BTCUSDT")) [ETH] = request.security("BINANCE:ETHUSDT", "", calc_sroc("BINANCE:ETHUSDT")) [BNB] = request.security("BINANCE:BNBUSDT", "", calc_sroc("BINANCE:BNBUSDT")) [XRP] = request.security("BINANCE:XRPUSDT", "", calc_sroc("BINANCE:XRPUSDT")) [ADA] = request.security("BINANCE:ADAUSDT", "", calc_sroc("BINANCE:ADAUSDT")) [SOL] = request.security("BINANCE:SOLUSDT", "", calc_sroc("BINANCE:SOLUSDT")) [DOT] = request.security("BINANCE:DOTUSDT", "", calc_sroc("BINANCE:DOTUSDT")) [DOGE] = request.security("BINANCE:DOGEUSDT", "", calc_sroc("BINANCE:DOGEUSDT")) [MATIC] = request.security("BINANCE:MATICUSDT", "", calc_sroc("BINANCE:MATICUSDT")) [AVAX] = request.security("BINANCE:AVAXUSDT", "", calc_sroc("BINANCE:AVAXUSDT")) [UNI] = request.security("BINANCE:UNIUSDT", "", calc_sroc("BINANCE:UNIUSDT")) [SHIB] = request.security("BINANCE:SHIBUSDT", "", calc_sroc("BINANCE:SHIBUSDT")) [TRX] = request.security("BINANCE:TRXUSDT", "", calc_sroc("BINANCE:TRXUSDT")) [ETC] = request.security("BINANCE:ETCUSDT", "", calc_sroc("BINANCE:ETCUSDT")) [LTC] = request.security("BINANCE:LTCUSDT", "", calc_sroc("BINANCE:LTCUSDT")) [FTT] = request.security("BINANCE:FTTUSDT", "", calc_sroc("BINANCE:FTTUSDT")) [CRO] = request.security("BYBIT:CROUSDT", "", calc_sroc("BYBIT:CROUSDT")) [LINK] = request.security("BINANCE:LINKUSDT", "", calc_sroc("BINANCE:LINKUSDT")) [NEAR] = request.security("BINANCE:NEARUSDT", "", calc_sroc("BINANCE:NEARUSDT")) [ATOM] = request.security("BINANCE:ATOMUSDT", "", calc_sroc("BINANCE:ATOMUSDT")) [XMR] = request.security("BINANCE:XMRUSDT", "", calc_sroc("BINANCE:XMRUSDT")) [XLM] = request.security("BINANCE:XLMUSDT", "", calc_sroc("BINANCE:XLMUSDT")) [BCH] = request.security("BINANCE:BCHUSDT", "", calc_sroc("BINANCE:BCHUSDT")) [ALGO] = request.security("BINANCE:ALGOUSDT", "", calc_sroc("BINANCE:ALGOUSDT")) [APE] = request.security("BINANCE:APEUSDT", "", calc_sroc("BINANCE:APEUSDT")) [VET] = request.security("BINANCE:VETUSDT", "", calc_sroc("BINANCE:VETUSDT")) [FIL] = request.security("BINANCE:FILUSDT", "", calc_sroc("BINANCE:FILUSDT")) [ICP] = request.security("BINANCE:ICPUSDT", "", calc_sroc("BINANCE:ICPUSDT")) [FLOW] = request.security("BINANCE:FLOWUSDT", "", calc_sroc("BINANCE:FLOWUSDT")) [MANA] = request.security("BINANCE:MANAUSDT", "", calc_sroc("BINANCE:MANAUSDT")) plot(plotAll ? BTC : na, title="BTC", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? ETH : na, title="ETH", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? BNB : na, title="BNB", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? XRP : na, title="XRP", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? ADA : na, title="ADA", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? SOL : na, title="SOL", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? DOT : na, title="DOT", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? DOGE : na, title="DOGE", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? MATIC : na, title="MATIC", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? AVAX : na, title="AVAX", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? UNI : na, title="UNI", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? SHIB : na, title="SHIB", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? TRX : na, title="TRX", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? ETC : na, title="ETC", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? LTC : na, title="LTC", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? FTT : na, title="FTT", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? CRO : na, title="CRO", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? LINK : na, title="LINK", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? NEAR : na, title="NEAR", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? ATOM : na, title="ATOM", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? XMR : na, title="XMR", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? XLM : na, title="XLM", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? BCH : na, title="BCH", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? ALGO : na, title="ALGO", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? APE : na, title="APE", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? VET : na, title="VET", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? FIL : na, title="FIL", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? ICP : na, title="ICP", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? FLOW : na, title="FLOW", linewidth=1, color=color.new(color.white, 65), display=display.pane) plot(plotAll ? MANA : na, title="MANA", linewidth=1, color=color.new(color.white, 65), display=display.pane) plotAlllabel("BTC", BTC, color.new(color.white, 65)) plotAlllabel("ETH", ETH, color.new(color.white, 65)) plotAlllabel("BNB", BNB, color.new(color.white, 65)) plotAlllabel("XRP", XRP, color.new(color.white, 65)) plotAlllabel("ADA", ADA, color.new(color.white, 65)) plotAlllabel("SOL", SOL, color.new(color.white, 65)) plotAlllabel("DOT", DOT, color.new(color.white, 65)) plotAlllabel("DOGE", DOGE, color.new(color.white, 65)) plotAlllabel("MATIC", MATIC, color.new(color.white, 65)) plotAlllabel("AVAX", AVAX, color.new(color.white, 65)) plotAlllabel("UNI", UNI, color.new(color.white, 65)) plotAlllabel("SHIB", SHIB, color.new(color.white, 65)) plotAlllabel("TRX", TRX, color.new(color.white, 65)) plotAlllabel("ETC", ETC, color.new(color.white, 65)) plotAlllabel("LTC", LTC, color.new(color.white, 65)) plotAlllabel("FTT", FTT, color.new(color.white, 65)) plotAlllabel("CRO", CRO, color.new(color.white, 65)) plotAlllabel("LINK", LINK, color.new(color.white, 65)) plotAlllabel("NEAR", NEAR, color.new(color.white, 65)) plotAlllabel("ATOM", ATOM, color.new(color.white, 65)) plotAlllabel("XMR", XMR, color.new(color.white, 65)) plotAlllabel("XLM", XLM, color.new(color.white, 65)) plotAlllabel("BCH", BCH, color.new(color.white, 65)) plotAlllabel("ALGO", ALGO, color.new(color.white, 65)) plotAlllabel("APE", APE, color.new(color.white, 65)) plotAlllabel("VET", VET, color.new(color.white, 65)) plotAlllabel("FIL", FIL, color.new(color.white, 65)) plotAlllabel("ICP", ICP, color.new(color.white, 65)) plotAlllabel("FLOW", FLOW, color.new(color.white, 65)) plotAlllabel("MANA", MANA, color.new(color.white, 65)) // ----------- // PLOT INDEX // ----------- asroc = math.avg(BTC, ETH, BNB, XRP, ADA, SOL, DOT, DOGE, MATIC, AVAX, UNI, SHIB, TRX, ETC, LTC, FTT, CRO, LINK, NEAR, ATOM, XMR, XLM, BCH, ALGO, APE, VET, FIL, ICP, FLOW, MANA) plot(plotAverage ? asroc : na, title="Crypto Index Line", linewidth=3, color=color.white, display=display.pane) plotAveragelabel("Crypto Index", asroc, color.white) hline(0, title="Zero Level", linestyle=hline.style_dotted, color=#989898) // ------------- // PLOT 5 CUSTOM // ------------- [sroc1] = request.security(ticker1, "", calc_sroc(ticker1)) plot(plotEach ? sroc1 : na, title="ticker1", linewidth=1, color=color1, display=display.pane) plotEachlabel(str.tostring(ticker1), sroc1, color1) [sroc2] = request.security(ticker2, "", calc_sroc(ticker2)) plot(plotEach ? sroc2 : na, title="ticker2", linewidth=1, color=color2, display=display.pane) plotEachlabel(str.tostring(ticker2), sroc2, color2) [sroc3] = request.security(ticker3, "", calc_sroc(ticker3)) plot(plotEach ? sroc3 : na, title="ticker3", linewidth=1, color=color3, display=display.pane) plotEachlabel(str.tostring(ticker3), sroc3, color3) [sroc4] = request.security(ticker4, "", calc_sroc(ticker4)) plot(plotEach ? sroc4 : na, title="ticker4", linewidth=1, color=color4, display=display.pane) plotEachlabel(str.tostring(ticker4), sroc4, color4) [sroc5] = request.security(ticker5, "", calc_sroc(ticker5)) plot(plotEach ? sroc5 : na, title="ticker5", linewidth=1, color=color5, display=display.pane) plotEachlabel(str.tostring(ticker5), sroc5, color5)
BSM OPM 1973 w/ Continuous Dividend Yield [Loxx]
https://www.tradingview.com/script/ecJOXGMw-BSM-OPM-1973-w-Continuous-Dividend-Yield-Loxx/
loxx
https://www.tradingview.com/u/loxx/
5
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © loxx //@version=5 indicator("BSM OPM 1973 w/ Continuous Dividend Yield [Loxx]", shorttitle ="BSMOPM1973CDY [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 //'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 div = input.float(2., "% Dividend Yiled", group = "Rates Settings") / 100 string divcmp = input.string(Continuous, "% Dividend Yield 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 divcmpvalue = switch divcmp 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 = kouta - convertingToCCRate(div, divcmpvalue) divmorph = convertingToCCRate(div, divcmpvalue) 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 PhiRho = CGBlackScholes("f", 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 = 37, 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 = "% Dividend Yield: " + str.tostring(div * 100, "##.##") + "%\n" + "Compounding Type: " + divcmp + "\nCC Dividend: " + str.tostring(divmorph * 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 = "% Cost of 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 15, 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 = 16, 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 = 17, 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 = 18, 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 = 19, 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 = 20, 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 = 21, 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 = 22, 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 = 23, 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 = 24, 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 = 25, 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 = 26, 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 = 27, 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 = 28, 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 = 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 = "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 = 31, 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 = 32, 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 = 33, 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 = 34, 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 = 35, 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 = 36, text = "Implied Volatility Newton Raphson: " + str.tostring(impvolnewt * 100, "##.##") + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Highlight candles by time by Vincent
https://www.tradingview.com/script/vntRQSmy-Highlight-candles-by-time-by-Vincent/
vincentmusset2011
https://www.tradingview.com/u/vincentmusset2011/
44
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/ // © u_20bf //@version=5 indicator('Highlight candles by time', overlay=true) // Inputs // TODO: Provide better options display_timeframes = input.string(title='What timeframes to display ?', defval='M5', options=['M5', 'M15', 'M30','H1' ,'H4']) // Times need to be the exchange timezone right now (eg +2 from GMT for FXCM) display_period_one = input.bool(true, 'Display period one?') period_one_session = input.session('1600-1900', 'Period one times') display_period_two = input.bool(false, 'Display period two?') period_two_session = input.session('0800-0900', 'Period two times') display_period_three = input.bool(false, 'Display period three?') period_three_session = input.session('1200-1300', 'Period three times') // TODO: Colour per session candle_colour = color.yellow // Checks display_on_current_timeframe = display_timeframes == 'M5' is_in_session = (display_period_one and time(timeframe.period, period_one_session)) or (display_period_two and time(timeframe.period, period_two_session)) or (display_period_three and time(timeframe.period, period_three_session)) can_colour_candle = display_on_current_timeframe and is_in_session // Colouring barcolor(color=can_colour_candle ? candle_colour : na)
True Range Score
https://www.tradingview.com/script/575aRSfR-True-Range-Score/
peacefulLizard50262
https://www.tradingview.com/u/peacefulLizard50262/
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/ // © peacefulLizard50262 //11 wpnr //@version=5 indicator("True Range Score", "TRS", overlay = false) length = input.int(20, minval=1) 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") src = close tr = ta.rma(high - low, length) dev = (src - ta.sma(src, length))/tr 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) plot(hist, "True Range Score", hist_col, style = plot.style_columns)
Garman and Kohlhagen (1983) for Currency Options [Loxx]
https://www.tradingview.com/script/43KUMLqw-Garman-and-Kohlhagen-1983-for-Currency-Options-Loxx/
loxx
https://www.tradingview.com/u/loxx/
8
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("Garman and Kohlhagen (1983) for Currency Options [Loxx]", shorttitle ="GK1983CO [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 //'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 frrate = input.float(2., "% Foregin Risk-free Rate", group = "Rates Settings") / 100 string frratecmp = input.string(Annual, "% Foregin 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 frratecmpvalue = switch frratecmp 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 = kouta - convertingToCCRate(frrate, frratecmpvalue) frratemorph = convertingToCCRate(frrate, frratecmpvalue) 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 PhiRho = CGBlackScholes("f", 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 = 2, rows = 24, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Garman and Kohlhagen (1983) for Currency Options", 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 = "% Foregin Risk-free: " + str.tostring(frrate * 100, "##.##") + "%\n" + "Compounding Type: " + frratecmp + "\nCC FRRate: " + str.tostring(frratemorph * 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 = "% Cost of 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 15, 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 = 16, 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 = 17, 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 = "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 = 1, row = 2, 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 = 3, text = "Value %Spot: " + str.tostring(price/spot * 100, format.mintick) + "%", bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 4, 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 = 5, 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = 1, row = 15, 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 = 1, row = 16, 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 = 17, 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 = 18, 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 = 19, text = "Risk Neutral Density: " + str.tostring(RiskNeutralDensity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
BB Signal v2.1 [ABA Invest]
https://www.tradingview.com/script/MUsQbltj/
abainvest
https://www.tradingview.com/u/abainvest/
88
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/ // © abainvest //@version=5 indicator(shorttitle="BB Signal v2.1 [ABA Invest]", title="BB Signal v2.1 [ABA Invest]", overlay=true) length = input.int(20, minval=1) source = close multiplier = input.float(2, minval=0.001, maxval=50, title="StdDev") basis = ta.sma(source, length) bb_deviation = multiplier * ta.stdev(source, length) upper_band = basis + bb_deviation lower_band = basis - bb_deviation offset = 0 p1 = plot(upper_band, "Upper", color=color.navy, offset = offset) p2 = plot(lower_band, "Lower", color=color.navy, offset = offset) fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95)) ma1 = ta.sma(close, 1) ma20 = ta.sma(close, 20) ema50 = ta.ema(close, 50) ema200 = ta.ema(close, 200) plot(ma20, "Mid BB", color=color.navy) plot(ema50, "Ema 50", color=color.red, display=display.none) plot(ema200, "Ema 200", color=color.white, display=display.none) upTrend = ma20 > ema50 and ema50 > ema200 and close > ema200 and close[1] > ema200[1] downTrend = ma20 < ema50 and ema50 < ema200 and close < ema200 and close[1] < ema200[1] downCross = ma1 > ema200 and ma1[1] <= ema200[1] upCross = ma1 < ema200 and ma1[1] >= ema200[1] buySignal = upTrend and close >= upper_band and close[1] >= upper_band[1] and close >= open and close[1] >= open[1] sellSignal = downTrend and close <= lower_band and close[1] <= lower_band[1] and close <= open and close[1] <= open[1] var labelsArr = array.new_label(0) var labelsString = array.new_string(0) if (high >= ma20 and downTrend) or downCross array.push(labelsString, "UP") if low <= ma20 and upTrend or upCross array.push(labelsString, "DOWN") if buySignal if array.size(labelsString) > 0 prevLabel = array.get(labelsString, math.max(0, array.size(labelsString) -1)) if prevLabel == "DOWN" or prevLabel == "RESET_SELL" array.push(labelsString, "UP") array.push(labelsArr, label.new(x = bar_index, y = math.max(high, high[1]), text = "BUY",color = color.green, textcolor = color.white,style = label.style_label_up, size=size.tiny, yloc = yloc.belowbar )) if array.size(labelsString) <= 0 array.push(labelsString, "UP") array.push(labelsArr, label.new(x = bar_index, y = math.max(high, high[1]), text = "BUY",color = color.green, textcolor = color.white,style = label.style_label_up, size=size.tiny, yloc = yloc.belowbar )) if sellSignal if array.size(labelsString) > 0 prevLabel = array.get(labelsString, math.max(0, array.size(labelsString) -1)) if prevLabel == "UP" or prevLabel == "RESET_BUY" array.push(labelsString, "DOWN") array.push(labelsArr, label.new(x = bar_index, y = math.min(low, low[1]), text = "SELL",color = color.red,textcolor = color.white,style = label.style_label_down, size=size.tiny, yloc = yloc.abovebar )) if array.size(labelsString) <= 0 array.push(labelsString, "DOWN") array.push(labelsArr, label.new(x = bar_index, y = math.min(low, low[1]), text = "SELL",color = color.red, textcolor = color.white,style = label.style_label_down, size=size.tiny, yloc = yloc.abovebar ))
Asay (1982) Margined Futures Option Pricing Model [Loxx]
https://www.tradingview.com/script/W362GSmU-Asay-1982-Margined-Futures-Option-Pricing-Model-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("Asay (1982) Margined Futures Option Pricing Model [Loxx]", shorttitle ="A1982MFOPM [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 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 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 price = CGBlackScholes("p", OpType, spot, K, T, 0, 0, v) Delta = CGBlackScholes("d", OpType, spot, K, T, 0, 0, v) * sideout Elasticity = CGBlackScholes("e", OpType, spot, K, T, 0, 0, v) * sideout Gamma = CGBlackScholes("g", OpType, spot, K, T, 0, 0, v) * sideout DgammaDvol = CGBlackScholes("gv", OpType, spot, K, T, 0, 0, v) * sideout GammaP = CGBlackScholes("gp", OpType, spot, K, T, 0, 0, v) * sideout Vega = CGBlackScholes("v", OpType, spot, K, T, 0, 0, v) * sideout DvegaDvol = CGBlackScholes("dvdv", OpType, spot, K, T, 0, 0, v) * sideout VegaP = CGBlackScholes("vp", OpType, spot, K, T, 0, 0, v) * sideout Theta = CGBlackScholes("t", OpType, spot, K, T, 0, 0, v) * sideout DDeltaDvol = CGBlackScholes("dddv", OpType, spot, K, T, 0, 0, v) * sideout Speed = CGBlackScholes("s", OpType, spot, K, T, 0, 0, v) * sideout DeltaX = CGBlackScholes("dx", OpType, spot, K, T, 0, 0, v) * sideout RiskNeutralDensity = CGBlackScholes("dxdx", OpType, spot, K, T, 0, 0, v) * sideout impvolbi = gBlackScholesImpVolBisection(OpType, spot, K, T, 0, 0, price) impvolnewt = gImpliedVolatilityNR(OpType, spot, K, T, 0, 0, price, 0.00001) var testTable = table.new(position = position.middle_right, columns = 2, rows = 16, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Asay (1982) Margined Futures 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 = "% 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, 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 = 14, 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 = "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 = 13, 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 = 14, 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 = 15, 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 on Variance Form [Loxx]
https://www.tradingview.com/script/SHgHh05Y-Generalized-Black-Scholes-Merton-on-Variance-Form-Loxx/
loxx
https://www.tradingview.com/u/loxx/
10
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 on Variance Form [Loxx]", shorttitle ="GBSMVF [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 //The generalized Black and Scholes formula on variance form GBlackScholesVariance(string CallPutFlag, float S, float x, float T, float r, float b, float v)=> float d1 = 0 float d2 = 0 float GBlackScholesVariance = 0 d1 := (math.log(S / x) + (b + v / 2) * T) / math.sqrt(v * T) d2 := d1 - math.sqrt(v * T) if CallPutFlag == callString GBlackScholesVariance := S * math.exp((b - r) * T) * cnd.CND1(d1) - x * math.exp(-r * T) * cnd.CND1(d2) else GBlackScholesVariance := x * math.exp(-r * T) * cnd.CND1(-d2) - S * math.exp((b - r) * T) * cnd.CND1(-d1) GBlackScholesVariance GBlackScholesVarianceNGreeks(string OutPutFlag, string CallPutFlag, float S, float x, float T, float r, float b, float v, float dSin)=> float dS = 0 dS := 0.01 float GBlackScholesVarianceNGreeks = 0 if OutPutFlag == "p" GBlackScholesVarianceNGreeks := GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) else if OutPutFlag == "d" // Delta GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v) - GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v)) / (2 * dS) else if OutPutFlag == "e" // Elasticity GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v) - GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v)) / (2 * dS) * S / GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) else if OutPutFlag == "g" // Gamma GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v) - 2 * GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) + GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "gv" // DGammaDvariance GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v + 0.01) - 2 * GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v + 0.01) + GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v + 0.01) - GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v - 0.01) + 2 * GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v - 0.01) - GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if OutPutFlag == "gp" // GammaP GBlackScholesVarianceNGreeks := S / 100 * (GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v) - 2 * GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) + GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v)) / math.pow(dS, 2) else if OutPutFlag == "dddv" // DDeltaDvariance GBlackScholesVarianceNGreeks := 1 / (4 * dS * 0.01) * (GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v + 0.01) - GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v - 0.01) - GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v + 0.01) + GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v - 0.01)) / 100 else if OutPutFlag == "v" // Variance Vega GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v + 0.01) - GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "vp" // Variance VegaP GBlackScholesVarianceNGreeks := v / 0.1 * (GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v + 0.01) - GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v - 0.01)) / 2 else if OutPutFlag == "dvdv" // Variance Dvegavariance GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v + 0.01) - 2 * GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) + GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v - 0.01)) else if OutPutFlag == "t" // Theta if T <= (1 / 365) GBlackScholesVarianceNGreeks := GBlackScholesVariance(CallPutFlag, S, x, 1E-05, r, b, v) - GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) else GBlackScholesVarianceNGreeks := GBlackScholesVariance(CallPutFlag, S, x, T - 1 / 365, r, b, v) - GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) else if OutPutFlag == "r" // Rho GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x, T, r + 0.01, b + 0.01, v) - GBlackScholesVariance(CallPutFlag, S, x, T, r - 0.01, b - 0.01, v)) / 2 else if OutPutFlag == "fr" // Futures options rho GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x, T, r + 0.01, 0, v) - GBlackScholesVariance(CallPutFlag, S, x, T, r - 0.01, 0, v)) / 2 else if OutPutFlag == "f" // Rho2 GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x, T, r, b - 0.01, v) - GBlackScholesVariance(CallPutFlag, S, x, T, r, b + 0.01, v)) / 2 else if OutPutFlag == "b" // Carry GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x, T, r, b + 0.01, v) - GBlackScholesVariance(CallPutFlag, S, x, T, r, b - 0.01, v)) / 2 else if OutPutFlag == "s" // Speed GBlackScholesVarianceNGreeks := 1 / math.pow(dS, 3) * (GBlackScholesVariance(CallPutFlag, S + 2 * dS, x, T, r, b, v) - 3 * GBlackScholesVariance(CallPutFlag, S + dS, x, T, r, b, v) + 3 * GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) - GBlackScholesVariance(CallPutFlag, S - dS, x, T, r, b, v)) else if OutPutFlag == "dx" // Strike Delta GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x + dS, T, r, b, v) - GBlackScholesVariance(CallPutFlag, S, x - dS, T, r, b, v)) / (2 * dS) else if OutPutFlag == "dxdx" // Gamma GBlackScholesVarianceNGreeks := (GBlackScholesVariance(CallPutFlag, S, x + dS, T, r, b, v) - 2 * GBlackScholesVariance(CallPutFlag, S, x, T, r, b, v) + GBlackScholesVariance(CallPutFlag, S, x - dS, T, r, b, v)) / math.pow(dS, 2) GBlackScholesVarianceNGreeks 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(100, "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(10., "% 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 cc = input.float(5., "% Cost of Carry", group = "Rates Settings") / 100 string cccmp = input.string(Continuous, "% Cost of Carry Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float v = input.float(4., "% Variance", 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 cccmpvalue = switch cccmp 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(cc, cccmpvalue) price = GBlackScholesVarianceNGreeks("p", OpType, spot, K, T, kouta, koutb, v, na) Delta = GBlackScholesVarianceNGreeks("d", OpType, spot, K, T, kouta, koutb, v, na) * sideout Elasticity = GBlackScholesVarianceNGreeks("e", OpType, spot, K, T, kouta, koutb, v, na) * sideout Gamma = GBlackScholesVarianceNGreeks("g", OpType, spot, K, T, kouta, koutb, v, na) * sideout DgammaDvol = GBlackScholesVarianceNGreeks("gv", OpType, spot, K, T, kouta, koutb, v, na) * sideout GammaP = GBlackScholesVarianceNGreeks("gp", OpType, spot, K, T, kouta, koutb, v, na) * sideout Vega = GBlackScholesVarianceNGreeks("v", OpType, spot, K, T, kouta, koutb, v, na) * sideout DvegaDvol = GBlackScholesVarianceNGreeks("dvdv", OpType, spot, K, T, kouta, koutb, v, na) * sideout VegaP = GBlackScholesVarianceNGreeks("vp", OpType, spot, K, T, kouta, koutb, v, na) * sideout Theta = GBlackScholesVarianceNGreeks("t", OpType, spot, K, T, kouta, koutb, v, na) * sideout Rho = GBlackScholesVarianceNGreeks("r", OpType, spot, K, T, kouta, koutb, v, na) * sideout RhoFutures = GBlackScholesVarianceNGreeks("fr", OpType, spot, K, T, kouta, koutb, v, na) * sideout PhiRho = GBlackScholesVarianceNGreeks("f", OpType, spot, K, T, kouta, koutb, v, na) * sideout Carry = GBlackScholesVarianceNGreeks("b", OpType, spot, K, T, kouta, koutb, v, na) * sideout DDeltaDvol = GBlackScholesVarianceNGreeks("dddv", OpType, spot, K, T, kouta, koutb, v, na) * sideout Speed = GBlackScholesVarianceNGreeks("s", OpType, spot, K, T, kouta, koutb, v, na) * sideout DeltaX = GBlackScholesVarianceNGreeks("dx", OpType, spot, K, T, kouta, koutb, v, na) * sideout RiskNeutralDensity = GBlackScholesVarianceNGreeks("dxdx", OpType, spot, K, T, kouta, koutb, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 20, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Generalized Black-Scholes-Merton on Variance form", 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(cc * 100, "##.##") + "%\n" + "Compounding Type: " + cccmp + "\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 = "% Variance (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 = 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 = 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 = "Numerical 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 = "DGammaDvariance: " + 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 = "Variance 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 = "Var-Vomma: " + 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 = "Variance 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 ρ: " + str.tostring(Rho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, 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 = 14, text = "Phi/Rho : " + str.tostring(PhiRho, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 15, 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 = 1, row = 16, text = "DDeltaDvariance: " + 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 = 17, 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 = 18, 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 = 19, text = "Risk Neutral Density: " + str.tostring(RiskNeutralDensity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Samuelson 1965 Option Pricing Formula [Loxx]
https://www.tradingview.com/script/QHFCDFzu-Samuelson-1965-Option-Pricing-Formula-Loxx/
loxx
https://www.tradingview.com/u/loxx/
10
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("Samuelson 1965 Option Pricing Formula [Loxx]", shorttitle ="S1965OPF [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 else if OutPutFlag == "b" // Carry Rho CGBlackScholes := GCarry(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 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., "% Average Growth Rate Option", group = "Rates Settings") / 100 string rhocmp = input.string(Continuous, "% Average Growth Rate Option Compounding Type", options = [Continuous, PeriodRate, Annual, SemiAnnual, Quaterly, Monthly], group = "Rates Settings") float grw = input.float(6., "% Average Growth Rate Share", group = "Rates Settings") / 100 string grwcmp = input.string(Continuous, "% Average Growth Rate Share 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 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 rhocmpvalue = switch rhocmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 float grwcmpvalue = switch grwcmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 if barstate.islast sideout = side == "Long" ? 1 : -1 kouta = convertingToCCRate(rf, rhocmpvalue) koutb = convertingToCCRate(grw, grwcmpvalue) 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 RhoExpRoR = CGBlackScholes("r", OpType, spot, K, T, kouta, koutb, v) * sideout Shgrs = 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 StrikeGamma = CGBlackScholes("dxdx", OpType, spot, K, T, kouta, koutb, v) * sideout var testTable = table.new(position = position.middle_right, columns = 2, rows = 18, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Samuelson 1965 Option Pricing Formula", 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 Option: " + 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 = "% Average Growth Rate Share: " + str.tostring(grw * 100, "##.##") + "%\n" + "Compounding Type: " + grwcmp + "\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 = 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 = "Option Growth Rate Sensitivity: " + str.tostring(RhoExpRoR, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 13, text = "Share Growth Rate Sensitivity: " + str.tostring(Shgrs, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, 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 = 15, 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 = 16, 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 = 17, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
True Average Period Traded Range
https://www.tradingview.com/script/joBfkIWY-True-Average-Period-Traded-Range/
priceprophet
https://www.tradingview.com/u/priceprophet/
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/ // © priceprophet //@version=5 indicator("True Average Period Traded Range",shorttitle="Orion:TAPTR",precision=4) masterTrend = 21 APTRvalue = timeframe.period == "12M" ? 10 : timeframe.period == "M" ? 12 : timeframe.period == "W" ? 12 : timeframe.period == "D" ? 21 : timeframe.period == "240" ? 9 : timeframe.period == "60" ? 33 : timeframe.period == "45" ? 9 : timeframe.period == "30" ? 14 : timeframe.period == "15" ? 28 : timeframe.period == "10" ? 42 : timeframe.period == "5" ? 84 : timeframe.period == "1" ? 420 : 21 // Bar Type bt = 0 h0 = math.round(high[0],2) h1 = math.round(high[1],2) l0 = math.round(low[0],2) l1 = math.round(low[1],2) bt := h0 > h1 and l0 > l1 ? 1 : // HHHL - Bull h0 < h1 and l0 < l1 ? 2 : // LHLL - Bear h0 > h1 and l0 < l1 ? 3 : // HHLL - Engulfing h0 < h1 and l0 > l1 ? 4 : // LHHL - Adjustment h0 == h1 and l0 > l1 ? 5 : // EHHL h0 == h1 and l0 < l1 ? 6 : // EHLL h0 > h1 and l0 == l1 ? 7 : // HHEL h0 < h1 and l0 == l1 ? 8 : bt // LHEL currentRange = high - low currentPercent = (currentRange/close[0]) true_APTR = ta.sma(currentRange, APTRvalue) consolidation_APTR = true_APTR * .618 percentOfPrice = (true_APTR/close) consolidation_percentOfPrice = percentOfPrice * .618 meanPercentOfPrice = (percentOfPrice + consolidation_percentOfPrice) / 2 APTRMean = math.avg(true_APTR,consolidation_APTR) masterTrendMA = ta.sma(close,math.round(masterTrend)) masterTrend_TrendDelta = math.abs((close - masterTrendMA))/true_APTR D1 = bt == 1 ? h0 - h1 : 0 D2 = bt == 2 ? l1 - l0 : 0 D3 = bt == 3 ? (h0 - h1) + (l1 - l0) : 0 D4 = bt == 4 ? (h1 - h0) + (l0 - l1) : 0 D = D1 + D2 + D3 + D4 // open space - not overlapping AvgD = ta.sma(D,APTRvalue) // average open space DPoP = (AvgD/close) column_color = masterTrend_TrendDelta > 4.236 ? color.red : masterTrend_TrendDelta > 2.618 ? color.orange : masterTrend_TrendDelta > 1.618 ? color.yellow : masterTrend_TrendDelta > .618 ? color.green: color.blue plot(currentRange,style=plot.style_columns,color=column_color,title='Current Range') plot(currentPercent,color=column_color,title='Current Range Percent of Price') plot(true_APTR,color=color.white,title='APTR') plot(percentOfPrice,color=color.white,title='APTR Percent of Price') plot(consolidation_APTR,color=color.orange,title='Consolidation APTR') plot(consolidation_percentOfPrice,color=color.orange,title='Consolidation Percent of Price') plot(APTRMean,color=color.blue,title='APTR Mean') plot(meanPercentOfPrice,color=color.blue,title='Mean Percent of Price') plot(AvgD,color=color.green,title="Free ATR") plot(DPoP,color=color.green,title="Free ATR Percent of Price")
Boness 1964 Option Pricing Formula [Loxx]
https://www.tradingview.com/script/RjLacOHv-Boness-1964-Option-Pricing-Formula-Loxx/
loxx
https://www.tradingview.com/u/loxx/
10
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("Boness 1964 Option Pricing Formula [Loxx]", shorttitle ="B1964OPF [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., "% Expected Rate of Return Share", group = "Rates Settings") / 100 string rhocmp = input.string(Continuous, "% Expected Rate of Return Share 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 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 rhocmpvalue = switch rhocmp Continuous=> 0 PeriodRate=> math.max(1 / T, 1) Annual=> 1 SemiAnnual=> 2 Quaterly=> 4 Monthly=> 12 => 0 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 RhoExpRoR = 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 StrikeGamma = CGBlackScholes("dxdx", OpType, spot, K, T, kouta, kouta, v) * sideout impvolbi = gBlackScholesImpVolBisection(OpType, spot, K, T, 0, 0, price) impvolnewt = gImpliedVolatilityNR(OpType, spot, K, T, 0, 0, price, 0.00001) var testTable = table.new(position = position.middle_right, columns = 2, rows = 18, bgcolor = color.gray, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Boness 1964 Option Pricing Formula", 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 = "% Expected Rate of Return Share: " + str.tostring(rf * 100, "##.##") + "%\n" + "Compounding Type: " + rhocmp + "\nCC Growth 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 = 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 = "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 = 1, row = 2, 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 = 3, 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 = 4, 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 = 5, 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 = 6, 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 = 7, 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 = 8, 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 = 9, 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 = 10, 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 = 11, 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 = 12, 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 = 13, text = "Rho Expected Rate of Return: " + str.tostring(RhoExpRoR, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left) table.cell(table_id = testTable, column = 1, row = 14, 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 = 15, 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 = 16, 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 = 17, text = "Strike Gamma: " + str.tostring(StrikeGamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = outsize, text_halign = text.align_left)
Trapoints
https://www.tradingview.com/script/pm8ZkyKX-Trapoints/
Sateriok
https://www.tradingview.com/u/Sateriok/
57
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/ // © sateriok //@version=5 indicator("Trapoints", shorttitle = "TP", overlay = true) //Inputs show_c = input(true, title = "Display", group = "Traparilla") i_c_tf = input.timeframe("D", title = "Resolution", options=["D", "W", "M"], tooltip = "Look at using the weekly resolution if you are on the hourly timeframe or higher.", group = "Traparilla") show_f = input(true, title = "Display", group = "Trapanacci") i_f_tf = input.timeframe("", title = "Resolution", group = "Trapanacci") //Price Data //Traparilla [_close, _low, _high, _open] = request.security(syminfo.tickerid, i_c_tf, [close[1], low[1], high[1], open[1]], lookahead = barmerge.lookahead_on) //Trapanacci [f_close, f_low, f_high, f_open] = request.security(syminfo.tickerid, i_f_tf, [close[1], low[1], high[1], open[1]], lookahead = barmerge.lookahead_on) //Colors c5 = _open != _open[1] ? na : color.red c4 = _open != _open[1] ? na : color.orange c3 = _open != _open[1] ? na : color.green c2 = _open != _open[1] ? na : color.yellow c1 = _open != _open[1] ? na : color.silver c0 = _open != _open[1] ? na : color.white //Floor Pivots floor_pivot = (_high + _low + _close) / 3 floor_l1 = (floor_pivot * 2) - _high floor_l2 = floor_pivot - (_high - _low) floor_l3 = _low - 2 * (_high - floor_pivot) floor_h1 = (floor_pivot * 2) - _low floor_h2 = floor_pivot + (_high - _low) floor_h3 = _high + 2 * (floor_pivot - _low) //Traparilla Pivots r = _high - _low center = (_close) h1 = _close + r * (1.1 / 12) h2 = _close + r * (1.1 / 6) h3 = _close + r * (1.1 / 4) h4 = _close + r * (1.1 / 2) h5 = (_high / _low) * _close l1 = _close - r * (1.1 / 12) l2 = _close - r * (1.1 / 6) l3 = _close - r * (1.1 / 4) l4 = _close - r * (1.1 / 2) l5 = _close - (h5 - _close) //Trapanacci Pivots fib_h5 = floor_pivot + ((_high - _low) * 1.000) fib_h4 = floor_pivot + ((_high - _low) * 0.786) fib_h3 = floor_pivot + ((_high - _low) * 0.618) fib_h2 = floor_pivot + ((_high - _low) * 0.500) fib_h1 = floor_pivot + ((_high - _low) * 0.382) fib_l1 = floor_pivot - ((_high - _low) * 0.382) fib_l2 = floor_pivot - ((_high - _low) * 0.500) fib_l3 = floor_pivot - ((_high - _low) * 0.618) fib_l4 = floor_pivot - ((_high - _low) * 0.786) fib_l5 = floor_pivot - ((_high - _low) * 1.000) //Traparilla Plots plot(show_c ? math.round_to_mintick(h5) : na, title = "Traparilla H5", style = plot.style_line, linewidth = 1, color = c5) plot(show_c ? math.round_to_mintick(h4) : na, title = "Traparilla H4", style = plot.style_line, linewidth = 1, color = c4) plot(show_c ? math.round_to_mintick(h3) : na, title = "Traparilla H3", style = plot.style_line, linewidth = 2, color = c2) plot(show_c ? math.round_to_mintick(h2) : na, title = "Traparilla H2", style = plot.style_line, linewidth = 1, color = c3) plot(show_c ? math.round_to_mintick(h1) : na, title = "Traparilla H1", style = plot.style_line, linewidth = 1, color = c3) plot(show_c ? math.round_to_mintick(center) : na, title = "Traparilla Central", style = plot.style_line, linewidth = 1, color = c1) plot(show_c ? math.round_to_mintick(l1) : na, title = "Traparilla L1", style = plot.style_line, linewidth = 1, color = c3) plot(show_c ? math.round_to_mintick(l2) : na, title = "Traparilla L2", style = plot.style_line, linewidth = 1, color = c3) plot(show_c ? math.round_to_mintick(l3) : na, title = "Traparilla L3", style = plot.style_line, linewidth = 2, color = c2) plot(show_c ? math.round_to_mintick(l4) : na, title = "Traparilla L4", style = plot.style_line, linewidth = 1, color = c4) plot(show_c ? math.round_to_mintick(l5) : na, title = "Traparilla L5", style = plot.style_line, linewidth = 1, color = c5) //Trapanacci Plots plot(show_f ? fib_h5 : na, title = "Trapanacci H5", linewidth = 1, style = plot.style_line, color = c3) plot(show_f ? fib_h4 : na, title = "Trapanacci H4", linewidth = 1, style = plot.style_line, color = c3) plot(show_f ? fib_h3 : na, title = "Trapanacci H3", linewidth = 1, style = plot.style_line, color = c3) plot(show_f ? fib_h2 : na, title = "Trapanacci H2", linewidth = 1, style = plot.style_line, color = c3) plot(show_f ? fib_h1 : na, title = "Trapanacci H1", linewidth = 1, style = plot.style_line, color = c3) plot(show_f ? floor_pivot : na, title = "Trapanacci Pivot", linewidth = 1, style = plot.style_line, color = c0) plot(show_f ? fib_l1 : na, title = "Trapanacci L1", linewidth = 1, style = plot.style_line, color = c5) plot(show_f ? fib_l2 : na, title = "Trapanacci L2", linewidth = 1, style = plot.style_line, color = c5) plot(show_f ? fib_l3 : na, title = "Trapanacci L3", linewidth = 1, style = plot.style_line, color = c5) plot(show_f ? fib_l4 : na, title = "Trapanacci L4", linewidth = 1, style = plot.style_line, color = c5) plot(show_f ? fib_l5 : na, title = "Trapanacci L5", linewidth = 1, style = plot.style_line, color = c5)
Orion:Supertrend Hybrid
https://www.tradingview.com/script/6rwdyfZ0-Orion-Supertrend-Hybrid/
priceprophet
https://www.tradingview.com/u/priceprophet/
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/ // © priceprophet //@version=5 indicator("Orion:Supertrend Hybrid", overlay=true, timeframe="", timeframe_gaps=true) len = input.int(title="Length", defval = 12) atrPeriod = input(10, "ATR Length") factor = input.float(3.0, "Factor", step = 0.01) HH = ta.highest(high,len) LL = ta.lowest(low,len) [supertrend, direction] = ta.supertrend(factor, atrPeriod) mean = direction < 0 ? supertrend + (HH - supertrend)/2 : supertrend - (supertrend - LL)/2 bodyMiddle = plot(mean,color=color.yellow) //, display=display.none upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr) downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
Modified Bachelier Option Pricing Model w/ Num. Greeks [Loxx]
https://www.tradingview.com/script/KTT2ddmK-Modified-Bachelier-Option-Pricing-Model-w-Num-Greeks-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("Modified Bachelier Option Pricing Model w/ Num. Greeks [Loxx]", shorttitle ="MBOPMNG [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 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 // Bachelier original 1900 formula bachelierModified(string callputflg, float S, float x, float T, float r, float v)=> float d1 = 0 float d2 = 0 float bachelierModified = 0 d1 := (S - x) / (v * math.sqrt(T)) if callputflg == callString bachelierModified := S * cnd(d1) - x * math.exp(-r * T) * cnd(d1) + v * math.sqrt(T) * nd(d1) else bachelierModified := x * math.exp(-r * T) * cnd(-d1) - S * cnd(-d1) + v * math.sqrt(T) * nd(d1) bachelierModified eBachelierModified(string outputflg, string callputflg, float S, float x, float T, float r, float v, float dSin)=> float dS = 0 if na(dSin) dS := 0.01 float eBachelierModified = 0 if outputflg == "p" // price eBachelierModified := bachelierModified(callputflg, S, x, T, r, v) else if outputflg == "d" // delta eBachelierModified := (bachelierModified(callputflg, S + dS, x, T, r, v) - bachelierModified(callputflg, S - dS, x, T, r, v)) / (2 * dS) else if outputflg == "e" // elasticity eBachelierModified := (bachelierModified(callputflg, S + dS, x, T, r, v) - bachelierModified(callputflg, S - dS, x, T, r, v)) / (2 * dS) * S / bachelierModified(callputflg, S, x, T, r, v) else if outputflg == "g" // gamma eBachelierModified := (bachelierModified(callputflg, S + dS, x, T, r, v) - 2 * bachelierModified(callputflg, S, x, T, r, v) + bachelierModified(callputflg, S - dS, x, T, r, v)) / math.pow(dS, 2) else if outputflg == "gv" //DGammaDVol eBachelierModified := (bachelierModified(callputflg, S + dS, x, T, r, v + 0.01) - 2 * bachelierModified(callputflg, S, x, T, r, v + 0.01) + bachelierModified(callputflg, S - dS, x, T, r, v + 0.01) - bachelierModified(callputflg, S + dS, x, T, r, v - 0.01) + 2 * bachelierModified(callputflg, S, x, T, r, v - 0.01) - bachelierModified(callputflg, S - dS, x, T, r, v - 0.01)) / (2 * 0.01 * math.pow(dS, 2)) / 100 else if outputflg == "gp" // GammaP eBachelierModified := S / 100 * (bachelierModified(callputflg, S + dS, x, T, r, v) - 2 * bachelierModified(callputflg, S, x, T, r, v) + bachelierModified(callputflg, S - dS, x, T, r, v)) / math.pow(dS, 2) else if outputflg == "tg" // time Gamma eBachelierModified := (bachelierModified(callputflg, S, x, T + 1 / 365, r, v) - 2 * bachelierModified(callputflg, S, x, T, r, v) + bachelierModified(callputflg, S, x, T - 1 / 365, r, v)) / math.pow(1 / 365, 2) else if outputflg == "dddv" // DDeltaDvol eBachelierModified := 1 / (4 * dS * 0.01) * (bachelierModified(callputflg, S + dS, x, T, r, v + 0.01) - bachelierModified(callputflg, S + dS, x, T, r, v - 0.01) - bachelierModified(callputflg, S - dS, x, T, r, v + 0.01) + bachelierModified(callputflg, S - dS, x, T, r, v - 0.01)) / 100 else if outputflg == "v" // vega eBachelierModified := (bachelierModified(callputflg, S, x, T, r, v + 0.01) - bachelierModified(callputflg, S, x, T, r, v - 0.01)) / 2 else if outputflg == "vv" // DvegaDvol/vomma eBachelierModified := (bachelierModified(callputflg, S, x, T, r, v + 0.01) - 2 * bachelierModified(callputflg, S, x, T, r, v) + bachelierModified(callputflg, S, x, T, r, v - 0.01)) / math.pow(0.01, 2) / 10000 else if outputflg == "vp" // vegap eBachelierModified := v / 0.1 * (bachelierModified(callputflg, S, x, T, r, v + 0.01) - bachelierModified(callputflg, S, x, T, r, v - 0.01)) / 2 else if outputflg == "dvdv" // DvegaDvol eBachelierModified := (bachelierModified(callputflg, S, x, T, r, v + 0.01) - 2 * bachelierModified(callputflg, S, x, T, r, v) + bachelierModified(callputflg, S, x, T, r, v - 0.01)) else if outputflg == "t" // Theta if T <= (1 / 365) eBachelierModified := bachelierModified(callputflg, S, x, 1E-05, r, v) - bachelierModified(callputflg, S, x, T, r, v) else eBachelierModified := bachelierModified(callputflg, S, x, T - 1 / 365, r, v) - bachelierModified(callputflg, S, x, T, r, v) else if outputflg == "r" // rho eBachelierModified := (bachelierModified(callputflg, S, x, T, r + 0.01, v) - bachelierModified(callputflg, S, x, T, r - 0.01, v)) / 2 else if outputflg == "s" // speed eBachelierModified := 1 / math.pow(dS, 3) * (bachelierModified(callputflg, S + 2 * dS, x, T, r, v) - 3 * bachelierModified(callputflg, S + dS, x, T, r, v) + 3 * bachelierModified(callputflg, S, x, T, r, v) - bachelierModified(callputflg, S - dS, x, T, r, v)) else if outputflg == "dx" // Strike Delta eBachelierModified := (bachelierModified(callputflg, S, x + dS, T, r, v) - bachelierModified(callputflg, S, x - dS, T, r, v)) / (2 * dS) else if outputflg == "dxdx" // strike gamma eBachelierModified := (bachelierModified(callputflg, S, x + dS, T, r, v) - 2 * bachelierModified(callputflg, S, x, T, r, v) + bachelierModified(callputflg, S, x - dS, T, r, v)) / math.pow(dS, 2) eBachelierModified 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 v = input.float(25.6, "Volatility", group = "Volatility Settings", tooltip = "This is volatlity in dollars or whatever currency you choose. This is not a % volatility") 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 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") 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 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) 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' 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, close) / 100 if barstate.islast sideout = side == "Long" ? 1 : -1 price = eBachelierModified("p", OpType, spot, K, T, r, v, na) Delta = eBachelierModified("d", OpType, spot, K, T, r, v, na) * sideout Elasticity = eBachelierModified("e", OpType, spot, K, T, r, v, na) * sideout Gamma = eBachelierModified("g", OpType, spot, K, T, r, v, na) * sideout DgammaDvol = eBachelierModified("gv", OpType, spot, K, T, r, v, na) * sideout GammaP = eBachelierModified("gp", OpType, spot, K, T, r, v, na) * sideout Vega = eBachelierModified("v", OpType, spot, K, T, r, v, na) * sideout DvegaDvol = eBachelierModified("dvdv", OpType, spot, K, T, r, v, na) * sideout VegaP = eBachelierModified("vp", OpType, spot, K, T, r, v, na) * sideout Theta = eBachelierModified("t", OpType, spot, K, T, r, v, na) * sideout DDeltaDvol = eBachelierModified("dddv", OpType, spot, K, T, r, v, na) * sideout Rho = eBachelierModified("r", OpType, spot, K, T, r, v, na) * sideout Speed = eBachelierModified("s", OpType, spot, K, T, r, v, na) * sideout DeltaX = eBachelierModified("dx", OpType, spot, K, T, r, v, na) * sideout GammaX = eBachelierModified("dxdx", OpType, spot, K, T, r, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 1, rows = 31, bgcolor = color.yellow, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Modified Bachelier Option Pricing Model", bgcolor=color.yellow, text_color = color.black, text_size = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, text = "Volatility in currency (annual): " + str.tostring(v, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 6, text = "Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 7, text = "Risk-free Rate Type: " + rfrtype , bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 8, text = "Risk-free Rate: " + str.tostring(r * 100, "##.##") + "% ", bgcolor=darkGreenColor, text_color = color.white, 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 = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 10, text = "Calculated Values (in currency)", bgcolor=color.yellow, text_color = color.black, text_size = size.normal, 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 = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 12, text = "Hist. Daily Volatility: " + str.tostring(hvolout * spot, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 13, text = "Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * spot, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 14, text = "Price", bgcolor=color.yellow, text_color = color.black, text_size = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 30, text = "Strike Gamma: " + str.tostring(GammaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left)
Bachelier 1900 Option Pricing Model w/ Numerical Greeks [Loxx]
https://www.tradingview.com/script/NIVdMK6Y-Bachelier-1900-Option-Pricing-Model-w-Numerical-Greeks-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("Bachelier 1900 Option Pricing Model w/ Numerical Greeks [Loxx]", shorttitle ="B1900OPMNG [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 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 // Bachelier original 1900 formula bachelier(string callputflg, float S, float x, float T, float v)=> float d1 = 0 float d2 = 0 d1 := (S - x) / (v * math.sqrt(T)) float bachelier = 0 if callputflg == callString bachelier := (S - x) * cnd(d1) + v * math.sqrt(T) * nd(d1) else bachelier := (x - S) * cnd(-d1) + v * math.sqrt(T) * nd(d1) bachelier eBachelier(string outputflg, string callputflg, float S, float x, float T, float v, float dSin)=> float eBachelier = 0 float dS = 0 if na(dSin) dS := 0.01 if outputflg == "p" // price eBachelier := bachelier(callputflg, S, x, T, v) else if outputflg == "d" // delta eBachelier := (bachelier(callputflg, S + dS, x, T, v) - bachelier(callputflg, S - dS, x, T, v)) / (2 * dS) else if outputflg == "e" // elasticity eBachelier := (bachelier(callputflg, S + dS, x, T, v) - bachelier(callputflg, S - dS, x, T, v)) / (2 * dS) * S / bachelier(callputflg, S, x, T, v) else if outputflg == "g" // gamma eBachelier := (bachelier(callputflg, S + dS, x, T, v) - 2 * bachelier(callputflg, S, x, T, v) + bachelier(callputflg, S - dS, x, T, v)) / math.pow(dS, 2) else if outputflg == "gv" // DGammaDVol eBachelier := (bachelier(callputflg, S + dS, x, T, v + 0.01) - 2 * bachelier(callputflg, S, x, T, v + 0.01) + bachelier(callputflg, S - dS, x, T, v + 0.01) - bachelier(callputflg, S + dS, x, T, v - 0.01) + 2 * bachelier(callputflg, S, x, T, v - 0.01) - bachelier(callputflg, S - dS, x, T, v - 0.01)) / (2 * 0.01 * dS * dS) / 100 else if outputflg == "gp" // GammaP eBachelier := S / 100 * (bachelier(callputflg, S + dS, x, T, v) - 2 * bachelier(callputflg, S, x, T, v) + bachelier(callputflg, S - dS, x, T, v)) / math.pow(dS ,2) else if outputflg == "tg" // time Gamma eBachelier := (bachelier(callputflg, S, x, T + 1 / 365, v) - 2 * bachelier(callputflg, S, x, T, v) + bachelier(callputflg, S, x, T - 1 / 365, v)) / math.pow((1 / 365), 2) else if outputflg == "dddv" // DvegaDvol eBachelier := 1 / (4 * dS * 0.01) * (bachelier(callputflg, S + dS, x, T, v + 0.01) - bachelier(callputflg, S + dS, x, T, v - 0.01) - bachelier(callputflg, S - dS, x, T, v + 0.01) + bachelier(callputflg, S - dS, x, T, v - 0.01)) / 100 else if outputflg == "v" // vega eBachelier := (bachelier(callputflg, S, x, T, v + 0.01) - bachelier(callputflg, S, x, T, v - 0.01)) / 2 else if outputflg == "vv" // DvegaDvol/vomma eBachelier := (bachelier(callputflg, S, x, T, v + 0.01) - 2 * bachelier(callputflg, S, x, T, v) + bachelier(callputflg, S, x, T, v - 0.01)) / math.pow(0.01, 2) / 10000 else if outputflg == "vp" // VegaP eBachelier := v / 0.1 * (bachelier(callputflg, S, x, T, v + 0.01) - bachelier(callputflg, S, x, T, v - 0.01)) / 2 else if outputflg == "dvdv" // DvegaDvol eBachelier := (bachelier(callputflg, S, x, T, v + 0.01) - 2 * bachelier(callputflg, S, x, T, v) + bachelier(callputflg, S, x, T, v - 0.01)) else if outputflg == "t" // Theta if T <= (1 / 365) eBachelier := bachelier(callputflg, S, x, 1E-05, v) - bachelier(callputflg, S, x, T, v) else eBachelier := bachelier(callputflg, S, x, T - 1 / 365, v) - bachelier(callputflg, S, x, T, v) else if outputflg == "s" // speed eBachelier := 1 / math.pow(dS, 3) * (bachelier(callputflg, S + 2 * dS, x, T, v) - 3 * bachelier(callputflg, S + dS, x, T, v) + 3 * bachelier(callputflg, S, x, T, v) - bachelier(callputflg, S - dS, x, T, v)) else if outputflg == "dx" // strike delta eBachelier := (bachelier(callputflg, S, x + dS, T, v) - bachelier(callputflg, S, x - dS, T, v)) / (2 * dS) else if outputflg == "dxdx" // strike gamma eBachelier := (bachelier(callputflg, S, x + dS, T, v) - 2 * bachelier(callputflg, S, x, T, v) + bachelier(callputflg, S, x - dS, T, v)) / math.pow(dS, 2) eBachelier 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 v = input.float(25.6, "Volatility", group = "Volatility Settings", tooltip = "This is volatlity in dollars or whatever currency you choose. This is not a % volatility") 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") // 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 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 price = eBachelier("p", OpType, spot, K, T, v, na) Delta = eBachelier("d", OpType, spot, K, T, v, na) * sideout Elasticity = eBachelier("e", OpType, spot, K, T, v, na) * sideout Gamma = eBachelier("g", OpType, spot, K, T, v, na) * sideout DgammaDvol = eBachelier("gv", OpType, spot, K, T, v, na) * sideout GammaP = eBachelier("gp", OpType, spot, K, T, v, na) * sideout Vega = eBachelier("v", OpType, spot, K, T, v, na) * sideout DvegaDvol = eBachelier("dvdv", OpType, spot, K, T, v, na) * sideout VegaP = eBachelier("vp", OpType, spot, K, T, v, na) * sideout Theta = eBachelier("t", OpType, spot, K, T, v, na) * sideout DDeltaDvol = eBachelier("dddv", OpType, spot, K, T, v, na) * sideout Speed = eBachelier("s", OpType, spot, K, T, v, na) * sideout DeltaX = eBachelier("dx", OpType, spot, K, T, v, na) * sideout GammaX = eBachelier("dxdx", OpType, spot, K, T, v, na) * sideout var testTable = table.new(position = position.middle_right, columns = 1, rows = 28, bgcolor = color.yellow, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Bachelier 1900 Option Pricing Model", bgcolor=color.yellow, text_color = color.black, text_size = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, 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 = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, text = "Volatility in currency (annual): " + str.tostring(v, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 6, text = "Time Now: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", timenow), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 7, text = "Expiry Date: " + str.format("{0,date,MMMM dd, yyyy - HH:mm:ss}", finish), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 8, text = "Calculated Values (in currency)", bgcolor=color.yellow, text_color = color.black, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 9, text = "Hist. Volatility Type: " + hvoltype, bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 10, text = "Hist. Daily Volatility: " + str.tostring(hvolout * spot, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 11, text = "Hist. Annualized Volatility: " + str.tostring(hvolout * math.sqrt(daysinyear) * spot, "##.##"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 12, text = "Price", bgcolor=color.yellow, text_color = color.black, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 13, text = "Price: " + str.tostring(price, format.mintick), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 14, text = "Numerical Option Sensitivities", bgcolor=color.yellow, text_color = color.black, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 15, text = "Delta Δ: " + str.tostring(Delta, "##.#####"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 16, text = "Elasticity Λ: " + str.tostring(Elasticity, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 17, text = "Gamma Γ: " + str.tostring(Gamma, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 18, text = "DGammaDvol: " + str.tostring(DgammaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 19, text = "GammaP Γ: " + str.tostring(GammaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 20, text = "Vega: " + str.tostring(Vega, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 21, text = "DVegaDvol: " + str.tostring(DvegaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 22, text = "VegaP: " + str.tostring(VegaP, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 23, text = "Theta Θ (1 day): " + str.tostring(Theta, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 24, text = "DDeltaDvol: " + str.tostring(DDeltaDvol, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 25, text = "Speed: " + str.tostring(Speed, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 26, text = "Strike Delta: " + str.tostring(DeltaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 27, text = "Strike Gamma: " + str.tostring(GammaX, "##.########"), bgcolor=darkGreenColor, text_color = color.white, text_size = size.normal, text_halign = text.align_left)