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
|
---|---|---|---|---|---|---|---|---|
SMA Cross with a Price Filter | https://www.tradingview.com/script/A1IRXgJM-SMA-Cross-with-a-Price-Filter/ | Wormhole007 | https://www.tradingview.com/u/Wormhole007/ | 0 | 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/
// © Wormhole007
//@version=5
indicator("SMA Cross with a Filter", overlay=true)
// Input for the length of the SMA
smaLength = input(200, title="SMA Length")
// Input for the percentage threshold
threshold = input(3, title="Percentage Threshold")
// Calculate the 200-day SMA
sma200 = ta.sma(close, smaLength)
// Initialize variables
var bool lastBuySignal = na
var bool lastSellSignal = na
// Generate buy and sell signals
buySignal = ta.crossover(close, sma200 * (1 + threshold / 100)) and (na(lastSellSignal) or lastSellSignal)
sellSignal = ta.crossunder(close, sma200 * (1 - threshold / 100)) and (na(lastBuySignal) or lastBuySignal)
// Track the last buy and sell signals
lastBuySignal := buySignal ? true : (sellSignal ? false : lastBuySignal)
lastSellSignal := sellSignal ? true : (buySignal ? false : lastSellSignal)
// Plot arrows on the chart for entry and exit signals
plotshape(buySignal, title="ENTRY Signal", color=color.green, style=shape.triangleup, location = location.belowbar, size = size.small, text="ENTRY", textcolor = color.green)
plotshape(sellSignal, title="EXIT Signal", color=color.red, style=shape.triangledown, location = location.abovebar, size = size.small, text="EXIT", textcolor = color.red)
// Plot the specified SMA on the chart
plot(sma200, color=color.white, title="SMA")
|
成交额 | https://www.tradingview.com/script/sXeeG50c/ | qqqq95 | https://www.tradingview.com/u/qqqq95/ | 1 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © qqqq95
//@version=5
indicator("成交额")
plot(volume*(close+open+high+low)/4 , style =plot.style_columns)
// TSO = request.financial("BINANCE:BTCUSDT", "EARNINGS_PER_SHARE", "TTM")
// MarketCap = TSO*close
// TV 没有更新加密货币的流通数量数据 也就是说想看换手率要么现差 要么手动撸
// 暂时不急迫 边边角角 |
3 EMA | https://www.tradingview.com/script/LMSsn3gx-3-EMA/ | jatinder.sodhi | https://www.tradingview.com/u/jatinder.sodhi/ | 0 | 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/
// © jatinder.sodhi
//@version=5
//plot(ta.sMA(close,5))
//indicator("ta.sma")
indicator(title="ta.ema", shorttitle="8/21EMA", overlay=true)
m8=ta.ema(close, input(8))
m21=ta.ema(close, input(21))
m200=ta.ema(close,input(200))
plot(m8, color=color.blue)
plot(m21, color=color.black)
plot(m200, color=color.blue, style=plot.style_circles, linewidth = 3)
|
Combined MAs | https://www.tradingview.com/script/n8uSV163/ | OkanAkarsu1 | https://www.tradingview.com/u/OkanAkarsu1/ | 0 | study | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © okan_akarsu1
//@version=5
indicator("Combined MAs", shorttitle="Combined MAs", overlay=true)
// EMA calculations
ema5 = ta.ema(close, 5)
ema13 = ta.ema(close, 13)
ema21 = ta.ema(close, 21)
ema50 = ta.ema(close, 50)
// Moving Averages
ma20 = ta.sma(close, 20)
ma50 = ta.sma(close, 50)
ma100 = ta.sma(close, 100)
ma200 = ta.sma(close, 200)
ma250 = ta.sma(close, 250)
plot(ema5, color=color.blue, title="EMA 5")
plot(ema13, color=color.red, title="EMA 13")
plot(ema21, color=color.black, title="EMA 21")
plot(ema50, color=color.gray, title="EMA 50")
// Plot MAs
plot(ma20, color=color.yellow, title="MA 50")
plot(ma50, color=color.green, title="MA 50")
plot(ma100, color=color.orange, title="MA 100")
plot(ma200, color=color.purple, title="MA 200")
|
NYSE Advance/Decline - OM | https://www.tradingview.com/script/CAEbEH6d-NYSE-Advance-Decline-OM/ | OkoMoye | https://www.tradingview.com/u/OkoMoye/ | 0 | study | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OkoMoye
//@version=5
//ADL Plotting
indicator("NYSE Advance/Decline - OM", 'NYSE Advance/Decline')
snp = request.security("SPX", timeframe = timeframe.period, expression = close)
ad = request.security('NSHF', timeframe = timeframe.period, expression = close)
adcum = ta.cum(ad)
adline = plot(adcum, "A/D Line", color.rgb(149, 207, 255), linewidth = 2)
//Moving Averages
ma20 = ta.sma(adcum, 21)
plot(ma20, 'A/D 89MA', color.blue)
ma50 = ta.sma(adcum, 55)
plot(ma50, '50 Day MA', color.blue)
ma200 = ta.sma(adcum, 244)
plot(ma200, '200 Day MA', color.rgb(149, 207, 255), linewidth = 2)
//Thank you!
//Thank You!
var table thankyou = table.new(position.bottom_left, 1, 1, color.rgb(255, 255, 255, 88))
table.cell(thankyou, 0,0, 'Oko Moye', text_color = color.rgb(255, 255, 255, 66))
|
Custom Price Levels and Averages | https://www.tradingview.com/script/nLm0TsB4-Custom-Price-Levels-and-Averages/ | drmch2020 | https://www.tradingview.com/u/drmch2020/ | 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/
// © drmch2020
//@version=5
indicator("Custom Price Levels and Averages", shorttitle="CPLA", overlay=true)
// Input parameters
inputTimeframe = input("D", title="Input Timeframe")
distancePercentageUp = input(1.5, title="Distance Percentage Up")
distancePercentageDown = input(1.5, title="Distance Percentage Down")
position = input(100, title="Position (USD)")
increaseFactor = input(1.5, title="Increase Factor")
// Color customization
colorPriceA = input(color.white, title="Color Price A")
colorPriceB = input(color.white, title="Color Price B")
colorPriceC = input(color.white, title="Color Price C")
colorAvgPriceUp = input(color.white, title="Color Avg Price Up")
colorPriceX = input(color.white, title="Color Price X")
colorPriceY = input(color.white, title="Color Price Y")
colorPriceZ = input(color.white, title="Color Price Z")
colorAvgPriceDown = input(color.white, title="Color Avg Price Down")
// Function to calculate the average price
calcAvgPrice(priceA, priceB, priceC, position, increaseFactor) =>
(priceA * position + priceB * (position * increaseFactor) + priceC * position * increaseFactor * increaseFactor) / (position + position * increaseFactor + position * increaseFactor * increaseFactor)
// Calculate last candle close price
lastPrice = request.security(syminfo.tickerid, inputTimeframe, close)
// Calculate prices
priceA = lastPrice * (1 + distancePercentageUp / 100)
priceB = priceA * (1 + distancePercentageUp / 100)
priceC = priceB * (1 + distancePercentageUp / 100)
priceX = lastPrice * (1 - distancePercentageDown / 100)
priceY = priceX * (1 - distancePercentageDown / 100)
priceZ = priceY * (1 - distancePercentageDown / 100)
// Calculate average prices
avgPriceUp = calcAvgPrice(priceA, priceB, priceC, position, increaseFactor)
avgPriceDown = calcAvgPrice(priceX, priceY, priceZ, position, increaseFactor)
// Plot horizontal lines
plot(priceA, color=colorPriceA, linewidth=1, title="Price A")
plot(priceB, color=colorPriceB, linewidth=1, title="Price B")
plot(priceC, color=colorPriceC, linewidth=1, title="Price C")
plot(avgPriceUp, color=colorAvgPriceUp, linewidth=1, title="Avg Price Up")
plot(priceX, color=colorPriceX, linewidth=1, title="Price X")
plot(priceY, color=colorPriceY, linewidth=1, title="Price Y")
plot(priceZ, color=colorPriceZ, linewidth=1, title="Price Z")
plot(avgPriceDown, color=colorAvgPriceDown, linewidth=1, title="Avg Price Down")
|
Super Profit sell and buy | https://www.tradingview.com/script/wFtU6ORD/ | angel1224_sanchez | https://www.tradingview.com/u/angel1224_sanchez/ | 4 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © angel1224_sanchez
//@version=4
study("MACD y EMA señales de compra y venta con filtro ATR", overlay=true)
// Definimos la EMA de 20 periodos
ema20 = ema(close, 20)
// Definimos el MACD
[macdLine, signalLine, _] = macd(close, 12, 26, 9)
// Definimos el ATR con un periodo de 14
atr14 = atr(14)
// Definimos la variable de filtro ATR
atrFilter = atr14 * 2 // Ajusta el factor de multiplicación según tu preferencia
// Condiciones para la señal de compra
buySignal = crossover(macdLine, 0) and close > ema20 and close - atrFilter > ema20
// Condiciones para la señal de venta
sellSignal = crossunder(macdLine, 0) and close < ema20 and close + atrFilter < ema20
// Pintamos las señales en el gráfico
plotshape(buySignal, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="BUY")
plotshape(sellSignal, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SELL")
// Pintamos la EMA y el MACD en el gráfico
plot(ema20, color=color.orange, linewidth=2)
plot(macdLine, color=color.blue, linewidth=2)
plot(signalLine, color=color.red, linewidth=2)
|
Range Breakout Signals (Intrabar) [LuxAlgo] | https://www.tradingview.com/script/2Zsl3LwQ-Range-Breakout-Signals-Intrabar-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 892 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Range Breakout Signals (Intrabar) [LuxAlgo]", "LuxAlgo - Range Breakout Signals (Intrabar)", overlay = true)
//-----------------------------------------------------------------------------}
//Settings
//-----------------------------------------------------------------------------{
tf = input.timeframe('1', 'Intrabar Timeframe', inline = 'tf')
auto = input(true, inline = 'tf')
mode = input.string('Trend Following', options = ['Trend Following', 'Reversal'])
filter = input(false, 'Filter Out Successive Signals')
//-----------------------------------------------------------------------------}
//Extremities
//-----------------------------------------------------------------------------{
var float max = na
var float min = na
var usetf = auto ? timeframe.from_seconds(timeframe.in_seconds(timeframe.period) / 20) : tf
[c, n] = request.security_lower_tf(syminfo.tickerid, usetf, [close, bar_index])
//Check for array size
if not auto and timeframe.in_seconds(timeframe.period) / timeframe.in_seconds(tf) <= 2
runtime.error("Chart timeframe is incompatible with intrabar timeframe. Use a lower intrabar timeframe or an higher chart timeframe.")
//Intrabar R2
float r = na
if c.size() > 2
cov = c.covariance(n)
den = c.stdev() * n.stdev()
r := cov / den
r := r * r
max := r < .5 ? high : max
min := r < .5 ? low : min
//-----------------------------------------------------------------------------}
//Breakouts
//-----------------------------------------------------------------------------{
var os = 0
var allow_up = true
var allow_dn = true
up = switch mode
'Reversal' => close > min and open < min and allow_up and os != 1
=> close > max and open < max and allow_up and os != 1
dn = switch mode
'Reversal' => close < max and open > max and allow_dn and os != -1
=> close < min and open > min and allow_dn and os != -1
allow_up := max != max[1] ? true : up ? false : allow_up
allow_dn := min != min[1] ? true : dn ? false : allow_dn
os := not filter ? 0 : up ? 1 : dn ? -1 : os
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Levels
plot(max, 'Upper', max != max[1] ? na : #2157f3)
plot(min, 'Lower', min != min[1] ? na : #2157f3)
//Breakout labels
plotshape(up ? low : na, "Upward Breakout"
, shape.labelup
, location.absolute
, color(na)
, text = "▲"
, textcolor = #089981
, size = size.tiny)
plotshape(dn ? high : na, "Downward Breakout"
, shape.labeldown
, location.absolute
, color(na)
, text = "▼"
, textcolor = #f23645
, size = size.tiny)
//Barcolor
barcolor(close > open and r > .5 ? #089981
: close < open and r > .5 ? #f23645
: c.size() > 0 ? color(na) : na)
//-----------------------------------------------------------------------------} |
Global Central Banks Balance Sheet USD-Adjusted | https://www.tradingview.com/script/S7VdlN4P-Global-Central-Banks-Balance-Sheet-USD-Adjusted/ | SirChub | https://www.tradingview.com/u/SirChub/ | 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/
// © SirChub
//@version=5
indicator("Global Central Banks Balance Sheet USD-Adjusted", overlay=true, scale=scale.right)
i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M'])
unit_input = input.string('Trillions', options=['Millions', 'Billions', 'Trillions'])
units = unit_input == 'Billions' ? 1e3 : unit_input == 'Millions' ? 1e0 : unit_input == 'Trillions' ? 1e6 : na
US_CBBS = (request.security('ECONOMICS:USCBBS', i_res, close)*100)/request.security('TVC:DXY',i_res,close)
CN_CBBS = (request.security('ECONOMICS:CNCBBS',i_res, close))/request.security('FX:USDCNH',i_res,close)
JP_CBBS = (request.security('ECONOMICS:JPCBBS',i_res, close))/request.security('FX:USDJPY',i_res,close)
EU_CBBS = (request.security('ECONOMICS:EUCBBS',i_res, close))*request.security('FX:EURUSD',i_res,close)
UK_CBBS = (request.security('ECONOMICS:GBCBBS',i_res, close))*request.security('FX:GBPUSD',i_res,close)
CH_CBBS = (request.security('ECONOMICS:CHCBBS',i_res, close))*request.security('FX_IDC:CHFUSD',i_res,close)
NO_CBBS = (request.security('ECONOMICS:NOCBBS',i_res, close))/request.security('FX_IDC:USDNOK',i_res,close)
CA_CBBS = (request.security('ECONOMICS:CACBBS',i_res, close))*request.security('FX_IDC:CADUSD',i_res,close)
AU_CBBS = (request.security('ECONOMICS:AUCBBS',i_res, close))*request.security('FX:AUDUSD',i_res,close)
BR_CBBS = (request.security('ECONOMICS:BRCBBS',i_res, close))/request.security('FX_IDC:USDBRL',i_res,close)
ID_CBBS = (request.security('ECONOMICS:IDM2',i_res, close))/request.security('FX_IDC:USDIDR',i_res,close)+(request.security('ECONOMICS:IDFER',i_res, close)-150000000001)
RU_CBBS = (request.security('ECONOMICS:RUCBBS',i_res, close))/request.security('FX_IDC:USDRUB',i_res,close)
MX_CBBS = (request.security('ECONOMICS:MXCBBS',i_res, close))/request.security('FX:USDMXN',i_res,close)
IN_CBBS = (request.security('ECONOMICS:INCBBS',i_res, close))/request.security('FX_IDC:USDINR',i_res,close)
TW_CBBS = (request.security('ECONOMICS:TWCBBS',i_res, close))/request.security('FX_IDC:USDTWD',i_res,close)
TH_CBBS = (request.security('ECONOMICS:THCBBS',i_res, close))/request.security('FX_IDC:USDTHB',i_res,close)
SG_CBBS = (request.security('ECONOMICS:SGCBBS',i_res, close))/request.security('FX_IDC:USDSGD',i_res,close)
KR_CBBS = (request.security('ECONOMICS:KRCBBS',i_res, close))/request.security('FX_IDC:USDKRW',i_res,close)
HK_CBBS = (request.security('ECONOMICS:HKM1',i_res, close))/request.security('FX_IDC:USDHKD',i_res,close)+(request.security('ECONOMICS:HKFER',i_res, close))
Global_CBBS = (US_CBBS+CN_CBBS+JP_CBBS+EU_CBBS+UK_CBBS+KR_CBBS+IN_CBBS+CA_CBBS+AU_CBBS+TW_CBBS+BR_CBBS+CH_CBBS+RU_CBBS+MX_CBBS+TH_CBBS+ID_CBBS+SG_CBBS+HK_CBBS+NO_CBBS)/1e12
var Global_CBBS_offset = 0 // 2-week offset for use with daily charts
if timeframe.isdaily
Global_CBBS_offset := 0
if timeframe.isweekly
Global_CBBS_offset := 0
if timeframe.ismonthly
Global_CBBS_offset := 0
plot(Global_CBBS, title='Global Central Banks Balance Sheet', color=color.new(color.black, 50), style=plot.style_line, offset=Global_CBBS_offset) |
Parabolic Zones | https://www.tradingview.com/script/MjyeWbzi-Parabolic-Zones/ | uzairtahiroffical | https://www.tradingview.com/u/uzairtahiroffical/ | 1 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © UzairTahir
//@version=5
indicator("Parabolic Zonesusd", overlay=true)
start = input(0.02)
increment = input(0.02)
maximum = input(0.2, "Max Value")
sar_values = ta.sar(start, increment, maximum)
sar_value_candle0 = sar_values[0]
sar_value_candle1 = sar_values[1]
//log.info(str.tostring(sar_value_candle1))
//length = input.int(500, title="Line length")
width = input.int(1, title ="Line Width")
//Number of Bars
lastBarsFilterInput = input.int(500, title ="Plotting on past candles")
styleOption = input.string("solid (─)", title="Line Style",
options=["solid (─)", "dotted (┈)", "dashed (╌)",
"arrow left (←)", "arrow right (→)", "arrows both (↔)"])
// STEP 2. Convert the input to a proper line style value
lineStyle = styleOption == "dotted (┈)" ? line.style_dotted :
styleOption == "dashed (╌)" ? line.style_dashed :
styleOption == "arrow left (←)" ? line.style_arrow_left :
styleOption == "arrow right (→)" ? line.style_arrow_right :
styleOption == "arrows both (↔)" ? line.style_arrow_both :
line.style_solid
line = input(title="Show PSAR/SR Reversal? ", defval=true)
red_line = input(title="Red Line ", defval=true)
green_line = input(title="Green Line ", defval=true)
high_of_candle0 = high[0]
low_of_candle0 = low[0]
high_of_candle1 = high[1]
low_of_candle1 = low[1]
var lastbar = last_bar_index
allowedToTrade = (lastbar - bar_index <= lastBarsFilterInput) or barstate.isrealtime
if(low_of_candle1 >= sar_value_candle1 and high_of_candle0 <= sar_value_candle0 and allowedToTrade == true)
alert("Alert in buy zone", alert.freq_once_per_bar_close)
if(line == true and red_line == true)
buy_line = line.new(x1=bar_index-1, y1=sar_value_candle1, x2=bar_index, y2=sar_value_candle1, color=color.rgb(188, 14, 14), width=width, style=lineStyle) //x2=bar_index+length
// Extend the line forever to the right
line.set_extend(id=buy_line, extend=extend.right)
else if(high_of_candle1 <= sar_value_candle1 and low_of_candle0 >= sar_value_candle0 and allowedToTrade == true)
alert("Alert in Sell Zone", alert.freq_once_per_bar_close)
if(line == true and green_line == true)
sell_line = line.new(x1=bar_index-1, y1=sar_value_candle1, x2=bar_index, y2=sar_value_candle1, color=#27d73b, width=width, style=lineStyle) //x2=bar_index+length
// Extend the line forever to the right
line.set_extend(id = sell_line, extend = extend.right) |
[dharmatech] Area Under Yield Curve : US | https://www.tradingview.com/script/CLC3VxCW-dharmatech-Area-Under-Yield-Curve-US/ | dharmatech | https://www.tradingview.com/u/dharmatech/ | 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/
// © dharmatech
//@version=5
// indicator("[dharmatech] Area Under Yield Curve : US", "Area Under Yield Curve : US", overlay = true)
indicator("[dharmatech] Area Under Yield Curve : US", "Area Under Yield Curve : US")
except_4M = 'except 4M'
except_2M_4M_7Y_20Y = 'except 2M 4M 7Y 20Y'
except_1M_2M_4M_7Y_20Y = 'except 1M 2M 4M 7Y 20Y'
except_6M = 'except 6M'
items = input.string(defval = "all", options = ['all', 'except 4M', 'except 4M 20Y', 'except 2M 4M 20Y', except_2M_4M_7Y_20Y, except_1M_2M_4M_7Y_20Y, except_6M])
US01MY = request.security('US01MY', '', close)
US02MY = request.security('US02MY', '', close)
US03MY = request.security('US03MY', '', close)
US04MY = request.security('US04MY', '', close)
US06MY = request.security('US06MY', '', close)
US01Y = request.security('US01Y', '', close)
US02Y = request.security('US02Y', '', close)
US03Y = request.security('US03Y', '', close)
US05Y = request.security('US05Y', '', close)
US07Y = request.security('US07Y', '', close)
US10Y = request.security('US10Y', '', close)
US20Y = request.security('US20Y', '', close)
US30Y = request.security('US30Y', '', close)
// area_section(float width, float a, float b) =>
// math.min(a, b) + width / 2 * math.abs(a - b)
// area of rectangle + area of triangle
// width * height of rectangle + 1/2 * width * height of triangle
area_section(float width, float a, float b) =>
width * math.min(a, b) + width / 2 * math.abs(a - b)
// area =
// area_section(2, DGS1MO, DGS3MO) +
// area_section(3, DGS3MO, DGS6MO) +
// area_section(6, DGS6MO, DGS1) +
// area_section(12, DGS1, DGS2) +
// area_section(12, DGS2, DGS3) +
// area_section(24, DGS3, DGS5) +
// area_section(24, DGS5, DGS7) +
// area_section(36, DGS7, DGS10) +
// area_section(120, DGS10, DGS20) +
// area_section(120, DGS20, DGS30) +
// 0
// complete
area_all =
area_section( 1, US01MY , US02MY ) +
area_section( 1, US02MY , US03MY ) +
area_section( 1, US03MY , US04MY ) +
area_section( 2, US04MY , US06MY ) +
area_section( 6, US06MY , US01Y ) +
area_section( 12, US01Y , US02Y ) +
area_section( 12, US02Y , US03Y ) +
area_section( 24, US03Y , US05Y ) +
area_section( 24, US05Y , US07Y ) +
area_section( 36, US07Y , US10Y ) +
area_section(120, US10Y , US20Y ) +
area_section(120, US20Y , US30Y ) +
0
// except 4M
area_except_4M =
area_section( 1, US01MY , US02MY ) +
area_section( 1, US02MY , US03MY ) +
area_section( 3, US03MY , US06MY ) +
area_section( 6, US06MY , US01Y ) +
area_section( 12, US01Y , US02Y ) +
area_section( 12, US02Y , US03Y ) +
area_section( 24, US03Y , US05Y ) +
area_section( 24, US05Y , US07Y ) +
area_section( 36, US07Y , US10Y ) +
area_section(120, US10Y , US20Y ) +
area_section(120, US20Y , US30Y ) +
0
// except 4M 20Y
area_except_4M_20Y =
area_section( 1, US01MY , US02MY ) +
area_section( 1, US02MY , US03MY ) +
area_section( 3, US03MY , US06MY ) +
area_section( 6, US06MY , US01Y ) +
area_section( 12, US01Y , US02Y ) +
area_section( 12, US02Y , US03Y ) +
area_section( 24, US03Y , US05Y ) +
area_section( 24, US05Y , US07Y ) +
area_section( 36, US07Y , US10Y ) +
area_section(240, US10Y , US30Y ) +
0
// except 2M 4M 20Y
area_except_2M_4M_20Y =
area_section( 2, US01MY , US03MY ) +
area_section( 3, US03MY , US06MY ) +
area_section( 6, US06MY , US01Y ) +
area_section( 12, US01Y , US02Y ) +
area_section( 12, US02Y , US03Y ) +
area_section( 24, US03Y , US05Y ) +
area_section( 24, US05Y , US07Y ) +
area_section( 36, US07Y , US10Y ) +
area_section(240, US10Y , US30Y ) +
0
// except 2M 4M 7Y 20Y
area_except_2M_4M_7Y_20Y =
area_section( 2, US01MY , US03MY ) +
area_section( 3, US03MY , US06MY ) +
area_section( 6, US06MY , US01Y ) +
area_section( 12, US01Y , US02Y ) +
area_section( 12, US02Y , US03Y ) +
area_section( 24, US03Y , US05Y ) +
area_section( 24, US05Y , US10Y ) +
area_section(240, US10Y , US30Y ) +
0
// except 1M 2M 4M 7Y 20Y
area_except_1M_2M_4M_7Y_20Y =
area_section( 3, US03MY , US06MY ) +
area_section( 6, US06MY , US01Y ) +
area_section( 12, US01Y , US02Y ) +
area_section( 12, US02Y , US03Y ) +
area_section( 24, US03Y , US05Y ) +
area_section( 24, US05Y , US10Y ) +
area_section(240, US10Y , US30Y ) +
0
area_except_6M =
area_section( 9, US03MY , US01Y ) +
area_section( 12, US01Y , US02Y ) +
area_section( 12, US02Y , US03Y ) +
area_section( 24, US03Y , US05Y ) +
area_section( 24, US05Y , US10Y ) +
area_section(240, US10Y , US30Y ) +
0
// except 4M 20Y
// area =
// area_section( 1, US01MY , US02MY ) +
// area_section( 1, US02MY , US03MY ) +
// area_section( 3, US03MY , US06MY ) +
// area_section( 6, US06MY , US01Y ) +
// area_section( 12, US01Y , US02Y ) +
// area_section( 12, US02Y , US03Y ) +
// area_section( 24, US03Y , US05Y ) +
// area_section( 24, US05Y , US07Y ) +
// area_section( 36, US07Y , US10Y ) +
// area_section(240, US10Y , US30Y ) +
// 0
// except 4 and 6
// area =
// area_section( 1, US01MY , US02MY ) +
// area_section( 1, US02MY , US03MY ) +
// area_section( 9, US03MY , US01Y ) +
// area_section( 12, US01Y , US02Y ) +
// area_section( 12, US02Y , US03Y ) +
// area_section( 24, US03Y , US05Y ) +
// area_section( 24, US05Y , US07Y ) +
// area_section( 36, US07Y , US10Y ) +
// area_section(120, US10Y , US20Y ) +
// area_section(120, US20Y , US30Y ) +
// 0
area = if items == 'all'
area_all
else if items == 'except 4M'
area_except_4M
else if items == 'except 4M 20Y'
area_except_4M_20Y
else if items == 'except 2M 4M 20Y'
area_except_2M_4M_20Y
else if items == except_2M_4M_7Y_20Y
area_except_2M_4M_7Y_20Y
else if items == except_1M_2M_4M_7Y_20Y
area_except_1M_2M_4M_7Y_20Y
else if items == except_6M
area_except_6M
plot(area, color = color.yellow) |
highwindssoon0411 | https://www.tradingview.com/script/hEP7lr0X-highwindssoon0411/ | thenmozhys | https://www.tradingview.com/u/thenmozhys/ | 0 | 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/
// © thenmozhys
//@version=5
indicator("highwinds soon", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, 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)
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.int(0, title="Offset", group="VWAP Settings", minval=0)
BANDS_GROUP = "Bands Settings"
CALC_MODE_TOOLTIP = "Determines the units used to calculate the distance of the bands. When 'Percentage' is selected, a multiplier of 1 means 1%."
calcModeInput = input.string("Standard Deviation", "Bands Calculation Mode", options = ["Standard Deviation", "Percentage"], group = BANDS_GROUP, tooltip = CALC_MODE_TOOLTIP)
showBand_1 = input(true, title = "", group = BANDS_GROUP, inline = "band_1")
bandMult_1 = input.float(1.0, title = "Bands Multiplier #1", group = BANDS_GROUP, inline = "band_1", step = 0.5, minval=0)
showBand_2 = input(false, title = "", group = BANDS_GROUP, inline = "band_2")
bandMult_2 = input.float(2.0, title = "Bands Multiplier #2", group = BANDS_GROUP, inline = "band_2", step = 0.5, minval=0)
showBand_3 = input(false, title = "", group = BANDS_GROUP, inline = "band_3")
bandMult_3 = input.float(3.0, title = "Bands Multiplier #3", group = BANDS_GROUP, inline = "band_3", step = 0.5, minval=0)
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
bandBasis = calcModeInput == "Standard Deviation" ? stdevAbs : _vwap * 0.01
upperBandValue1 := _vwap + bandBasis * bandMult_1
lowerBandValue1 := _vwap - bandBasis * bandMult_1
upperBandValue2 := _vwap + bandBasis * bandMult_2
lowerBandValue2 := _vwap - bandBasis * bandMult_2
upperBandValue3 := _vwap + bandBasis * bandMult_3
lowerBandValue3 := _vwap - bandBasis * bandMult_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)
len = input.int(9, minval=1, title="Length")
src1 = input(close, title="Source")
offset1= input.int(title="Offset1", defval=0, minval=-500, maxval=500)
out = ta.ema(src1, len)
plot(out, title="EMA", color=color.rgb(55, 12, 247), offset=offset1)
len1 = input.int(44, minval=1, title="Length")
src2 = input(close, title="Source")
offset2 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out1 = ta.ema(src2, len1)
plot(out1, title="EMA", color=color.rgb(179, 8, 247), offset=offset2)
len2 = input.int(20, minval=1, title="Length")
src3 = input(close, title="Source")
offset3 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out2 = ta.ema(src3, len2)
plot(out2, title="EMA", color=color.rgb(247, 231, 8), offset=offset3)
len3 = input.int(200, minval=1, title="Length")
src4 = input(close, title="Source")
offset4= input.int(title="Offset", defval=0, minval=-500, maxval=500)
out3 = ta.ema(src4, len3)
plot(out3, title="EMA", color=color.rgb(255, 255, 252), offset=offset4) |
TotalCustom | https://www.tradingview.com/script/NHJ0TveP-TotalCustom/ | AJMourot | https://www.tradingview.com/u/AJMourot/ | 0 | 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/
// © AJMourot
//@version=5
indicator("TotalCustom", overlay=true, scale=scale.left)
// Fetching MarketCap of each symbol:
MC_CAKE = request.security("CAKE", timeframe.period, close)
MC_ADA = request.security("ADA", timeframe.period, close)
MC_DOT = request.security("DOT", timeframe.period, close)
MC_UNI = request.security("UNI", timeframe.period, close)
MC_SOL = request.security("SOL", timeframe.period, close)
MC_DOGE = request.security("DOGE", timeframe.period, close)
MC_1INCH = request.security("1INCH", timeframe.period, close)
MC_JOE = request.security("JOE", timeframe.period, close)
MC_MATIC = request.security("MATIC", timeframe.period, close)
MC_XRP = request.security("XRP", timeframe.period, close)
MC_BNB = request.security("BNB", timeframe.period, close)
MC_AVAX = request.security("AVAX", timeframe.period, close)
MC_DYDX = request.security("DYDX", timeframe.period, close)
MC_CRV = request.security("CRV", timeframe.period, close)
MC_XMR = request.security("XMR", timeframe.period, close)
MC_LDO = request.security("LDO", timeframe.period, close)
MC_COMP = request.security("COMP", timeframe.period, close)
MC_AAVE = request.security("AAVE", timeframe.period, close)
MC_ICP = request.security("ICP", timeframe.period, close)
MC_LQTY = request.security("LQTY", timeframe.period, close)
MC_SUSHI = request.security("SUSHI", timeframe.period, close)
MC_APTO = request.security("APTO", timeframe.period, close)
MC_OP = request.security("OP", timeframe.period, close)
MC_ARBI = request.security("ARBI", timeframe.period, close)
// Summing up the prices
sumMarketcap = MC_CAKE + MC_ADA + MC_DOT + MC_UNI + MC_SOL + MC_DOGE + MC_1INCH + MC_JOE + MC_MATIC + MC_XRP + MC_BNB + MC_AVAX + MC_DYDX + MC_CRV + MC_XMR + MC_COMP + MC_AAVE + MC_ICP + MC_SUSHI
// Plotting the sum
plot(sumMarketcap, title="TotalCustom", color=color.blue) |
Alert on Candle Close | https://www.tradingview.com/script/4UCBJDQS-Alert-on-Candle-Close/ | SimpleTradingTools | https://www.tradingview.com/u/SimpleTradingTools/ | 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/
// © SimpleTradingTools
//@version=5
indicator("Alert on Candle Close", overlay = true)
var string msg = "{{interval}} Close on {{exchange}}:{{ticker}}\nPrice {{close}}"
alertcondition(timenow >= time_close, title = "Alert on Candle Close", message=msg) |
Tops & Bottoms - Time of Day Report | https://www.tradingview.com/script/ucux0RJL-Tops-Bottoms-Time-of-Day-Report/ | sbtnc | https://www.tradingview.com/u/sbtnc/ | 457 | 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/
// © sbtnc
// Created: 2023-09-26
// Last modified: 2023-11-15
// Version 2.0
//@version=5
indicator("Tops & Bottoms - Time of Day Report", format = format.percent, max_labels_count = 72)
//--------------------------------------------------------------------
//#region Constants
//--------------------------------------------------------------------
int COLUMN_WIDTH = 2
int COLUMN_GAP = 2
color COLUMN_BORDERCOLOR = color.new(chart.fg_color, 80)
color COLUMN_TOP_MAX_COLOR = color.green
color COLUMN_TOP_MIN_COLOR = #0c3299
color COLUMN_BOTTOM_MAX_COLOR = color.red
color COLUMN_BOTTOM_MIN_COLOR = #311b92
color CATEGORY_LABEL_BGCOLOR = color.new(chart.bg_color, 50)
color CATEGORY_LABEL_TEXTCOLOR = chart.fg_color
array<string> TIMEFRAMES = array.from("15", "30", "60")
//#endregion
//--------------------------------------------------------------------
//#region Inputs
//--------------------------------------------------------------------
timezoneTooltip = "Exchange and geographical timezones may observe Daylight Saving Time (DST)."
sessionTooltip = "By default, the indicator identifies the top and bottom over the symbol's session. " +
"You can specify your custom session (in the indicator's timezone)."
noticeTitle = "Navigate to the 1-hour timeframe (30-minute timeframe if the market starts at 𝑥:30 AM or " +
"15-minute timeframe if 𝑥:15 AM) for the indicator to analyze the bars and collect tops and bottoms."
timezoneInput = input.string ("Exchange", "Timezone",
[
"UTC",
"Exchange",
"Africa/Cairo",
"Africa/Johannesburg",
"Africa/Lagos",
"Africa/Nairobi",
"Africa/Tunis",
"America/Argentina/Buenos_Aires",
"America/Bogota",
"America/Caracas",
"America/Chicago",
"America/Denver",
"America/El_Salvador",
"America/Juneau",
"America/Lima",
"America/Los_Angeles",
"America/New_York",
"America/Mexico_City",
"America/Phoenix",
"America/Santiago",
"America/Sao_Paulo",
"America/Toronto",
"America/Vancouver",
"Asia/Almaty",
"Asia/Ashgabat",
"Asia/Bahrain",
"Asia/Bangkok",
"Asia/Dubai",
"Asia/Chongqing",
"Asia/Colombo",
"Asia/Ho_Chi_Minh",
"Asia/Hong_Kong",
"Asia/Istanbul",
"Asia/Jakarta",
"Asia/Jerusalem",
"Asia/Karachi",
"Asia/Kathmandu",
"Asia/Kolkata",
"Asia/Kuwait",
"Asia/Manila",
"Asia/Muscat",
"Asia/Nicosia",
"Asia/Qatar",
"Asia/Riyadh",
"Asia/Seoul",
"Asia/Shanghai",
"Asia/Singapore",
"Asia/Taipei",
"Asia/Tehran",
"Asia/Tokyo",
"Asia/Yangon",
"Atlantic/Reykjavik",
"Australia/Adelaide",
"Australia/Brisbane",
"Australia/Perth",
"Australia/Sydney",
"Europe/Amsterdam",
"Europe/Athens",
"Europe/Belgrade",
"Europe/Berlin",
"Europe/Bratislava",
"Europe/Brussels",
"Europe/Bucharest",
"Europe/Budapest",
"Europe/Copenhagen",
"Europe/Dublin",
"Europe/Helsinki",
"Europe/Madrid",
"Europe/Malta",
"Europe/Moscow",
"Europe/Lisbon",
"Europe/London",
"Europe/Luxembourg",
"Europe/Oslo",
"Europe/Paris",
"Europe/Riga",
"Europe/Rome",
"Europe/Stockholm",
"Europe/Tallinn",
"Europe/Vilnius",
"Europe/Warsaw",
"Europe/Zurich",
"Pacific/Auckland",
"Pacific/Chatham",
"Pacific/Fakaofo",
"Pacific/Honolulu",
"Pacific/Norfolk"
],
timezoneTooltip,
display = display.none
)
customSessionInput = input.bool (false, "Custom Session", inline = "Session")
sessionInput = input.session ("0000-0000", "", tooltip = sessionTooltip, inline = "Session", display = display.none)
sessionTypeInput = input.string ("All", "Session", ["All", "Up", "Down"], group = "Filters")
startDateInput = input.time (timestamp("01 Jan 1975"), "From", group = "Filters")
endDateInput = input.time (timestamp("31 Dec 2050"), "To", group = "Filters")
noticeInput = input.bool (true, noticeTitle, group = "How To Use?", confirm = true, display = display.none)
//#endregion
//--------------------------------------------------------------------
//#region Types
//--------------------------------------------------------------------
type Marker
float price = na
int time = na
//#endregion
//--------------------------------------------------------------------
//#region Variables declarations
//--------------------------------------------------------------------
var topsByHourMap = map.new<int, int>()
var bottomsByHourMap = map.new<int, int>()
var openTimesByHourMap = map.new<int, string>()
var closeTimesByHourMap = map.new<int, string>()
var top = Marker.new()
var bottom = Marker.new()
//#endregion
//--------------------------------------------------------------------
//#region Functions & methods
//--------------------------------------------------------------------
// @function Produce the timezone parameter from the user-selected setting.
// @returns (string) Timezone
getTimezone() =>
var _tz = switch timezoneInput
"UTC" => "UTC+0"
"Exchange" => syminfo.timezone
=> timezoneInput
// @function Get the hour in the user-selected timezone from a given UNIX time.
// @returns (int) Hour
getHour(int barTime) =>
hour(barTime, getTimezone())
// @function Get the color based on a gradient between the minimum and maximum values.
// @returns color
getGradientColor(float value, float minValue, float maxValue, color minColor, color maxColor) =>
// When `minValue` and `maxValue` are identical (on the first collected values), return the mid gradient color instead of no color.
minValue != maxValue ? color.from_gradient(value, minValue, maxValue, minColor, maxColor) : color.from_gradient(0.5, 0, 1, minColor, maxColor)
// @function Draw the columns for a given hour.
// @returns void
drawHourlyColumns(int key) =>
var _upperColumnBox = box.new(na, na, na, na, COLUMN_BORDERCOLOR)
var _lowerColumnBox = box.new(na, na, na, na, COLUMN_BORDERCOLOR)
var _upperDataLabel = label.new(na, na, color = color(na), style = label.style_label_down)
var _lowerDataLabel = label.new(na, na, color = color(na), style = label.style_label_up)
var _categoryLabel = label.new(na, na, color = CATEGORY_LABEL_BGCOLOR, style = label.style_label_center, textcolor = CATEGORY_LABEL_TEXTCOLOR)
var _gridMultiplier = COLUMN_WIDTH + COLUMN_GAP
if barstate.islast
_topsArray = topsByHourMap.values()
_bottomsArray = bottomsByHourMap.values()
// Sum the number of data sampled.
_dataSum = _topsArray.sum()
// Calculate the shares of occurrence of tops and bottoms.
_top = topsByHourMap.get(key)
_bottom = bottomsByHourMap.get(key)
_topY = nz(_top / _dataSum * 100)
_bottomY = nz(_bottom / _dataSum * 100)
// Get the coordinates for plotting the columns chart (on the left or right side of the last bar, given enough space).
_hasSpace = bar_index - 24 * _gridMultiplier > 0
_x1 = _hasSpace ? bar_index + (key - 24) * _gridMultiplier : bar_index + key * _gridMultiplier
_x2 = _x1 + COLUMN_WIDTH
_center = _x1 + COLUMN_WIDTH / 2
// Get the coloring of the columns and data labels.
_topsMin = _topsArray.min() / _dataSum * 100
_topsMax = _topsArray.max() / _dataSum * 100
_bottomsMin = _bottomsArray.min() / _dataSum * 100
_bottomsMax = _bottomsArray.max() / _dataSum * 100
_topColor = getGradientColor(_topY, _topsMin, _topsMax, COLUMN_TOP_MIN_COLOR, COLUMN_TOP_MAX_COLOR)
_bottomColor = getGradientColor(_bottomY, _bottomsMin, _bottomsMax, COLUMN_BOTTOM_MIN_COLOR, COLUMN_BOTTOM_MAX_COLOR)
// Plot the upper and lower columns for tops and bottoms.
_upperColumnBox.set_lefttop (_x1, _topY)
_upperColumnBox.set_rightbottom (_x2, 0)
_upperColumnBox.set_bgcolor (_topColor)
_lowerColumnBox.set_lefttop (_x1, 0)
_lowerColumnBox.set_rightbottom (_x2, -_bottomY)
_lowerColumnBox.set_bgcolor (_bottomColor)
// Plot the X-axis category label.
_openTime = openTimesByHourMap.get(key)
_closeTime = closeTimesByHourMap.get(key)
_isCategoryDefined = not (na(_openTime) or na(_closeTime))
_categoryLabel.set_xy (_center, 0)
_categoryLabel.set_text (str.tostring(key))
_categoryLabel.set_tooltip (_isCategoryDefined ? str.format("{0} to {1} ({2})", _openTime, _closeTime, getTimezone()) : "Not Collected")
// Plot the data labels for tops and bottoms.
if not na(_top)
_upperDataLabel.set_xy (_center, _topY)
_upperDataLabel.set_text (str.tostring(math.round(_topY)))
_upperDataLabel.set_textcolor (_topColor)
_upperDataLabel.set_tooltip (str.format("{0} based on {1} sampled days", str.tostring(_topY, format.percent), _dataSum))
if not na(_bottom)
_lowerDataLabel.set_xy (_center, -_bottomY)
_lowerDataLabel.set_text (str.tostring(math.round(_bottomY)))
_lowerDataLabel.set_textcolor (_bottomColor)
_lowerDataLabel.set_tooltip (str.format("{0} based on {1} sampled days", str.tostring(_bottomY, format.percent), _dataSum))
// @function Check if the day/custom session matches the user-selected session type filter.
// @returns bool
isValidSessionType(start, end) =>
var float _open = na
bool _isValid = na
if start
_open := open
if end
_isValid := switch sessionTypeInput
"All" => not na(_open[1])
"Up" => close[1] > _open[1]
"Down" => close[1] < _open[1]
_isValid
// @function Check if the current bar time is in the user-selected time range filter.
// @returns bool
isInTimeRange() =>
time >= startDateInput and time <= endDateInput
// @function Produce the UNIX time of the current date at a specified time in the user-selected timezone.
// @returns (int) UNIX time
getTime(int h, int m) =>
timestamp(getTimezone(), year, month, dayofmonth, h, m, second)
// @function Get the current day's session dates from a given session string.
// @returns ([int, int]) Start and end UNIX time
getSessionTimes(sessionString) =>
[getTime(int(str.tonumber(str.substring(sessionString, 0, 2))), int(str.tonumber(str.substring(sessionString, 2, 4)))),
getTime(int(str.tonumber(str.substring(sessionString, 5, 7))), int(str.tonumber(str.substring(sessionString, 7))))]
// @function Detect changes in the day/custom session and if the current bar is in the session.
// @returns [bool, bool, bool]
sessionChange() =>
if customSessionInput
var int _startTime = na
var int _endTime = na
_isInSession = not na(time(timeframe.period, sessionInput, getTimezone()))
[_currentStartTime, _currentEndTime] = getSessionTimes(sessionInput)
// On overnight sessions (e.g., EURUSD), preserve original start and end times.
_startTime := time >= _currentStartTime ? _currentStartTime : _startTime
_endTime := time >= _currentEndTime ? _currentEndTime : _endTime
// Start on the first bar of the session.
_start = ta.change(_startTime) > 0 and _isInSession
// End after the last bar of the session.
_end = ta.change(_endTime) > 0 and _isInSession[1]
[_start, _end, _isInSession]
else
// Start and end on the day change.
_dayChange = timeframe.change("D")
[_dayChange, _dayChange, true]
//#endregion
//--------------------------------------------------------------------
//#region Logic
//--------------------------------------------------------------------
if TIMEFRAMES.indexof(timeframe.period) == -1
runtime.error("The report can not compute data on the chart's timeframe. Please navigate to the 1-hour, 30-minute, or 15-minute timeframe.")
//@variable Is true when the current bar is inside the time range filter.
isInRange = isInTimeRange()
// Session variables from the day/custom session.
[sessionStart, sessionEnd, isInSession] = sessionChange()
// @variable Is true when the day/custom session closes per the session type filter.
isValidType = isValidSessionType(sessionStart, sessionEnd)
// Track the top and bottom of the day/custom session.
if isInRange
// Reset the top and bottom on the first bar of a new day/custom session.
if sessionStart
top.price := na
top.time := na
bottom.price := na
bottom.time := na
// Track the top and bottom.
if na(top.price) or high > top.price
top.price := high
top.time := time
if na(bottom.price) or low < bottom.price
bottom.price := low
bottom.time := time
// Collect the top, bottom, and time data.
if isInRange and barstate.isconfirmed
// @variable Is true on the first bar of the time range.
_isFirstBar = na(top.time[1]) or na(bottom.time[1])
// Collect the top and bottom on matching type on a day/custom session change.
if isValidType and not _isFirstBar
_topHour = getHour(top.time[1])
_bottomHour = getHour(bottom.time[1])
_topCount = nz(topsByHourMap.get(_topHour)) +1
_bottomCount = nz(bottomsByHourMap.get(_bottomHour)) +1
topsByHourMap.put (_topHour, _topCount)
bottomsByHourMap.put(_bottomHour, _bottomCount)
log.info("\n▲ Top at {0} ({1}/{4})\n▼ Bottom at {2} ({3}/{4})", _topHour, _topCount, _bottomHour, _bottomCount, topsByHourMap.values().sum())
// Collect the hourly opening and closing times
// On hourly time change, collect the open time and preceding close time.
// The times are be displayed in the tooltips of category labels.
_barHour = getHour(time)
_prevBarHour = getHour(time[1])
if _prevBarHour != _barHour
openTimesByHourMap.put (_barHour, str.format_time(time, "HH:mm", getTimezone()))
closeTimesByHourMap.put(_prevBarHour, str.format_time(time_close[1], "HH:mm", getTimezone()))
//#endregion
//--------------------------------------------------------------------
//#region Visuals
//--------------------------------------------------------------------
drawHourlyColumns(0)
drawHourlyColumns(1)
drawHourlyColumns(2)
drawHourlyColumns(3)
drawHourlyColumns(4)
drawHourlyColumns(5)
drawHourlyColumns(6)
drawHourlyColumns(7)
drawHourlyColumns(8)
drawHourlyColumns(9)
drawHourlyColumns(10)
drawHourlyColumns(11)
drawHourlyColumns(12)
drawHourlyColumns(13)
drawHourlyColumns(14)
drawHourlyColumns(15)
drawHourlyColumns(16)
drawHourlyColumns(17)
drawHourlyColumns(18)
drawHourlyColumns(19)
drawHourlyColumns(20)
drawHourlyColumns(21)
drawHourlyColumns(22)
drawHourlyColumns(23)
//#endregion |
New York Sessions Morning, Lunch and afternoon. AMK | https://www.tradingview.com/script/Yxew6PJC-New-York-Sessions-Morning-Lunch-and-afternoon-AMK/ | Ahmed_Alshammari | https://www.tradingview.com/u/Ahmed_Alshammari/ | 1 | 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/
// © mickeyahs, tony-ho
//@version=4
study("New York Sessions with Timezone", shorttitle="NY Sessions", overlay=true)
// User Inputs for New York Sessions and Times
show_rectangleNY = input(true, title="Show New York Session?")
colorMorning = input(color.blue, title="Morning Session Color")
colorLunch = input(color.orange, title="Lunchtime Session Color")
colorAfternoon = input(color.green, title="Afternoon Session Color")
// User Input for Timezone (in minutes, default is EST)
timeZoneOffset = input(0, title="Timezone offset in minutes", minval=-720, maxval=720)
timeMorning_start = input(9 * 60 + 30, title="Morning Start Time in minutes from midnight EST")
timeMorning_end = input(11 * 60 + 30, title="Morning End Time in minutes from midnight EST")
timeLunch_start = input(11 * 60 + 30, title="Lunch Start Time in minutes from midnight EST")
timeLunch_end = input(13 * 60 + 30, title="Lunch End Time in minutes from midnight EST")
timeAfternoon_start = input(13 * 60 + 30, title="Afternoon Start Time in minutes from midnight EST")
timeAfternoon_end = input(16 * 60, title="Afternoon End Time in minutes from midnight EST")
// Time Session Function
isSession(timeStart, timeEnd) =>
adjustedTime = (timestamp("America/New_York", year, month, dayofmonth, hour, minute) - timestamp("America/New_York", year, month, dayofmonth, 0, 0) + timeZoneOffset * 60 * 1000) % 86400000
adjustedTime >= timeStart * 60 * 1000 and adjustedTime <= timeEnd * 60 * 1000
// Apply Background Color for each sub-session
bgcolor(show_rectangleNY and isSession(timeMorning_start, timeMorning_end) ? colorMorning : na, transp=90)
bgcolor(show_rectangleNY and isSession(timeLunch_start, timeLunch_end) ? colorLunch : na, transp=90)
bgcolor(show_rectangleNY and isSession(timeAfternoon_start, timeAfternoon_end) ? colorAfternoon : na, transp=90)
|
sᴛᴀɢᴇ ᴀɴᴀʏʟsɪs | https://www.tradingview.com/script/9g0z2oBy-s%E1%B4%9B%E1%B4%80%C9%A2%E1%B4%87-%E1%B4%80%C9%B4%E1%B4%80%CA%8F%CA%9Fs%C9%AAs/ | thebearfib | https://www.tradingview.com/u/thebearfib/ | 126 | 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/
// © thebearfib
//@version=5
indicator("sᴛᴀɢᴇ ᴀɴᴀʏʟsɪs", overlay = true)
sma30 = ta.sma(close,30)
plot(sma30,title = "SMA 30",
color=color.rgb(255, 0, 0),
linewidth=2,
display=display.all)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Inputs ———————————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
_Xxq = input(false,'═══════ sᴛᴀɢᴇ ᴀɴᴀʏʟsɪs ════════════════════')
showxA = input.bool(defval = true, title = "Show sᴛᴀɢᴇ ᴀɴᴀʏʟsɪs",
group='Toggle Stats', inline='1')
position3b = input.string("Bottom Right","- Table Position",
options = ["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"],
group='Toggle Stats', inline='1')
_skSP500 = input.symbol("SP:SPX", "Symbol")
_sp500 = request.security(_skSP500, 'D', close)
autodraw_lookback_period =input.int(defval = 504,title = "LookBack AutoDraw resistance & support",minval = 63,maxval = 1260,step = 21)
gap_between_2_lines =input.int(defval = 15,title = "Days gap between 2 same stage lines",minval = 5,maxval =63,step = 1)
///
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Start Array / Moving Avgs ————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
var stages = array.new_int()
var stages2 = array.new_float()
ema126=ta.ema(close,126),vwmah126=ta.vwma(high,126),vwma126=ta.vwma(ohlc4,126)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Market Conditions Table Stats ——————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
rs=(close/_sp500)
rs21=ta.ema(rs,21)
rs42=ta.ema(rs,42)
rs63=ta.ema(rs,63)
rs72=ta.ema(rs,72)
rs84=ta.ema(rs,84)
rs126=ta.ema(rs,126)
rs147=ta.ema(rs,147)
rs168=ta.ema(rs,168)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Set High/Low —————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
hh7=ta.highest(high,7)
hh15=ta.highest(high,15)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Variables ————————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
var stage1_line_bar_index = 0
var stage1_proper_line_bar_index = 0
var stage3_line_bar_index = 0
var stage2_line_bar_index = 0
var stage2_proper_line_bar_index = 0
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Stage Conditions ————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
if(rs>=rs84 and rs < rs126)
//stage 1
array.push(stages,1)
array.push(stages2,1)
else if(rs < rs42 and rs >= rs72 and rs >= rs84 and rs >= rs126 and (rs42 > rs63 or rs < rs63) and rs63 > rs126 and close >= ema126)
//stage 3
array.push(stages,3)
array.push(stages2,3)
else if(rs >= rs168 and rs >= rs147 and rs>=rs126 and close>=ema126 and (rs21 >= rs42 or rs42 >= rs63))
//stage 2
array.push(stages,2)
array.push(stages2,2.1)
else if(rs>=rs126 and close>=ema126 and (rs21 >= rs42 or rs42 >= rs63))
//stage 2
array.push(stages,2)
array.push(stages2,2)
else if((rs<rs63 and rs < rs126) or (rs63 < rs126 and rs < rs126))
//stage 4
array.push(stages,4)
array.push(stages2,4)
else if((open >= ema126 or close >= ema126) and rs >= rs72 and rs < rs126)
//stage 1
array.push(stages,1)
array.push(stages2,1)
else if(rs >= rs84 and rs >= rs72 and (open >= ema126 or close >= ema126))
//stage 1
array.push(stages,1)
array.push(stages2,1)
else
array.push(stages,0)
array.push(stages2,0)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Table Layouts ————————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
tableposGo2 = switch position3b
"Top Right" => position.top_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Middle Right" => position.middle_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Bottom Right" => position.bottom_right
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
if barstate.islast or barstate.islastconfirmedhistory
var table tab = table.new(tableposGo2, 99, 99,
bgcolor = color.rgb(255, 255, 255, 100),
frame_color=color.rgb(255, 255, 255, 100),
frame_width = 1,
border_color =color.rgb(255, 255, 255, 100),
border_width = 1)
if showxA
table.cell(tab, 1, 1, "sᴛᴀɢᴇ ᴀɴᴀʏʟsɪs:",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 1, str.tostring(stages.last()), text_color = color.white, text_halign = text.align_left)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Is it ever really the End? ——————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// |
Price Volume Divergence | https://www.tradingview.com/script/Znymjshs-Price-Volume-Divergence/ | kikfraben | https://www.tradingview.com/u/kikfraben/ | 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/
// © kikfraben
// Updated last on Sep. 24, 2023
//@version=5
indicator("Price Volume Divergence", shorttitle = "PVD", overlay = false)
// User Inputs
pvd_cor_len = input(30, "PVD Length", group = "PVD Inputs")
// Calculations
pvd_price = close
pvd_vol = volume
pvd_cor = ta.correlation(pvd_price, pvd_vol, pvd_cor_len)
pvd_col = pvd_cor > 0 ? #3fa8c9 : #c93f3f
// Plots
plot(pvd_cor, color = pvd_col)
// H-Lines
zero_line = hline(0, color = color.gray, linestyle = hline.style_dashed, linewidth = 1)
l = hline(-0.75, color = color.new(#c93f3f, 90), linestyle = hline.style_solid)
ll = hline(-1, color = color.new(#c93f3f, 90), linestyle = hline.style_solid)
h = hline(0.75, color = color.new(#3fa8c9, 90), linestyle = hline.style_solid)
hh = hline(1, color = color.new(#3fa8c9, 90), linestyle = hline.style_solid)
// H-Line Fill
fill(l, ll, color = color.new(#c93f3f, 90))
fill(h, hh, color = color.new(#3fa8c9, 90)) |
BearMetrics | https://www.tradingview.com/script/8ErgYJlr-BearMetrics/ | thebearfib | https://www.tradingview.com/u/thebearfib/ | 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/
// © thebearfib
//
//@version=5
indicator("BearMetrics", overlay = true)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Time / Ticker / Source —————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
///
res = timeframe.period
s = syminfo.tickerid
closeDa = request.security(s, res, close)
source = close
//
// Day Closing range
[dayOpen, dayHigh, dayLow, dayClose] = request.security(syminfo.tickerid, 'D',[open,high,low,close], lookahead = barmerge.lookahead_on)
_dChg = (dayClose - dayLow) / (dayHigh - dayLow)
// week Closing range
[weekOpen, weekHigh, weekLow, weekClose] = request.security(syminfo.tickerid, 'W',[open,high,low,close], lookahead = barmerge.lookahead_on)
_wkChg = (weekClose - weekLow) / (weekHigh - weekLow)
//
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— sᴛᴀᴛs ᴛᴀʙʟᴇ Inputs —————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
_Xxd = input(false,'═══════ sᴛᴀᴛs ᴛᴀʙʟᴇ ═════════════════════')
showxD = input.bool(defval = false, title = "🏦 Show Bankrupcy Potential Scored & Factors: ", group='Toggle Stats', inline='2')
showxA = input.bool(defval = true, title = "🧮 Show Key Fundamental Metrics",
group='Toggle Stats', inline='1')
position3b = input.string("Bottom Right","Table Position",
options = ["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"],
group='Toggle Stats', inline='3')
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Shares outstanding calcs —————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
TSO = request.financial(s, 'TOTAL_SHARES_OUTSTANDING', 'FQ', ignore_invalid_symbol=true)
MCap = TSO
MCapCalc = MCap
uM = ''
if(MCap >= 1000 and MCap < 1000000)
MCap := MCap/1000
uM := 'K'
if(MCap >= 1000000 and MCap < 1000000000)
MCap := MCap/1000000
uM := 'M'
if(MCap >= 1000000000)
MCap := MCap/1000000000
uM := 'B'
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Float Calcs ———————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
FSO = request.financial(s, 'FLOAT_SHARES_OUTSTANDING', 'FY', ignore_invalid_symbol=true)
FFMCap = FSO * closeDa
floatPer = FFMCap/MCapCalc*100
_sN = syminfo.ticker
_alt = request.financial(syminfo.tickerid, "ALTMAN_Z_SCORE", "FY")
_gram = request.financial(syminfo.tickerid, "GRAHAM_NUMBERS", "FY")
_pk = request.financial(syminfo.tickerid, "PIOTROSKI_F_SCORE", "FQ")
_ff = request.financial(syminfo.tickerid, "FULMER_H_FACTOR", "FY")//
_fso = request.financial(syminfo.tickerid, "FLOAT_SHARES_OUTSTANDING", "FY")
institutionData = request.security(syminfo.tickerid, 'D', close)
totalSharesOutstanding = _fso // Replace with the actual total shares outstanding for your symbol
institutionPercent = ((institutionData / totalSharesOutstanding) * institutionData)
arp = 100 * (ta.sma(high / low, 21) - 1)
adrp = request.security(syminfo.tickerid, 'D', arp)
MCapz = _fso*closeDa
MCapCalcz = MCapz
uMz = ''
if(MCapz >= 1000 and MCapz < 1000000)
MCapz := MCapz/1000
uMz := 'K'
if(MCapz >= 1000000 and MCapz < 1000000000)
MCapz := MCapz/1000000
uMz := 'M'
if(MCapz >= 1000000000)
MCapz := MCapz/1000000000
uMz := 'B'
///
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Pull in Data ——————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
finra_fnra = 'QUANDL:FINRA/FNRA_' + syminfo.ticker
finra_fnyx = 'QUANDL:FINRA/FNYX_' + syminfo.ticker
finra_fnsq = 'QUANDL:FINRA/FNSQ_' + syminfo.ticker
bats_bats = 'QUANDL:BATS/BATS_' + syminfo.ticker
bats_byxx = 'QUANDL:BATS/BYXX_' + syminfo.ticker
bats_edga = 'QUANDL:BATS/EDGA_' + syminfo.ticker
bats_edgx = 'QUANDL:BATS/EDGX_' + syminfo.ticker
sector = syminfo.sector
industry = syminfo.industry
_TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
MarketCap = _TSO * close
/////
total_short_interest = request.security(finra_fnyx, 'D',
close, barmerge.gaps_on) + request.security(finra_fnsq, 'D', close, barmerge.gaps_on)
///
//To calculate the short interest ratio, divide the number of shorted shares by the average daily trading volume.
//The number tells you how many days it would take investors to close out short positions on the open market.
//When the short interest ratio is high, it suggests investors are bearish about a stock.
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Colors library ——————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
import kaigouthro/hsvColor/15 as HSV
var colArr = array.new_color()
if barstate.isfirst
for i = 0 to 5
colX = HSV.hsv_gradient(i, 0, 5, color.lime, color.white)
colArr.push(colX)
percent = 1 - ((ta.accdist - math.sum(ta.accdist, 252) / 252) / ta.accdist)
col = switch ta.accdist > ta.sma(ta.accdist, 21)
true => color.lime
=> color.red
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Colors calcs —————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
_colorAlt = _alt > 3 ? color.rgb(0, 255, 8) : color.rgb(255, 0, 0)
_colorgm = close > _gram ? color.rgb(0, 255, 8) : color.rgb(255, 0, 0)
_colorpk = _pk >=1 ? color.rgb(0, 255, 8) : color.rgb(255, 0, 0)
_textff = _ff >0 ? 'ᴘᴀss' : 'ғᴀɪʟ'
_colorff = _ff >0 ? color.rgb(0, 255, 8) : color.rgb(255, 0, 0)
_colorchgD =_dChg > 0 ? color.rgb(0, 255, 8) : color.rgb(255, 0, 0)
_colorchgW =_wkChg > 0 ? color.rgb(0, 255, 8) : color.rgb(255, 0, 0)
//Long term debt excl. lease liabilities FQ, FY LONG_TERM_DEBT_EXCL_CAPITAL_LEASE
_LTD = request.financial(syminfo.tickerid, "LONG_TERM_DEBT_EXCL_CAPITAL_LEASE", "FQ")
MCapz0 = _LTD
MCapCalcz0 = MCapz0
uMz0 = ''
if(MCapz0 >= 1000 and MCapz0 < 1000000)
MCapz0 := MCapz0/1000
uMz0 := 'K'
if(MCapz0 >= 1000000 and MCapz0 < 1000000000)
MCapz0 := MCapz0/1000000
uMz0 := 'M'
if(MCapz0 >= 1000000000)
MCapz0 := MCapz0/1000000000
uMz0 := 'B'
// Total assets FQ, FY TOTAL_ASSETS
_TR = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FQ")
MCapz1 = _TR
MCapCalcz1 = MCapz1
uMz1 = ''
if(MCapz1 >= 1000 and MCapz1 < 1000000)
MCapz1 := MCapz1/1000
uMz1 := 'K'
if(MCapz1 >= 1000000 and MCapz1 < 1000000000)
MCapz1 := MCapz1/1000000
uMz1 := 'M'
if(MCapz1 >= 1000000000)
MCapz1 := MCapz1/1000000000
uMz1 := 'B'
// Total equity FQ, FY TOTAL_EQUITY
_TE = request.financial(syminfo.tickerid, "TOTAL_EQUITY", "FY")
MCapz2 = _TE
MCapCalcz2 = MCapz2
uMz2 = ''
if(MCapz2 >= 1000 and MCapz2 < 1000000)
MCapz2 := MCapz2/1000
uMz2 := 'K'
if(MCapz2 >= 1000000 and MCapz2 < 1000000000)
MCapz2 := MCapz2/1000000
uMz2 := 'M'
if(MCapz2 >= 1000000000)
MCapz2 := MCapz2/1000000000
uMz2 := 'B'
// Cash & equivalents FQ, FY CASH_N_EQUIVALENTS
_CNE = request.financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FY")
MCapz3 = _CNE
MCapCalcz3 = MCapz3
uMz3 = ''
if(MCapz3 >= 1000 and MCapz3 < 1000000)
MCapz3 := MCapz3/1000
uMz3 := 'K'
if(MCapz3 >= 1000000 and MCapz3 < 1000000000)
MCapz3 := MCapz3/1000000
uMz3 := 'M'
if(MCapz3 >= 1000000000)
MCapz3 := MCapz3/1000000000
uMz3 := 'B'
// Revenue estimates FQ, FY SALES_ESTIMATES
_RE = request.financial(syminfo.tickerid, "SALES_ESTIMATES", "FY")
MCapz4 = _RE
MCapCalcz4 = MCapz4
uMz4 = ''
if(MCapz4 >= 1000 and MCapz4 < 1000000)
MCapz4 := MCapz4/1000
uMz4 := 'K'
if(MCapz4 >= 1000000 and MCapz4 < 1000000000)
MCapz4 := MCapz4/1000000
uMz4 := 'M'
if(MCapz4 >= 1000000000)
MCapz4 := MCapz4/1000000000
uMz4 := 'B'
// Free cash flow FQ, FY, TTM FREE_CASH_FLOW
_FCF = request.financial(syminfo.tickerid, "FREE_CASH_FLOW", "FY")
MCapz5 = _FCF
MCapCalcz5 = MCapz5
uMz5 = ''
if(MCapz5 >= 1000 and MCapz5 < 1000000)
MCapz5 := MCapz5/1000
uMz5 := 'K'
if(MCapz5 >= 1000000 and MCapz5 < 1000000000)
MCapz5 := MCapz5/1000000
uMz5 := 'M'
if(MCapz5 >= 1000000000)
MCapz5 := MCapz5/1000000000
uMz5 := 'B'
// EBITDA FQ, FY, TTM EBITDA
_EB = request.financial(syminfo.tickerid, "EBITDA", "FY")
MCapz6 = _EB
MCapCalcz6 = MCapz6
uMz6 = ''
if(MCapz6 >= 1000 and MCapz6 < 1000000)
MCapz6 := MCapz6/1000
uMz6 := 'K'
if(MCapz6 >= 1000000 and MCapz6 < 1000000000)
MCapz6 := MCapz6/1000000
uMz6 := 'M'
if(MCapz6 >= 1000000000)
MCapz6 := MCapz6/1000000000
uMz6 := 'B'
// MarketCa
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Table Layouts ————————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
tableposGo2 = switch position3b
"Top Right" => position.top_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Middle Right" => position.middle_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Bottom Right" => position.bottom_right
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
if barstate.islast or barstate.islastconfirmedhistory
var table tab = table.new(tableposGo2, 99, 99,
bgcolor = color.rgb(255, 255, 255, 100),
frame_color=color.rgb(255, 255, 255, 100),
frame_width = 1,
border_color =color.rgb(255, 255, 255, 100),
border_width = 1)
if showxD
table.cell(tab, 1, 13, " ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 1, 19, "ᴀʟᴛᴍᴀɴ ᴢ-sᴄᴏʀᴇ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 19, str.tostring(_alt,'0.00'), text_color = _colorAlt, text_halign = text.align_left)
table.cell(tab, 1, 20, "ɢʀᴀʜᴀᴍs ɴᴏ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 20, str.tostring(_gram,'0.0'), text_color = _colorgm, text_halign = text.align_left)
table.cell(tab, 1, 21, "ᴘɪᴏᴛʀᴏsᴋɪ ғ-sᴄᴏʀᴇ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 21, str.tostring(_pk, '0.0'), text_color = _colorpk, text_halign = text.align_left)
table.cell(tab, 1, 22, "ғᴜʟᴍᴇʀ ғᴀᴄᴛᴏʀ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 22, _textff , text_color = _colorff, text_halign = text.align_left, text_size=size.normal)
table.cell(tab, 1, 23, " ",text_halign = text.align_left, text_color = color.white)
if showxA
table.cell(tab, 1, 24, "ʟᴏɴɢᴛᴇʀᴍ ᴅᴇʙᴛ \nᴇx-ᴄᴀᴘɪᴛᴀʟ ʟᴇᴀsᴇ ~ ғǫ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 24, str.tostring(math.round(MCapz0,2),'0.000')+uMz0, text_color = color.rgb(255, 0, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
table.cell(tab, 1, 25, "ᴛᴏᴛᴀʟ ʀᴇᴠᴇɴᴜᴇ ~ ғǫ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 25, str.tostring(math.round(MCapz1,2),'0.000')+uMz1, text_color = color.rgb(9, 255, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
table.cell(tab, 1, 26, "ᴛᴏᴛᴀʟ ᴇǫᴜɪᴛʏ ~ ғʏ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 26, str.tostring(math.round(MCapz2,2),'00.000')+uMz2, text_color = color.rgb(9, 255, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
table.cell(tab, 1, 27, "ᴄᴀsʜ & ᴇǫᴜɪᴠᴀʟᴇɴᴛs ~ ғʏ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 27, str.tostring(math.round(MCapz3,2),'0.000')+uMz3, text_color = color.rgb(9, 255, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
table.cell(tab, 1, 28, "ʀᴇᴠᴇɴᴜᴇ ᴇsᴛɪᴍᴀᴛᴇs ~ ғʏ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 28, str.tostring(math.round(MCapz4,2),'00.000')+uMz4, text_color = color.rgb(9, 255, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
table.cell(tab, 1, 29, "ғʀᴇᴇ ᴄᴀsʜ ғʟᴏᴡs ~ ғʏ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 29, str.tostring(math.round(MCapz5,2),'0.000')+uMz5, text_color = color.rgb(9, 255, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
table.cell(tab, 1, 30, "ᴇʙɪᴛᴅᴀ ~ ғʏ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 30, str.tostring(math.round(MCapz6,3),'0.000')+uMz6, text_color = color.rgb(255, 145, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
table.cell(tab, 1, 31, "ᴍᴀʀᴋᴇᴛᴄᴀᴘ: ",text_halign = text.align_left, text_color = color.white)
table.cell(tab, 2, 31, str.tostring(math.round(MCapz,2),'00.000')+uMz, text_color = color.rgb(255, 145, 0), bgcolor = color.rgb(24, 24, 24,100),text_halign = text.align_center)
|
wosabi Investment assistant and Swing trading CRYPTO | https://www.tradingview.com/script/zuWSKfvk/ | ahmadALwosabi | https://www.tradingview.com/u/ahmadALwosabi/ | 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/
// © ahmadALwosabi
//@version=5
indicator("wosabi Investment assistant and Swing trading CRYPTO","waist",overlay = false)
//خاص بمؤشرات المتوسطات
widthInput_1 = input.int(20, minval=1, title="width line horzintal", group="width line horzintal")
var vstyletype1 = plot.style_steplinebr
symbol_100 = syminfo.tickerid
Piriod_101 = input(7,title ='ema Symbol_1 1' ) //630
index_101 = request.security(symbol_100,timeframe.period, close > ta.ema(close,Piriod_101))
plot(90 ,title='1',color=index_101?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(87.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_102 = input(21,title ='ema Symbol_1 2' ) //630
index_102 = request.security(symbol_100,timeframe.period, close > ta.ema(close,Piriod_102))
plot(85 ,title='2',color=index_102?color.green:color.red,linewidth = widthInput_1,style=vstyletype1)
hline(82.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_103 = input(140,title ='ema Symbol_1 3' ) //630
index_103 = request.security(symbol_100,timeframe.period, close > ta.ema(close,Piriod_103))
plot(80 ,title='3',color=index_103?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(77.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_104 = input(360,title ='ema Symbol_1 4' ) //630
index_104 = request.security(symbol_100,timeframe.period, close > ta.ema(close,Piriod_104))
plot(75 ,title='4',color=index_104?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(72.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_105 = input(720,title ='ema Symbol_1 5' ) //630
index_105 = request.security(symbol_100,timeframe.period, close > ta.ema(close,Piriod_105))
plot(70 ,title='5',color=index_105?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(65, "split", color=color.new(#ffffff, 10),linewidth = 3,linestyle=hline.style_dotted)
symbol_200 = input.symbol(title='Symbol_2', defval='CRYPTO:BTCUSD')
Piriod_201 = input(7,title ='ema Symbol_2 01' ) //630
index_201 = request.security(symbol_200,timeframe.period, close > ta.ema(close,Piriod_201))
plot(60 ,title='01',color=index_201?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(57.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_202 = input(21,title ='ema Symbol_2 02' ) //630
index_202 = request.security(symbol_200,timeframe.period, close > ta.ema(close,Piriod_202))
plot(55,title='02',color=index_202?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(52.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_203 = input(140,title ='ema Symbol_2 03' ) //630
index_203 = request.security(symbol_200,timeframe.period, close > ta.ema(close,Piriod_203))
plot(50 ,title='03',color=index_203?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(47.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_204 = input(360,title ='ema Symbol_2 04' ) //630
index_204 = request.security(symbol_200,timeframe.period, close > ta.ema(close,Piriod_204))
plot(45 ,title='04',color=index_204?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(42.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_205 = input(720,title ='ema Symbol_2 05' ) //630
index_205 = request.security(symbol_200,timeframe.period, close > ta.ema(close,Piriod_205))
plot(40 ,title='05',color=index_205?color.green:color.red,linewidth = widthInput_1,style =vstyletype1)
hline(35, "split", color=color.new(#ffffff, 10),linewidth = 3,linestyle=hline.style_dotted)
symbol_300 = input.symbol(title='Symbol_3', defval='FX:USDOLLAR')
Piriod_301 = input(7,title ='ema Symbol_3 01' ) //630
index_301 = request.security(symbol_300,timeframe.period, close > ta.ema(close,Piriod_301))
plot(30 ,title='001',color=index_301?color.red:color.green,linewidth = widthInput_1,style =vstyletype1)
hline(27.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_302 = input(21,title ='ema Symbol_3 02' ) //630
index_302 = request.security(symbol_300,timeframe.period, close > ta.ema(close,Piriod_302))
plot(25 ,title='002',color=index_302?color.red:color.green,linewidth = widthInput_1,style =vstyletype1)
hline(22.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_303 = input(140,title ='ema Symbol_3 03' ) //630
index_303 = request.security(symbol_300,timeframe.period, close > ta.ema(close,Piriod_303))
plot(20 ,title='003',color=index_303?color.red:color.green,linewidth = widthInput_1,style =vstyletype1)
hline(17.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_304 = input(360,title ='ema Symbol_3 04' ) //630
index_304 = request.security(symbol_300,timeframe.period, close > ta.ema(close,Piriod_304))
plot(15 ,title='004',color=index_304?color.red:color.green,linewidth = widthInput_1,style =vstyletype1)
hline(12.5, "split", color=color.new(#ffffff, 10),linewidth = 1,linestyle=hline.style_dotted)
Piriod_305 = input(720,title ='ema Symbol_3 05' ) //630
index_305 = request.security(symbol_300,timeframe.period, close > ta.ema(close,Piriod_305))
plot(10 ,title='005',color=index_305?color.red:color.green,linewidth = widthInput_1,style =vstyletype1)
// اسماء الرموز
string sym1 = symbol_100
sym1name = syminfo.ticker
string sym2 = symbol_200
sym2name = syminfo.ticker(sym2)
string sym3 = symbol_300
sym3name = syminfo.ticker(sym3)
// Plot Table
var RSI_table = table.new(
"middle" + "_" + 'left', columns=1, rows=4, bgcolor=color.rgb(255, 82, 82, 50),
frame_color=color.gray, frame_width = 1, border_color=color.new(color.green, 70), border_width = 1)
Cell = 0
table.cell (RSI_table , 0, Cell, text = str.tostring(sym1name) , text_color = color.white ,bgcolor=color.new(color.blue, 70), text_size = size.auto,height=15)
Cell := 01
table.cell (RSI_table , 0, Cell, text = str.tostring(sym2name) , text_color = color.white,bgcolor=color.new(color.blue, 70) , text_size = size.auto,height=15)
Cell := 02
table.cell (RSI_table , 0, Cell, text = str.tostring(sym3name) , text_color = color.white,bgcolor=color.new(color.blue, 70) , text_size = size.auto,height=15)
//End |
Trendline Breakouts With Targets [ChartPrime] | https://www.tradingview.com/script/hb6J9iHI-Trendline-Breakouts-With-Targets-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 2,908 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Trendline Breakouts With Targets [ Chartprime ]",shorttitle = "TBT [ Chartprime ]",overlay = true,max_bars_back = 500,max_lines_count = 500)
bool ChartTime = time > chart.left_visible_bar_time and time < chart.right_visible_bar_time
string CORE = "➞ Core Settings 🔸"
var bool TradeisON = false
var bool LongTrade = false
var bool ShortTrade = false
var float TP = 0.0
var float SL = 0.0
int BarTIME = time - time[1]
var line tpLine = na
var label LAB = na
var int UpdatedX = 0
var float UpdatedY = 0.0
var float UpdatedSLP = 0.0
var int UpdatedXLow = 0
var float UpdatedYLow = 0.0
var float UpdatedSLPLow = 0.0
int Period = input.int(10, title=' Period ➞',
group = CORE,
inline = "001")
bool Trendtype = input.string(title = " Type ➞",
defval='Wicks',
options=['Wicks', 'Body'],
group = CORE,
inline = "001")
== 'Wicks'
string Extensions = input.string(title=' Extend ➞',
defval=' 25',
options=[' 25', ' 50', ' 75'],
group = CORE,
inline = "001")
color LineCol1 = input.color(color.rgb(109, 111, 111, 19),"",group = CORE,inline = "001")
bool ShowTargets = input.bool(true,"Show Targets",group = CORE,inline = "002")
ExtenSwitcher(ex) =>
switch ex
' 25' => 1 ,
' 50' => 2 ,
=> 3
WidthSwitcher(ex) =>
switch ex
'1' => 1 ,
'2' => 2 ,
=> 3
StyleSwitcher(style) =>
switch style
'Dashed' => line.style_dashed ,
'Dotted' => line.style_dotted ,
=> line.style_solid
method volAdj(int len)=>
math.min(ta.atr(len) * 0.3, close * (0.3/100)) [20] /2
Zband = volAdj(30)
method Trendlines(float src, int timeIndex,bool dir) =>
var int Start = 1 , var int End = 0 , var int TIME = 1
var float YEnd = 0, var float YStart = 0 , var float Slope = 0
var line Line1 = line.new(na,na,na,na)
var line Line2 = line.new(na,na,na,na)
var line Line3 = line.new(na,na,na,na)
SCR = fixnan(src)
if ta.change(SCR) != 0
TIME := time[timeIndex]
YStart := SCR[1]
Start := TIME[1]
Slope := (SCR - YStart) / (TIME - Start)
Slope
EXTime = ExtenSwitcher(Extensions) * BarTIME * 25
End := TIME + EXTime
YEnd := SCR + EXTime * Slope
if ta.change(SCR) != 0 and not TradeisON[1]
LineCond = Slope * time < 0 ? dir ? na : color.rgb(11, 139, 7, 53) : dir ? color.rgb(212, 46, 0, 54) : na
if not na(LineCond) //and ChartTime
Line1 := line.new(Start,
YStart,
End,
YEnd,
xloc.bar_time,
extend.none,
color=color.new(color.white,100)
)
Line2:=line.new(Start,
YStart - (Zband * 2),
End,
YEnd - (Zband * 2),
xloc.bar_time,
extend.none,
color=color.new(color.black,100)
)
Line3:=line.new(Start,
YStart - (Zband * 1),
End,
YEnd - (Zband * 1),
xloc.bar_time,
extend.none,
color=color.new(color.black,100)
)
linefill.new(Line3,Line2,color= LineCol1)
linefill.new(Line3,Line1,color= LineCond)
// linefill.new(Line,Line2,color= color.rgb(28, 15, 2, 76))
[Start, YStart, Slope]
PH = ta.pivothigh(Trendtype ? high : close > open ? close : open, Period, Period / 2)
PL = ta.pivotlow(Trendtype ? low : close > open ? open : close, Period, Period / 2)
method GetlinePrice(int TIME, float Price, float SLOP, int LookB) =>
var float Current = 0.0
EsTime = time - TIME
Current := Price + (EsTime - LookB * BarTIME) * SLOP
Current
method CheckCross(float Price, int StartTime, float StartPrice, float SLP) =>
var float Current = 0.0
var float Previous = 0.0
if StartPrice[Period] != StartPrice
Current := GetlinePrice(StartTime, StartPrice, SLP, 0)
Previous := GetlinePrice(StartTime, StartPrice, SLP, 1)
Crossover = Price[1] < Previous and Price > Current ? 1 : Price[1] > Previous - (Zband*0.1) and Price < Current - (Zband*0.1) ? -1 : 0
Crossover
[Xx, XZ, SLPXZ] = Trendlines(PH, Period / 2,false)
[XxL, XZL, SLPXZL] = Trendlines(PL, Period / 2, true)
if ta.change(fixnan(PH)) != 0
UpdatedX := Xx
UpdatedY := XZ
UpdatedSLP := SLPXZ
UpdatedSLP
if ta.change(fixnan(PL)) != 0
UpdatedXLow := XxL
UpdatedYLow := XZL
UpdatedSLPLow := SLPXZL
UpdatedSLPLow
Long = not (UpdatedSLP * time > 0)
and CheckCross(close, UpdatedX, UpdatedY, UpdatedSLP)== 1
and not TradeisON
Short = not (UpdatedSLPLow * time < 0)
and CheckCross(close, UpdatedXLow, UpdatedYLow, UpdatedSLPLow)==-1
and not TradeisON
TradeFire = Long or Short
if Long and not TradeisON
LongTrade:= true
ShortTrade:= false
if Short and not TradeisON
LongTrade:= false
ShortTrade:= true
if true
if TradeFire and not TradeisON
TP := switch
Long => high + (Zband *20)
Short => low - (Zband *20)
SL := switch
Long => low - (Zband *20)
Short => high + (Zband *20)
TradeisON:= true
if ShowTargets
line.new(bar_index,
Long ? high : low,
bar_index,
TP,
width=2,
color = color.rgb(154, 103, 20),
style= line.style_dashed)
tpLine:= line.new(bar_index,
TP,
bar_index+2,
TP,
style= line.style_dashed,
color = color.rgb(154, 103, 20)
)
LAB:=label.new(bar_index,
TP,
"Target",
color = color.rgb(154, 103, 20),
style= label.style_label_left,
size=size.small,
textcolor = color.white
)
if TradeisON
line.set_x2(tpLine,bar_index)
label.set_x(LAB,bar_index+1)
if LongTrade and TradeisON
if high >= TP
label.set_color(LAB,color.rgb(6, 128, 10, 37))
TradeisON:=false
if close <= SL
label.set_color(LAB,color.new(color.rgb(246, 7, 7),70))
TradeisON:=false
else if ShortTrade and TradeisON
if low <= TP
label.set_color(LAB,color.rgb(6, 128, 10, 37))
TradeisON:=false
if close >= SL
label.set_color(LAB,color.new(color.rgb(246, 7, 7),70))
TradeisON:=false
plotshape(Long and not TradeisON[1],
size = size.small,
color = color.rgb(46, 192, 6, 11),
location = location.belowbar,
style = shape.labelup ,
text = "",
textcolor = color.white)
plotshape(Short and not TradeisON[1],
size = size.small,
color = color.rgb(241, 2, 2, 11),
location = location.abovebar,
style = shape.labeldown ,
text = "",
textcolor = color.white)
// -- END -- .
|
AI Momentum [YinYang] | https://www.tradingview.com/script/NKUsm5uR-AI-Momentum-YinYang/ | YinYangAlgorithms | https://www.tradingview.com/u/YinYangAlgorithms/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// © YinYangAlgorithms
//@version=5
indicator("AI Momentum [YinYang] ", overlay=true)
// ~~~~~~~~~~~ IMPORTS ~~~~~~~~~~~ //
//Credits go to jdehorty for the rationalQuadratic and gaussian Functions
import jdehorty/KernelFunctions/2 as kernels
// ~~~~~~~~~~~ INPUTS ~~~~~~~~~~~ //
showSignals = input.bool(true, "Show Signals", group="Momentum", tooltip="Sometimes it can be difficult to visualize the zones with signals enabled.")
factorVolume = input.bool(false, "Factor Volume", group="Momentum", tooltip="Factor Volume only applies to Overly Bullish and Bearish Signals. It's when the Volume is > VWMA Volume over the Smoothing Length.")
zoneLengths = input.int(50, "Zone Inside Length", group="Momentum", tooltip="The Zone Inside is the Inner zone of the High and Low. This is the length used to create it.")
zoneOutsideLengths = input.int(75, "Zone Outside Length", group="Momentum", tooltip="The Zone Outside is the Outer zone of the High and Low. This is the length used to create it.")
smoothingLength = input.int(14, "Smoothing length", group="Momentum", tooltip="Smoothing length is the length used to smooth out our Bullish and Bearish signals, along with our Overly Bullish and Overly Bearish Signals.")
// Kernel Settings
lookbackWindow = input.int(8, "Lookback Window", tooltip="The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50", group="Kernel Settings")
relativeWeighting = input.float(8., "Relative Weighting", step=0.25, tooltip="Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25", group="Kernel Settings")
startBar = input.int(25, "Start Regression at Bar", tooltip="Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit. Recommended range: 5-25", group="Kernel Settings")
// ~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~ //
//Kernal Zones
highestHigh = kernels.rationalQuadratic(ta.highest(high, zoneLengths), lookbackWindow, relativeWeighting, startBar)
lowestLow = kernels.rationalQuadratic(ta.lowest(low, zoneLengths), lookbackWindow, relativeWeighting, startBar)
highestHighOutside = kernels.rationalQuadratic(ta.highest(high, zoneOutsideLengths), lookbackWindow, relativeWeighting, startBar)
lowestLowOutside = kernels.rationalQuadratic(ta.lowest(low, zoneOutsideLengths), lookbackWindow, relativeWeighting, startBar)
kernClose = kernels.rationalQuadratic(close, lookbackWindow, relativeWeighting, startBar)
zoneMid = math.avg(highestHigh, lowestLow)
//Bullish and bearish (these hold momentum and may be a safe way to know if the momentum is still going strong for the trend)
bullishBar = kernels.rationalQuadratic(close, lookbackWindow, relativeWeighting, startBar) > kernels.rationalQuadratic(ta.highest(ta.vwma(ohlc4, smoothingLength), smoothingLength), lookbackWindow, relativeWeighting, startBar)
bearishBar = kernels.rationalQuadratic(close, lookbackWindow, relativeWeighting, startBar) < kernels.rationalQuadratic(ta.lowest(ta.vwma(ohlc4, smoothingLength), smoothingLength), lookbackWindow, relativeWeighting, startBar)
//Very bullish and bearish (these may represent when the momentum is about to change as they are almost TOO Bullish and Bearish
rsi = kernels.rationalQuadratic(ta.rsi(close, smoothingLength), lookbackWindow, relativeWeighting, startBar)
vol = kernels.rationalQuadratic(volume, lookbackWindow, relativeWeighting, startBar)
volAvg = kernels.rationalQuadratic(ta.vwma(volume, smoothingLength), lookbackWindow, relativeWeighting, startBar)
veryBullish = bullishBar and rsi >= 57 and (not factorVolume or vol > volAvg)
veryBearish = bearishBar and rsi <= 43 and (not factorVolume or vol > volAvg)
//Kernal Crossing Calculations
kern1 = kernels.rationalQuadratic(close, lookbackWindow, relativeWeighting, startBar)
kern2 = kernels.gaussian(close, lookbackWindow - 2, startBar)
// Kernel Crossovers
bool isBullishCross = ta.crossover(kern2, kern1)
bool isBearishCross = ta.crossunder(kern2, kern1)
// ~~~~~~~~~~~ PLOTS ~~~~~~~~~~~ //
//Bullish and bearish bars (keeping the movement strong, may be safe to stay in)
plotshape(showSignals and bullishBar and not veryBullish, style=shape.xcross, color = color.green, location=location.abovebar, title="Bullish Momentum")
plotshape(showSignals and bearishBar and not veryBearish, style=shape.xcross, color = color.red, location=location.belowbar, title="Bearish Momentum")
//Very Bullish and Bearish bars (has potential for a momentum change)
plotshape(showSignals and veryBullish, style=shape.cross, color = color.orange, location=location.abovebar, size=size.tiny, title="Overly Bullish")
plotshape(showSignals and veryBearish, style=shape.cross, color = color.teal, location=location.belowbar, size=size.tiny, title="Overly Bearish")
//Kernal Cross
plotshape(showSignals and isBullishCross, style=shape.cross, color = color.green, location=location.abovebar, size=size.small, title="Bull Cross")
plotshape(showSignals and isBearishCross, style=shape.cross, color = color.red, location=location.belowbar, size=size.small, title="Bear Cross")
//Kernal Zones
pHighInside = plot(highestHigh, color=color.orange)
pClose = plot(kernClose, color=color.white)
pLowInside = plot(lowestLow, color=color.teal)
pMid = plot(zoneMid, color=color.yellow)
pHighOutside = plot(highestHighOutside, color=color.red)
pLowOutside = plot(lowestLowOutside, color=color.green)
fillColor = kernClose > zoneMid ? color.green : color.red
fill(pClose, pMid, color=color.new(fillColor, 90))
fill(pHighInside, pHighOutside, color=color.new(color.red, 90))
fill(pLowInside, pLowOutside, color=color.new(color.green, 90))
// ~~~~~~~~~~~ END ~~~~~~~~~~~ // |
Weighted Bulls-Bears Variety Smoothed [Loxx] | https://www.tradingview.com/script/fnOC5TyI-Weighted-Bulls-Bears-Variety-Smoothed-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 188 | 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("Weighted Bulls-Bears Variety Smoothed [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
color greencolor = #2DD204
color redcolor = #D2042D
fema(float src, simple int len)=>
alpha = (2.0 / (2.0 + (len - 1.0) / 2.0))
out = 0.
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
variant(simple string typein, src, per)=>
out = 0.
if typein == "Exponential Moving Average - EMA"
out := ta.ema(src, per)
if typein == "Fast Exponential Moving Average - FEMA"
out := fema(src, per)
if typein == "Linear Weighted Moving Average - LWMA"
out := ta.wma(src, per)
if typein == "Simple Moving Average - SMA"
out := ta.sma(src, per)
if typein == "Smoothed Moving Average - SMMA"
out := ta.rma(src, per)
out
weight(fng, dist)=>
(fng + fng / dist)
float CalcPrice = input.source(close, "Source", group = "Basic Settings")
int CalcPeriod = input.int(50, "Period", group = "Basic Settings")
int CalcMaPeriod = input.int(1, "Smooting Period", group = "Basic Settings")
string matype = input.string("Simple Moving Average - SMA", "Smoothing Type",
options = ["Exponential Moving Average - EMA",
"Fast Exponential Moving Average - FEMA",
"Linear Weighted Moving Average - LWMA",
"Simple Moving Average - SMA", "Smoothed Moving Average - SMMA"],
group = "Basic Settings")
bool colorbars = input.bool(true, "Color bars", group= "UI Options")
bool showSigs = input.bool(true, "Show signals", group= "UI Options")
float prices = variant(matype, CalcPrice, CalcMaPeriod)
int hbar = ta.highestbars(prices, CalcPeriod)
float hval = nz(CalcPrice[math.abs(hbar)])
int lbar = ta.lowestbars(prices, CalcPeriod)
float lval = nz(CalcPrice[math.abs(lbar)])
float bear = -weight(hval - prices, hbar + 1)
float bull = +weight(prices - lval, lbar + 1)
float temp = bull * 2 + bear * 2
float buffer5 = temp ? temp : nz(temp[1])
color colorout = buffer5 > 0 ? greencolor : redcolor
plot(buffer5, "Weighted Bulls-Bbears Variety Smoothed", color = colorout, style = plot.style_columns, linewidth = 2)
barcolor(colorbars ? colorout : na)
float middle = 0.0
bool goLong = ta.crossover(buffer5, middle)
bool goShort = ta.crossunder(buffer5, middle)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top)
alertcondition(goLong, title = "Long", message = "Weighted Bulls-Bears Variety Smoothed [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Weighted Bulls-Bears Variety Smoothed [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
HTF Fair Value Gap [LuxAlgo] | https://www.tradingview.com/script/oOPK4P2K-HTF-Fair-Value-Gap-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,378 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("HTF Fair Value Gap [LuxAlgo]", "LuxAlgo - HTF Fair Value Gap", overlay = true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
tf = input.timeframe('D', 'Timeframe')
//Style
offset = input.int(20, minval = 1, group = 'Style')
width = input.int(20, minval = 1, group = 'Style')
bullCss = input(#089981, 'Bullish FVG', group = 'Style')
bearCss = input(#f23645, 'Bearish FVG', group = 'Style')
//Dashboard
showDash = input(true, 'Show Dashboard', group = 'Dashboard')
dashLoc = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = input.string('Small', 'Size' , options = ['Tiny', 'Small', 'Normal'], group = 'Dashboard')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type fvg
float max
float min
int left
int right
bool isbull
bool ismitigated = false
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
detect(itf)=>
var fvg fvg_object = na
[h, l, t] = request.security_lower_tf(syminfo.tickerid, itf, [high, low, time])
//If bullish FVG
if low > high[2] and close > high[2]
left = 0, right = 0, min_top = low, min_btm = low
//Search for top time coordinate
if l.size() > 0
for i = 0 to l.size()-1
dtop = math.abs(l.get(i) - low)
min_top := math.min(dtop, min_top)
right := dtop == min_top ? t.get(i) : right
//Search for bottom time coordinate
if (h[2]).size() > 0
for i = 0 to (h[2]).size()-1
dbtm = math.abs((h[2]).get(i) - high[2])
min_btm := math.min(dbtm, min_btm)
left := dbtm == min_btm ? (t[2]).get(i) : left
fvg_object := fvg.new(low, high[2], left, right, true)
//If bearish FVG
else if high < low[2] and close < low[2]
left = 0, right = 0, min_top = low, min_btm = low
//Search for top time coordinate
if (l[2]).size() > 0
for i = 0 to (l[2]).size()-1
dtop = math.abs((l[2]).get(i) - low[2])
min_top := math.min(dtop, min_top)
right := dtop == min_top ? (t[2]).get(i) : right
//Search for bottom time coordinate
if h.size() > 0
for i = 0 to h.size()-1
dbtm = math.abs(h.get(i) - high)
min_btm := math.min(dbtm, min_btm)
left := dbtm == min_btm ? t.get(i) : left
fvg_object := fvg.new(low[2], high, left, right, false)
fvg_object
method set_line_properties(line id, x1, y1, x2, y2, css)=>
id.set_xy1(x1, y1)
id.set_xy2(x2, y2)
id.set_color(css)
//-----------------------------------------------------------------------------}
//Check TF
//-----------------------------------------------------------------------------{
if timeframe.in_seconds(timeframe.period) >= timeframe.in_seconds(tf)
runtime.error('Chart timeframe needs to be lower than user set timeframe')
//-----------------------------------------------------------------------------}
//FVG Detection
//-----------------------------------------------------------------------------{
var float max = na
var float min = na
var int top_x1 = na
var int btm_x1 = na
var mitigated = false
n = bar_index
fvg_object = request.security(syminfo.tickerid, tf, detect(timeframe.period))
new_fvg = fvg_object.left != fvg_object.left[1]
//Trailing maximum/minimum
if new_fvg
max := high
min := low
else
max := math.max(high, max)
min := math.min(low, min)
if fvg_object.isbull
if close < fvg_object.min
fvg_object.ismitigated := true
else
if close > fvg_object.min
fvg_object.ismitigated := true
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 2, 2
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if barstate.isfirst
tb.cell(0, 0, 'HTF FVG', text_color = color.white, text_size = table_size)
tb.cell(0, 1, 'Status', text_color = color.white, text_size = table_size)
tb.merge_cells(0, 0, 1, 0)
//-----------------------------------------------------------------------------}
//Display
//-----------------------------------------------------------------------------{
var area = box.new(na,na,na,na,na)
var avgl = line.new(na,na,na,na)
var upwick = line.new(na,na,na,na)
var dnwick = line.new(na,na,na,na)
var topcord = line.new(na,na,na,na, xloc.bar_time, style = line.style_dashed)
var btmcord = line.new(na,na,na,na, xloc.bar_time, style = line.style_dashed)
var topcord_ext = line.new(na,na,na,na, style = line.style_dashed)
var btmcord_ext = line.new(na,na,na,na, style = line.style_dashed)
var status = label.new(na,na, style = label.style_label_left, size = size.tiny)
if barstate.islast
css = fvg_object.isbull ? bullCss : bearCss
avg = math.avg(fvg_object.max, fvg_object.min)
//FVG Area
area.set_lefttop(n + offset, fvg_object.max)
area.set_rightbottom(n + offset + width, fvg_object.min)
area.set_bgcolor(color.new(css, 50))
area.set_border_color(fvg_object.ismitigated ? na : css)
//FVG Average
avgl.set_line_properties(n + offset, avg, n + offset + width, avg, css)
//Wicks
upwick.set_line_properties(n + offset + int(width / 2), math.max(max, fvg_object.max), n + offset + int(width / 2), fvg_object.max, css)
dnwick.set_line_properties(n + offset + int(width / 2), math.min(min, fvg_object.min), n + offset + int(width / 2), fvg_object.min, css)
//Coordinates
topcord.set_line_properties(fvg_object.right, fvg_object.max, time, fvg_object.max, css)
btmcord.set_line_properties(fvg_object.left, fvg_object.min, time, fvg_object.min, css)
//Extend
topcord_ext.set_line_properties(n, fvg_object.max, n + offset-1, fvg_object.max, css)
btmcord_ext.set_line_properties(n, fvg_object.min, n + offset-1, fvg_object.min, css)
//Set dashboard status
tb.cell(1, 1, fvg_object.ismitigated ? 'Mitigated' : 'Unmitigated'
, bgcolor = color.new(css, 80)
, text_color = css
, text_size = table_size)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
bgcolor(new_fvg and fvg_object.isbull ? color.new(bullCss, 50)
: new_fvg and not fvg_object.isbull ? color.new(bearCss, 50)
: na
, title = 'HTF FVG Detection')
//-----------------------------------------------------------------------------} |
Seasonal Trend by LogReturn | https://www.tradingview.com/script/z2WAGp3e/ | bronko791 | https://www.tradingview.com/u/bronko791/ | 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/
// © bronko791
//@version=5
indicator("Seasonal Trend by LogReturn", overlay = false, max_lines_count = 500)
closeSrc = input.source(close, "Source")
int lookbackYears = input.int(10, "Past Years", tooltip = "The number of years in the past for the calculation. Note: If you select more years than data is available, the line turns red.")
//resolution = input.timeframe('D', "Resolution", options=['D'], display = display.none, tooltip = "Only daily timeframe is available. Other timeframes produce incorrect results.")
//closeSrc = request.security(syminfo.tickerid, resolution, close)
withAbsolute = false
int yesterday = timenow - 86400000
int currentYear = year(timenow)
int previousYear = currentYear - 1
startDate = timestamp(previousYear - lookbackYears, 12, 31)
endDate = timestamp(previousYear, 12, 31)
var array<float> dataContainer = array.new_float(100000, 0.0)
var array<float> logReturnResults = array.new_float(0)
var collectDayIndex = 0
var tmpYear = year
var printIndex = -1
var daysOffset = 0
var tradingDayOfCurrentYear = 0
if year == currentYear
tradingDayOfCurrentYear := tradingDayOfCurrentYear + 1
var plotColor = color.red
if time <= startDate and plotColor == color.red
plotColor := color.gray
if time >= startDate and time <= endDate
if tmpYear < year
collectDayIndex := 0
value = array.get(dataContainer, collectDayIndex)
logReturn = math.log(closeSrc[0] / closeSrc[1])
value := value + logReturn
array.set(dataContainer, collectDayIndex, value)
tmpYear := year
collectDayIndex := collectDayIndex + 1
if time > (timestamp(year(yesterday) - 1, month(yesterday), dayofmonth(yesterday) , 0 ,0 ))
printIndex := printIndex + 1
if year < currentYear
daysOffset := daysOffset + 1
if printIndex == 0
array.push(logReturnResults, 0.0)
else
averageDailyReturn = array.get(dataContainer, printIndex) / (lookbackYears)
array.push(logReturnResults, averageDailyReturn)
plot (printIndex >= 0 ? array.sum(logReturnResults) * 100: na, offset = daysOffset, color=plotColor)
hline(0, title='ZeroLine', color=color.black, linestyle=hline.style_dashed, linewidth=1) |
MACD Area | https://www.tradingview.com/script/StYpDTe2-MACD-Area/ | algotraderdev | https://www.tradingview.com/u/algotraderdev/ | 143 | 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/
// ©algotraderdev
// @version=5
indicator('MACD Area', explicit_plot_zorder = true)
float SRC = input.source(close, 'Source')
int FAST_LEN = input.int(12, 'Fast Length', minval = 1)
int SLOW_LEN = input.int(26, 'Slow Length', minval = 1)
int SIGNAL_LEN = input.int(9, 'Signal Length', minval = 1)
bool MACD_DISPLAY = input.bool(true, 'MACD Line', group = 'Lines', inline = 'MACD')
color MACD_COLOR = input.color(#2962ff, '', group = 'Lines', inline = 'MACD')
bool SIGNAL_DISPLAY = input.bool(true, 'Signal Line', group = 'Lines', inline = 'Signal')
color SIGNAL_COLOR = input.color(#ff6d00, '', group = 'Lines', inline = 'Signal')
bool HIST_DISPLAY = input.bool(true, 'Display', group = 'Histogram')
color ABOVE_GROW_COLOR = input.color(#26a69a, 'Above Zero Grow', group = 'Histogram', inline = 'Above')
color ABOVE_FALL_COLOR = input.color(#b2dfdb, 'Fall', group = 'Histogram', inline = 'Above')
color BELOW_GROW_COLOR = input.color(#ffcdd2, 'Below Zero Grow', group = 'Histogram', inline = 'Below')
color BELOW_FALL_COLOR = input.color(#ff5252, 'Fall', group = 'Histogram', inline = 'Below')
bool AREA_DISPLAY = input.bool(true, 'Display Histogram', group = 'Area')
bool AREA_LABEL_DISPLAY = input.bool(true, 'Display Label', group = 'Area')
color ABOVE_AREA_COLOR = input.color(#00bcd455, 'Above Zero', group = 'Area')
color BELOW_AREA_COLOR = input.color(#e91e6355, 'Below Zero', group = 'Area')
color ABOVE_AREA_LABEL_COLOR = color.new(ABOVE_AREA_COLOR, 0.8)
color BELOW_AREA_LABEL_COLOR = color.new(BELOW_AREA_COLOR, 0.8)
// Calculations.
[macd, signal, hist] = ta.macd(SRC, FAST_LEN, SLOW_LEN, SIGNAL_LEN)
float area = 0
if ta.change(math.sign(hist))
area := hist
else
area := area[1] + hist
// Plot the lines and histograms.
color areaColor = area >= 0 ? ABOVE_AREA_COLOR : BELOW_AREA_COLOR
color histColor = if hist >= 0
hist[1] < hist ? ABOVE_GROW_COLOR : ABOVE_FALL_COLOR
else
hist[1] < hist ? BELOW_GROW_COLOR : BELOW_FALL_COLOR
hline(0, 'Zero Line', color = #777777)
plot(AREA_DISPLAY ? area : na, 'Area Histogram', color = areaColor, style = plot.style_columns)
plot(HIST_DISPLAY ? hist : na, 'Histogram', color = histColor, style=plot.style_columns)
plot(MACD_DISPLAY ? macd : na, 'MACD', color = MACD_COLOR)
plot(SIGNAL_DISPLAY ? signal : na, 'Signal', color = SIGNAL_COLOR)
// Create a label to display cumulative area.
string areaStr = str.format('{0,number,#.#}', area)
newLabel() =>
label.new(
x = bar_index,
y = area,
text = areaStr,
textcolor = area >= 0 ? ABOVE_AREA_LABEL_COLOR : BELOW_AREA_LABEL_COLOR,
color = #00000000,
style = area >= 0 ? label.style_label_down : label.style_label_up)
var label areaLabel = newLabel()
if ta.change(math.sign(area)) and not na(area[1])
areaLabel := newLabel()
else
areaLabel.set_xy(bar_index, area)
areaLabel.set_text(areaStr) |
VWAP with Characterization | https://www.tradingview.com/script/HTvXJACT-VWAP-with-Characterization/ | AleSaira | https://www.tradingview.com/u/AleSaira/ | 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/
// © AleSaira
//============///////==========================/////////////////===============}
//@version=5
indicator("VWAP with Characterization", overlay = true)
//============///////==========================/////////////////===============}
sma_length = input (14, title="SMA Length")
// Input per la scelta del calcolo del VWAP
useCustomVWAP = input (true, title="Use Custom VWAP Calculation")
//============///////==========================/////////////////===============}
// Calcola il VWAP in base alla scelta dell'utente
vwap = useCustomVWAP ? ta.sma(close * volume, sma_length) / ta.sma(volume, sma_length) : ta.sma(request.security(syminfo.tickerid, "1D", close * volume) / request.security(syminfo.tickerid, "1D", volume), sma_length)
char(vwap_value, length) =>
sum = 0.0
for i = 0 to length - 1
sum := sum + vwap_value[i]
sum / length
char_vwap = char(vwap, sma_length)
//============///////==========================/////////////////===============}
isUptrend = ta.highestbars(high, 10) < ta.highestbars(low, 10)
isDowntrend = ta.highestbars(high, 10) > ta.highestbars(low, 10)
//============///////==========================/////////////////===============}
linecolor = isUptrend ? color.blue : isDowntrend ? color.rgb(255, 82, 238) : color.rgb(243, 254, 144)
plot(char_vwap, title="Characterized VWAP", color=linecolor, linewidth=2)
//============///////==========================/////////////////===============}
// Set alarm when the 200 period EMA rises above or below the characterized VWAP
vwapThreshold = input.float(200, title="VWAP Threshold")
vwapAboveThreshold = ta.crossover(char_vwap, vwapThreshold)
vwapBelowThreshold = ta.crossunder(char_vwap, vwapThreshold)
alertcondition(vwapAboveThreshold, title="VWAP Above Threshold Alert", message="VWAP has crossed above the specified threshold.")
alertcondition(vwapBelowThreshold, title="VWAP Below Threshold Alert", message="VWAP has crossed below the specified threshold.")
//============///////==========================/////////////////===============}
|
Price Volume Trend Crosses | https://www.tradingview.com/script/OY5vcdNI-Price-Volume-Trend-Crosses/ | kikfraben | https://www.tradingview.com/u/kikfraben/ | 71 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kikfraben
// Updated last on Sep. 22, 2023
//@version=5
indicator("Price Volume Trend Crosses ", "PVTC ", false, format.volume)
// PVTC User Inputs
pvt_sig_length = input(22, "PVTC Signal Length", group = "PVTC Inputs")
pvt_sig_type = input.string(title = "PVTC Signal Type", group = "PVTC Inputs", defval = "EMA", options = ["EMA", "SMA"])
pvt_fill_gap = input.bool(true, "Fill Gaps", group = "PVTC Inputs")
pvt_plot_cross = input.bool(false, "Highlight Crosses", group = "PVTC Inputs")
// Colors
col_up = input.color(#3fa8c9 , "UP Color", group = "PVTC Inputs")
col_down = input.color(#c93f3f, "DOWN Color", group = "PVTC Inputs")
fill_col_up = input.color(color.new(#3fa8c9, 75), "UP Fill Color", group = "PVTC Inputs")
fill_col_down = input.color(color.new(#c93f3f, 75), "DOWN Fill Color", group = "PVTC Inputs")
// Price Volume Trend
pvt_src = close
pvt = ta.cum(ta.change(pvt_src)/pvt_src[1]*volume)
// Signal PVTC
pvt_sig = pvt_sig_type == "EMA" ? ta.ema(pvt, pvt_sig_length) : ta.sma(pvt, pvt_sig_length)
// Plot Rules PVTC
pvt_color_trend = pvt > pvt_sig ? col_up : col_down
pvt_color_fill = pvt > pvt_sig ? fill_col_up : fill_col_down
pvt_show_color_fill = pvt_fill_gap ? pvt_color_fill : na
pvt_cross_up = ta.crossover(pvt, pvt_sig)
pvt_cross_down = ta.crossunder(pvt, pvt_sig)
// Plot PVTC
plot_pvt = plot(pvt, color = pvt_color_trend)
plot_pvt_sig = plot(pvt_sig, color = pvt_color_trend)
fill(plot_pvt, plot_pvt_sig, color = pvt_show_color_fill)
bgcolor(pvt_plot_cross ? pvt_cross_up ? color.new(#3fa8c9, 50) : na : na)
bgcolor(pvt_plot_cross ? pvt_cross_down ? color.new(#c93f3f, 50) : na : na)
// Strategy Inputs
// pvtc_long = pvt > pvt_sig
// pvtc_short = pvt < pvt_sig
|
Monte Carlo Simulation - Your Strategy [Kioseff Trading] | https://www.tradingview.com/script/cvEVOXaH-Monte-Carlo-Simulation-Your-Strategy-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 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/
// © KioseffTrading
//@version=5
indicator("Monte Carlo Simulation [Kioseff Trading]", max_lines_count = 500, overlay = false, max_labels_count = 500, max_boxes_count = 500)
justPriceS = input.string (defval = "Price", title = "I Want To Simulate: ", options = ["Price" , "My Strategy"])
seed = input.int (defval = 0, title = "Set Seed", minval = 0)
distT = input.string (defval = "Normal", title = "Type", options = ["Normal", "Bootstrap"])
txt = input.text_area(defval = "-3\n-2\n-1\n0\n1\n2\n3\n *If You Selected 'My Strategy'\n(Paste Your Returns Here Following This Format)", title ="Returns")
cumu = input.float (defval = 70, title = "Cumulative Probability Target", maxval = 99, minval = 5) / 100
lin = input.bool (defval = false, title = "Line Plot Only")
lab = input.bool (defval = false, title = "Represent With Circles")
hist = input.bool (defval = false, title = "Probability Distribution Only")
binT = input.string (defval = "Rice", title = "Binning Method", options = ["Sturges", "Rice", "Square Root", "Custom"])
sims = input.int (defval = 250, title = "Simulations", minval = 1)
forx = input.int (defval = 15, title = "Forecast") + 1
only = input.bool (defval = false, title = "Show Best Case / Worst Case Only")
back = input.int (defval = 200, title = "Historical Data Points", minval = 5, group = "Simulate Price Instead", step = 10)
lineS = input.string (defval = "Solid", title = "Line Style", options= ["Solid", "Dotted", "Dashed"], group = "Line Style")
finS = switch lineS
"Dotted" => line.style_dotted
"Solid" => line.style_solid
"Dashed" => line.style_dashed
var ret = array.new_float(), endPoints = array.new_float()
justPrice = justPriceS == "Price"
if lab
only := false
hist := false
if hist
only := false
lin := false
binSize(size) =>
switch binT
"Square Root" => math.sqrt(size)
"Rice" => 2 * (math.pow(size, 1./3))
"Sturges" => math.log(size) / math.log(2) + 1,
"Custom" => input.int(20, title = "Custom Bin Amount (If Selected)", minval = 5, maxval = 200, group = "Custom Bin Amount")
txt2 = input.text_area(defval = "", title = "Additional Returns")
txt3 = input.text_area(defval = "", title = "Additional Returns")
txt4 = input.text_area(defval = "", title = "Additional Returns")
Gauss(z, avg, std) =>
avg + std * z
method boot(array <float> id) =>
id.get(int(math.random(0, id.size(), seed)))
distribution() =>
avg = ret.avg(), std = ret.stdev(false), size = ret.size()
r1 = math.random(0.01, 0.99, seed)
r2 = math.random(0.01, 0.99, seed)
result = math.sqrt (-2.0 * math.log(r1)) * math.cos(2.0 * math.pi * r2)
switch distT
"Normal" => Gauss(result, avg, std)
=> ret.boot()
method num(float id, val) =>
switch justPrice
false => id + val
=> id * math.exp(val)
method dete (matrix <float> id, val, i, x, int col, matrix<color> id2, color val2) =>
if not lab
if i < id.rows()
id.set (i, col, val)
id2.set(i, col, val2)
else
if x == forx - 1 and i < 1000
id .set(i, 0, val)
id2.set(i, 0, val2)
atr = ta.atr(14)
method mult(float id, up = 1.002, dn = .998) =>
switch
justPrice => id - atr
math.sign(id) == -1 => id * up
math.sign(id) == 1 => id * dn
if last_bar_index - bar_index <= back and justPrice
ret.push(math.log(close / close[1]))
method iSwitch(matrix <float> id, lastClos, i, x, colData, col, matrix <float> minMax) =>
switch only
false and not hist => id.dete(lastClos, i, x, x, colData, col)
=> minMax.set(0, x, math.min(nz(minMax.get(0, x), 1e8 ), lastClos)),
minMax.set(1, x, math.max(nz(minMax.get(1, x), -1e8), lastClos))
method endTrim (array <box> histBox, array<float> val, array<float> freq, array<label> histLabs) =>
if freq.size() > 0 and val.size() == freq.size() and histLabs.size() == freq.size() and histBox.size() == freq.size()
for i = 0 to freq.size() - 1
switch val.get(i) == 9e9
true => histBox.get(i).delete(), histLabs.get(i).delete()
=> break
for i = freq.size() - 1 to 0
switch val.get(i) == 9e9
true => histBox.get(i).delete(), histLabs.get(i).delete()
=> break
//
method returnCheck(array<float> id, array<string> id2) =>
if id2.size() > 0
for i = 0 to id2.size() - 1
if not na(str.tonumber(id2.get(i)))
id.push(str.tonumber(id2.get(i)))
if barstate.islastconfirmedhistory
subs = str.split(txt , "\n")
subs1 = str.split(txt2, "\n")
subs2 = str.split(txt3, "\n")
subs3 = str.split(txt4, "\n")
if not justPrice
ret.returnCheck(subs ), ret.returnCheck(subs1),
ret.returnCheck(subs2), ret.returnCheck(subs3)
sum = switch justPrice
false => ret.sum()
=> close
[row, column] = switch lab
false => [math.floor(500 / forx), forx]
=> [ 1000, 1 ]
lines = array.new_line()
minMax = matrix.new<float>(2, forx + 1)
lineData = matrix.new<float>(row, column)
colData = matrix.new<color>(row, column)
res = 0.
for i = 0 to sims
col = color.rgb(math.random(0, 255), math.random(0, 255), math.random(0, 255))
lastClose = sum
if not lab
lineData.dete(sum, i, 0, 0, colData, col)
for x = 1 to forx - 1
res := distribution()
lineData .iSwitch(lastClose, i, x, colData, col, minMax)
lastClose := lastClose.num(res)
endPoints.push(lastClose.num(res))
log.info(str.tostring(lastClose.num(res)))
if not hist
if only
minMax.set(0, 0, sum)
minMax.set(1, 0, sum)
for i = 1 to forx
line.new(bar_index + i - 1, minMax.get(0, i - 1), bar_index + i, minMax.get(0, i), color = color.red , style = finS)
line.new(bar_index + i - 1, minMax.get(1, i - 1), bar_index + i, minMax.get(1, i), color = color.lime, style = finS)
else
if not lab
for x = 0 to lineData.rows() - 1
for i = 1 to lineData.columns() - 1
modulo = i % forx
line.new(bar_index + modulo - 1, lineData.get(x, i - 1), bar_index + modulo, lineData.get(x, i),
color = colData.get(x, i),
style = finS
)
else
for x = 0 to lineData.rows() - 1
random = int(math.random(1, 250, seed))
switch label.all.size() >= 500
false => label.new(bar_index + random, lineData.get(x, 0), color = colData.get(x, 0),
text = "◉",
style = label.style_text_outline,
size = size.tiny,
textcolor = chart.fg_color
)
true => box.new (bar_index + random, lineData.get(x, 0), bar_index + random, lineData.get(x, 0),
text_color = colData.get(x, 0),
text = "◉",
text_size = size.tiny
)
if not justPrice
line.new (bar_index - 1, ret.sum(), bar_index, ret.sum(), color = chart.fg_color, extend = extend.left)
label.new (bar_index - 1, ret.sum(), text = str.tostring(ret.sum()), size = size.tiny,
style = label.style_label_down,
color = #00000000,
textcolor = color.white
)
min = 1e8, max = -1e8, xmax = int(-1e8)
if not only and not hist
endPoint = switch lab
false => line.all .size() - 1
=> label.all.size() - 1
for i = 0 to endPoint
switch lab
false => min := math.min(line.all .get(i).get_y2(), min),
max := math.max(line.all .get(i).get_y2(), max)
=> min := math.min(nz(label.all.get(i).get_y (), 1e8), min ),
max := math.max(nz(label.all.get(i).get_y (), -1e8), max ),
xmax := math.max(nz(label.all.get(i).get_x(), int(-1e8)), xmax)
if lab
if box.all.size() > 0
for i = 0 to box.all.size() - 1
btm = box.all.get(i).get_bottom()
min := math.min(min, nz(btm, 1e8))
max := math.max(max, nz(btm, -1e8))
xmax := math.max(xmax, nz(box.all.get(i).get_right (), int(-1e8)))
else
if not hist
min := minMax.min()
max := minMax.max()
if not lab and not hist
for i = 0 to forx - 1
label.new(bar_index + i, min.mult(), str.tostring(i), style = label.style_label_up, color = #00000000, textcolor = chart.fg_color, size = size.tiny)
if not hist
[xcoor, txtt, xcoor2] = switch lab
false => [bar_index - 2, justPrice ? "Time #" : "Trade #", bar_index + forx + 1]
=> [bar_index - 4, "All Results For " + (justPrice ? "Time # " : "Trade # ") + str.tostring(forx - 1), xmax + 5]
label.new(xcoor, min.mult(), text = txtt, color = #00000000,
textcolor = chart.fg_color,
size = size.tiny,
style = label.style_label_up)
line.new (bar_index - 3, min.mult(), xcoor2, min.mult(), color = chart.fg_color)
line.new (xcoor2, min.mult(), xcoor2, max.mult(), color = chart.fg_color)
calc = (max.mult() - min.mult()) / 10
for i = 0 to 10
label.new(xcoor2, min.mult() + (i * calc), str.tostring(min.mult() + (i * calc), format.mintick),
textcolor = chart.fg_color,
style = label.style_label_left,
size = size.tiny,
color = #00000000
)
if not only and not lin
k = math.ceil(binSize(endPoints.size()))
maxR = endPoints.max()
minR = endPoints.min()
freq = array.new_float(k, hist ? 0 : sum)
count = array.new_float(k, 0)
val = array.new_float(k, 9e9)
sizE = (maxR - minR) / k
for i = 0 to endPoints.size() - 1
ind = math.floor((endPoints.get(i) - minR) / sizE)
if ind >= 0 and ind < k
freq.set(ind, freq.get(ind) + 1)
count.set(ind, count.get(ind) + 1)
if endPoints.get(i) < val.get(ind)
val.set(ind, endPoints.get(i))
newMin = 1e8, newMax = -1e8
if not hist
if not only
for i = 0 to line.all.size() - 1
newMin := math.min(newMin, line.all.get(i).get_y2())
newMax := math.max(newMax, line.all.get(i).get_y2())
else
newMin := minMax.min(), newMax := minMax.max()
else
newMin := close * .975, newMax := close * 1.025
if not lab
histLabs = array.new_label(), histBox = array.new_box()
if not hist
freqMin = freq.min(), freqMax = freq.max(), freqRange = freqMax - freqMin, minimum = 1e8
for i = 0 to freq.size() - 1
freq.set(i, ((freq.get(i) - freqMin) / freqRange) * (newMax - newMin) + newMin)
if freq.get(i) != newMin
minimum := math.min(minimum, freq.get(i))
for i = 0 to freq.size() - 1
pretext = switch justPrice
true => str.tostring((val.get(i) - close) / close, "###.0000") + "\n" + str.tostring(count.get(i))
=> str.tostring(val.get(i), format.mintick) + "\n" + str.tostring(count.get(i))
strtxt = switch val.get(i) == 9e9
true => "--"
=> pretext
histBox.push(box.new(bar_index + forx + 6 + i, newMin, bar_index + forx + 6 + i + 1, math.max(freq.get(i), minimum),
bgcolor = color.new(#6929F2, 50),
border_color = chart.fg_color
))
histLabs.push(label.new(bar_index + forx + 6 + i, newMin, " " + strtxt,
style = label.style_label_up,
color = #00000000,
textcolor = chart.fg_color,
size = size.tiny))
histBox.endTrim(val, freq, histLabs)
else
for i = 0 to freq.size() - 1
pretext = switch justPrice
true => str.tostring((val.get(i) - close) / close, "###.0000") + "\n" + str.tostring(count.get(i))
=> str.tostring(val.get(i), format.mintick) + "\n" + str.tostring(count.get(i))
strtxt = switch val.get(i) == 9e9
true => "--"
=> pretext
histBox.push(box.new(bar_index - 20 + i , 0, bar_index - 20 + i + 1, math.max(freq.get(i), 0.2),
bgcolor = color.new(#6929F2, 50),
border_color = chart.fg_color))
histLabs.push(label.new(bar_index - 20 + i, 0,
" " + strtxt,
style = label.style_label_up,
color = #00000000,
textcolor = chart.fg_color,
size = size.tiny
))
histBox.endTrim(val, freq, histLabs)
[yloc1, yloc2] = switch hist
false => [newMin, newMax]
=> [0, freq.max()]
xloc = box.all.last ().get_right() + 2
xloc1 = box.all.first().get_left()
line.new(xloc , yloc1, xloc, yloc2, color = chart.fg_color)
line.new(xloc1, yloc1, xloc, yloc1, color = chart.fg_color)
calc = ((count.max() / count.sum() * 100) - (count.min() / count.sum() * 100)) / 10
calcy = (yloc2 - yloc1) / 10
label.new(xloc1 - 1, yloc1, "Return\nCount", style = label.style_label_up, color = #00000000, textcolor = chart.fg_color, size = size.tiny)
for i = 0 to 10
label.new(xloc, yloc1 + (calcy * i), text = str.tostring(count.min() + (calc * i), format.percent),
style = label.style_label_left,
color = #00000000,
textcolor = chart.fg_color,
size = size.tiny
)
highest = count.indexof(count.max())
if not lab and not lin
for i = 1 to count.size() - 1
slice = count.slice(highest - i, highest + i + 1)
if slice.sum() / count.sum() >= cumu
for x = highest - i to highest + i
histBox.get(x).set_bgcolor(color.new(#6929F2, 50))
label.new(
math.round(
math.avg(
histBox.get(highest).get_left(), histBox.get(highest).get_right())), histBox.get(highest).get_bottom(),
text = "Cumulative Prob: " + str.tostring(slice.sum() / count.sum() * 100, format.percent),
color = #00000000, textcolor = #6929F2, size = size.tiny)
left = histBox.get(highest - i)
right = histBox.get(highest + i)
top = histBox.get(highest)
l = line.new(left.get_left(), top.get_top(), left.get_left(), top.get_bottom() , color = #00000000)
r = line.new(right.get_right(), top.get_top(), right.get_right(), top.get_bottom(), color = #00000000)
linefill.new(l, r, color.new(chart.fg_color, 75))
break
floatna () =>
[float(na), float(na), float(na), float(na), color(na)]
[o, h, l, c, color] = switch justPrice
false => floatna()
true and not hist => [open, high, low, close, close > open ? color.aqua : color.red]
=> floatna()
plotcandle(o, h, l, c, color = color, wickcolor = color, bordercolor = chart.fg_color, display = display.pane)
// |
The Opening Range / First Bar By Market Mindset - Zero To Endles | https://www.tradingview.com/script/sfZQlYhj-The-Opening-Range-First-Bar-By-Market-Mindset-Zero-To-Endles/ | marketmindset | https://www.tradingview.com/u/marketmindset/ | 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/
// © marketmindset
//Copied from v14
AUTO = "Auto"
DAILY = "Daily"
WEEKLY = "Weekly"
MONTHLY = "Monthly"
QUARTERLY = "Quarterly"
HALFYEARLY = "Half Yearly"
YEARLY = "Yearly"
sol = line.style_solid
dot = line.style_dotted
dsh = line.style_dashed
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//@version=5
indicator("The Opening Range / First Bar By Market Mindset", "OR/FB - Z2E", overlay=true, max_lines_count=500)
import TradingView/ta/5
res = input.string( AUTO , "Resolution" , options=[AUTO, DAILY, WEEKLY, MONTHLY, QUARTERLY, HALFYEARLY, YEARLY])
timeframe = input.timeframe( "" , "Timeframe")
lookback = input.int( 10 , "Lookback" , 1)
midLine = input.bool( true, "Show Midline")
boxStyle = input.string( dot , 'Range : ' , options = [sol,dot,dsh] , inline = "Box" , group = "Style")
lineStyle = input.string( sol , 'Middle : ' , options = [sol,dot,dsh] , inline = "Line" , group = "Style")
borderWidth = input.int( 1 , ' / ' , 1 , 10 , inline = "Box" , group = "Style")
lineWidth = input.int( 1 , ' / ' , 1 , 10 , inline = "Line" , group = "Style")
_color = input.color(color.lime, "Color : " , inline = "Color" , group = "Style")
_fillcolor = input.color(color.new(color.lime,85), " / " , inline = "Color" , group = "Style")
get_auto_resolution() =>
resolution = '12M'
if timeframe.isintraday
resolution := timeframe.multiplier <= 15 ? 'D' : 'W'
else if timeframe.isdaily
resolution := 'M'
resolution
resolution = switch res
AUTO => get_auto_resolution()
DAILY => "D"
WEEKLY => "W"
MONTHLY => "M"
QUARTERLY => "3M"
HALFYEARLY => "6M"
=> "12M"
if (resolution == "D" or resolution == "W") and timeframe.isdwm
runtime.error("Timeframe is higher than the resolution used.")
[start, end, isLast] = request.security(syminfo.tickerid, resolution , [time, time_close, barstate.islast], lookahead=barmerge.lookahead_on)
[BarTime, H, L, M, isConfirmedBar] = request.security(syminfo.tickerid, timeframe , [time, high , low , hl2 , barstate.isconfirmed])
var line _mid = na
var _mids = array.new_line()
var box _range = na
var _ranges = array.new_box()
if ta.change(start) and isConfirmedBar
if midLine
_mid := line.new(start, M, end, M, color = _color , style = lineStyle, width=lineWidth, xloc = xloc.bar_time)
array.push(_mids, _mid)
_range := box.new(start, H, end, L, color.new(_color,50), borderWidth, boxStyle, bgcolor = _fillcolor, xloc = xloc.bar_time)
array.push(_ranges, _range)
if array.size(_mids) > lookback + 1
line.delete(array.shift(_mids))
box.delete(array.shift(_ranges))
|
Extended Hour Candle | https://www.tradingview.com/script/LweEbTug-Extended-Hour-Candle/ | fyntrade | https://www.tradingview.com/u/fyntrade/ | 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/
// © fyntrade
// Version 1.1.2 - 23 Sep 2023
//@version=5
indicator("Extended Hour Candle", overlay = true, shorttitle = "Ext")
i_col_up = input.color(defval = #26a69a, title = "Up Color", group = "Colors")
i_col_down = input.color(defval = #ef5350, title = "Down Color", group = "Colors")
ext_close = array.last(request.security_lower_tf(ticker.new(syminfo.prefix, syminfo.ticker, session.extended), "30", close))
ext_session = array.last(request.security_lower_tf(ticker.new(syminfo.prefix, syminfo.ticker, session.extended), "30", session.ismarket == false))
ext_high = request.security_lower_tf(ticker.new(syminfo.prefix, syminfo.ticker, session.extended), "30", session.ismarket == false ? high : na)
ext_low = request.security_lower_tf(ticker.new(syminfo.prefix, syminfo.ticker, session.extended), "30", session.ismarket == false ? low : na)
hh = array.max(ext_high)
ll = array.min(ext_low)
type bar
array<box> body
array<line> wick
bi = bar_index
var plot_bar = bar.new(array.new<box>(1), array.new<line>(1))
method candle(bar b)=>
int dist = 1 //distance to last bar
int bb = ext_close > close ? 1 : ext_close < close ? -1 : 0 //bull or bear
top = bb > 0 ? ext_close : close
bot = bb > 0 ? close : ext_close
col = bb == 1 ? i_col_up : bb == -1 ? i_col_down : chart.fg_color
b.body.set(0, box.new(bi + dist, top, bi + dist + 2, bot, na, bgcolor = col))
b.wick.set(0, line.new(bi + dist + 1, hh , bi + dist + 1, ll, color = col))
if barstate.islast and timeframe.isdaily and ext_session
plot_bar.candle()
|
YD_Volume_Alert | https://www.tradingview.com/script/ZzGrCTcr/ | Yonsei_dent | https://www.tradingview.com/u/Yonsei_dent/ | 182 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Yonsei_dent
//
// \\ // ⇗⩸⇖ || || ⇗⁼⁼⁼⁼⁼ ∥⁼⁼⁼⁼ ⁼⁼₪⁼⁼ ₪₪⁼⁼⁼⁼⇘
// \\// ∥ ∥ ||\\ || ⇘‗‗‗‗‗ ∥‗‗‗‗ ‖ || ∥ ⇗⁼⁼⁼⇘ ∥⇗⁼⁼⁼⇘ ‗‗‖‗‗
// ‖‖ ∥ ∥ || \\|| ⇘ ∥ ‖ || ∥ ‖⇘₌₌⇗ ∥ ∥ ‖
// ‖‖ ⇘⩸⇙ || || ‗‗‗‗‗⇗ ∥‗‗‗‗ ‗‗‖‗‗ ‗‗‗ ||‗‗‗‗⇗ ⇘‗‗‗ ∥ ∥ ‖‗‗⇗ ©©
//
//@version=5
indicator("YD_Volume_Alert", overlay = true)
// 증가 Percent #1
upgroup1 = 'Increased #1'
Uppercent1 = input.int(200, step=10, minval=10, title='Increased Percentage 1 (%)', group = upgroup1)
text1 = input.bool(true, 'Text ', inline = '1-1', group = upgroup1)
textpick1 = input.string('Increased Volume', '', options = ['Increased Volume', 'Increased', 'Increased #1'], inline = '1-1', group = upgroup1)
textcol1 = input.color(color.blue, '', inline = '1-1', group = upgroup1)
shape1 = input.bool(true, 'Shape ', inline = '1-2', group = upgroup1)
shapepick1 = input.string('Triangle', '', options = ['Triangle', 'Arrow', 'Circle', 'Cross'], inline = '1-2', group = upgroup1)
shapecol1 = input.color(color.green, ' ', inline = '1-2', group = upgroup1)
shapesize1 = input.string('Tiny', '', options = ['Tiny', 'Small', 'Normal','Large', 'Huge', 'Auto'], inline = '1-2', group = upgroup1)
beartip = "음봉은 봉 위에 마커 표시"
bearbool1 = input.bool(true, 'Bearish Candle : Mark above the candlestick', tooltip = beartip, group = upgroup1)
// 증가 Percent #2
upgroup2 = 'Increased #2'
Uppercent2 = input.int(500, step=10, minval=10, title="Increased Percentage 2 (%)", group = upgroup2)
text2 = input.bool(true, 'Text ', inline = '2-1', group = upgroup2)
textpick2 = input.string('Hugely increased Volume', '', options = ['Hugely increased Volume', 'Hugely Increased', 'Increased #2'], inline = '2-1', group = upgroup2)
textcol2 = input.color(color.blue, '', inline = '2-1', group = upgroup2)
shape2 = input.bool(true, 'Shape ', inline = '2-2', group = upgroup2)
shapepick2 = input.string('Triangle', '', options = ['Triangle', 'Arrow', 'Circle', 'Cross'], inline = '2-2', group = upgroup2)
shapecol2 = input.color(color.red, ' ', inline = '2-2', group = upgroup2)
shapesize2 = input.string('Small', '', options = ['Tiny', 'Small', 'Normal','Large', 'Huge', 'Auto'], inline = '2-2', group = upgroup2)
bearbool2 = input.bool(true, 'Bearish Candle : Mark above the candlestick', tooltip = beartip, group = upgroup2)
// 증가분
is_increased_1 = (Uppercent1 * .01) * volume[1]
is_increased_2 = (Uppercent2 * .01) * volume[1]
// 그리기
switchshape1(x) =>
if bearbool1 and close < open
switch x
'Triangle' => label.style_triangledown
'Arrow' => label.style_arrowdown
'Circle' => label.style_circle
'Cross' => label.style_cross
else if bearbool1 == false or close >= open
switch x
'Triangle' => label.style_triangleup
'Arrow' => label.style_arrowup
'Circle' => label.style_circle
'Cross' => label.style_cross
switchshape2(x) =>
if bearbool2 and close < open
switch x
'Triangle' => label.style_triangledown
'Arrow' => label.style_arrowdown
'Circle' => label.style_circle
'Cross' => label.style_cross
else if bearbool2 == false or close >= open
switch x
'Triangle' => label.style_triangleup
'Arrow' => label.style_arrowup
'Circle' => label.style_circle
'Cross' => label.style_cross
switchsize(x) =>
switch x
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
'Auto' => size.auto
if (volume >= is_increased_1) and (volume < is_increased_2) and shape1
label.new(
x=bar_index, y=bar_index, text = text1?textpick1:na,
yloc = bearbool1 and close<open?yloc.abovebar: yloc.belowbar,
color = shapecol1, textcolor = textcol1,
style = switchshape1(shapepick1),
size = switchsize(shapesize1)
)
else if shape1 ==false
na
if (volume >= is_increased_2) and shape2
label.new(
x=bar_index, y=bar_index, text = text2?textpick2:na,
yloc = bearbool2 and close<open?yloc.abovebar: yloc.belowbar,
color = shapecol2, textcolor = textcol2,
style = switchshape2(shapepick2),
size = switchsize(shapesize2)
)
else if shape2 ==false
na
// 알람생성
if (volume > is_increased_1) and (volume < is_increased_2)
alert(""+str.tostring(syminfo.tickerid)+"'s volume : "+str.tostring(Uppercent1)+"% increased.")
else if (volume >= is_increased_2)
alert(""+str.tostring(syminfo.tickerid)+"'s volume : "+str.tostring(Uppercent2)+"% increased.") |
Auto trend overlay | https://www.tradingview.com/script/tFzmflNZ-Auto-trend-overlay/ | alexhyer13 | https://www.tradingview.com/u/alexhyer13/ | 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/
// © alexhyer13
//@version=5
indicator("Auto trend overlay",overlay=true)
length=input.int(title="CMA Length", defval=42)
color_overlay = input.bool(title="Overlay color (must change visual order to front)", defval=1)
plot_cma = input.bool(title="Plot CMA", defval=1)
rate=input.int(title="CMA derive rate", defval=13)
if (length%2==1)
length+=1
front_half=0.0
second_half=0.0
for i=0 to (length/2)-1
front_half := front_half+close[i+(length/2)]
second_half := second_half+close[i]
new_cma = ((front_half/1.5)+(second_half/0.75))/length
front_half:=0.0
second_half:=0.0
for i=0 to (length/2)-1
front_half := front_half+close[i+(length/2)+rate]
second_half := second_half+close[i+rate]
old_cma = ((front_half/1.5)+(second_half/0.75))/length
slope = (new_cma-old_cma)/rate
if (plot_cma==0)
new_cma:=na
bar_color = color.green
if (slope>=0)
bar_color := color.green
if (slope<0)
bar_color := color.red
plotcandle(color_overlay ? open : na,color_overlay ? high : na,color_overlay ? low : na,color_overlay ? close : na,color = bar_color,wickcolor = bar_color,bordercolor = bar_color)
plot(new_cma ? new_cma : na, color=color.purple) |
Triple Moving Averages + RSI Divergence + Trade Creator [CSJ7] | https://www.tradingview.com/script/QZNUZnFy-Triple-Moving-Averages-RSI-Divergence-Trade-Creator-CSJ7/ | gtellezgiron2009 | https://www.tradingview.com/u/gtellezgiron2009/ | 201 | 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/
// © gtellezgiron2009
//@version=5
indicator(title = "Triple Moving Averages + RSI Divergence + Trade Creator [CSJ7]", shorttitle = "Triple Moving Averages + Trade Creator [CSJ7]", overlay = true, max_bars_back = 2000)
//======================================================================================//
// //
// MOVING AVERAGES INDICATOR //
// //
//======================================================================================//
// Adjust colors according to background color
get_dark_bg_flag()=>
background_color = chart.bg_color
bg_color_r = color.r(background_color)
bg_color_g = color.g(background_color)
bg_color_b = color.b(background_color)
avg_bg_color = math.avg(bg_color_r, bg_color_g, bg_color_b)
dark_bg_flag = avg_bg_color < 50
dark_bg_flag = get_dark_bg_flag()
//--------------------------------------------------------------------------------------//
// CONSTANTS //
//--------------------------------------------------------------------------------------//
// Titles for input groups
string GR_MOVING_AVERAGES = "Moving Averages ------------------------------------"
string GR_SIGNALS = "Buy & Sell Signals ---------------------------------"
// Tooltips
string MA_TYPE_TOOLTIP = 'Select the moving average type: simple or exponential.'
string LENGTH_FAST_TOOLTIP = 'Set the duration (in bars) for the short-term average.'
string LENGTH_MEDIUM_TOOLTIP = 'Set the duration (in bars) for the medium-term average.'
string LENGTH_SLOW_TOOLTIP = 'Set the duration (in bars) for the long-term average.'
// Trend labels
string BULLISH_MOMENTUM_TXT = 'Bullish\nMomentum'
string BEARISH_MOMENTUM_TXT = 'Bearish\nMomentum'
string BULLISH_TREND_START_TXT = 'Bullish\nTrend\nStart'
string BEARISH_TREND_START_TXT = 'Bearish\nTrend\nStart'
string TREND_END_TXT = 'Trend\nEnd'
string ENTRY_ZONE_TXT = 'Entry\nZone'
string BUY_TXT = 'Buy'
string SELL_TXT = 'Sell'
// Entry Rating
string ENTRY_RATING_0_TXT = 'No clear momentum or trend identified.'
string ENTRY_RATING_1_TXT = 'Initial Momentum Observed'
string ENTRY_RATING_2_TXT = 'Trend Commenced'
string ENTRY_RATING_3_TXT = 'Entry Zone Established'
string ENTRY_RATING_4_TXT = 'Entry Signal Triggered'
string ENTRY_RATING_5_TXT = 'Currently Sideways Ranging'
// Define color constants for various scenarios and states
color BRIGHT_RED = color.rgb(255, 0, 0)
color DARK_RED = color.rgb(128, 0, 0)
color BRIGHT_GREEN = color.rgb(0, 255, 8)
color DARK_GREEN = color.rgb(0, 112, 4)
color COL_BEARGR = dark_bg_flag ? color.rgb(133, 17, 17) : color.new(color.red,0) // Bearish Growing
color COL_BULLGR = dark_bg_flag ? color.green : color.new(color.green,0) // Bullish Growing
color COL_BEARSH = dark_bg_flag ? color.red : color.new(color.red, 0) // Bearish Shrinking
color COL_BULLSH = dark_bg_flag ? color.rgb(27, 96, 29) : color.new(color.green, 0) // Bullish Shrinking
color COL_TRANSP = color.new(color.blue,100) // Transparent color
color COLOR_UP = dark_bg_flag ? color.green : color.green // Color for upward movement
color COLOR_DOWN = dark_bg_flag ? color.red : color.red // Color for downward movement
color COLOR_BUY = dark_bg_flag ? color.rgb(0, 255, 8) : color.green // Buy signal color
color COLOR_SELL = dark_bg_flag ? color.rgb(255, 0, 0) : color.red // Sell signal color
color TEXT_COLOR_BUY = dark_bg_flag ? color.rgb(0, 255, 8) : color.green // Buy signal LABEL color
color TEXT_COLOR_SELL = dark_bg_flag ? color.rgb(255, 0, 0) : color.red // Sell signal LABEL color
color COLOR_NEUTRAL = color.gray // Neutral color
color COLOR_TREND_END = dark_bg_flag ? color.yellow : color.black
color BG_COLOR_BUY_ZONE = dark_bg_flag ? color.new(color.green,92) : color.new(color.green,90)
color BG_COLOR_SELL_ZONE = dark_bg_flag ? color.new(color.red,92) : color.new(color.red,90)
color BG_COLOR_BUY = dark_bg_flag ? color.new(color.green,85) : color.new(color.green,80)
color BG_COLOR_SELL = dark_bg_flag ? color.new(color.red,85) : color.new(color.red,80)
color BG_COLOR_RANGING = color.new(color.yellow,95)
// Define line widths for the moving averages
int FAST_LINE_WIDTH = 1
int MEDIUM_LINE_WIDTH = 3
int SLOW_LINE_WIDTH = 5
// Moving Averages
float src_ma = close
int MA_TRANSPARENCY = 0 // Transparency level for moving averages
bool fill_areas_input = true
int MAXIMUM_BARS = 2000
//--------------------------------------------------------------------------------------//
// INPUTS
//--------------------------------------------------------------------------------------//
string ma_type_input = input.string('Exponential','Type',options = ['Simple', 'Exponential'], group = GR_MOVING_AVERAGES, display = display.none, tooltip = MA_TYPE_TOOLTIP)
int length_fast_input = input(50, "Fast", group = GR_MOVING_AVERAGES, display = display.none, tooltip = LENGTH_FAST_TOOLTIP)
int length_medium_input = input(100, "Medium", group = GR_MOVING_AVERAGES, display = display.none, tooltip = LENGTH_MEDIUM_TOOLTIP)
int length_slow_input = input(200, "Slow", group = GR_MOVING_AVERAGES, display = display.none, tooltip = LENGTH_SLOW_TOOLTIP)
//--------------------------------------------------------------------------------------//
// FUNCTIONS
//--------------------------------------------------------------------------------------//
get_moving_averages(source, length_fast_input, length_medium_input, length_slow_input, ma_type_input) =>
float ma_fast = 0.0
float ma_med = 0.0
float ma_slow = 0.0
if ma_type_input == "Simple"
ma_fast := ta.sma(source, length_fast_input)
ma_med := ta.sma(source, length_medium_input)
ma_slow := ta.sma(source, length_slow_input)
else if ma_type_input == "Exponential"
ma_fast := ta.ema(source, length_fast_input)
ma_med := ta.ema(source, length_medium_input)
ma_slow := ta.ema(source, length_slow_input)
[ma_fast, ma_med, ma_slow]
get_color_by_direction(source,lookback, col_up,col_dn, transp) =>
col_p = source > source[lookback] ? col_up : source < source[lookback] ? col_dn : COLOR_NEUTRAL
col = color.new(col_p, transp)
get_scenarios(signal_fast,signal_slow) =>
trend_bull = signal_fast > signal_slow
trend_bear = signal_fast < signal_slow
dif_ma = math.abs(signal_fast - signal_slow)
signal_fast_up = signal_fast > signal_fast[1]
signal_fast_dn = signal_fast < signal_fast[1]
signal_slow_up = signal_slow > signal_slow[1]
signal_slow_dn = signal_slow < signal_slow[1]
trend_shrinking = dif_ma < dif_ma[1] and not(trend_bull ? signal_fast_up and signal_slow_up : signal_fast_dn and signal_slow_dn)
trend_growing = not(trend_shrinking)
bullGr = trend_bull and trend_growing
bullSh = trend_bull and trend_shrinking
bearGr = trend_bear and trend_growing
bearSh = trend_bear and trend_shrinking
[bullGr,bullSh,bearGr,bearSh, signal_fast_up, signal_fast_dn, signal_slow_up, signal_slow_dn]
check_for_rejects(reference) =>
// Candle Parts
bool candle_up = close > open
bool candle_dn = close < open
float body_top = math.max(close, open)
float body_bottom = math.min(close, open)
float body = body_top - body_bottom
bool bottom_reject_candle = low <= reference and body_bottom > reference
bool top_reject_candle = high >= reference and body_top < reference
// Top Rejects
top_reject_1 = top_reject_candle[1] and candle_dn // Simple one candle reject
top_reject_2 = candle_up[1] and low[1] <= reference[1] and close[1] >= reference[1] and
candle_dn and open >= reference and close < reference // crosses up/touches -> crosses down
top_reject_3 = high[2] < reference[2] and
top_reject_candle[1] and
high < reference and candle_dn
top_reject = top_reject_1 or top_reject_2 or top_reject_3
// Bottom Rejects
bottom_reject_1 = bottom_reject_candle[1] and candle_up // Simple one candle reject
bottom_reject_2 = candle_dn[1] and high[1] >= reference[1] and close[1] <= reference[1] and
candle_up and open <= reference and close > reference // crosses/touches down -> crosses up
bottom_reject_3 = low[2] > reference[2] and
bottom_reject_candle[1] and
low > reference and candle_up // above | reject | above
bottom_reject = bottom_reject_1 or bottom_reject_2 or bottom_reject_3
[top_reject, bottom_reject]
get_time_as_text(time_format)=>
str.format_time(time(timeframe.period),time_format, syminfo.timezone)
//--------------------------------------------------------------------------------------//
// LOGS SETUP
//--------------------------------------------------------------------------------------//
// Set system barsback
max_bars_back(time, MAXIMUM_BARS)
max_bars_back(open, MAXIMUM_BARS)
max_bars_back(high, MAXIMUM_BARS)
max_bars_back(close, MAXIMUM_BARS)
max_bars_back(low, MAXIMUM_BARS)
error_log_array = array.new_string()
status_log_array = array.new_string()
conditions_log_array = array.new_string()
//--------------------------------------------------------------------------------------//
// MOVING AVERAGES
//--------------------------------------------------------------------------------------//
// Calculate moving averages
[ma_fast, ma_med, ma_slow] = get_moving_averages(src_ma, length_fast_input, length_medium_input, length_slow_input, ma_type_input)
// Determine market scenarios based on moving averages
[bullGr,bullSh,bearGr,bearSh, signal_fast_up, signal_fast_dn, signal_slow_up, signal_slow_dn] = get_scenarios(ma_fast,ma_slow)
//--------------------------------------------------------------------------------------//
// SIGNALS
//--------------------------------------------------------------------------------------//
// Entry Ratings Variables
var int long_entry_rating = 0
var int short_entry_rating = 0
// Initial Momentum Signal
bullish_momentum_signal = ta.crossover(ma_fast, ma_slow) and ma_slow > ma_med
bearish_momentum_signal = ta.crossunder(ma_fast,ma_slow) and ma_slow < ma_med
// Trend start signal
bullish_trend_start_signal = ta.crossover(ma_med, ma_slow) and ma_fast > ma_med
bearish_trend_start_signal = ta.crossunder(ma_med, ma_slow) and ma_fast < ma_med
// Trend end signal
end_bullish_trend_signal = ta.crossunder(close[2],ma_slow[2]) and close[1] < ma_slow[1] and close < ma_slow and long_entry_rating > 0
end_bearish_trend_signal = ta.crossover(close[2],ma_slow[2]) and close[1] > ma_slow[1] and close > ma_slow and short_entry_rating > 0
//--------------------------------------------------------------------------------------//
// ENTRY RATINGS
//--------------------------------------------------------------------------------------//
// 0 = Nothing
// 1 = Initial Momentum
// 2 = Trend Ongoing
// 3 = Zone Initiated
// 4 = Entry Signal occurred
// 5 = Ranging
// Variable for divergence boxes
var float trend_start_bar = 0.0
// Momentum signal
if bullish_momentum_signal
long_entry_rating := 1
if bearish_momentum_signal
short_entry_rating := 1
// Trend start signal
if bullish_trend_start_signal
long_entry_rating := 2
trend_start_bar := bar_index
if bearish_trend_start_signal
short_entry_rating :=2
trend_start_bar := bar_index
// End of Trend
if end_bullish_trend_signal
long_entry_rating := 0
if end_bearish_trend_signal
short_entry_rating := 0
// Check for rejects
[top_reject_med, bottom_reject_med] = check_for_rejects(ma_med)
// Start of entry zones
start_short_entry_zone_signal = top_reject_med and short_entry_rating == 2
start_long_entry_zone_signal = bottom_reject_med and long_entry_rating == 2
// Entry Signals
if start_long_entry_zone_signal
long_entry_rating := 3
if start_short_entry_zone_signal
short_entry_rating := 3
// TRADE ENTRY_CONDITIONS_TITLE
short_entry = ta.crossunder(close, ma_fast) and short_entry_rating == 3
long_entry = ta.crossover(close, ma_fast) and long_entry_rating == 3
// Entry Signals
if long_entry
long_entry_rating := 4
if short_entry
short_entry_rating := 4
//--------------------------------------------------------------------------------------//
// MARKET OUTLOOK EVENTS
//--------------------------------------------------------------------------------------//
// Initialize Variables
string market_outlook_txt = ENTRY_RATING_0_TXT
string indicator_trade_side = na
var outlook_log_array = array.new_string()
var outlook_log_array_times = array.new_string()
string time_now_txt = get_time_as_text('yyyy-MM-dd HH:mm')
// Create arrays from conext strings
entry_rating_txts_array = array.from(ENTRY_RATING_0_TXT, ENTRY_RATING_1_TXT, ENTRY_RATING_2_TXT, ENTRY_RATING_3_TXT, ENTRY_RATING_4_TXT, ENTRY_RATING_5_TXT)
// If current rating is 0 we clear the outlook logs
if (long_entry_rating == 0 and short_entry_rating == 0) or (long_entry_rating == 5 and short_entry_rating == 5)
array.clear(outlook_log_array)
array.clear(outlook_log_array_times)
// Get indicator trade side
indicator_trade_side := long_entry_rating > 0 and long_entry_rating <= 4 ? 'Bullish' :
short_entry_rating > 0 and short_entry_rating <= 4 ? 'Bearish' :
long_entry_rating == 4 ? 'Long' :
short_entry_rating == 4 ? 'Short':
(long_entry_rating == 5 or short_entry_rating == 5) ? '' : indicator_trade_side
// Define UpTrend or DownTrend
up_trend_flag = long_entry_rating >= 2 and long_entry_rating < 5
dn_trend_flag = short_entry_rating >= 2 and short_entry_rating < 5
// Create the market outlook entry log
if long_entry_rating > 0
market_outlook_txt := indicator_trade_side + ' ' + array.get(entry_rating_txts_array, long_entry_rating)
if short_entry_rating > 0
market_outlook_txt := indicator_trade_side + ' ' + array.get(entry_rating_txts_array, short_entry_rating)
// Update the market outlook log
if long_entry_rating != long_entry_rating[1] or short_entry_rating != short_entry_rating[1]
array.push(outlook_log_array, market_outlook_txt)
array.push(outlook_log_array_times, time_now_txt)
//--------------------------------------------------------------------------------------//
// PLOTS
//--------------------------------------------------------------------------------------//
// Plot buy and sell signals on the chart
plotshape(bullish_momentum_signal,'Bullish Momentum Signal', shape.triangleup,location.belowbar, COLOR_BUY,0, BULLISH_MOMENTUM_TXT, COLOR_BUY,true,size.tiny)//, display = display.none)
plotshape(bearish_momentum_signal,'Bearish Momentum Signal', shape.triangledown,location.abovebar, COLOR_SELL,0, BEARISH_MOMENTUM_TXT,COLOR_SELL,true,size.tiny)//, display = display.none)
plotshape(bullish_trend_start_signal,'Bullish Trend Start Signal', shape.triangleup,location.belowbar, COLOR_BUY,0, BULLISH_TREND_START_TXT,COLOR_BUY,true,size.small)//, display = display.)
plotshape(bearish_trend_start_signal,'Bearish Trend Start Signal', shape.triangledown,location.abovebar, COLOR_SELL,0, BEARISH_TREND_START_TXT,COLOR_SELL,true,size.small)//, display = display.none)
plotshape(end_bullish_trend_signal,'End Bullish Trend Signal', shape.xcross,location.belowbar, COLOR_TREND_END,0,TREND_END_TXT,COLOR_TREND_END,true,size.tiny)//, display = display.none)
plotshape(end_bearish_trend_signal,'End Bearish Trend Signal', shape.xcross,location.abovebar, COLOR_TREND_END,0,TREND_END_TXT,COLOR_TREND_END,true,size.tiny)//, display = display.none)
plotshape(start_long_entry_zone_signal,'Bottom Reject Bull Confirmation', shape.triangleup,location.belowbar, COLOR_BUY,0,ENTRY_ZONE_TXT,COLOR_BUY,true,size.small)//, display = display.none)
plotshape(start_short_entry_zone_signal,'Top Reject Bear Confirmation', shape.triangledown,location.abovebar, COLOR_SELL,0,ENTRY_ZONE_TXT,COLOR_SELL,true,size.small)//, display = display.none)
plotshape(long_entry,'Long Entry', shape.arrowup,location.belowbar, COLOR_BUY,0,BUY_TXT, TEXT_COLOR_BUY,true,size.normal)//, display = display.none)
plotshape(short_entry,'Short Entry', shape.arrowdown,location.abovebar, COLOR_SELL,0,SELL_TXT, TEXT_COLOR_SELL,true,size.normal)//, display = display.none)
// Background color
bgcolor(short_entry_rating >= 3 and short_entry_rating <= 4 ? BG_COLOR_SELL :
long_entry_rating >= 3 and long_entry_rating <= 4 ? BG_COLOR_BUY :
short_entry_rating == 2 ? BG_COLOR_SELL_ZONE :
long_entry_rating == 2 ? BG_COLOR_BUY_ZONE : COL_TRANSP)
// Determine lookback periods for moving averages
int div = 5
ma_slow_lookback = int(math.round(length_slow_input / div,0))
ma_medium_lookback = int(math.round(length_medium_input / div,0))
ma_fast_lookback = int(math.round(length_slow_input / div,0))
// Determine trend color based on scenarios
col_trend = bullGr ? COL_BULLGR : bullSh ? COL_BULLSH : bearGr ? COL_BEARGR : bearSh ? COL_BEARSH : color.yellow
// Configuration for plot transparency
int ma_transparency_fill = 50
int transp_superBull_fill = 40
int transp_superBear_fill = 20
if not(fill_areas_input)
ma_transparency_fill := 100
transp_superBull_fill := 100
transp_superBear_fill := 100
// Plot moving averages on the chart
ln_ma_fast = plot(ma_fast, title="Fast", color=get_color_by_direction(ma_fast,ma_fast_lookback, COLOR_UP,COLOR_DOWN, MA_TRANSPARENCY), linewidth = FAST_LINE_WIDTH)
ln_ma_medium = plot(ma_med, title="Medium", color=get_color_by_direction(ma_med,ma_medium_lookback, COLOR_UP,COLOR_DOWN, MA_TRANSPARENCY), linewidth = MEDIUM_LINE_WIDTH)
ln_ma_slow = plot(ma_slow, title="Slow", color=get_color_by_direction(ma_slow,ma_slow_lookback, COLOR_UP,COLOR_DOWN, MA_TRANSPARENCY), linewidth = SLOW_LINE_WIDTH)
// Fill the area between Medium and Slow moving averages based on trend color
fill(ln_ma_medium, ln_ma_slow, color = color.new(col_trend,ma_transparency_fill), fillgaps = true)
//======================================================================================//
// //
// DIVERGENCE BOX //
// //
//======================================================================================//
//--------------------------------------------------------------------------------------//
// CONSTANTS //
//--------------------------------------------------------------------------------------//
// Colors
color BORDER_COLOR_BOX = dark_bg_flag ? color.new(color.black,0) : color.new(color.gray,50) // RSI Box
color BGCOLOR_BOX = dark_bg_flag ? color.new(color.black,50) : color.new(color.white,40) // RSI Box
color RSI_LINE_COLOR = dark_bg_flag ? color.new(color.yellow,0): color.orange // RSI Box
color CLOSE_LINE_COLOR = dark_bg_flag ? color.new(color.yellow,50): color.orange // RSI Box
color RSI_50_LINE_COLOR = dark_bg_flag ? color.new(color.gray,0): color.black // RSI Box
color BOX_TEXT_COLOR = dark_bg_flag ? color.new(color.gray,0): color.black // RSI Box
color COLOR_RSI_LINREG = dark_bg_flag ? color.new(color.yellow,0) :color.orange // Linear regresssion
color COLOR_CLOSE_LINREG = dark_bg_flag ? color.new(color.yellow,0): color.orange // Linear regresssion
color TEXTCOLOR_RSI_LINREG_LABEL = dark_bg_flag ? color.new(color.white,0) : color.white // Linear regresssion
color TEXTCOLOR_CLOSE_LINREG_LABEL = dark_bg_flag ? color.new(color.white,0) : color.white // Linear regresssion
// Strings
string GR_RSI_BOX = 'Divergence ---------------------------------------'
string BULLISH_RSI_DVRG_LOG_TXT = 'Detected Bullish RSI Divergence.'
string BEARISH_RSI_DVRG_LOG_TXT = 'Detected Bearish RSI Divergence.'
string BULLISH_RSI_DVRG_ERROR_LOG_TXT = 'Bullish RSI Divergence: Consider evaluating a Long trade.'
string BEARISH_RSI_DVRG_ERROR_LOG_TXT = 'Bearish RSI Divergence: Consider evaluating a Short trade.'
string SHOW_RSI_BOX_TOOLTIP = "Toggle the display of a box showing the linear regression of RSI during the current Long or Short trend (if present)."
string SHOW_LINREG_LABELS_TOOLTIP = "Toggle the display of labels for the RSI and Close linear regression lines."
string BOX_TEXT = 'RSI'
string RSI_LINREG_TXT = 'RSI (LR)'
string CLOSE_LINREG_TXT = 'Close (LR)'
string RSI_BOX_SIZE_TOOLTIP = 'Select the size of the vertical size of the RSI box.'
// RSI Box
int LENGTH_RSI = 14
float SRC_RSI = close
float BOX_SEPARATION_FACTOR = 0.05 // Percentage of the highest lowest range for placeing the box.
float COMPACT_BOX_VERTICAL_SIZE_FACTOR = 0.25 // Percentage of the higest/lowest range
float NORMAL_BOX_VERTICAL_SIZE_FACTOR = 0.5 // Percentage of the higest/lowest range
float LARGE_BOX_VERTICAL_SIZE_FACTOR = 1.0 // Percentage of the higest/lowest range
// BOX Configuration
string BOX_TEXT_SIZE = size.small
string BOX_TEXT_HALING = text.align_left
string BOX_TEXT_VALIGN = text.align_top
// BOX Line Styles
string VOLUME_LINE_STYLE = line.style_solid
string RSI_LINE_STYLE = line.style_solid
string CLOSE_LINE_STYLE = line.style_solid
string RSI_50_LINE_STYLE = line.style_dashed
// BOX line Widths
int BORDER_WIDTH_BOX = 1
int VOLUME_LINE_WIDTH = 1
int RSI_LINE_WIDTH = 3
int CLOSE_LINE_WIDTH = 3
int RSI_50_LINE_WIDTH = 1
// Lineal Regression labels
string SIZE_RSI_LINREG = size.small
string SIZE_CLOSE_LINREG = size.small
string STYLE_RSI_LINREG = label.style_label_right
string STYLE_CLOSE_LINREG = label.style_label_right
//--------------------------------------------------------------------------------------//
// INPUTS //
//--------------------------------------------------------------------------------------//
bool show_rsi_box = input.bool(true, "Show RSI box", group = GR_RSI_BOX, display = display.none, tooltip = SHOW_RSI_BOX_TOOLTIP)
string rsi_box_size_input = input.string('Compact','Vertical size of RSI box', options = ['Compact', 'Normal','Large'], group = GR_RSI_BOX, tooltip = RSI_BOX_SIZE_TOOLTIP, display = display.none)
bool show_linreg_labels = input.bool(true, "Show Linear Regression Labels", group = GR_RSI_BOX, display = display.none, tooltip = SHOW_LINREG_LABELS_TOOLTIP)
// Selection of box size
box_vertical_size_factor = switch rsi_box_size_input
'Compact' => COMPACT_BOX_VERTICAL_SIZE_FACTOR
'Normal' => NORMAL_BOX_VERTICAL_SIZE_FACTOR
'Large' => LARGE_BOX_VERTICAL_SIZE_FACTOR
//--------------------------------------------------------------------------------------//
// FUNCTIONS //
//--------------------------------------------------------------------------------------//
get_best_fitting_line(bar_index_array, data_array)=>
// Initialize Variables
int first_barIndex = na
int last_barIndex = na
float y_first = na
float y_last = na
float m = na
float b = na
float R2 = na
float sum_x = 0.0
float sum_y = 0.0
float sum_x_squared = 0.0
float sum_xy = 0.0
// Get array size
int N = array.size(bar_index_array)
int NP = array.size(data_array)
// Only if array contains more than one
if (N > 0 and NP > 0) and N == NP
for i = 0 to N - 1
x = array.get(bar_index_array, i)
y = array.get(data_array, i)
sum_x := sum_x + x
sum_y := sum_y + y
sum_x_squared := sum_x_squared + (x * x)
sum_xy := sum_xy + (x * y)
// Calculate slope (m) and y-intercept (b) for y = mx + b
m := (N * sum_xy - sum_x * sum_y) / (N * sum_x_squared - sum_x * sum_x)
b := (sum_y - m * sum_x) / N
// Finding lowest bar_index and last bar_index
first_barIndex := int(array.min(bar_index_array))
last_barIndex := int(array.max(bar_index_array))
// Calculate y-values for the lowest and last bar_index
y_first := m * first_barIndex + b
y_last := m * last_barIndex + b
// Initialize variables for calculating R2
SST = 0.0
SSE = 0.0
// Calculate mean of y-values
y_mean = sum_y / N
// Calculate SST and SSE
for i = 0 to N - 1
y = array.get(data_array, i)
x = array.get(bar_index_array, i)
y_hat = m * x + b
SST := SST + math.pow(y - y_mean, 2)
SSE := SSE + math.pow(y - y_hat, 2)
// Calculate R-squared
R2 := 1 - (SSE / SST)
[first_barIndex, last_barIndex, y_first, y_last, m, b, R2]
//--------------------------------------------------------------------------------------//
// RSI & BARSBACK //
//--------------------------------------------------------------------------------------//
// Get RSI
rsi = ta.rsi(SRC_RSI,LENGTH_RSI)
// Get barsback
int trend_start_barsback = 1
if (long_entry_rating >= 2 or short_entry_rating >= 2) and barstate.islast
trend_start_barsback := int(last_bar_index - trend_start_bar)
//--------------------------------------------------------------------------------------//
// CALCULATE RSI BOX DIMENTIONS //
//--------------------------------------------------------------------------------------//
// Create array for datasets
volume_array = array.new_float()
rsi_array = array.new_float()
close_array = array.new_float()
bar_index_array = array.new_float()
// Get highest / lowest range
barsback_highest = ta.highest(trend_start_barsback)
barsback_lowest = ta.lowest(trend_start_barsback)
highest_lowest_range = barsback_highest - barsback_lowest
// Get box measurements and coordinates
box_separation = highest_lowest_range * BOX_SEPARATION_FACTOR
box_height = highest_lowest_range * box_vertical_size_factor
// Get box coordinates
//------------------------------------
int box_left_margin = int(trend_start_bar)
int box_right_margin = last_bar_index
float box_top_margin = na
float box_bottom_margin = na
// If trend is bullish
if up_trend_flag
box_bottom_margin := barsback_highest + box_separation
box_top_margin := box_bottom_margin + box_height
//If trend is Bearish
if dn_trend_flag
box_top_margin := barsback_lowest - box_separation
box_bottom_margin := box_top_margin - box_height
box_vertical_middle = math.avg(box_top_margin, box_bottom_margin)
//--------------------------------------------------------------------------------------//
// DRAW RSI BOX //
//--------------------------------------------------------------------------------------//
// Divergence variables
float close_m = na
float rsi_m = na
float rsi_dvrg = na
// Draw initial box and lines
var rsi_line = line.new(1,1,1,1,xloc.bar_index,extend.none, RSI_LINE_COLOR, RSI_LINE_STYLE, RSI_LINE_WIDTH)
var close_line = line.new(1,1,1,1,xloc.bar_index,extend.none, CLOSE_LINE_COLOR, CLOSE_LINE_STYLE, CLOSE_LINE_WIDTH)
var rsi_50_line = line.new(1,1,1,1,xloc.bar_index,extend.none, RSI_50_LINE_COLOR, RSI_50_LINE_STYLE, RSI_50_LINE_WIDTH)
var dvrg_box = box.new(1,1,1,1, BORDER_COLOR_BOX, BORDER_WIDTH_BOX, line.style_solid, extend.none, xloc.bar_index, BGCOLOR_BOX, BOX_TEXT, BOX_TEXT_SIZE, BOX_TEXT_COLOR, BOX_TEXT_HALING, BOX_TEXT_VALIGN)
var rsi_linreg_label = label.new(1,1,'',xloc.bar_index,color = COLOR_RSI_LINREG, style = STYLE_RSI_LINREG, textcolor = TEXTCOLOR_RSI_LINREG_LABEL, size = SIZE_RSI_LINREG)
var close_linreg_label = label.new(1,1,'',xloc.bar_index,color = COLOR_CLOSE_LINREG, style = STYLE_CLOSE_LINREG, textcolor = TEXTCOLOR_CLOSE_LINREG_LABEL, size = SIZE_CLOSE_LINREG)
// Update boxes and lines
if barstate.islast and show_rsi_box
// Loop through all barsback
for i = 0 to trend_start_barsback - 1
// Add data to arrays
array.push(rsi_array,rsi[i])
array.push(close_array,close[i])
array.push(bar_index_array, last_bar_index - i)
// Get the best fitting lines for each dataset
[first_barIndex_rsi, last_barIndex_rsi, y_first_rsi, y_last_rsi, m_rsi, b_rsi, R2_rsi] = get_best_fitting_line(bar_index_array, rsi_array)
[first_barIndex_close, last_barIndex_close, y_first_close, y_last_close, m_close, b_close, R2_close] = get_best_fitting_line(bar_index_array, close_array)
// Get RSI y levels
y1_rsi = ((y_first_rsi / 100) * box_height) + box_bottom_margin
y2_rsi = ((y_last_rsi / 100) * box_height) + box_bottom_margin
// Box middle
box_middle = box_bottom_margin + (box_height / 2)
// Update divergence values
close_m := m_close
rsi_m := m_rsi
// Line colors
rsi_color = rsi_m > 0 ? color.green : color.red
close_color = close_m > 0 ? color.green : color.red
// Update dvrg_box
box.set_lefttop(dvrg_box, box_left_margin, box_top_margin)
box.set_rightbottom(dvrg_box, box_right_margin, box_bottom_margin)
// Update RSI line
line.set_xy1(rsi_line,box_left_margin, y1_rsi)
line.set_xy2(rsi_line,box_right_margin, y2_rsi)
line.set_color(rsi_line, rsi_color)
// Update Close line
line.set_xy1(close_line,box_left_margin, y_first_close)
line.set_xy2(close_line,box_right_margin, y_last_close)
line.set_color(close_line, close_color)
// RSI 50
line.set_xy1(rsi_50_line,box_left_margin, box_middle)
line.set_xy2(rsi_50_line,box_right_margin, box_middle)
// Update the labels
if show_linreg_labels
// Update RSI labels
label.set_xy(rsi_linreg_label,box_left_margin, y1_rsi)
label.set_text(rsi_linreg_label, RSI_LINREG_TXT)
label.set_color(rsi_linreg_label, rsi_color)
// Update CLOSE labels
label.set_xy(close_linreg_label,box_left_margin, y_first_close)
label.set_text(close_linreg_label, CLOSE_LINREG_TXT)
label.set_color(close_linreg_label, close_color)
//---------------------------------------//
// GET DIVERGENCE //
//---------------------------------------//
// Variagles
string rsi_dvrg_flag = 'None'
// Calculate divergence
rsi_dvrg := close_m + rsi_m
// Get divergence flag and log entry
if rsi_dvrg > 0 and dn_trend_flag
rsi_dvrg_flag := 'Bullish'
array.push(status_log_array, BULLISH_RSI_DVRG_LOG_TXT)
if rsi_dvrg < 0 and up_trend_flag
rsi_dvrg_flag := 'Negative'
array.push(status_log_array, BEARISH_RSI_DVRG_LOG_TXT)
//======================================================================================//
//**************************************************************************************//
//********************************* ************************************//
//********************************* TRADE CREATOR ************************************//
//********************************* ************************************//
//**************************************************************************************//
//======================================================================================//
//**************************************************************************************//
// TYPES
//**************************************************************************************//
type entry_condition
string name = na
string description = na
float actual_float = na
float min_condition = na
bool true_condition = na
bool pass = na
//**************************************************************************************//
// CONSTANTS
//**************************************************************************************//
// Colors
color COLOR_TRANSP = color.new(color.gray, 100) // General
color EMPTY_CELL_BG_COLOR = dark_bg_flag ? color.white : color.new(#eaeaea, 0) // Dashboard
color DASHBOARD_FRAME_COLOR = color.gray // Dashboard
color MAIN_HEADER_COLOR = dark_bg_flag ? color.new(#000000, 0) : color.new(#000000, 0) // Dashboard
color TABLE_HEADER_COLOR = dark_bg_flag ? color.new(#373737, 0) : color.new(#373737, 0) // Dashboard
color TABLE_SUBHEADER_COLOR = dark_bg_flag ? color.new(#5f5f5f, 0) : color.new(#5f5f5f, 0) // Dashboard
color TABLE_CELL_COLOR = dark_bg_flag ? color.new(#767676, 0) : color.new(#767676, 0) // Dashboard
color COLOR_CONDITION_PASS = dark_bg_flag ? color.new(color.green,0) : color.new(color.green,0) // Dashboard
color COLOR_CONDITION_FAIL = dark_bg_flag ? EMPTY_CELL_BG_COLOR : EMPTY_CELL_BG_COLOR // Dashboard
color TRADEBOX_PROFIT_COLOR = dark_bg_flag ? color.new(color.green,80) : color.new(color.green,60) // Tradebox
color TRADEBOX_LOSS_COLOR = dark_bg_flag ? color.new(color.red,80) : color.new(color.red,60) // Tradebox
color FIRST_ENTRY_LINE_COLOR = dark_bg_flag ? color.gray : color.gray // Tradebox
color AVG_ENTRY_LINE_COLOR = dark_bg_flag ? color.gray : color.gray // Tradebox
color LAST_ENTRY_LINE_COLOR = dark_bg_flag ? color.gray : color.gray // Tradebox
color EXIT_LINE_COLOR = dark_bg_flag ? color.green : color.green // Tradebox
color STOPLOSS_LINE_COLOR = dark_bg_flag ? color.red : color.red // Tradebox
color TRADEBOX_POSITION_TEXT_COLOR = dark_bg_flag ? color.white : color.white // Tradebox
color PRICE_LABEL_COLOR = dark_bg_flag ? color.new(color.gray,50) : color.new(color.gray,20) // Tradebox
color PRICE_LABEL_TEXTCOLOR = dark_bg_flag ? color.new(color.white,0) : color.new(color.white,0) // Tradebox
color ACTIVE_TRADE_LABEL_COLOR = dark_bg_flag ? color.new(color.black,30) : color.new(color.black,30) // Active Trade
color ACTIVE_TRADE_LABEL_TEXTCOLOR = dark_bg_flag ? color.white : color.white // Active Trade
// Temporary input
string execution_mode_input = 'Analyze'
// Dashboard Table
string DASHBOARD_TITLE = 'Trade Creator [CSJ7]'
string MARKET_OUTLOOK_TITLE = "Market Outlook Events"
string ENTRY_CONDITIONS_TITLE = "Entry Conditions"
string ESTIMATED_PNL_TITLE = "Estimated P&L"
string OPERATION_LOGS_TITLE = "Operation Logs"
// Inputs titles
string GR_DASHBOARD_COMPONENTS = "[TC]: DASHBOARD COMPONENTS ====================================="
string GR_ACTIVE_TRADE_SETUP = "[TC]: TRADE SETUP =============================================="
string GR_SHORT = "SHORT LEVELS"
string GR_LONG = "LONG LEVELS"
string GR_RISK_SETUP = "RISK CONTROL"
string GR_ENTRY_CONDITIONS = 'ENTRY CONDITIONS'
string GR_EXCHANGE = "[TC]: ECONOMICS ================================================"
string GR_ALERTS = "[TC]: ALERTS ============================================="
string GR_LAYOUT = "[TC]: LAYOUT ============================================="
// Tooltips
string TABLE_HEADER_TOOLTIP = 'Toggle content visibility via Settings.'
string SHOW_MARKET_OUTLOOK_TOOLTIP = 'Toggle the list of detected Market Outlook events.'
string SHOW_ENTRY_CONDITIONS_TOOLTIP = 'Toggle the table displaying selected conditions for trade entry and their current values.'
string SHOW_ESTIMATED_PNL_TOOLTIP = 'Toggle the table displaying estimated Profit and Loss based on current trade settings.'
string SHOW_LOGS_TOOLTIP = 'Toggle the list of status and error log entries.'
string DRAW_TRADE_BOX_TOOLTIP = 'Toggle the trade box displaying entry, exit levels, and profit and loss areas for the planned trade.'
string SHOW_PRICE_LABELS_TOOLTIP = 'Toggle the display of price levels for the planned trade.'
string SIDE_TOOLTIP = 'Choose the trade side. When set to Auto, the Trade Creator recommends the appropriate side based on the trend.'
string LEVERAGE_TOOLTIP = 'Specify the leverage level (multiplier of equity investment) for each trade.'
string LAST_ENTRY_SHORT_TOOLTIP = 'Set the price level for the final entry in a short trade.'
string FIRST_ENTRY_SHORT_TOOLTIP = 'Set the price level for the initial entry in a short trade.'
string EXIT_SHORT_TOOLTIP = 'Set the target exit price for a short trade. If set to Auto, the Trade Creator will determine an exit level meeting the established minimum conditions.'
string EXIT_LONG_TOOLTIP = 'Set the target exit price for a long trade. If set to Auto, the Trade Creator will determine an exit level meeting the established minimum conditions.'
string FIRST_ENTRY_LONG_TOOLTIP = 'Set the price level for the initial entry in a long trade.'
string LAST_ENTRY_LONG_TOOLTIP = 'Set the price level for the final entry in a long trade.'
string EQUITY_INVESTMENT_PER_TRADE_TOOLTIP = 'Specify the percentage of available equity to use for each trade.'
string STOPLOSS_TYPE_TOOLTIP = 'Choose the type of stoploss to be calculated.'
string ACT_MINIMUM_WINING_ROI_TOOLTIP = 'Toggle whether a minimum Return On Equity (ROI) is required for trade entry.'
string ACT_MAXIMUM_LOOSING_ROI_TOOLTIP = 'Toggle whether a maximum negative Return On Equity (ROI) is set as a condition for trade entry.'
string ACT_MINIMUM_RRR_TOOLTIP = 'Toggle whether a minimum Risk Reward Ratio (RRR) is required for trade entry.'
string MINIMUM_WINING_ROI_TOOLTIP = 'Specify the minimum Return On Equity (ROI) required for trade entry.'
string MAXIMUM_LOOSING_ROI_TOOLTIP = 'Specify the maximum negative ROI acceptable for trade entry.'
string MINIMUM_RRR_TOOLTIP = 'Specify the minimum Risk Reward Ratio for trade entry.'
string OUTLOOK_RATING_INPUT_TOOLTIP = 'Choose the minimum Trend Stage needed for trade entry.'
string ACT_RSI_DIVERGENCE_TOOLTIP = 'Toggle whether an RSI Divergence is a condition for trade entry.'
string MINIMUM_TRADE_RATING_TOOLTIP = 'Specify the minimum Trade Rating required for trade entry.'
string EQUITY_TOOLTIP = 'Specify the starting equity available for trading.'
string ENTRY_FEE_RATE_TOOLTIP = 'Specify the fee rate charged by your exchange/broker for trade entry.'
string EXIT_FEE_RATE_TOOLTIP = 'Specify the fee rate charged by your exchange/broker for trade exit.'
string MARKET_OUTLOOK_ALERT_TOOLTIP = 'Toggle whether an alert should be triggered upon a specific market outlook status change.'
string MINIMUM_TRADE_RATING_ALERT_TOOLTIP = 'Toggle whether an alert should be triggered when minimum trade entry conditions are met.'
string TEXT_SIZE_INPUT_TOOLTIP = 'Select the text size for the dashboard.'
string TABLEYPOS_TOOLTIP = 'Adjust the vertical position of the dashboard.'
string TABLEXPOS_TOOLTIP = 'Adjust the horizontal position of the dashboard.'
// Error log messages
string LONG_LEVELS_INPUT_ERROR_TXT = 'Invalid Long levels: Please adjust.'
string SHORT_LEVELS_INPUT_ERROR_TXT = 'Invalid Short levels: Please adjust.'
string NO_SIDE_DETECTED_TXT = 'Trade side not detected.'
string NO_CLIENT_DATA_MESSAGE_TXT = 'Client Data required for trading is incomplete.\nPlease check Settings.'
string FAR_BARSBACK_ERROR_TXT = 'Support & Resistance start dates are too distant.\nPlease bring them closer.'
string ZERO_BARSBACK_ERROR_TXT = 'Issue with Support & Resistance start dates.\nPlease adjust their positions.'
string BARSBACK_ERROR_FIX_ZERO_TXT = 'A Start Date was reset to default\nas it was set to Zero. Please review.'
string BARSBACK_ERROR_FIX_NA_TXT = 'A Start Date was reset to default\nas it was set to NA. Please review.'
string BARSBACK_ERROR_FIX_TOOFAR_TXT = 'A Start Date was reset to default\nas it was too distant. Please review.'
// Ok log messages
string LONG_LEVELS_INPUT_OK_TXT = 'Long levels set correctly.'
string SHORT_LEVELS_INPUT_OK_TXT = 'Short levels set correctly.'
string AUTO_SIDE_DETECT_ACTIVATED_TXT = 'Auto Side Detection enabled.'
string ENTRY_REJECTS_CONFIRMATION = 'Entry rejections confirmed.'
string SEND_ENTRY_ORDERS_TXT = 'Entry conditions satisfied; entry orders ready to be placed.'
// Alerts
string ENTRY_CONDITIONS_ALERT_MESSAGE = 'All conditions for entry are satisfied.'
string INITIAL_MOMENTUM_ALERT_DETECTED_TXT = 'Initial Momentum detected'
string INITIAL_MOMENTUM_ALERT_PROGRAMED_TXT = 'Initial Momentum alert has been programmed.'
string TREND_STARTS_TXT = 'Trend Starts'
string TREND_STARTING_TXT = 'Trend Starting.'
string TREND_STARTING_ALERT_PROGRAMED_TXT = 'Trend Starting alert has been programmed.'
string ENTRY_ZONE_STARTS_TXT = 'Entry Zone Starts'
string ENTRY_ZONE_STARTING_TXT = 'Entry Zone Starting.'
string ENTRY_ZONE_ALERT_PROGRAMMED_TXT = 'Entry Zone alert has been programmed.'
string FIRST_ENTRY_SIGNAL_TXT = 'First Entry Signal'
string FIRST_ENTRY_SIGNAL_TRIGGERED_TXT = 'First Entry Signal Triggered.'
string FIRST_ENTRY_SIGNAL_PROGRAMED_TXT = 'First Entry Signal alert has been programmed.'
string MINIMUM_RATING_ALERT_PROGRAMMED_TXT = 'Minimum Trade Rating alert has been programmed.'
// Conditions
string CONDITION_WINNING_ROI_NAME = 'Positive ROI (%)'
string CONDITION_LOOSING_ROI_NAME = 'Negative ROI (%)'
string CONDITION_RRR_NAME = 'Risk Reward Ratio (x)'
string CONDITION_TREND_NAME = 'Trend Stage'
string CONDITION_RSI_DIVERGENCE = 'RSI Divergence Indicator'
string CONDITION_PASS_TXT = 'OK'
string CONDITION_FAIL_TXT = '--'
// Debugging
bool ACTIVATE_ENTRY_CONDITIONS_EVAL = true
bool SHOW_TRADE_TABLE = true
// Entry Conditions
float MINIMUM_RSI_M = 0.2 //'Min m for RSI divergence', group = GR_ENTRY_CONDITIONS)
float MINIMUM_RSI_R2 = 0.65 //'Min R2 in RSI', group = GR_ENTRY_CONDITIONS)
int NUMBER_OF_ENTRIES_PER_ZONE = 2
float MARGIN_OVER_RRR = 0.2 // Margin used to calculate automatic target
float MIN_DVRG_M = 0.1
// Support and Resistance zones
float STOPLOSS_BUFFER_MARGIN_TIGHT = 50 // % of ATR
float STOPLOSS_BUFFER_MARGIN_MEDIUM = 100 // % of ATR
float STOPLOSS_BUFFER_MARGIN_LOOSE = 200 // % of ATR
float TAKEPROFIT_BUFFER_MARGIN_INPUT = 0 // % of ATR
// Dashboard
int TOTAL_COLUMNS = 6
int TOTAL_ROWS = 30
int DASHBOARD_FRAME_WIDTH = dark_bg_flag ? 0 : 1
// TradeBox
int SEPARATION_FROM_LEVELS_INPUT = 3 // Separation from level boxes
int TRADEBOX_WIDTH_INPUT = 40 // Trade Box width (bars)
int TRADEBOX_WIDTH_OPEN_POSITION_INPUT = 30
string TRADEBOX_POSITION_TXT = ''
string PRICE_LABEL_STYLE = label.style_label_left
string TRADEBOX_TEXT_HALIGN = text.align_center
string TRADEBOX_TEXT_VALIGN = text.align_center
string TRADEBOX_TEXT_SIZE = size.small
// Active Trade Label
string ACTIVE_TRADE_LABEL_STYLE = label.style_label_down // label.style_label_lower_left
string AUTO_TRADE_NAME = 'Trade' // Name used in the input selector for choosing auto trade
string ACTIVE_TRADE_LABEL_TEXT_ALIGN = text.align_left
// Price labels
int DECIMALS_QTY_LABELS = 4
//**************************************************************************************//
// INPUTS
//**************************************************************************************//
// Initial options
bool show_market_outlook = input.bool(true, 'Expand Market Outlook', display = display.none, group = GR_DASHBOARD_COMPONENTS, tooltip = SHOW_MARKET_OUTLOOK_TOOLTIP)
bool show_entry_conditions = input.bool(false, 'Expand Entry Conditions Table', display = display.none, group = GR_DASHBOARD_COMPONENTS, tooltip = SHOW_ENTRY_CONDITIONS_TOOLTIP)
bool show_estimated_pnl_input = input.bool(false, 'Expand Estimated P&L Table', display = display.none, group = GR_DASHBOARD_COMPONENTS, tooltip = SHOW_ESTIMATED_PNL_TOOLTIP)
bool show_logs = input.bool(false, 'Expand Logs Table', display = display.none, group = GR_DASHBOARD_COMPONENTS, tooltip = SHOW_LOGS_TOOLTIP)
bool draw_trade_box = input.bool(true, 'Show Trade Box', display = display.none, group = GR_DASHBOARD_COMPONENTS, tooltip = DRAW_TRADE_BOX_TOOLTIP)
bool show_price_labels = input.bool(false, 'Show Trade Levels', display = display.none, group = GR_DASHBOARD_COMPONENTS, tooltip = SHOW_PRICE_LABELS_TOOLTIP)
string side_input = input.string('Auto','Side',options = ['Auto','Long','Short'], group = GR_ACTIVE_TRADE_SETUP, display = display.none, tooltip = SIDE_TOOLTIP)
float leverage_input = input.float(30,'Leverage (x)', group = GR_ACTIVE_TRADE_SETUP, display = display.none, tooltip = LEVERAGE_TOOLTIP, minval = 1, maxval = 100)
// Short Trade Setup
string last_entry_short_input = input.string('Medium MA', 'Last Entry', options = [
'400 Highest',
'200 Highest',
'100 Highest',
'50 Highest',
'20 Highest',
'Slow MA',
'Medium MA',
'Fast MA',
'20 Lowest',
'50 Lowest',
'100 Lowest',
'200 Lowest',
'400 Lowest'
], group = GR_SHORT, display = display.none, tooltip = LAST_ENTRY_SHORT_TOOLTIP)
string first_entry_short_input = input.string('Fast MA', 'First Entry', options = [
'400 Highest',
'200 Highest',
'100 Highest',
'50 Highest',
'20 Highest',
'Slow MA',
'Medium MA',
'Fast MA',
'20 Lowest',
'50 Lowest',
'100 Lowest',
'200 Lowest',
'400 Lowest'
], group = GR_SHORT, display = display.none, tooltip = FIRST_ENTRY_SHORT_TOOLTIP)
string exit_short_input = input.string('Auto', 'Target', options = [
'Auto',
'400 Highest',
'200 Highest',
'100 Highest',
'50 Highest',
'20 Highest',
'Slow MA',
'Medium MA',
'Fast MA',
'20 Lowest',
'50 Lowest',
'100 Lowest',
'200 Lowest',
'400 Lowest'
], group = GR_SHORT, display = display.none, tooltip = EXIT_SHORT_TOOLTIP )
// Long Trade Setup
string exit_long_input = input.string('Auto', 'Target', options = [
'Auto',
'400 Highest',
'200 Highest',
'100 Highest',
'50 Highest',
'20 Highest',
'Fast MA',
'Medium MA',
'Slow MA',
'20 Lowest',
'50 Lowest',
'100 Lowest',
'200 Lowest',
'400 Lowest'
], group = GR_LONG, display = display.none, tooltip = EXIT_LONG_TOOLTIP)
string first_entry_long_input = input.string('Fast MA', 'First Entry', options = [
'400 Highest',
'200 Highest',
'100 Highest',
'50 Highest',
'20 Highest',
'Fast MA',
'Medium MA',
'Slow MA',
'20 Lowest',
'50 Lowest',
'100 Lowest',
'200 Lowest',
'400 Lowest'
], group = GR_LONG, display = display.none, tooltip = FIRST_ENTRY_LONG_TOOLTIP)
string last_entry_long_input = input.string('Medium MA', 'Last Entry', options = [
'400 Highest',
'200 Highest',
'100 Highest',
'50 Highest',
'20 Highest',
'Fast MA',
'Medium MA',
'Slow MA',
'20 Lowest',
'50 Lowest',
'100 Lowest',
'200 Lowest',
'400 Lowest'
], group = GR_LONG, display = display.none, tooltip = LAST_ENTRY_LONG_TOOLTIP)
// Risk Control
float equity_investment_per_trade_input = input.float(10, 'Equity investment per entry (%)', group = GR_RISK_SETUP, display = display.none, tooltip = EQUITY_INVESTMENT_PER_TRADE_TOOLTIP, minval = 0.1, maxval = 100)
string stoploss_type_input = input.string('Medium','Stoploss size', options =['Tight', 'Medium', 'Loose'], group = GR_RISK_SETUP, display = display.none, tooltip = STOPLOSS_TYPE_TOOLTIP)
// Entry Conditions
bool act_minimum_wining_roi_input = input.bool(true, '', inline = 'EC1', group = GR_ENTRY_CONDITIONS, tooltip = ACT_MINIMUM_WINING_ROI_TOOLTIP)
bool act_maximum_loosing_roi_input = input.bool(true, '', inline = 'EC2', group = GR_ENTRY_CONDITIONS, tooltip = ACT_MAXIMUM_LOOSING_ROI_TOOLTIP)
bool act_minimum_rrr_input = input.bool(true, '', inline = 'EC3',group = GR_ENTRY_CONDITIONS, tooltip = ACT_MINIMUM_RRR_TOOLTIP)
float minimum_wining_roi_input = input.float(45, 'Min winning ROI (%)', inline = 'EC1', group = GR_ENTRY_CONDITIONS, display = display.none, tooltip = MINIMUM_WINING_ROI_TOOLTIP, minval = 1)
float maximum_loosing_roi_input = input.float(20, 'Max loosing ROI (%)', inline = 'EC2', group = GR_ENTRY_CONDITIONS, display = display.none, tooltip = MAXIMUM_LOOSING_ROI_TOOLTIP, minval = 0, maxval = 100)
float minimum_rrr_input = input.float(3,'Min Risk Reward Ratio (x)', inline = 'EC3',group = GR_ENTRY_CONDITIONS, display = display.none, tooltip = MINIMUM_RRR_TOOLTIP, minval = 0)
string outlook_rating_input_txt = input.string(
'Entry Zone','Trend Stage',options =[
'Initial Momentmum','Trend Started','Entry Zone','Entry Signal','None'
], inline = 'EC4',group = GR_ENTRY_CONDITIONS, display = display.none, tooltip = OUTLOOK_RATING_INPUT_TOOLTIP)
bool act_rsi_divergence = input.bool(true,'Auto RSI Divergence',group = GR_ENTRY_CONDITIONS, display = display.none, tooltip = ACT_RSI_DIVERGENCE_TOOLTIP)
int minimum_trade_rating_input = input.int(80,'Minimum Trade Rating (%)', group = GR_ENTRY_CONDITIONS, display = display.none, tooltip = MINIMUM_TRADE_RATING_TOOLTIP, minval = 0, maxval = 100)
// Exchange setup
float equity_input = input.float(5000,'Available equity (USDT)', group = GR_EXCHANGE, display = display.none, tooltip = EQUITY_TOOLTIP, minval = 0)
float entry_fee_rate_input = input.float(0.02, 'Exchange Entry Fees (%)', group = GR_EXCHANGE, display = display.none, tooltip = ENTRY_FEE_RATE_TOOLTIP, minval = 0)
float exit_fee_rate_input = input.float(0.055, 'Exchange Exit Fees (%)', group = GR_EXCHANGE, display = display.none, tooltip = EXIT_FEE_RATE_TOOLTIP, minval = 0)
// Alerts
string market_outlook_alert = input.string('None','Activate when ', options = [
'Initial Momentmum detected','Trend Starts','Entry Zone Starts','First Entry Signal','None'], group = GR_ALERTS, display = display.none, tooltip = MARKET_OUTLOOK_ALERT_TOOLTIP)
bool minimum_trade_rating_alert = input.bool(false,'Activate when minimum Entry Conditions are met', group = GR_ALERTS, display = display.none, tooltip = MINIMUM_TRADE_RATING_ALERT_TOOLTIP)
// Dashboard
var string text_size_input = input.string('Small','Dashboard text size', options = ['Tiny','Small','Normal','Auto'], group = GR_LAYOUT, display = display.none, tooltip = TEXT_SIZE_INPUT_TOOLTIP)
var string tableYposInput = input.string("top", "Dashboard position", inline = "11", options = ["top", "middle", "bottom"], group = GR_LAYOUT, display = display.none, tooltip = TABLEYPOS_TOOLTIP)
var string tableXposInput = input.string("right", "", inline = "11", options = ["left", "center", "right"], group = GR_LAYOUT, display = display.none, tooltip = TABLEXPOS_TOOLTIP)
//**************************************************************************************//
// FUNCTIONS
//**************************************************************************************//
toPercentageString(x, decimals) =>
str.tostring(math.round(x * 100, decimals)) + '%'
toFactorString(x, decimals) =>
str.tostring(math.round(x,decimals)) + 'x'
toNumberString(x,decimals) =>
str.tostring(math.round(x,decimals),"#,###.#####")
toCurrencyString(x,decimals) =>
'$' + str.tostring(math.round(x,decimals),"#,###.##")
get_buffer_margin(atr_length, buffer_margin_input)=>
ta.atr(atr_length) * (buffer_margin_input / 100)
get_log_text(log_array)=>
txt_log = ''
log_array_size = array.size(log_array)
if log_array_size > 0
for i = 0 to log_array_size - 1
log = array.get(log_array, i)
txt_log := txt_log + log
txt_log := i == log_array_size - 1 ? txt_log : txt_log + '\n'
txt_log
create_and_populate_entry_condition(name, description, min_condition, true_condition)=>
// Create condition
entry_condition condition = entry_condition.new()
// Populate condition fields
condition.name := name
condition.description := description
condition.actual_float := na
condition.min_condition := min_condition
condition.true_condition := true_condition
condition.pass := na
condition
//**************************************************************************************//
// INITIAL SETUP
//**************************************************************************************//
// Update log with type of operation.
array.push(status_log_array, execution_mode_input +' operation mode selected.')
// Update log with side selection.
if side_input == 'Auto'
array.push(status_log_array,AUTO_SIDE_DETECT_ACTIVATED_TXT)
else
array.push(status_log_array,'Manually, ' + side_input + ' trade side selected.')
//**************************************************************************************//
// INITIALIZE ENTRY CONDITIONS
//**************************************************************************************//
// Get numeric value of outlook rating input
float outlook_rating_input = switch outlook_rating_input_txt
'Initial Momentmum' => 1
'Trend Started' => 2
'Entry Zone' => 3
'Entry Signal' => 4
// Get the RSI Divergence requirement
required_rsi_divergence = true // <<<<<<<<ARREGLAR
// Creae array where entry conditions will be stored
entry_conditions_array = array.new<entry_condition>()
// Create entry condition variables
if act_minimum_wining_roi_input
condition = create_and_populate_entry_condition('minimum_wining_roi_input', CONDITION_WINNING_ROI_NAME, minimum_wining_roi_input, false)
array.push(entry_conditions_array, condition)
if act_maximum_loosing_roi_input
condition = create_and_populate_entry_condition('maximum_loosing_roi_input', CONDITION_LOOSING_ROI_NAME, maximum_loosing_roi_input, false)
array.push(entry_conditions_array, condition)
if act_minimum_rrr_input
condition = create_and_populate_entry_condition('minimum_rrr_input', CONDITION_RRR_NAME, minimum_rrr_input, false)
array.push(entry_conditions_array, condition)
if outlook_rating_input > 0
condition = create_and_populate_entry_condition('outlook_rating_input', CONDITION_TREND_NAME, outlook_rating_input, false)
array.push(entry_conditions_array, condition)
if act_rsi_divergence
condition = create_and_populate_entry_condition('rsi_divergence', CONDITION_RSI_DIVERGENCE, 0, required_rsi_divergence)
array.push(entry_conditions_array, condition)
//**************************************************************************************//
// TRADE
//**************************************************************************************//
// Variable initiation
float long_target_auto = na
float short_target_auto = na
// Highest and lowest datapoint
float highest_400 = ta.highest(400)
float highest_200 = ta.highest(200)
float highest_100 = ta.highest(100)
float highest_50 = ta.highest(50)
float highest_20 = ta.highest(20)
float lowest_20 = ta.lowest(20)
float lowest_50 = ta.lowest(50)
float lowest_100 = ta.lowest(100)
float lowest_200 = ta.lowest(200)
float lowest_400 = ta.lowest(200)
// SWITCH OF SELECTED TRADE LEVELS
//---------------------------------------------------------------------
// Short
float last_entry_price_short = switch last_entry_short_input
'400 Highest' => highest_400
'200 Highest' => highest_200
'100 Highest' => highest_100
'50 Highest' => highest_50
'20 Highest' => highest_20
'Slow MA' => ma_slow
'Medium MA' => ma_med
'Fast MA' => ma_fast
'20 Lowest' => lowest_20
'50 Lowest' => lowest_50
'100 Lowest' => lowest_100
'200 Lowest' => lowest_200
'400 Lowest' => lowest_400
float first_entry_price_short = switch first_entry_short_input
'400 Highest' => highest_400
'200 Highest' => highest_200
'100 Highest' => highest_100
'50 Highest' => highest_50
'20 Highest' => highest_20
'Slow MA' => ma_slow
'Medium MA' => ma_med
'Fast MA' => ma_fast
'20 Lowest' => lowest_20
'50 Lowest' => lowest_50
'100 Lowest' => lowest_100
'200 Lowest' => lowest_200
'400 Lowest' => lowest_400
float exit_price_win_short = switch exit_short_input
'Auto' => short_target_auto
'400 Highest' => highest_400
'200 Highest' => highest_200
'100 Highest' => highest_100
'50 Highest' => highest_50
'20 Highest' => highest_20
'Slow MA' => ma_slow
'Medium MA' => ma_med
'Fast MA' => ma_fast
'20 Lowest' => lowest_20
'50 Lowest' => lowest_50
'100 Lowest' => lowest_100
'200 Lowest' => lowest_200
'400 Lowest' => lowest_400
// Long
float exit_price_win_long = switch exit_long_input
'Auto' => long_target_auto
'400 Highest' => highest_400
'200 Highest' => highest_200
'100 Highest' => highest_100
'50 Highest' => highest_50
'20 Highest' => highest_20
'Slow MA' => ma_slow
'Medium MA' => ma_med
'Fast MA' => ma_fast
'20 Lowest' => lowest_20
'50 Lowest' => lowest_50
'100 Lowest' => lowest_100
'200 Lowest' => lowest_200
'400 Lowest' => lowest_400
float first_entry_price_long = switch first_entry_long_input
'400 Highest' => highest_400
'200 Highest' => highest_200
'100 Highest' => highest_100
'50 Highest' => highest_50
'20 Highest' => highest_20
'Slow MA' => ma_slow
'Medium MA' => ma_med
'Fast MA' => ma_fast
'20 Lowest' => lowest_20
'50 Lowest' => lowest_50
'100 Lowest' => lowest_100
'200 Lowest' => lowest_200
'400 Lowest' => lowest_400
float last_entry_price_long = switch last_entry_long_input
'400 Highest' => highest_400
'200 Highest' => highest_200
'100 Highest' => highest_100
'50 Highest' => highest_50
'20 Highest' => highest_20
'Slow MA' => ma_slow
'Medium MA' => ma_med
'Fast MA' => ma_fast
'20 Lowest' => lowest_20
'50 Lowest' => lowest_50
'100 Lowest' => lowest_100
'200 Lowest' => lowest_200
'400 Lowest' => lowest_400
// Stoploss Buffer
float STOPLOSS_BUFFER_MARGIN_MULT = switch stoploss_type_input
'Tight' => STOPLOSS_BUFFER_MARGIN_TIGHT
'Medium' => STOPLOSS_BUFFER_MARGIN_MEDIUM
'Loose' => STOPLOSS_BUFFER_MARGIN_LOOSE
// GET STOPLOSS PRICE
//-------------------------
stoploss_buffer_margin = get_buffer_margin(14, STOPLOSS_BUFFER_MARGIN_MULT)
long_stoploss_price = last_entry_price_long - stoploss_buffer_margin
short_stoploss_price = last_entry_price_short + stoploss_buffer_margin
// GET TARGET PRICE WHEN AUTO
//--------------------------------
// Get price definitions
avg_entry_price_long = math.avg(first_entry_price_long, last_entry_price_long)
avg_entry_price_short = math.avg(first_entry_price_short, last_entry_price_short)
equity_investment = (equity_investment_per_trade_input / 100) * equity_input
total_investment = equity_investment * leverage_input
exchange_entry_fees = (total_investment * (entry_fee_rate_input/100))
exchange_exit_fees_rrr = exchange_entry_fees * minimum_rrr_input
exchange_exit_fees_roi = exchange_entry_fees * (1 + (minimum_wining_roi_input/100))
exchange_exit_fees = math.max(exchange_exit_fees_rrr,exchange_exit_fees_roi)
total_exchange_fees = exchange_entry_fees + exchange_exit_fees
minimum_profit = equity_investment * (minimum_wining_roi_input / 100)
min_exit_amount = minimum_profit + total_investment + exchange_entry_fees + exchange_exit_fees
// Get exit price when Long
if na(exit_price_win_long)
// Get target by RRR
long_loss_range = (avg_entry_price_long - long_stoploss_price) //+ total_exchange_fees
long_profit_range = long_loss_range * minimum_rrr_input * (1 + MARGIN_OVER_RRR)
long_price_win_rrr = avg_entry_price_long + long_profit_range
// Get target by ROI
qty_invested_long = total_investment / avg_entry_price_long
long_price_win_roi = min_exit_amount / qty_invested_long
// Choose target
exit_price_win_long := math.max(long_price_win_rrr, long_price_win_roi)
// Get exit price when Short
float short_loss_range = na
float short_profit_range = na
float short_price_win_rrr = na
if na(exit_price_win_short)
// GEt target by RRR
short_loss_range := (short_stoploss_price - avg_entry_price_short) //+ total_exchange_fees
short_profit_range := short_loss_range * minimum_rrr_input * (1 + MARGIN_OVER_RRR)
short_price_win_rrr := avg_entry_price_short - short_profit_range
// Get target by ROI
qty_invested_short = total_investment / avg_entry_price_short
short_price_win_roi = min_exit_amount / qty_invested_short
// Choose target
exit_price_win_short := math.min(short_price_win_rrr, short_price_win_roi)
// Validate that levels are correctly selected
//------------------------------------------------------
bool long_levels_input_ok_flg = exit_price_win_long > first_entry_price_long and first_entry_price_long > last_entry_price_long
bool short_levels_input_ok_flg = exit_price_win_short < first_entry_price_short and first_entry_price_short < last_entry_price_short
// Log success or error messages on validation
//-----------------------------------------------
if long_levels_input_ok_flg
array.push(status_log_array, LONG_LEVELS_INPUT_OK_TXT)
else if not(long_levels_input_ok_flg) and (up_trend_flag or side_input == 'Long')
array.push(error_log_array, LONG_LEVELS_INPUT_ERROR_TXT)
if short_levels_input_ok_flg
array.push(status_log_array, SHORT_LEVELS_INPUT_OK_TXT)
else if not(short_levels_input_ok_flg) and (dn_trend_flag or side_input == 'Short')
array.push(error_log_array, SHORT_LEVELS_INPUT_ERROR_TXT)
// Trade side definition
//-------------------------
// Variable initialization
float first_entry_price = na
float last_entry_price = na
float exit_price_win = na
bool detected_side_long = na
bool detected_side_short = na
bool selected_side_long = na
bool selected_side_short = na
string trade_side = na
// Side detection depending on trend direction
long_side_flag = (indicator_trade_side == 'Bullish' or indicator_trade_side == 'Long') //and long_levels_input_ok_flg
short_side_flag = (indicator_trade_side == 'Bearish' or indicator_trade_side == 'Short') //and short_levels_input_ok_flg
detected_side_txt = long_side_flag and short_side_flag ? 'Long & Short' :
long_side_flag ? 'Long' :
short_side_flag ? 'Short' : 'No'
// If no side was detected, inform it.
if not(long_side_flag) and not(short_side_flag)
array.push(error_log_array,NO_SIDE_DETECTED_TXT)
// Automatic vs manual detection
if side_input == 'Auto'
detected_side_long := long_side_flag ? true : false
detected_side_short := short_side_flag ? true : false
// Update log
array.push(status_log_array, detected_side_txt + ' side detected.' )
// Manual side assignment
else
selected_side_long := long_levels_input_ok_flg and side_input == 'Long' ? true : false
selected_side_short := short_levels_input_ok_flg and side_input == 'Short' ? true : false
// Get the correct price
if detected_side_long or selected_side_long
first_entry_price := first_entry_price_long
last_entry_price := last_entry_price_long
exit_price_win := exit_price_win_long
trade_side := 'Long'
else if detected_side_short or selected_side_short
first_entry_price := first_entry_price_short
last_entry_price := last_entry_price_short
exit_price_win := exit_price_win_short
trade_side := 'Short'
// Trade Levels
//---------------------------------------------------------------------
// Prices
avg_entry_price = trade_side == 'Long' ? avg_entry_price_long : avg_entry_price_short
price_change_win = (exit_price_win / avg_entry_price) - 1
//equity_investment = (equity_investment_per_trade_input / 100) * equity_input
// Takerprofit
takeprofit_buffer_margin = get_buffer_margin(14, TAKEPROFIT_BUFFER_MARGIN_INPUT)
exit_price_win := trade_side == 'Long' ? exit_price_win - takeprofit_buffer_margin : exit_price_win + takeprofit_buffer_margin
// Stoploss
stoploss_price = trade_side == 'Long' ? long_stoploss_price : short_stoploss_price
price_change_loss = (stoploss_price / avg_entry_price) - 1
// Entry and exit values
entry_value = equity_investment * leverage_input
entry_qty = entry_value / avg_entry_price
first_entry_qty = entry_qty / 2
last_entry_qty = entry_qty / 2
exit_value_win = entry_qty * exit_price_win
exit_value_loss = entry_qty * stoploss_price
first_entry_value = first_entry_qty * first_entry_price
last_entry_value = last_entry_qty * last_entry_price
// Trade P&L
//---------------------------------------------------------------------
// Initialize variables
float target_profit = na
float potential_loss = na
float pnl_win = na
float pnl_loss = na
float roi_win = na
float roi_loss = na
float rrr = na
float roe_win = na
float roe_loss = na
// Update values if a trade exists
if entry_value > 0 and exit_value_win > 0
// Fees
entry_fees = entry_value * (entry_fee_rate_input / 100)
exit_fees_win = exit_value_win * (exit_fee_rate_input / 100)
exit_fees_loss = exit_value_loss * (exit_fee_rate_input / 100)
// PNL
target_profit := trade_side == 'Long' ? exit_value_win - entry_value : entry_value - exit_value_win
potential_loss := trade_side == 'Long' ? exit_value_loss - entry_value : entry_value - exit_value_loss
pnl_win := target_profit - entry_fees - exit_fees_win
pnl_loss := potential_loss - entry_fees - exit_fees_loss
// ROI
roi_win := pnl_win / equity_investment
roi_loss := pnl_loss / equity_investment
rrr := roi_win / math.abs(roi_loss)
roe_win := pnl_win / equity_input
roe_loss := pnl_loss / equity_input
else
// If no trade exists update values so that they are zero
price_change_win := 0
price_change_loss := 0
// Trade Evaluation
//---------------------------------------------------------------------
minimum_winning_roi_ok_flag = roi_win >= (minimum_wining_roi_input / 100)
maximum_loosing_roi_input_ok_flag = math.abs(roi_loss) <= (maximum_loosing_roi_input / 100)
minimum_rrr_input_ok_flag = rrr >= minimum_rrr_input
trade_economics_ok_flag = minimum_winning_roi_ok_flag and maximum_loosing_roi_input_ok_flag and minimum_rrr_input_ok_flag
//---------------------------------------------------------------------
// Trade Flags
//---------------------------------------------------------------------
bool bullish_trend = na
bool bearish_trend = na
// Messages
txt_trend =
bullish_trend ? 'Bullish' :
bearish_trend ? 'Bearish' : 'None'
txt_economics =
trade_economics_ok_flag ? 'Ok' : 'Not Good'
//**************************************************************************************//
// MARKET OUTLOOK RATING
//**************************************************************************************//
market_outlook_rating = trade_side == 'Long' ? long_entry_rating :
trade_side == 'Short' ? short_entry_rating : 0
market_outlook_rating_OK_flag = market_outlook_rating >= outlook_rating_input
//**************************************************************************************//
// UPDATE DIVERGENCE CONDITION
//**************************************************************************************//
// Initialize variables
float rsi_divrg_min_condition = na
bool rsi_divergence_ok_flag = na
// if trade is long
if trade_side == 'Long' and act_rsi_divergence
// Define minimu condition
rsi_divrg_min_condition := MIN_DVRG_M
// Get divergence flag
rsi_divergence_ok_flag := rsi_dvrg >= MIN_DVRG_M
// If trade is short
else if trade_side == 'Short' and act_rsi_divergence
// Define minimum conditon
rsi_divrg_min_condition := - MIN_DVRG_M
// Get divergence flag
rsi_divergence_ok_flag := rsi_dvrg <= MIN_DVRG_M
// If Divergence and selected trade incorrect the suggest changing sides
if rsi_dvrg > 0 and dn_trend_flag and trade_side == 'Short'
array.push(error_log_array, BULLISH_RSI_DVRG_ERROR_LOG_TXT)
if rsi_dvrg < 0 and up_trend_flag and trade_side == 'Long'
array.push(error_log_array, BEARISH_RSI_DVRG_ERROR_LOG_TXT)
//**************************************************************************************//
// DEFINE ENTRY CONDITIONS & GET TRADE RATING
//**************************************************************************************//
// Initialize variables
bool buyZone_active = 0
bool sellZone_active = 0
float start_buyZone_webh = na
float end_buyZone_webh = na
float start_sellZone_webh = na
float end_sellZone_webh = na
bool confirmation_flag = false
int num_confirmation_rejects = 0
// Initiate variables for rating
int total_entry_conditions = array.size(entry_conditions_array)
int passed_entry_conditions = 0
float trade_rating = 0.0
// Evaluate Entry Conditions if trading has been activated
if barstate.islast and ACTIVATE_ENTRY_CONDITIONS_EVAL
// Check for Entry Conditions
//-------------------------------------
for i = 0 to total_entry_conditions - 1
// Get conditions
condition = array.get(entry_conditions_array, i)
// Update condition values and update array
//-------------------------------------------
if condition.name == 'minimum_wining_roi_input'
condition.min_condition := minimum_wining_roi_input
condition.actual_float := roi_win * 100
condition.pass := minimum_winning_roi_ok_flag
if condition.name == 'maximum_loosing_roi_input'
condition.min_condition := - maximum_loosing_roi_input
condition.actual_float := roi_loss * 100
condition.pass := maximum_loosing_roi_input_ok_flag
if condition.name == 'minimum_rrr_input'
condition.min_condition := minimum_rrr_input
condition.actual_float := rrr
condition.pass := minimum_rrr_input_ok_flag
if condition.name == 'outlook_rating_input'
condition.min_condition := outlook_rating_input
condition.actual_float := market_outlook_rating
condition.pass := market_outlook_rating_OK_flag
if condition.name == 'rsi_divergence'
condition.min_condition := rsi_divrg_min_condition
condition.actual_float := rsi_dvrg
condition.pass := rsi_divergence_ok_flag
// Add a passed entry condition
passed_entry_conditions := condition.pass ? passed_entry_conditions + 1 : passed_entry_conditions
// Update array
array.set(entry_conditions_array,i, condition)
// Get trade rating
//---------------------
trade_rating := (passed_entry_conditions / total_entry_conditions) * 100
trade_rating_ok_flag = trade_rating >= minimum_trade_rating_input ? true : false
trade_rating_txt = toNumberString(trade_rating,1)
// If the reject is confirmed, send orders
//-------------------------------------------------------------------------------
send_entry_orders = false
if trade_rating_ok_flag //and confirmation_flag
send_entry_orders := true
array.push(status_log_array,SEND_ENTRY_ORDERS_TXT)
//Populate the fields that will be used to send the order
if trade_side == 'Long'
buyZone_active := 1
start_buyZone_webh := first_entry_price
end_buyZone_webh := last_entry_price
else if trade_side == 'Short'
sellZone_active := 1
start_sellZone_webh := first_entry_price
end_sellZone_webh := last_entry_price
//**************************************************************************************//
// ALERTS
//**************************************************************************************//
// Alerts when Market Outlook Events occur
if market_outlook_alert != 'None'
// Initial Momentum Alert
if market_outlook_alert == INITIAL_MOMENTUM_ALERT_DETECTED_TXT
if
(long_entry_rating == 1 and long_entry_rating[1] == 0) or
((short_entry_rating == 1 and short_entry_rating[1] == 0))
alert(INITIAL_MOMENTUM_ALERT_DETECTED_TXT, alert.freq_all)
array.push(status_log_array,INITIAL_MOMENTUM_ALERT_PROGRAMED_TXT)
// Trend starting alert
if market_outlook_alert == TREND_STARTS_TXT
if
(long_entry_rating == 2 and long_entry_rating[1] == 1) or
((short_entry_rating == 2 and short_entry_rating[1] == 1))
alert(TREND_STARTING_TXT, alert.freq_all)
array.push(status_log_array,TREND_STARTING_ALERT_PROGRAMED_TXT)
// Entry Zone Alert
if market_outlook_alert == ENTRY_ZONE_STARTS_TXT
if
(long_entry_rating == 3 and long_entry_rating[1] == 2) or
((short_entry_rating == 3 and short_entry_rating[1] == 2))
alert(ENTRY_ZONE_STARTING_TXT, alert.freq_all)
array.push(status_log_array,ENTRY_ZONE_ALERT_PROGRAMMED_TXT)
// First entry signal alert
if market_outlook_alert == FIRST_ENTRY_SIGNAL_TXT
if
(long_entry_rating == 4 and long_entry_rating[1] == 3) or
((short_entry_rating == 4 and short_entry_rating[1] == 3))
alert(FIRST_ENTRY_SIGNAL_TRIGGERED_TXT, alert.freq_all)
array.push(status_log_array,FIRST_ENTRY_SIGNAL_PROGRAMED_TXT)
// Alert when minimum trade rating has been met
if minimum_trade_rating_alert
// Only triggered when the flag is generated
if trade_rating_ok_flag and not(trade_rating_ok_flag[1])
alert(ENTRY_CONDITIONS_ALERT_MESSAGE, alert.freq_all)
array.push(status_log_array,MINIMUM_RATING_ALERT_PROGRAMMED_TXT)
//**************************************************************************************//
// LOGS
//**************************************************************************************//
// Determine number of error logs
number_errors = array.size(error_log_array)
// Create text messages of logs
txt_error_log = get_log_text(error_log_array)
txt_status_log = get_log_text(status_log_array)
//**************************************************************************************//
// DASHBOARD
//**************************************************************************************//
// Trade side color
color_trade_side = trade_side == 'Long' ? color.green : trade_side == 'Short' ? color.red : color.white
// Choose text size
string text_size = switch text_size_input
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Auto' => size.auto
// Create tables
var table dashboard = table.new(tableYposInput + "_" + tableXposInput, columns = TOTAL_COLUMNS, rows = TOTAL_ROWS, frame_color = DASHBOARD_FRAME_COLOR, frame_width = DASHBOARD_FRAME_WIDTH)
// Update table
if barstate.islast and SHOW_TRADE_TABLE
table.set_border_color(dashboard, TABLE_CELL_COLOR)
table.set_border_width(dashboard, 1)
//--------------------------------------------------- MAIN HEADER
row =0
table.cell(dashboard,0,row,DASHBOARD_TITLE, bgcolor = MAIN_HEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = size.large)
table.merge_cells(dashboard, 0, row, TOTAL_COLUMNS - 1, row)
table.cell_set_tooltip(dashboard, 0, row, TABLE_HEADER_TOOLTIP)
//--------------------------------------------------- MARKET OUTLOOK EVENTS
// Add plus minus sign for expanding and contracting
market_outlook_title = show_market_outlook ? MARKET_OUTLOOK_TITLE + ' [-]' : MARKET_OUTLOOK_TITLE + ' [+]'
// Logs Header
row +=1
table.cell(dashboard,0, row, market_outlook_title, bgcolor = TABLE_HEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.merge_cells(dashboard, 0, row, TOTAL_COLUMNS - 1, row)
if show_market_outlook
outlook_log_size = array.size(outlook_log_array)
if outlook_log_size > 0
for i = 0 to outlook_log_size - 1
row +=1
table.cell(dashboard,0,row,toNumberString(i + 1,0), bgcolor = TABLE_CELL_COLOR , text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row,array.get(outlook_log_array,i), bgcolor = EMPTY_CELL_BG_COLOR , text_color = color.black, text_halign = text.align_left, text_size = text_size)
table.merge_cells(dashboard, 1, row, TOTAL_COLUMNS - 2, row)
table.cell(dashboard,TOTAL_COLUMNS - 1,row,array.get(outlook_log_array_times,i), bgcolor = EMPTY_CELL_BG_COLOR , text_color = color.black, text_halign = text.align_left, text_size = text_size)
else
row +=1
table.cell(dashboard,0,row,'1', bgcolor = TABLE_CELL_COLOR , text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row,ENTRY_RATING_0_TXT, bgcolor = EMPTY_CELL_BG_COLOR , text_color = color.black, text_halign = text.align_left, text_size = text_size)
table.merge_cells(dashboard, 1, row, TOTAL_COLUMNS - 1, row)
//--------------------------------------------------- ENTRY CONDITIONS
// Colors
trade_rating_color = color.from_gradient(trade_rating, 0, 100, color.red, color.green)
trade_rating_color := trade_rating_txt == '0' ? TABLE_CELL_COLOR : trade_rating_color
// Add plus minus sign for expanding and contracting
entry_conditions_title = show_entry_conditions ? ENTRY_CONDITIONS_TITLE + ' [-]' : ENTRY_CONDITIONS_TITLE + ' [+]'
// Entry Conditions Header
row +=1
table.cell(dashboard,0, row, entry_conditions_title, bgcolor = TABLE_HEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.merge_cells(dashboard, 0, row, TOTAL_COLUMNS - 1, row)
if show_entry_conditions
// Sub Header
row +=1
table.cell(dashboard,0,row,'Trade\nRating\n(0-100)', bgcolor = TABLE_SUBHEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.cell(dashboard,1,row,'Name', bgcolor = TABLE_SUBHEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.merge_cells(dashboard, 1, row, 2, row)
table.cell(dashboard,3,row,'Minimum\nCondition', bgcolor = TABLE_SUBHEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.cell(dashboard,4,row,'Current\nValue', bgcolor = TABLE_SUBHEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.cell(dashboard,5,row,'Status', bgcolor = TABLE_SUBHEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
// Entry Conditions Entry Contents
//----------------------------------
// Get number of conditions
entry_conditions_array_size = array.size(entry_conditions_array)
// Only if conditions exist
if entry_conditions_array_size > 0
// Loop through all conditions
for i = 0 to entry_conditions_array_size - 1
// Get conditions
condition = array.get(entry_conditions_array,i)
condition_name_txt = condition.description
condition_min_txt = toNumberString(condition.min_condition, 1)
condition_actual_txt = na(condition.actual_float) ? '--' : toNumberString(condition.actual_float, 1)
condition_status_txt = condition.pass ? CONDITION_PASS_TXT : CONDITION_FAIL_TXT
// Set color for status
bg_color_condition_status = condition.pass ? COLOR_CONDITION_PASS : COLOR_CONDITION_FAIL
// Set default color for current value
bg_color_status = EMPTY_CELL_BG_COLOR
// Conditional colors for conditions
if not(condition_actual_txt == '--') and not(condition.actual_float == 0)
if condition.name == 'maximum_loosing_roi_input'
bg_color_status := color.from_gradient(condition.actual_float, condition.min_condition, 0, color.red, color.green)
else if condition.name == 'rsi_divergence'
if rsi_divrg_min_condition > 0
bg_color_status := color.from_gradient(condition.actual_float, 0, condition.min_condition, color.red, color.green)
else if rsi_divrg_min_condition < 0
bg_color_status := color.from_gradient(condition.actual_float, condition.min_condition, 0, color.green, color.red)
else
bg_color_status := color.from_gradient(condition.actual_float, 0, condition.min_condition, color.red, color.green)
row +=1
table.cell(dashboard,0,row,trade_rating_txt, bgcolor = trade_rating_color , text_color = color.black, text_halign = text.align_center, text_size = text_size)
table.cell(dashboard,1,row,condition_name_txt, bgcolor = EMPTY_CELL_BG_COLOR , text_color = color.black, text_halign = text.align_left, text_size = text_size)
table.merge_cells(dashboard, 1, row, 2, row)
table.cell(dashboard,3,row, condition_min_txt, bgcolor = EMPTY_CELL_BG_COLOR , text_color = color.black, text_halign = text.align_center, text_size = text_size)
table.cell(dashboard,4,row, condition_actual_txt, bgcolor = bg_color_status , text_color = color.black, text_halign = text.align_center, text_size = text_size)
table.cell(dashboard,5,row, condition_status_txt, bgcolor = bg_color_condition_status , text_color = color.black, text_halign = text.align_center, text_size = text_size)
// Merge the rows for the Trade Rating
table.merge_cells(dashboard, 0, row - entry_conditions_array_size + 1, 0, row)
//--------------------------------------------------- ESTIMATED P&L
// Conditioned colors
color_win_roi_flag = minimum_winning_roi_ok_flag ? color.green : color.red
color_loss_roi_flag = maximum_loosing_roi_input_ok_flag ? color.green : color.red
color_rrr_flag = minimum_rrr_input_ok_flag ? color.green : color.red
// Adjust if values are zero
color_win_roi_flag := na(roi_win) ? EMPTY_CELL_BG_COLOR : color_win_roi_flag
color_loss_roi_flag := na(roi_loss) ? EMPTY_CELL_BG_COLOR : color_loss_roi_flag
color_rrr_flag := na(rrr) ? EMPTY_CELL_BG_COLOR : color_rrr_flag
// Add plus minus sign for expanding and contracting
estimated_pnl_title = show_estimated_pnl_input ? ESTIMATED_PNL_TITLE + ' [-]' : ESTIMATED_PNL_TITLE + ' [+]'
// Trade Results Header
row +=1
table.cell(dashboard, 0, row, estimated_pnl_title, bgcolor = TABLE_HEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.merge_cells(dashboard, 0, row, TOTAL_COLUMNS - 1, row)
if show_estimated_pnl_input
// Sub Header: Investment Data
row +=1
table.cell(dashboard,0,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row, 'Active\nSide', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
table.cell(dashboard,2,row, 'Total\nEquity', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
table.cell(dashboard,3,row, 'Equity\nInvestment', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
table.cell(dashboard,4,row, 'Max Investment\nPer Trade', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
table.cell(dashboard,5,row, 'Leverage', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
// Equity Investment
row +=1
table.cell(dashboard,0,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row, trade_side, bgcolor = color_trade_side, text_color = color.black, text_size = text_size)
table.cell(dashboard,2,row, toCurrencyString(equity_input,1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,3,row, toCurrencyString(equity_investment,1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,4,row, toPercentageString(equity_investment_per_trade_input / 100,1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,5,row, toFactorString(leverage_input, 1) , bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
// Sub Header: P&L
row +=1
table.cell(dashboard,0,row,"", bgcolor = TABLE_CELL_COLOR, text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row,'Win', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
table.cell(dashboard,2,row,'Loss', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
table.cell(dashboard,3,row,'RRR', bgcolor = TABLE_SUBHEADER_COLOR, text_color = color.white, text_size = text_size)
table.cell(dashboard,4,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,5,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
// Price Change
row +=1
table.cell(dashboard,0,row,"Price Change", bgcolor = TABLE_CELL_COLOR, text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row,toPercentageString(price_change_win, 1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,2,row,toPercentageString(price_change_loss, 1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,3,row,'', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,4,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,5,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
// P&L
row +=1
table.cell(dashboard,0,row,"P&L", bgcolor = TABLE_CELL_COLOR, text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row, toCurrencyString(na(pnl_win)?0:pnl_win,1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,2,row, toCurrencyString(na(pnl_loss)?0:pnl_loss,1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,3,row,'', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,4,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,5,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
// ROI
row +=1
table.cell(dashboard,0,row,"ROI", bgcolor = TABLE_CELL_COLOR, text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row, toPercentageString(na(roi_win)?0:roi_win, 1), bgcolor = color_win_roi_flag, text_color = color.black, text_size = text_size)
table.cell(dashboard,2,row, toPercentageString(na(roi_loss)?0:roi_loss, 1), bgcolor = color_loss_roi_flag, text_color = color.black, text_size = text_size)
table.cell(dashboard,3,row, toFactorString(na(rrr)?0:rrr, 1), bgcolor = color_rrr_flag, text_color = color.black, text_size = text_size)
table.cell(dashboard,4,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,5,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
// ROI
row +=1
table.cell(dashboard,0,row,"ROE", bgcolor = TABLE_CELL_COLOR, text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row, toPercentageString(na(roe_win)?0:roe_win, 1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,2,row, toPercentageString(na(roe_loss)?0:roe_loss, 1), bgcolor = EMPTY_CELL_BG_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,3,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,4,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
table.cell(dashboard,5,row, '', bgcolor = TABLE_CELL_COLOR, text_color = color.black, text_size = text_size)
//--------------------------------------------------- LOGS
// Add plus minus sign for expanding and contracting
operation_logs_title = show_logs ? OPERATION_LOGS_TITLE + ' [-]' : OPERATION_LOGS_TITLE + ' [+]'
// Logs Header
row +=1
table.cell(dashboard,0, row, operation_logs_title, bgcolor = TABLE_HEADER_COLOR , text_color = color.white, text_halign = text.align_center, text_size = text_size)
table.merge_cells(dashboard, 0, row, TOTAL_COLUMNS - 1, row)
if show_logs
row +=1
table.cell(dashboard,0,row,'Status', bgcolor = TABLE_CELL_COLOR , text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row,txt_status_log, bgcolor = EMPTY_CELL_BG_COLOR , text_color = color.black, text_halign = text.align_left, text_size = text_size)
table.merge_cells(dashboard, 1, row, TOTAL_COLUMNS - 1, row)
if show_logs or number_errors > 0
row +=1
table.cell(dashboard,0,row,'Errors', bgcolor = TABLE_CELL_COLOR , text_color = color.white, text_halign = text.align_right, text_size = text_size)
table.cell(dashboard,1,row,txt_error_log, bgcolor = EMPTY_CELL_BG_COLOR , text_color = color.red, text_halign = text.align_left, text_size = text_size)
table.merge_cells(dashboard, 1, row, TOTAL_COLUMNS - 1, row)
//**************************************************************************************//
// TRADE BOX
//**************************************************************************************//
// Initialize variables
int tradeBox_left_margin = 0
int tradeBox_right_margin = 0
// Define Trade Box Margins
tradeBox_left_margin := execution_mode_input == AUTO_TRADE_NAME ? last_bar_index : last_bar_index + SEPARATION_FROM_LEVELS_INPUT
tradeBox_right_margin := execution_mode_input == AUTO_TRADE_NAME ? last_bar_index + TRADEBOX_WIDTH_INPUT : last_bar_index + SEPARATION_FROM_LEVELS_INPUT + TRADEBOX_WIDTH_INPUT
//Define Trade box Up
trade_box_up_x1 = tradeBox_left_margin
trade_box_up_y1 = trade_side == 'Long' ? exit_price_win : stoploss_price
trade_box_up_x2 = tradeBox_right_margin
trade_box_up_y2 = avg_entry_price
trade_box_up_text = ''
//Define Trade box Dn
trade_box_dn_x1 = tradeBox_left_margin
trade_box_dn_y1 = avg_entry_price
trade_box_dn_x2 = tradeBox_right_margin
trade_box_dn_y2 = trade_side == 'Long' ? stoploss_price : exit_price_win
trade_box_dn_text = ''
//Draw TradeBox
tradeBox_color_up = trade_side == 'Long' ? TRADEBOX_PROFIT_COLOR : TRADEBOX_LOSS_COLOR
tradeBox_color_dn = trade_side == 'Long' ? TRADEBOX_LOSS_COLOR : TRADEBOX_PROFIT_COLOR
var trade_box_up = box.new(1, 1, 1, 1, xloc = xloc.bar_index, border_color = COLOR_TRANSP, bgcolor = tradeBox_color_up,
text = '', text_halign = TRADEBOX_TEXT_HALIGN, text_valign = TRADEBOX_TEXT_VALIGN, text_color = TRADEBOX_POSITION_TEXT_COLOR, text_size = TRADEBOX_TEXT_SIZE)
var trade_box_dn = box.new(1, 1, 1, 1, xloc = xloc.bar_index, border_color = COLOR_TRANSP, bgcolor = tradeBox_color_dn,
text = '', text_halign = TRADEBOX_TEXT_HALIGN, text_valign = TRADEBOX_TEXT_VALIGN, text_color = TRADEBOX_POSITION_TEXT_COLOR, text_size = TRADEBOX_TEXT_SIZE)
var first_entry_line = line.new(x1=1, y1=1, x2=1, y2=1, color=FIRST_ENTRY_LINE_COLOR, width=1, xloc=xloc.bar_index, style = line.style_dashed)
var avg_entry_line = line.new(x1=1, y1=1, x2=1, y2=1, color=AVG_ENTRY_LINE_COLOR, width=1, xloc=xloc.bar_index)
var last_entry_line = line.new(x1=1, y1=1, x2=1, y2=1, color=LAST_ENTRY_LINE_COLOR, width=1, xloc=xloc.bar_index, style = line.style_dashed)
var exit_line = line.new(x1=1, y1=1, x2=1, y2=1, color=EXIT_LINE_COLOR, width=1, xloc=xloc.bar_index)
var stoploss_line = line.new(x1=1, y1=1, x2=1, y2=1, color=STOPLOSS_LINE_COLOR, width=1, xloc=xloc.bar_index)
if barstate.islast and tradeBox_left_margin > 0 and draw_trade_box and (trade_side == 'Long' or trade_side == 'Short')
// Update resistance box Up
box.set_lefttop(trade_box_up, trade_box_up_x1, trade_box_up_y1)
box.set_rightbottom(trade_box_up, trade_box_up_x2, trade_box_up_y2)
// Update resistance box Dn
box.set_lefttop(trade_box_dn, trade_box_dn_x1, trade_box_dn_y1)
box.set_rightbottom(trade_box_dn, trade_box_dn_x2, trade_box_dn_y2)
// Update trade box text
box.set_text(trade_box_up, trade_box_up_text)
box.set_text(trade_box_dn, trade_box_dn_text)
// Update Text Color
box.set_text_color(trade_box_up, TRADEBOX_POSITION_TEXT_COLOR)
box.set_text_color(trade_box_dn, TRADEBOX_POSITION_TEXT_COLOR)
// Update Background color
box.set_bgcolor(trade_box_up, tradeBox_color_up)
box.set_bgcolor(trade_box_dn, tradeBox_color_dn)
// Update lines
line.set_xy1(first_entry_line, tradeBox_left_margin , first_entry_price)
line.set_xy2(first_entry_line, tradeBox_right_margin , first_entry_price)
line.set_xy1(avg_entry_line, tradeBox_left_margin , avg_entry_price)
line.set_xy2(avg_entry_line, tradeBox_right_margin , avg_entry_price)
line.set_xy1(last_entry_line, tradeBox_left_margin , last_entry_price)
line.set_xy2(last_entry_line, tradeBox_right_margin , last_entry_price)
line.set_xy1(exit_line, tradeBox_left_margin , exit_price_win)
line.set_xy2(exit_line, tradeBox_right_margin , exit_price_win)
line.set_xy1(stoploss_line, tradeBox_left_margin , stoploss_price)
line.set_xy2(stoploss_line, tradeBox_right_margin , stoploss_price)
//**************************************************************************************//
// TRADE BOX LABELS
//**************************************************************************************//
// Positions
trd_summary_left_margin = tradeBox_left_margin + ((tradeBox_right_margin - tradeBox_left_margin) / 2)
trd_summary_up_top_margin = trade_box_up_y1 - ((trade_box_up_y1 - trade_box_up_y2) / 4)
trd_summary_dn_top_margin = trade_box_dn_y2 - (math.abs(stoploss_buffer_margin) * 2)
// Build required texts
entry_action_txt = trade_side == 'Long' ? 'Buy ' : 'Sell '
exit_action_txt = trade_side == 'Long' ? 'Sell ' : 'Buy '
// Text labels
entry_qty_txt = toNumberString(entry_qty, DECIMALS_QTY_LABELS)
first_entry_qty_txt = toNumberString(first_entry_qty,DECIMALS_QTY_LABELS)
last_entry_qty_txt = toNumberString(last_entry_qty, DECIMALS_QTY_LABELS)
first_entry_price_txt = toCurrencyString(first_entry_price,2)
last_entry_price_text = toCurrencyString(last_entry_price,2)
first_entry_value_txt = toCurrencyString(first_entry_value,2)
last_entry_value_txt = toCurrencyString(last_entry_value,2)
exit_price_win_txt = toCurrencyString(exit_price_win,2)
exit_value_win_txt = toCurrencyString(exit_value_win,2)
stoploss_price_txt = toCurrencyString(stoploss_price,2)
exit_value_loss_txt = toCurrencyString(exit_value_loss,2)
// Price definitions
price_labels_left_margin = tradeBox_right_margin + SEPARATION_FROM_LEVELS_INPUT
first_entry_price_label_txt = '1st Entry: ' + entry_action_txt + first_entry_qty_txt + ' @ ' + first_entry_price_txt + ' = ' + first_entry_value_txt
last_entry_price_label_txt = '2nd Entry: ' + entry_action_txt + last_entry_qty_txt + ' @ ' + last_entry_price_text + ' = ' + last_entry_value_txt
exit_price_label_txt = 'Target: ' + exit_action_txt + entry_qty_txt + ' @ ' + exit_price_win_txt + ' = ' + exit_value_win_txt
stoploss_label_txt = 'Stoploss: '+ exit_action_txt + entry_qty_txt + ' @ ' + stoploss_price_txt + ' = ' + exit_value_loss_txt
// Trade summary
win_txt = 'Win: \nPrice ▲: ' + str.tostring(price_change_win,"###.#%") + '\n'
roi_win_txt = 'ROI: ' + str.tostring(roi_win, '##.#%') + '\n'
loss_txt = 'Loss: \nPrice ▲: ' + str.tostring(price_change_loss,"###.#%") + '\n'
roi_loss_txt = 'ROI: ' + str.tostring(roi_loss, '##.#%') + '\n'
rrr_txt = 'RRR: ' + str.tostring(rrr,'###.#') + 'x' + '\n'
leverage_txt = 'Leverage: ' + str.tostring(leverage_input,'###.#') + 'x'
trd_summary_txt = win_txt + roi_win_txt + '\n' + loss_txt + roi_loss_txt + '\n' + rrr_txt + '\n' + leverage_txt
// Draw Labels
var first_entry_price_label = label.new(1, 1, '', color = PRICE_LABEL_COLOR, textcolor = PRICE_LABEL_TEXTCOLOR, style = PRICE_LABEL_STYLE)
var last_entry_price_label = label.new(1, 1, '', color = PRICE_LABEL_COLOR, textcolor = PRICE_LABEL_TEXTCOLOR, style = PRICE_LABEL_STYLE)
var exit_price_label = label.new(1, 1, '', color = PRICE_LABEL_COLOR, textcolor = PRICE_LABEL_TEXTCOLOR, style = PRICE_LABEL_STYLE)
var stoploss_price_label = label.new(1, 1, '', color = PRICE_LABEL_COLOR, textcolor = PRICE_LABEL_TEXTCOLOR, style = PRICE_LABEL_STYLE)
// Draw price labels
if barstate.islast and show_price_labels and draw_trade_box and (trade_side == 'Long' or trade_side == 'Short')
label.set_xy(first_entry_price_label,x = price_labels_left_margin , y = first_entry_price)
label.set_xy(last_entry_price_label,x = price_labels_left_margin , y = last_entry_price)
label.set_xy(exit_price_label,x = price_labels_left_margin , y = exit_price_win)
label.set_xy(stoploss_price_label,x = price_labels_left_margin , y = stoploss_price)
label.set_text(first_entry_price_label,first_entry_price_label_txt)
label.set_text(last_entry_price_label,last_entry_price_label_txt)
label.set_text(exit_price_label,exit_price_label_txt)
label.set_text(stoploss_price_label,stoploss_label_txt)
if barstate.islast and draw_trade_box and (trade_side == 'Long' or trade_side == 'Short')
// Trade summary to tradeBox
trade_box_side_for_summary = trade_side == 'Long' ? trade_box_up : trade_box_dn
box.set_text(trade_box_side_for_summary, trd_summary_txt)
|
K's Reversal Indicator III | https://www.tradingview.com/script/8sEyrciq-K-s-Reversal-Indicator-III/ | Sofien-Kaabar | https://www.tradingview.com/u/Sofien-Kaabar/ | 120 | 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/
// © Sofien-Kaabar
//@version=5
indicator("K's Reversal Indicator III", overlay = true)
// Defining the variables
price_return = close - close[1]
rsi = ta.rsi(close, 14)
// Calculating the correlation of price returns
correlation_measure = ta.correlation(price_return, price_return[14], 14)
// Generating signals
bullish_signal = correlation_measure > 0.60 and rsi < 40
bearish_signal = correlation_measure > 0.60 and rsi > 60
// Plotting signals
plotshape(bullish_signal, style = shape.triangleup, color = color.blue, location = location.belowbar, size = size.small)
plotshape(bearish_signal, style = shape.triangledown, color = color.orange, location = location.abovebar, size = size.small) |
2Rsi buy & sell & candlesticks patterns in rsi[Trader's Journal] | https://www.tradingview.com/script/dLAssm8B-2Rsi-buy-sell-candlesticks-patterns-in-rsi-Trader-s-Journal/ | SESE04 | https://www.tradingview.com/u/SESE04/ | 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/
// © TRADERS JOURNAL
//@version=5
indicator("2Rsi buy & sell & candlesticks patterns in rsi[Trader's Journal]", "RSI Buy Sell & Candlesticks patterns [Trader's Journal]", overlay = true, max_labels_count = 500
, max_lines_count = 500
, max_boxes_count = 500
, max_bars_back = 500)
len = input.int(14, minval=1, title='Length')
src = close
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
sellThreshold = 69
buyThreshold = 31
plotshape(series=ta.crossunder(rsi, sellThreshold) ? high : na, color=color.red, style=shape.labeldown, title="Sell", text="Sell", location=location.abovebar)
plotshape(series=ta.crossover(rsi, buyThreshold) ? low : na, color=color.blue, style=shape.labelup, title="Buy", text="Buy", location=location.belowbar, textcolor=color.yellow)
//Candlesticks Patterns
rsi_length = input.int(14, minval=1, title="RSI Length")
rsi_upper = 69
rsi_lower = 31
rsi_val = ta.rsi(close, rsi_length)
rsi_length1 = 14
rsi_upper1 = 69
rsi_lower1 = 31
rsi_val1 = ta.rsi(close, rsi_length1)
// Fonctions pour détecter les motifs des chandeliers
is_bullish_engulfing() =>
close[1] < open[1] and open < close and close > open[1] and open < close[1]
is_bearish_engulfing() =>
close[1] > open[1] and open > close and close < open[1] and open > close[1]
is_morning_star() =>
close[2] < open[2] and close[1] < close[2] and close > open
is_evening_star() =>
close[2] > open[2] and close[1] > close[2] and close < open
is_bullish_harami() =>
close[1] < open[1] and close > open and open > close[1] and close < open[1]
is_bearish_harami() =>
close[1] > open[1] and close < open and open < close[1] and close > open[1]
is_hammer_or_hanging_man() =>
(high - (open > close ? open : close)) <= 0.25 * (high - low) and open - low >= 0.66 * (high - low)
is_shooting_star_or_inverted_hammer() =>
open - high <= 0.25 * (high - low) and high - close >= 0.66 * (high - low)
is_doji() =>
math.abs(close - open) < 0.01 * (high - low)
is_bullish_piercing() =>
close[1] < open[1] and open < close[1] and close > (open[1] + close[1]) / 2 and close < open[1]
is_dark_cloud_cover() =>
close[1] > open[1] and open > close[1] and close < (open[1] + close[1]) / 2 and close > open[1]
// Affichage des motifs sur le graphique en fonction du RSI
plotshape(series=rsi_val > rsi_upper and is_bearish_engulfing() ? high : na, color=color.red, style=shape.triangledown, title="Avalement baissier", text="Avalement baissier", location=location.abovebar)
plotshape(series=rsi_val < rsi_lower and is_bullish_engulfing() ? low : na, color=color.blue, style=shape.triangleup, title="Avalement haussier", text="Avalement haussier", location=location.belowbar)
plotshape(series=rsi_val > rsi_upper and is_evening_star() ? high : na, color=color.red, style=shape.triangledown, title="Etoile du soir", text="Etoile du soir", location=location.abovebar)
plotshape(series=rsi_val < rsi_lower and is_morning_star() ? low : na, color=color.blue, style=shape.triangleup, title="Etoile du matin", text="Etoile du matin", location=location.belowbar)
plotshape(series=rsi_val > rsi_upper and is_bearish_harami() ? high : na, color=color.red, style=shape.triangledown, title="Harami baissier", text="Harami baissier", location=location.abovebar)
plotshape(series=rsi_val < rsi_lower and is_bullish_harami() ? low : na, color=color.blue, style=shape.triangleup, title="Harami haussier", text="Harami haussier", location=location.belowbar)
plotshape(series=rsi_val > rsi_upper and is_hammer_or_hanging_man() ? high : na, color=color.red, style=shape.triangledown, title="Pendu/Marteau", text="Pendu/Marteau", location=location.abovebar)
plotshape(series=rsi_val < rsi_lower and is_shooting_star_or_inverted_hammer() ? low : na, color=color.blue, style=shape.triangleup, title="Etoile filante/Marteau inversé", text="Etoile filante/Marteau inversé", location=location.belowbar)
plotshape(series=rsi_val > rsi_upper and is_doji() ? high : na, color=color.red, style=shape.triangledown, title="Doji", text="Doji", location=location.abovebar)
plotshape(series=rsi_val < rsi_lower and is_bullish_piercing() ? low : na, color=color.blue, style=shape.triangleup, title="Pénétrante haussière", text="Pénétrante haussière", location=location.belowbar)
plotshape(series=rsi_val > rsi_upper and is_dark_cloud_cover() ? high : na, color=color.red, style=shape.triangledown, title="Couverture nuage noir", text="Couverture nuage noir", location=location.abovebar)
|
Position Cost Distribution | https://www.tradingview.com/script/25py1UVB-Position-Cost-Distribution/ | algotraderdev | https://www.tradingview.com/u/algotraderdev/ | 280 | 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/
// © algotraderdev
// @version=5
indicator('Position Cost Distribution', overlay = true, max_lines_count = 500, max_bars_back = 500)
import algotraderdev/contrast/1
//#region Inputs
int LOOKBACK = input.int(1000, 'Number of Most Recent Bars to Process', maxval = 20000, minval = 500, step = 250)
int CHART_X_OFFSET = input.int(100, 'Chart Offset', step = 10)
int LABEL_X_OFFSET = CHART_X_OFFSET + 4
int CHART_MAX_WIDTH = input.int(80, 'Max Width', maxval = 500, minval = 10, step = 10)
int NUM_BUCKETS = input.int(400, 'Number of Buckets', maxval = 500, minval = 50, step = 50)
color PROFITABLE_COLOR = input.color(#5d606b, 'Profitable Positions')
color UNPROFITABLE_COLOR = input.color(#e91e63, 'Unprofitable Positions')
color CURRENT_PRICE_COLOR = input.color(color.yellow, 'Current Price')
color AVG_PRICE_COLOR = input.color(color.blue, 'Average Price')
color STATS_COLOR = input.color(#434651, 'Statistics')
//#endregion
//#region Candle
// @type The candle object holds the required information for each candle in the chart.
// @field index The `bar_index` of the candle.
// @field hi The `high` of the candle.
// @field lo The `low` of the candle.
// @field vol The `volume` of the candle.
// @field totalShares The number of total shares issued at the candle.
type Candle
int index
float hi
float lo
float vol
float totalShares
//#endregion
//#region PCD
// @type The PCD (Position Cost Distribution) type is responsible for calculating and visualizing the distribution of
// shares at various price points.
// @field candles The stored candles based on which the distribution will be calculated.
// @field minPrice The minimum price for all the stored candles.
// @field maxPrice The maximum price for all the stored candles.
// @field step The price difference between adjacent price buckets.
// @field lines The lines that are used to plot the distributions in the chart.
// @field currentPriceLabel The label that highlights the current price.
// @field avgPriceLabel The label that highlights the average price for all shares.
// @field statsLabel The label that shows statistics for the PCD.
type PCD
Candle[] candles
float minPrice
float maxPrice
float step
line[] lines
label currentPriceLabel
label avgPriceLabel
label statsLabel
// @function Creates a new label for highlighting certain price points in the PCD.
// @param bg The background color for the label.
// @returns The created label.
newPriceLabel(color bg) =>
label.new(
0, 0, '',
style = label.style_label_left,
color = bg,
textcolor = bg.contrast(0.6),
size = size.small)
// @function Instantiates a new PCD.
// @returns The created PCD instance.
newPCD() =>
line[] lns = array.new<line>()
for i = 1 to NUM_BUCKETS
lns.push(line.new(0, 0, 0, 0))
PCD.new(
candles = array.new<Candle>(),
lines = lns,
currentPriceLabel = newPriceLabel(CURRENT_PRICE_COLOR),
avgPriceLabel = newPriceLabel(AVG_PRICE_COLOR),
statsLabel = label.new(
0, 0, '',
style = label.style_label_up,
size = size.normal,
textalign = text.align_left,
color = STATS_COLOR,
textcolor = STATS_COLOR.contrast()))
// @function Stores the current candle for it to be analyzed later.
// Note that this method is expected to be called on every tick. The actual calculation of PCD is deferred to only when
// the last bar in the chart is reached, as an optimization.
method storeCandle(PCD this) =>
float totalShares = request.financial(syminfo.tickerid, 'TOTAL_SHARES_OUTSTANDING', 'FQ', ignore_invalid_symbol = true)
[index, hi, lo, vol] = request.security(syminfo.tickerid, 'D', [bar_index, high, low, volume], ignore_invalid_symbol = true)
if not (na(totalShares) or na(hi) or na(lo) or na(vol))
bool modified = if this.candles.size()
Candle c = this.candles.last()
if c.index == index
c.hi := hi
c.lo := lo
c.vol := vol
true
if not modified
Candle c = Candle.new(index, hi, lo, vol, totalShares)
this.candles.push(c)
this.minPrice := na(this.minPrice) ? lo : math.min(this.minPrice, lo)
this.maxPrice := na(this.maxPrice) ? hi : math.max(this.maxPrice, hi)
this.step := (this.maxPrice - this.minPrice) / NUM_BUCKETS
// @function Gets an existing line at the given index if it exists. If the line doesn't exist, then create a new line,
// insert it into the lines array, and return it instead.
// @param index The index for the line.
// @returns The line instance.
method getOrCreateLine(PCD this, int index) =>
if index >= this.lines.size()
line ln = line.new(0, 0, 0, 0)
this.lines.push(ln)
ln
else
this.lines.get(index)
// @function Gets the bucket index for the given price.
// @param price The price to get index for.
// @returns The bucket index for the price.
method getBucketIndex(PCD this, float price) =>
math.min(math.floor((price - this.minPrice) / this.step), NUM_BUCKETS - 1)
// @function Gets the bucketed price for the given index
// @param index The bucket index.
// @returns The average price for the bucket.
method getBucketedPrice(PCD this, int index) =>
(index + 0.5) * this.step + this.minPrice
// @function Calculates the distribution and visualizes it on the chart.
method update(PCD this) =>
// Create distribution buckets for the price range.
float[] dist = array.new_float(NUM_BUCKETS, 0)
bool isFirstCandle = this.candles.size() == 1
// For each candle, uniformly divide it into multiple price points based on the step.
// TODO: consider using triangular distribution or normal distribution in future versions.
for candle in this.candles
float turnover = candle.vol / candle.totalShares
// Calculate the start and end index of the buckets to fill the shares.
int start = this.getBucketIndex(candle.lo)
int end = this.getBucketIndex(candle.hi)
int buckets = end - start + 1
if isFirstCandle
// Distribute all shares to the initial buckets.
float shares = candle.totalShares / buckets
for i = start to end
dist.set(i, shares)
else
// For each existing bucket, reduce the number of shares by the turnover rate.
for i = 0 to NUM_BUCKETS - 1
dist.set(i, dist.get(i) * (1 - turnover))
// Distribute the volume to the buckets in the candle range.
float shares = candle.vol / buckets
for i = start to end
dist.set(i, dist.get(i) + shares)
// Draw the distribution as lines on the chart.
float lowestDisplayedPrice = na
float highestDisplayedPrice = na
float maxShares = dist.max()
for [i, shares] in dist
float price = (i + 0.5) * this.step + this.minPrice
int width = math.round(shares / maxShares * CHART_MAX_WIDTH)
if width != 0
if na(lowestDisplayedPrice)
lowestDisplayedPrice := price
highestDisplayedPrice := price
int x1 = bar_index + CHART_X_OFFSET
int x2 = x1 - width
color c = price < close ? PROFITABLE_COLOR : UNPROFITABLE_COLOR
line ln = this.getOrCreateLine(i)
ln.set_xy1(x1, price)
ln.set_xy2(x2, price)
ln.set_color(c)
// Calculate and highlight some interesting stats.
// * The current price.
// * The average price for all positions.
// * The profit ratio.
// * The 90% range.
// * The 70% range.
// Calculate the cumulative distribution.
float[] cumdist = dist.copy()
for i = 1 to cumdist.size() - 1
cumdist.set(i, cumdist.get(i - 1) + cumdist.get(i))
// Highlight the current price.
int closeIndex = this.getBucketIndex(close)
this.lines.get(closeIndex).set_color(CURRENT_PRICE_COLOR)
this.currentPriceLabel.set_text(str.format('{0,number,#.##} Current', close))
this.currentPriceLabel.set_xy(bar_index + LABEL_X_OFFSET, close)
// Calculate the profit ratio.
float totalShares = cumdist.last()
int profitIndex = math.min(closeIndex + 1, NUM_BUCKETS - 1)
float profitRatio = cumdist.get(profitIndex) / totalShares
// Calculate the average price for all positions.
float avg = 0
for [i, shares] in dist
float price = this.getBucketedPrice(i)
avg += price * (shares / totalShares)
this.avgPriceLabel.set_text(str.format('{0,number,#.##} Average', avg))
this.avgPriceLabel.set_xy(bar_index + LABEL_X_OFFSET, avg)
int avgIndex = this.getBucketIndex(avg)
this.lines.get(avgIndex).set_color(AVG_PRICE_COLOR)
// Calculate the position ranges.
float ninetyPctLow = this.getBucketedPrice(cumdist.binary_search_leftmost(totalShares * 0.05))
float ninetyPctHigh = this.getBucketedPrice(cumdist.binary_search_leftmost(totalShares * 0.95))
float seventyPctLow = this.getBucketedPrice(cumdist.binary_search_leftmost(totalShares * 0.15))
float seventyPctHigh = this.getBucketedPrice(cumdist.binary_search_leftmost(totalShares * 0.85))
float rangeOverlap = (seventyPctHigh- seventyPctLow) / (ninetyPctHigh- ninetyPctLow)
// Render the stats label.
this.statsLabel.set_text(str.format(
'Profit Ratio:\t{0,number,#.##}%\n' +
'90% Cost Range:\t{1,number,#.##}-{2,number,#.##}\n' +
'70% Cost Range:\t{3,number,#.##}-{4,number,#.##}\n' +
'Range Overlap:\t{5,number,#.##}%',
profitRatio * 100,
ninetyPctLow, ninetyPctHigh,
seventyPctLow, seventyPctHigh,
rangeOverlap * 100))
float displayedRange = highestDisplayedPrice - lowestDisplayedPrice
if highestDisplayedPrice - close > close - lowestDisplayedPrice
this.statsLabel.set_y(lowestDisplayedPrice - displayedRange * 0.03)
this.statsLabel.set_style(label.style_label_up)
else
this.statsLabel.set_y(highestDisplayedPrice + displayedRange * 0.03)
this.statsLabel.set_style(label.style_label_down)
this.statsLabel.set_x(bar_index + CHART_X_OFFSET)
//#endregion
//#region main
if syminfo.type == 'stock' and timeframe.in_seconds(timeframe.period) <= timeframe.in_seconds('D')
var PCD pcd = newPCD()
if last_bar_index - bar_index < LOOKBACK
pcd.storeCandle()
if barstate.islast
pcd.update()
//#endregion |
Vwap MTF | https://www.tradingview.com/script/zHRJrovA-Vwap-MTF/ | SESE04 | https://www.tradingview.com/u/SESE04/ | 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/
// © SESE04 TRADERS JOURNAL
//@version=5
indicator('Vwap MTF', 'vwap Mtf', overlay=true, max_bars_back=501)
// Fonction pour calculer le VWAP
vwapSource(src, length) =>
sum = 0.0
sumVolume = 0.0
for i = 0 to length - 1
sum := sum + request.security(syminfo.tickerid, src, close[i]) * volume[i]
sumVolume := sumVolume + volume[i]
vwap = sum / sumVolume
// Longueur de la période VWAP
length = 30
// Calcul du VWAP pour chaque unité de temps
vwap15 = request.security(syminfo.tickerid, "15", close)
vwap60 = request.security(syminfo.tickerid, "60", close)
vwap240 = request.security(syminfo.tickerid, "240", close)
vwapDaily = request.security(syminfo.tickerid, "D", close)
// Moyenne des VWAPs
vwapAvg = (vwap15 + vwap60 + vwap240 + vwapDaily) / 4
// Couleur en fonction de la direction du VWAP
vwap_color = vwapAvg > vwapAvg[1] ? #3b08f3 : color.rgb(247, 9, 9)
// Tracé du VWAP
plot(vwapAvg, color=vwap_color, linewidth=2, transp=0)
|
Price Variation Percent (PVP) | https://www.tradingview.com/script/yRdlrXNy/ | Jompatan | https://www.tradingview.com/u/Jompatan/ | 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/
// © Jompatan
//@version=4
study("Price Variation Percent (PVP)")
length = input(1,"Length (bars)")
source = input(close, "Source")
apper_band = input(1.0, "Apper Band (% variation)")
lower_band = input(-1.0, "Lower Band (% variation)")
crossover = input(true, "Show Crossover")
crossunder = input(true, "Show Crossunder")
//======================================================
pvp= (source - source[length]) / source[length] * 100
cross_over = crossover(pvp, apper_band)
cross_under = crossunder(pvp, lower_band)
p1= plot(pvp, color=color.white)
p0= plot(0, color= color.new(color.white, 100))
h0 = hline(0, linestyle = hline.style_dotted, color= color.new(color.white, 80))
h1 = hline(apper_band, color= color.new(color.white, 60))
h2 = hline(lower_band, color= color.new(color.white, 60))
fill(h1, h2)
fill(p1, p0, color= pvp > 0 ? color.lime : color.red, transp=0)
//======================================================
plotshape(crossover and cross_over ? pvp+1 : na, style=shape.triangledown, location= location.absolute, size=size.tiny, color=color.lime)
plotshape(crossunder and cross_under ? pvp-1 : na, style=shape.triangleup, location= location.absolute, size=size.tiny, color=color.fuchsia)
|
TradersCheckList | https://www.tradingview.com/script/82xDyKe9-TradersCheckList/ | goldmaxxx | https://www.tradingview.com/u/goldmaxxx/ | 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/
// © goldmaxxx
//simple table - customizable. Can assist with identifying trends and fitting criteria depending on strategy. Manual
//@version=5
indicator("Check List", shorttitle="Check List", overlay=true)
// Customizable Inputs
title = input.string("Check List", "Title")
currencyPair = syminfo.ticker
trend = input.string("Ranging", "Trend Direction", options=["Trending Higher", "Trending Lower", "Ranging"] )
trendConfirmation = input.string("Yes", "Trend Confirmed?", options=["Yes", "No"])
// Additional Rows
showRow1 = input.bool(false, "Show Row 1?")
row1Text = input.string("-----------", "Row 1")
row1Confirmation = input.string("No", "Row 1 Confirmed?", options=["Yes", "No", " "])
showRow2 = input.bool(false, "Show Row 2?")
row2Text = input.string("-----------", "Row 2")
row2Confirmation = input.string("No", "Row 2 Confirmed?", options=["Yes", "No", " "])
showRow3 = input.bool(false, "Show Row 3?")
row3Text = input.string("-----------", "Row 3")
row3Confirmation = input.string("No", "Row 3 Confirmed?", options=["Yes", "No", " "])
showRow4 = input.bool(false, "Show Row 4?")
row4Text = input.string("-----------", "Row 4")
row4Confirmation = input.string("No", "Row 4 Confirmed?", options=["Yes", "No", " "])
showRow5 = input.bool(false, "Show Row 5?")
row5Text = input.string("-----------", "Row 5")
row5Confirmation = input.string("No", "Row 5 Confirmed?", options=["Yes", "No", " "])
showRow6 = input.bool(false, "Show Row 6?")
row6Text = input.string("-----------", "Row 6")
row6Confirmation = input.string("No", "Row 6 Confirmed?", options=["Yes", "No", " "])
showRow7 = input.bool(false, "Show Row 7?")
row7Text = input.string("-----------", "Row 7")
row7Confirmation = input.string("No", "Row 7 Confirmed?", options=["Yes", "No", " "])
showRow8 = input.bool(false, "Show Row 8?")
row8Text = input.string("-----------", "Row 8")
row8Confirmation = input.string("No", "Row 8 Confirmed?", options=["Yes", "No", " "])
// Position Settings
_tableGrp = "Position"
_tableYpos = input.string('Top', 'Vertical Position', inline='01', group=_tableGrp, options=['Top', 'Middle', 'Bottom'])
tableYpos = _tableYpos == "Top" ? "top" : _tableYpos == "Bottom" ? "bottom" : "middle"
_tableXpos = input.string('Right', 'Horizontal Position', inline='01', group=_tableGrp, options=['Left', 'Center', 'Right'])
tableXpos = _tableXpos == "Right" ? "right" : _tableXpos == "Center" ? "center" : "left"
// Appearance Settings
fontColor = input.color(color.blue, "Font Color")
bgColor = input.color(color.new(#6d7ca5, 42), "Background Color")
showBorder = input.bool(false, "Show Table Border?")
borderThickness = input.int(1, "Border Thickness", minval=1)
borderColor = input.color(color.blue, "Border Color")
// Draw Table
var tradingPanel = table.new(position= tableYpos + '_' + tableXpos , columns=2, rows=11, bgcolor=bgColor, border_width = showBorder ? borderThickness : 0, border_color=borderColor)
if barstate.islast
table.cell(table_id=tradingPanel, column=0, row=0, text=title, text_size=size.huge, text_color=fontColor, text_halign=text.align_center)
table.cell(table_id=tradingPanel, column=0, row=1, text=currencyPair, text_size=size.large, text_color=fontColor, text_halign=text.align_center)
table.cell(table_id=tradingPanel, column=0, row=2, text=trend, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=2, text=trendConfirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
// Additional Rows
if showRow1
table.cell(table_id=tradingPanel, column=0, row=3, text=row1Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=3, text=row1Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
if showRow2
table.cell(table_id=tradingPanel, column=0, row=4, text=row2Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=4, text=row2Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
if showRow3
table.cell(table_id=tradingPanel, column=0, row=5, text=row3Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=5, text=row3Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
if showRow4
table.cell(table_id=tradingPanel, column=0, row=6, text=row4Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=6, text=row4Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
if showRow5
table.cell(table_id=tradingPanel, column=0, row=7, text=row5Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=7, text=row5Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
if showRow6
table.cell(table_id=tradingPanel, column=0, row=8, text=row6Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=8, text=row6Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
if showRow7
table.cell(table_id=tradingPanel, column=0, row=9, text=row7Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=9, text=row7Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
if showRow8
table.cell(table_id=tradingPanel, column=0, row=10, text=row8Text, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
table.cell(table_id=tradingPanel, column=1, row=10, text=row8Confirmation, text_size=size.normal, text_color=fontColor, text_halign=text.align_left)
|
Abz US Real rates | https://www.tradingview.com/script/Wh3VEvu6-Abz-US-Real-rates/ | Abzorba | https://www.tradingview.com/u/Abzorba/ | 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/. Original version by © MrDevDevy
//FED Funds Rate vs Inflation
//New:
//I have added the US 10 year yield. When this is higher than inflation and the Fed Funds Rate and the US10Y is trending downwards, then this is going generally be good for TLT.
//TLT demand will change based on being a flight to safety in a crash such as the Covid crash and this could occur despite other factors. Also if the government wants to sell more bonds than others will buy then TLT may go down in price despite the US10Y not going up as much or otherwise not reflecting that change.
//@version=5
indicator("Abz US Real rates", shorttitle = "Real rates")
showUS10Y = input.bool(true, "Show US 10 year yield rate - Strong green good for TLT")
FedRateColor = input.color(defval=color.rgb(149, 255, 0, 77), title="Fed Funds Rate color")
InflationColor = input.color(defval=color.rgb(122, 0, 221, 52), title="US Inflation rate color")
FedFundsRate = request.security("FEDFUNDS", "D", close)
USinflation = request.security("USIRYY", "D", close)
US10Y = request.security("US10Y", "D", close)
US10ma = ta.sma(ta.sma(US10Y,3),4)
FFRplot = plot(FedFundsRate, color=FedRateColor, title = "Fed Fund Rates plot")
Inflation = plot(USinflation, color=InflationColor, title = "US inflation plot")
Inversionplot = plot(US10ma, color= not showUS10Y ? na : FedFundsRate > US10Y or (FedFundsRate > FedFundsRate[1] and FedFundsRate > (US10Y + US10ma)/2) or (FedFundsRate > FedFundsRate[1] and USinflation> (US10Y + US10ma)/2) ? color.rgb(221, 0, 0, 35) : na, linewidth = 6, title = "Yield Inversion plot")
TLTtimeplot = plot(US10ma, color= not showUS10Y or (FedFundsRate > FedFundsRate[1] and FedFundsRate > (US10Y + US10ma)/2) or (FedFundsRate > FedFundsRate[1] and USinflation> (US10Y + US10ma)/2) ? na : FedFundsRate < US10Y and (US10Y + US10ma)/2 > FedFundsRate and (US10Y + US10ma)/2 - 0.7 > USinflation ? color.rgb(20, 255, 47, 35) : na, linewidth = 6, title = "Time for TLT plot")
US10maplot = plot(US10ma, color= not showUS10Y ? na : (US10Y + US10ma) > (US10Y[1] + US10ma[1]) ? color.rgb(255, 0, 255, 10) : color.rgb(30, 255, 0, 10), linewidth = 2, title = "US 10 Year Bond Yield % plot")
fill(FFRplot, Inflation, color =FedFundsRate > USinflation ? color.rgb(60, 60, 255, 5) : color.rgb(188, 217, 42, 45), title = "Fed Fund Rates vs US inflation FILL")
bgcolor(FedFundsRate > US10Y ? color.new(color.rgb(221, 0, 0),90) : na, title = "Yield Inversion BGcolor")
//============================================
//Plot Indicator Label
showIndicatorLabel = true
indicatorLabel = table.new(position.top_left, columns=1, rows=1, bgcolor=color.rgb(0, 0, 0, 50))
if showIndicatorLabel and barstate.islast
table.cell(table_id=indicatorLabel, column=0, row=0, text="US real rates", height=0, text_color=color.rgb(255, 255, 255, 20), text_halign=text.align_center, text_valign= text.align_center)
//============================================
//============================================
// Recessions are shown with a gray background. Same as my Abz US Recessions indicator
r = request.quandl('FRED/USRECD')
recession = r == 1 ? true : false
color shade = input(defval=color.new(color.gray, 85), title='Recession Shading')
bgcolor(recession ? shade : na, title = "US Recessions") |
Geometrical Mean Moving Average | https://www.tradingview.com/script/qTLAWmDW-Geometrical-Mean-Moving-Average/ | ThiagoSchmitz | https://www.tradingview.com/u/ThiagoSchmitz/ | 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/
// © ThiagoSchmitz
//@version=5
indicator("Geometrical Mean Moving Average", "GeoMMA", true)
float source = input.source(close, "Source")
int period = input.int(10, "Period")
float exponent = 1.0 / period
float sma = ta.sma(source, 1)
float multiple = 1.0
for i = 0 to period - 1 by 1
multiple := multiple * sma[i]
float gmma = math.pow(multiple, exponent)
plot(gmma, "GMMA", color.yellow, 2) |
Test - Symbiotic Exiton Measure Enthropic Nexus indicator | https://www.tradingview.com/script/UbraQho2-Test-Symbiotic-Exiton-Measure-Enthropic-Nexus-indicator/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 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/
// © RicardoSantos
//@version=5
indicator("Test - Symbiotic Exiton Measure Enthropic Nexus indicator")
// reference:
// https://azeemba.com/posts/boundaries-of-predictability.html
// The Symbiotic Exiton Measure Enthropic Nexus (SEMEN) Indicator is a
// technical analysis tool used in trading and investing. It's name might
// sound complex, but its function is quite simple - to help traders make
// informed decisions about buying or selling stocks by predicting market
// trends.
// The SEMEN indicator uses a combination of various factors such as volume,
// price action, moving averages, and other indicators to generate a single
// numerical value that represents the overall health of the market. A high
// reading indicates a strong uptrend, while a low one suggests a downtrend.
// Traders can use this information to enter or exit positions with
// confidence.
// In essence, the SEMEN indicator provides a comprehensive view of the
// market's sentiment and direction, making it an essential tool for any
// trader or investor looking to make profitable decisions in today's
// volatile stock markets.
// ~description generated with Airoboros7b
d0 (G, m, r, d, l, v) =>
_1_1 = -fixnan(2.0 * G * m)
_1_2 = fixnan(r - math.pow(d, 3.0))
_2_1 = math.pow(nz(l / v, 0.0), 2.0)
(_1_1 / _1_2) * _2_1
d1 (float src, float vol, int length) =>
float _src = math.log(src)
// G and m give the observed movement
float _G = ta.change(src, length) // gravity constant
float _m = math.log(ta.change(vol) / ta.highest(vol, length)) // mass
//
float _r = length // radius
float _d = ta.change(_src, length) // distance
float _l = ta.highestbars(length) - ta.lowestbars(length) //length / 2.0//ta.highestbars(length) - ta.lowestbars(length) // mean free path
float _v = ta.atr(length) //ta.change(c) // thermal velocity
ta.rsi(d0(_G, _m, _r, _d, _l, _v), length)
bool show_overlay = input.bool(true, 'Show Bar color overlay?')
bool compensate = input.bool(true, 'Compensate for small numeric perturbations?', inline = '1')
int power = input.int(3, 'Conpensation power:', inline = '1')
float src = input.source(close, 'Source Series:')
int length = input.int(14, 'Length')
// calculate basis source, calculate the series and the power to conpensate the
// numeric output of perturbations too small to detect.
float basis = compensate ? math.log(src * math.pow(power, 10)) : math.log(src)
f0 = d1(basis, volume, length)
f1 = d1(basis, volume, length*2)
f2 = d1(basis, volume, length*3)
col = switch
f0 > 80 => #d9dddc
f0 > 70 => #79c5c1
f0 > 50 => #98d163
f0 < 30 => #79c5c1
f0 < 20 => #d9dddc
=> #f19058
plot(f0, 'F0', #0050fc)
plot(f0, 'F0', color.new(col, 70), 3, plot.style_histogram, histbase=50)
plot(f1, 'F1', #c7c425)
plot(f2, 'F2', #ff7c02)
barcolor(col, display = show_overlay ? display.all : display.none) |
Division with other simbol | https://www.tradingview.com/script/E43E3WkT/ | derdavichu | https://www.tradingview.com/u/derdavichu/ | 1 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © derdavichu
//@version=5
indicator("Division with other simbol", overlay = false, shorttitle = "DIV")
symbolInput = input.symbol("BTCARS", "Symbol")
sourceInput = input.source(close, "Source")
// This takes into account additional settings enabled on chart, e.g. divident adjustment or extended session
adjustedSeries = ticker.modify(symbolInput)
requestedData = request.security(adjustedSeries, timeframe.period, sourceInput)
division = requestedData / sourceInput
plot(division, "Division", color.yellow, 2) |
Kaschko's Seasonal Trend | https://www.tradingview.com/script/BEQsOqoT-Kaschko-s-Seasonal-Trend/ | Kaschko | https://www.tradingview.com/u/Kaschko/ | 53 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kaschko
//@version=5
indicator("Kaschko's Seasonal Trend", shorttitle = "Seasonality", overlay = true, max_lines_count = 500, precision = 0)
_stdays = input.string(group = "Daily timeframe", title = "Trading days on daily timeframe", options = ["fixed (252)","variable"], defval = "fixed (252)", display = display.none)
_utdays = input.string(group = "Daily timeframe", title = "Use ... number of trading days in a year of the lookback period", options = ["maximum","minimum","average"], defval = "minimum", display = display.none)
_lookback = input.int (group = "All timeframes" , title = "Lookback period in years", minval = 1, maxval = 30, defval = 15)
_future = input.int (group = "All timeframes" , title = "Plot seasonality ... bars into the future", minval = 0, maxval = 252, defval = 30, display = display.none)
_color = input.color (group = "All timeframes" , title = "Color", defval = #cfcfcf)
_width = input.int (group = "All timeframes" , title = "Line width", minval = 1, defval = 3, display = display.none)
// Trading day of month, trading day of year
var int _tdom = na
var int _tdoy = na
if bool(ta.change(year(time_close))) and timeframe.isdaily and timeframe.multiplier == 1
_tdoy := 0
if bool(ta.change(month(time_close))) and timeframe.isdaily and timeframe.multiplier == 1
_tdom := 0
if not na(_tdoy)
_tdoy := _tdoy + 1
if not na(_tdom)
_tdom := _tdom + 1
int _twoy = weekofyear(time_close) // Trading week of year
int _nof_bins = na // Number of bins
int _slot = na // Trading day/week/month of bar
// Set up bins depending on timeframe
if timeframe.multiplier == 1
if timeframe.isdaily
_nof_bins := _stdays == "fixed (252)" ? 252 : 366
_slot := _tdoy
else if timeframe.isweekly
_nof_bins := 52
_slot := _twoy
else if timeframe.ismonthly
_nof_bins := 12
_slot := month(time_close)
// Show trading week oy year, trading day of month and trading day of year in status line
plot(na(_nof_bins) ? na : _twoy, title = "TWOY" , color = #000000, display = display.status_line)
plot(na(_nof_bins) ? na : _tdom, title = "TDOM" , color = #000000, display = display.status_line)
plot(na(_nof_bins) ? na : _tdoy, title = "TDOY" , color = #000000, display = display.status_line)
// One year has 52.18 weeks * 7 days * 86400000 msecs = 31558464000 msecs
var int _years = _lookback
var int _mindate = time_close
var int _start = math.max(_mindate,timenow - _years * 31558464000)
if barstate.isfirst and (timenow - _start)/31558464000 < _years
_years := math.floor((timenow - _start)/31558464000)
_start := timenow - _years * 31558464000
// Arrays of bars storing trading day/week/month, lows and highs for all bars
var _a_days = array.new_int(0)
var _a_slot = array.new_int(0)
var _a_lows = array.new_float(0)
var _a_high = array.new_float(0)
// Arrays of bins storing seasonal values, the number of years that
// contributed to the seasonal value and the Y coordinate of the line
var _a_bins = array.new_float(_nof_bins,0)
var _a_cntr = array.new_int (_nof_bins,0)
var _a_line = array.new_float(_nof_bins,0)
// Store trading day/week/month, low and high of the current bar
array.push(_a_slot,_slot)
array.push(_a_lows,low)
array.push(_a_high,high)
// The bin of the current bar (one less than the trading day/week/month since array indexes start with 0)
int _bin = na
if timeframe.isdaily
_bin := _tdoy-1
else if timeframe.isweekly
_bin := weekofyear(time_close)-1
else if timeframe.ismonthly
_bin := month(time_close)-1
// If the bar falls within the lookback period, add the price
// delta to the respective bin and increase the counter
var float _chg = na
if time > _start and bar_index > 0 and _bin < array.size(_a_bins)
_chg := close-close[1]
array.set(_a_bins,_bin,array.get(_a_bins,_bin)+_chg)
array.set(_a_cntr,_bin,array.get(_a_cntr,_bin)+1)
// Store number of trading days of previous year
if _tdoy < _tdoy[1]
array.push(_a_days,_tdoy[1])
var int _bleft = na // left visible bar
var int _bright = na // right visible bar
if time == chart.left_visible_bar_time
_bleft := bar_index
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
_bright := bar_index
var int _used = 0
var int _bin1 = na
var int _bin2 = na
var float _factor = na
var float _hhigh = na
var float _llow = na
var float _top = na
var float _bot = na
// Draw the seasonal chart on the last bar
if barstate.islast and not na(_nof_bins)
// On daily chart, determine number of trading days in "variable" mode
if _nof_bins == 366
_nof_bins := _utdays == "minimum" ? array.min(_a_days) : _utdays == "maximum" ? array.max(_a_days) : math.floor(array.avg(_a_days))
// Remove excess trading days
if array.size(_a_bins) > _nof_bins
for i = array.size(_a_bins)-1 to _nof_bins
array.remove(_a_bins,i)
array.remove(_a_cntr,i)
if not barstate.isrealtime
log.info("Number of trading days used: " + str.tostring(_nof_bins))
for i = 0 to array.size(_a_bins)-1
if array.get(_a_cntr,i) > 0
_used := i // on the daily chart, not all markets have the same number of trading days
// Divide sum of price deltas by number of years to get the average
array.set(_a_bins,i,array.get(_a_bins,i)/array.get(_a_cntr,i))
// Use the average price move from one bar to the next to
// get the dots to connect by lines to get a seasonal chart
if i > 0
array.set(_a_line,i,array.get(_a_line,i-1)+array.get(_a_bins,i))
// de-trend
_first = 0
_last = array.get(_a_line,_used)-_first
_step = _last/_used
for i = 1 to _used
array.set(_a_line,i,array.get(_a_line,i)-_step*i)
// Get the bins of the left and right visible bars
// Values of _a_slot are 1 .. max_tdoy or 1 .. max_twoy or 1 .. 12 (the bin of the bar)
_binL = math.min(_used,array.get(_a_slot,_bleft )-1) // min = 0
_binR = math.min(_used,array.get(_a_slot,_bright)-1) // max = 251 (or lower) / 51 / 11
// Calculate top and bottom of the projection onto the visible chart
float _offs = 0
_binP = _binL // bin of left visible bar
for i = _bleft to _bright+(_bright == last_bar_index ? _future-1 : 0) // visible bars + future projection
_binP := ((_binP + 1) > _used) ? 0 : (_binP + 1)
_top := (na(_top) or array.get(_a_line,_binP) > _top) ? array.get(_a_line,_binP) : _top
_bot := (na(_bot) or array.get(_a_line,_binP) < _bot) ? array.get(_a_line,_binP) : _bot
// Make seasonality start at 0
_offs := -_bot
_top := _top-_bot
_bot := 0
// Get the height of the visible chart
for i = _bleft to _bright
_hhigh := na(_hhigh) or array.get(_a_high,i) > _hhigh ? array.get(_a_high,i) : _hhigh
_llow := na(_llow ) or array.get(_a_lows,i) < _llow ? array.get(_a_lows,i) : _llow
// Calculate the factor to adjust the scale of seasonality to that of price
_factor := (_hhigh-_llow)/(_top-_bot)
// Draw the seasonality into the past
for i = math.max(_bleft,1) to _bright
_bin1 := math.min(_used,array.get(_a_slot,i-1)-1)
_bin2 := math.min(_used,array.get(_a_slot,i )-1)
_y1 = _llow+(array.get(_a_line,_bin1)+_offs)*_factor
_y2 = _llow+(array.get(_a_line,_bin2)+_offs)*_factor
line.new(i-1,_y1,i,_y2, xloc = xloc.bar_index, color = _color,width = _width)
// Draw the seasonality into the future
if _bright == last_bar_index // last visible bar is actually last bar
int _bidx = last_bar_index
_bin1 := _binR-1
for i = 1 to _future
_bin1 := _bin1 + 1
_bin2 := _bin1 + 1
if _bin2 > _used
_bin2 := 0
if _bin1 > _used
_bin1 := 0
_bin2 := 1
_y1 = _llow+(array.get(_a_line,math.min(_used,_bin1))+_offs)*_factor
_y2 = _llow+(array.get(_a_line,math.min(_used,_bin2))+_offs)*_factor
line.new(_bidx,_y1,_bidx+1,_y2, xloc = xloc.bar_index, color = _color, width = _width)
_bidx := _bidx + 1
|
Cumulative Symbol | https://www.tradingview.com/script/svYxuKIR-Cumulative-Symbol/ | syntaxgeek | https://www.tradingview.com/u/syntaxgeek/ | 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/
// © syntaxgeek
// _____ _____ _____ _____ _____ _____ _____ _____ _____
// /\ \ |\ \ /\ \ /\ \ /\ \ ______ /\ \ /\ \ /\ \ /\ \
// /::\ \ |:\____\ /::\____\ /::\ \ /::\ \ |::| | /::\ \ /::\ \ /::\ \ /::\____\
// /::::\ \ |::| | /::::| | \:::\ \ /::::\ \ |::| | /::::\ \ /::::\ \ /::::\ \ /:::/ /
// /::::::\ \ |::| | /:::::| | \:::\ \ /::::::\ \ |::| | /::::::\ \ /::::::\ \ /::::::\ \ /:::/ /
// /:::/\:::\ \ |::| | /::::::| | \:::\ \ /:::/\:::\ \ |::| | /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/ /
// /:::/__\:::\ \ |::| | /:::/|::| | \:::\ \ /:::/__\:::\ \ |::| | /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/____/
// \:::\ \:::\ \ |::| | /:::/ |::| | /::::\ \ /::::\ \:::\ \ |::| | /:::/ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /::::\ \
// ___\:::\ \:::\ \ |::|___|______ /:::/ |::| | _____ /::::::\ \ /::::::\ \:::\ \ |::| | /:::/ / \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /::::::\____\________
// /\ \:::\ \:::\ \ /::::::::\ \ /:::/ |::| |/\ \ /:::/\:::\ \ /:::/\:::\ \:::\ \ ______|::|___|___ ____ /:::/ / \:::\ ___\ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ \ /:::/\:::::::::::\ \
// /::\ \:::\ \:::\____\/::::::::::\____/:: / |::| /::\____\/:::/ \:::\____/:::/ \:::\ \:::\____|:::::::::::::::::| /:::/____/ ___\:::| /:::/__\:::\ \:::\____/:::/__\:::\ \:::\____/:::/ |:::::::::::\____\
// \:::\ \:::\ \::/ /:::/~~~~/~~ \::/ /|::| /:::/ /:::/ \::/ \::/ \:::\ /:::/ |:::::::::::::::::|____\:::\ \ /\ /:::|____\:::\ \:::\ \::/ \:::\ \:::\ \::/ \::/ |::|~~~|~~~~~
// \:::\ \:::\ \/____/:::/ / \/____/ |::| /:::/ /:::/ / \/____/ \/____/ \:::\/:::/ / ~~~~~~|::|~~~|~~~ \:::\ /::\ \::/ / \:::\ \:::\ \/____/ \:::\ \:::\ \/____/ \/____|::| |
// \:::\ \:::\ \ /:::/ / |::|/:::/ /:::/ / \::::::/ / |::| | \:::\ \:::\ \/____/ \:::\ \:::\ \ \:::\ \:::\ \ |::| |
// \:::\ \:::\____\/:::/ / |::::::/ /:::/ / \::::/ / |::| | \:::\ \:::\____\ \:::\ \:::\____\ \:::\ \:::\____\ |::| |
// \:::\ /:::/ /\::/ / |:::::/ /\::/ / /:::/ / |::| | \:::\ /:::/ / \:::\ \::/ / \:::\ \::/ / |::| |
// \:::\/:::/ / \/____/ |::::/ / \/____/ /:::/ / |::| | \:::\/:::/ / \:::\ \/____/ \:::\ \/____/ |::| |
// \::::::/ / /:::/ / /:::/ / |::| | \::::::/ / \:::\ \ \:::\ \ |::| |
// \::::/ / /:::/ / /:::/ / |::| | \::::/ / \:::\____\ \:::\____\ \::| |
// \::/ / \::/ / \::/ / |::|___| \::/____/ \::/ / \::/ / \:| |
// \/____/ \/____/ \/____/ ~~ \/____/ \/____/ \|___|
//@version=5
indicator("Cumulative Symbol", precision=2)
// { consts
c_mode_basic = "Basic"
c_mode_ad = "Advance or Decline"
c_mode_internalRatio = "Ratio"
// }
// { inputs
i_symbol = input.symbol("", "Symbol")
i_source = input.source(close, "Source")
i_mode = input.string(c_mode_ad, "Histogram Mode", [c_mode_basic, c_mode_ad, c_mode_internalRatio], "Basic tracks symbol source plain, advancements and declines are added or subtracted respectively from cumulative total or 0 point ratio adjusts internal formula to present directional crosses as well as advancements and declines.")
i_averagePeriod = input.int(8, "Trend Period", minval=1, step=1)
i_colorUp = input.color(color.green, 'Up', group='Colors')
i_colorDown = input.color(color.red, 'Down', group='Colors')
i_colorAvgUp = input.color(color.white, 'Up', group='Trend Colors')
i_colorAvgDown = input.color(color.purple, 'Down', group='Trend Colors')
i_colorStrengthStrong = input.color(color.fuchsia, 'Strong', group='Trend Strength Colors')
i_colorStrengthWeak = input.color(color.yellow, 'Weak', group='Trend Strength Colors')
// }
// { funcs
f_colorTrend(_v, _colorUp, _colorDown, _isTrend) =>
if _v > 0
if _v > _v[1]
_colorUp
else
_isTrend ? _colorDown : color.new(_colorUp, 50)
else
if _v < _v[1]
_colorDown
else
_isTrend ? _colorUp : color.new(_colorDown, 50)
f_cumOverAverage(_v, _vAvg) =>
if _v > 0
_v > _vAvg
else
_v < _vAvg
// }
// { vars
var v_cumulative = 0.0
var v_cumulativeAverage = 0.0
var v_cumulativeToAvgDiff = 0.0
var v_diff = 0.0
v_symbolSource = request.security(i_symbol, timeframe.period, i_source)
if not timeframe.isdwm and session.isfirstbar_regular
v_cumulative := 0.0
v_cumulativeAverage := 0.0
if i_mode == c_mode_basic
v_cumulative += v_symbolSource
else if i_mode == c_mode_ad
if v_symbolSource > v_symbolSource[1]
v_cumulative += v_symbolSource
else
v_cumulative -= v_symbolSource
else if i_mode == c_mode_internalRatio
v_diff := math.abs(v_symbolSource[1] - v_symbolSource)
if v_symbolSource > v_symbolSource[1]
if v_symbolSource < 0
v_cumulative -= v_symbolSource
else
v_cumulative += v_symbolSource
else
if v_symbolSource < 0
v_cumulative += v_symbolSource
else
v_cumulative -= v_symbolSource
v_cumulativeAverage := ta.sma(v_cumulative, i_averagePeriod)
v_cumulativeToAvgDiff := math.abs(v_cumulative - v_cumulativeAverage)
v_strongTrend = f_cumOverAverage(v_cumulative, v_cumulativeAverage)
v_trendSlowing = v_cumulativeToAvgDiff < v_cumulativeToAvgDiff[1]
// } vars
// { plots
plot(v_cumulative, title='Cum', style=plot.style_columns, color=f_colorTrend(v_cumulative, i_colorUp, i_colorDown, false))
plot(v_cumulativeAverage, title='Trend', color=color.new(f_colorTrend(v_cumulativeAverage, i_colorAvgUp, i_colorAvgDown, true), 0), linewidth=2)
plotshape(0, 'Strength', shape.circle, location.absolute, color.new(v_strongTrend ? i_colorStrengthStrong : i_colorStrengthWeak, v_trendSlowing ? 30 : 0), size=size.auto)
// }
// { alerts
// } |
Fibonacci Oscillator (Expo) | https://www.tradingview.com/script/KkAOEljd-Fibonacci-Oscillator-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 504 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman {
//@version=5
indicator("Fibonacci Oscillator (Expo)",overlay=false, precision = 1)
//~~}
// ~~ Inputs {
oscType = input.string("RSI","Oscillator Type", ["RSI", "MACD","Histogram"],group="Fibonacci Settings")
fibonacci = input.float(0.236,"Fibonacci Level ",options=[0.236,0.382,0.50,0.618,0.786], group="Fibonacci Settings")
custom = input.bool(false,"Custom Value",inline="custom", group="Fibonacci Settings")
customfib = input.float(0.1,"",.001,.999,.001,inline="custom", group="Fibonacci Settings")
rsi_len = input.int(14,"RSI Length ",group="Relative Strength Index",inline="rsi")
rsi_sig = input.int(14,"Signal Length",group="Relative Strength Index",inline="rsi_sig")
rsi_col = input.color(color.purple,"",group="Relative Strength Index",inline="rsi")
rsi_sigcol = input.color(color.yellow,"",group="Relative Strength Index",inline="rsi_sig")
macd_fast = input.int(12,"Fast ",group="MACD",inline="macd")
macd_slow = input.int(26,"Slow",group="MACD",inline="macd")
macd_sig = input.int(9,"Signal",group="MACD",inline="sig")
macd_col = input.color(#2962FF,"",group="MACD",inline="macd")
macd_sigcol = input.color(#FF6D00,"",group="MACD",inline="sig")
grow_above = input.color(#26A69A, "Above Grow", group="MACD", inline="Above")
fall_above = input.color(#B2DFDB, "Fall", group="MACD", inline="Above")
grow_below = input.color(#FFCDD2, "Below Grow", group="MACD", inline="Below")
fall_below = input.color(#FF5252, "Fall", group="MACD", inline="Below")
hist_src = input.source(close,"Source",group="Histogram",inline="hist")
hist_colup = input.color(color.green,"",group="Histogram",inline="hist")
hist_coldn = input.color(color.red,"",group="Histogram",inline="hist")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
b = bar_index
var pos = 0
var hi = high
var lo = low
var retrace = 0.0
fib = custom?customfib:fibonacci
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Track high/low and calculate fibonacci level {
if pos>=0
if high<retrace
pos := -1
lo := low
retrace := lo+(hi-lo)*fib
else if high>hi
hi := high
retrace := hi-(hi-lo)*fib
if pos<=0
if low>retrace
pos := 1
hi := high
retrace := hi-(hi-lo)*fib
else if low<lo
lo := low
retrace := lo+(hi-lo)*fib
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Switch Function {
OscType(r,h,m)=>
output = switch oscType
"RSI" => r
"Histogram"=> h
"MACD"=> m
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Oscillator Declaration {
[src,signal,osc] = switch oscType
"RSI" => [na,ta.sma(ta.rsi(retrace,rsi_len),rsi_sig),ta.rsi(retrace,rsi_len)]
"Histogram"=> [na,na,close-retrace]
"MACD"=> ta.macd(retrace,macd_fast,macd_slow,macd_sig)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plots {
p1 = plot(osc,"Oscillator Type",OscType(rsi_col,(osc>=0?hist_colup:hist_coldn),(osc>=0?(osc[1]<osc?grow_above:fall_above):(osc[1]<osc?grow_below:fall_below))),
1,OscType(plot.style_line,plot.style_columns,plot.style_columns))
m2 = plot(OscType(float(na),float(na),src),"MACD Line",macd_col)
m3 = plot(OscType(signal,float(na),signal),"Signal",OscType(rsi_sigcol,color(na),macd_sigcol))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Gradient Fill {
upper = OscType(100,ta.highest(osc,1000),ta.highest(src,1000))
lower = OscType(0,ta.lowest(osc,1000),ta.lowest(src,1000))
mid = OscType(50,0,0)
upper_ = OscType(90,upper-ta.ema(ta.stdev(osc,20),20),upper-ta.ema(ta.stdev(src,20),20))
lower_ = OscType(10,lower+ta.ema(ta.stdev(osc,20),20),lower+ta.ema(ta.stdev(src,20),20))
channel_upper = plot(upper, color = na, editable = false, display = display.none)
channel_lower = plot(lower, color = na, editable = false, display = display.none)
channel_mid = plot(mid, color=color.gray, editable = false)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Channel Gradient Fill {
fill(channel_mid, channel_upper, top_value = upper, bottom_value=mid, bottom_color = na, top_color = color.new(color.lime,75),title = "Channel Gradient Fill")
fill(channel_mid, channel_lower, top_value = mid, bottom_value=lower, bottom_color = color.new(color.red,75) , top_color = na,title = "Channel Gradient Fill")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Overbought/Oversold Gradient Fill {
fill(p1, channel_mid, upper, upper_, top_color = color.new(color.lime, 0), bottom_color = color.new(color.green, 100),title = "Overbought Gradient Fill")
fill(p1, channel_mid, lower_, lower, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0),title = "Oversold Gradient Fill")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
YinYang Bar Forecast | https://www.tradingview.com/script/1QdV13JG-YinYang-Bar-Forecast/ | YinYangAlgorithms | https://www.tradingview.com/u/YinYangAlgorithms/ | 81 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// © YinYangAlgorithms
//@version=5
indicator("YinYang Bar Forecast", overlay=true)
// ~~~~~~~~ INPUTS ~~~~~~~~ //
predictiveCount = input.int(13, "Forecast Length:", minval=1, maxval=13, tooltip="How many bars should we predict into the Future? Max 13")
eachBarLengthMult = input.int(5, "Each Bar Length Multiplier", minval=2, tooltip="For each new Forecast bar, how many more bars are averaged? Min 2")
vwmaAveragedLength = input.int(2, "VWMA Averaged Length:", minval=1, tooltip="All Forecast bars are put into a VWMA, what length should we use?")
emaAveragedLength = input.int(2, "EMA Averaged Length:", minval=1, tooltip="All Forecast bars are put into a EMA, what length should we use?")
filteredLength = input.int(10, "Filtered Length", minval=1, tooltip="What length should we use for Filtered Volume and RSI?")
emaStrengthLength = input.int(21, "EMA Strength Length:", minval=1, tooltip="What length should we use for the EMA Strength")
// ~~~~~~~~ VARIABLES ~~~~~~~~ //
//Bar values
predictiveHigh = array.new_float(predictiveCount)
predictiveLow = array.new_float(predictiveCount)
predictiveOpen = array.new_float(predictiveCount)
predictiveClose = array.new_float(predictiveCount)
// ~~~~~~~~ FUNCTIONS ~~~~~~~~ //
//Get individual source data for a bar
getSourceForecast(src, len) =>
//Average
returnValue = switch len
0 => ta.ema(ta.vwma(math.avg(ta.ema(src, eachBarLengthMult >= 2 ? 2 : eachBarLengthMult), ta.vwma(src, eachBarLengthMult >= 2 ? 2 : eachBarLengthMult)), vwmaAveragedLength), emaAveragedLength)
1 => ta.ema(ta.vwma(math.avg(ta.ema(src, eachBarLengthMult + 1), ta.vwma(src, eachBarLengthMult + 1)), vwmaAveragedLength), emaAveragedLength)
2 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 2) + 1), ta.vwma(src, (eachBarLengthMult * 2) + 1)), vwmaAveragedLength), emaAveragedLength)
3 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 3) + 1), ta.vwma(src, (eachBarLengthMult * 3) + 1)), vwmaAveragedLength), emaAveragedLength)
4 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 4) + 1), ta.vwma(src, (eachBarLengthMult * 4) + 1)), vwmaAveragedLength), emaAveragedLength)
5 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 5) + 1), ta.vwma(src, (eachBarLengthMult * 5) + 1)), vwmaAveragedLength), emaAveragedLength)
6 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 6) + 1), ta.vwma(src, (eachBarLengthMult * 6) + 1)), vwmaAveragedLength), emaAveragedLength)
7 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 7) + 1), ta.vwma(src, (eachBarLengthMult * 7) + 1)), vwmaAveragedLength), emaAveragedLength)
8 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 8) + 1), ta.vwma(src, (eachBarLengthMult * 8) + 1)), vwmaAveragedLength), emaAveragedLength)
9 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 9) + 1), ta.vwma(src, (eachBarLengthMult * 9) + 1)), vwmaAveragedLength), emaAveragedLength)
10 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 10) + 1), ta.vwma(src, (eachBarLengthMult * 10) + 1)), vwmaAveragedLength), emaAveragedLength)
11 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 11) + 1), ta.vwma(src, (eachBarLengthMult * 11) + 1)), vwmaAveragedLength), emaAveragedLength)
12 => ta.ema(ta.vwma(math.avg(ta.ema(src, (eachBarLengthMult * 12) + 1), ta.vwma(src, (eachBarLengthMult * 12) + 1)), vwmaAveragedLength), emaAveragedLength)
//Volume Filtered
avgVol = ta.vwma(volume, filteredLength)
volDiff = volume / avgVol
midVolSmoothed = ta.vwma(returnValue * volDiff, 3)
//RSI Filtered
midDifference = ta.sma(ta.ema(high, filteredLength) - ta.ema(low, filteredLength), filteredLength)
midRSI = ta.rsi(midVolSmoothed, filteredLength) * 0.01
midAdd = midRSI * midDifference
midAdjusted = close > open ? midAdd : midAdd * -1
rsiFiltered = returnValue + midAdjusted
//EMA strength
strength = close > ta.ema(close, emaStrengthLength) ? 1 + (0.0005 * (len + 2)) : 1 - (0.0005 * (len + 2))
strengthInterval = (rsiFiltered - (rsiFiltered * strength)) / predictiveCount
strengthFiltered = rsiFiltered + (strengthInterval * (len + 1))
//RSI Strength
rsi = ta.rsi(close, 14)
rsiMA = ta.sma(rsi, 14)
rsiCross = ta.cross(rsi, rsiMA)
rsiStrength = rsi >= 50 ? rsi - 50 : 50 - rsi
if rsiCross
rsiStrength := rsiStrength * (1 + (0.2 / (len + 1)))
rsiDivision = rsi >= 70 or rsi <= 30 ? rsi > rsiMA ? len + 2 : len + 3 : len + 4
rsiStrengthMult = (rsiStrength / rsiDivision) * 0.01
rsiPriceInfluence = src * rsiStrengthMult
rsiPriceInterval = (rsiPriceInfluence / predictiveCount) * (len + 1)
rsiStrengthFiltered = rsi >= 50 ? strengthFiltered - rsiPriceInterval : strengthFiltered + rsiPriceInterval
//Money Flow
mf = ta.mfi(close, (len + 1))
mfMA = ta.sma(mf, 14)
mfCross = ta.cross(mf, mfMA)
mfStrength = mf >= 50 ? mf - 50 : 50 - mf
if mfCross
mfStrength := mfStrength * (1 + (0.2 / (len + 1)))
mfDivision = mf >= 70 or mf <= 30 ? mf > mfMA ? len + 1 : len + 2 : len + 3
mfStrengthMult = (mfStrength / mfDivision) * 0.01
mfPriceInfluence = src * mfStrengthMult
mfPriceInterval = (mfPriceInfluence / predictiveCount) * (len + 1)
returnValue := mf >= 50 ? rsiStrengthFiltered - mfPriceInterval : rsiStrengthFiltered + mfPriceInterval
returnValue
// ~~~~~~~~ CALCULATIONS ~~~~~~~~ //
//Assign bar values
for i = 0 to predictiveCount - 1
array.set(predictiveHigh, i, getSourceForecast(high, i))
array.set(predictiveLow, i, getSourceForecast(low, i))
array.set(predictiveOpen, i, getSourceForecast(open, i))
array.set(predictiveClose, i, getSourceForecast(close, i))
// ~~~~~~~~ PLOTS ~~~~~~~~ //
//Draw the bars
if barstate.islast
for i = 0 to predictiveCount - 1
//draw
index = i + 1
lineHigh = line.new(bar_index + index, array.get(predictiveHigh, i), bar_index + i, array.get(predictiveHigh, i), color=color.green, width=1)
lineLow = line.new(bar_index + index, array.get(predictiveLow, i), bar_index + i, array.get(predictiveLow, i), color=color.red, width=1)
lineOpen = line.new(bar_index + index, array.get(predictiveOpen, i), bar_index + i, array.get(predictiveOpen, i), color=color.orange, width=1)
lineClose = line.new(bar_index + index, array.get(predictiveClose, i), bar_index + i, array.get(predictiveClose, i), color=color.teal, width=1)
//high zone
if array.get(predictiveClose, i) >= array.get(predictiveOpen, i)
linefill.new(lineClose, lineHigh, color=color.new(color.green, 95))
else
linefill.new(lineOpen, lineHigh, color=color.new(color.green, 95))
//low zone
if array.get(predictiveClose, i) < array.get(predictiveOpen, i)
linefill.new(lineClose, lineLow, color=color.new(color.red, 95))
else
linefill.new(lineOpen, lineLow, color=color.new(color.red, 95))
//Mid zone
lineColor = color.red
if i == 0
if array.get(predictiveClose, i) >= close
lineColor := color.green
else if (i != 0 and array.get(predictiveClose, i) >= array.get(predictiveClose, nz(i - 1)))
lineColor := color.green
linefill.new(lineOpen, lineClose, color=color.new(lineColor, 75))
// ~~~~~~~~ END ~~~~~~~~ // |
Tribute to David Paul | https://www.tradingview.com/script/xxO0M00v-Tribute-to-David-Paul/ | LOKEN94 | https://www.tradingview.com/u/LOKEN94/ | 126 | 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/
// © LOKEN94
// I made this indicator as a tribute to the late David Paul.
// He mentioned quite a lot about 89 periods moving average, also the 21 and 55.
//@version=5
indicator("Tribute to David Paul",shorttitle="MA",overlay=true,timeframe = "",timeframe_gaps = false)
ma21=ta.sma(close,21)
ma55=ta.sma(close,55)
ma89=ta.sma(close,89)
//
//
float BULL=0
if ma21<=close and ma55<=close and ma89<=close
BULL:=1
float BEAR=0
if ma21>close and ma55>close and ma89>close
BEAR:=1
//
float lowest_ma=ma89
if ma21<=ma55 and ma21<=ma89
lowest_ma:=ma21
if ma55<=ma21 and ma55<=ma89
lowest_ma:=ma55
//
float highest_ma=ma89
if ma21>=ma55 and ma21>=ma89
highest_ma:=ma21
if ma55>=ma21 and ma55>=ma89
highest_ma:=ma55
//
float IDEAL_LONG_ENTRY=na
if BULL==1 and BULL[1]==0
IDEAL_LONG_ENTRY:=low
//
float IDEAL_SHORT_ENTRY=na
if BEAR==1 and BEAR[1]==0
IDEAL_SHORT_ENTRY:=high
//
float REAL_LONG_ENTRY=na
if BULL==1 and BULL[1]==0
REAL_LONG_ENTRY:=highest_ma
//
float REAL_SHORT_ENTRY=na
if BEAR==1 and BEAR[1]==0
REAL_SHORT_ENTRY:=lowest_ma
//
iLP=ta.sma(IDEAL_LONG_ENTRY,1)
iSP=ta.sma(IDEAL_SHORT_ENTRY,1)
rLP=ta.sma(REAL_LONG_ENTRY,1)
rSP=ta.sma(REAL_SHORT_ENTRY,1)
float ilong=na
if BULL==1
ilong:=iLP
float ishort=na
if BEAR==1
ishort:=iSP
//
float rlong=na
if BULL==1
rlong:=rLP
float rshort=na
if BEAR==1
rshort:=rSP
//
IR=input.int(2,minval=-1,maxval=2,title="Show ideal entries rather than pragmatic ones.",tooltip="If -1, no entries zone will be displayed. If 0, entries will be ploted on the crossing level of the highest or lowest sma. If 1, entries will be ploted on high of the canlde that crossunder the lowest ma or low of the candle that crossover the highest. If 2, the two previous will be ploted, making an order block area.")
botdemand=plot(IR==1 or IR==2 ? ilong:na,"Ideal Long entry",color=color.blue,style=plot.style_linebr)
topsupply=plot(IR==1 or IR==2 ? ishort:na,"Ideal Short entry",color=color.red,style=plot.style_linebr)
topdemand=plot(IR==0 or IR==2 ? rlong:na,"Real Long entry",color=color.blue,style=plot.style_linebr)
botsupply=plot(IR==0 or IR==2 ? rshort:na,"Real Short entry",color=color.red,style=plot.style_linebr)
SDZ=input(true,title="Show Supply & Demand zone",tooltip="Previous setting need to be set on 2.")
fill(botdemand,topdemand,title="Fill Demand Zone",color=SDZ==true?color.rgb(33, 149, 243, 60):na)
fill(topsupply,botsupply,title="Fill Supply Zone",color=SDZ==true?color.rgb(255, 82, 82, 60):na)
//
ama=(ma21+ma55+ma89)/3
float AC=0
if close>ama
AC:=1
if close<ama
AC:=-1
//
float FLAT=na
if AC==1 and AC[1]!=1
FLAT:=ama
if AC==-1 and AC[1]!=-1
FLAT:=ama
//
float entries=rlong+rshort
if IR==true
entries:=ilong+ishort
//
float FLAT1=ta.sma(FLAT,1)
if FLAT1!=FLAT1[1]
FLAT1:=na
//
MA=input.int(4,minval=-1,maxval=5,title="Show ma",tooltip="If -1, no MA will be displayed. If 0, only sma21,sma55,sma89 will be. If 1, only AMA will be. If 2, the lowest ma in uptrend and the highest in downtrend, so the furthest. If 3, the highest ma in uptrend and the lowest in downtrend will be displayed, so the closest. If 4, all MA will be displayed. If 5, ma55 and ama will be displayed.")
plot(MA==1 or MA==4 or MA==5?ama:na,"AMA",color=ama<=close?color.rgb(0, 25, 45):color.rgb(10, 0, 0))
FA=plot(FLAT1,color=ama<=close?color.blue:color.red,style=plot.style_linebr,display=display.none,editable=false)
FHL=plot(hl2,display=display.none,editable=false)
fill(FA,FHL,color=ama<=close?(ilong==iLP?color.rgb(33, 149, 243, 80):color.rgb(19, 92, 151, 80)):(ishort==iSP?color.rgb(255, 82, 82, 80):color.rgb(155, 28, 28, 80)),title="Fill: trend based on AMA")
//
plot(MA==0 or MA==4?ma21:na,"sma21",color=ma21<=close?color.blue:color.red,transp=60)
plot(MA==0 or MA==4 or MA==5?ma55:na,"sma55",color=ma55<=close?color.blue:color.red,transp=60)
plot(MA==0 or MA==4?ma89:na,"sma89",color=ma89<=close?color.blue:color.red,transp=60)
plot((MA==3 and (BULL==1 or ama<=close)) or (MA==2 and (BEAR==1 or ama>=close))?highest_ma:na,"highest ma",color=highest_ma<=close?color.blue:color.red,transp=60,style=plot.style_linebr)
plot((MA==3 and (BEAR==1 or ama>=close)) or (MA==2 and (BULL==1 or ama<=close))?lowest_ma:na,"lowest ma",color=lowest_ma<=close?color.blue:color.red,transp=60,style=plot.style_linebr)
//
enableTrendColors = input(true, title='Enable sma based candles colors ?',group="Color Code settings :",tooltip="Color candles in blue/red if close is simultaneously above/below ma21, ma55, ma89, and in gray if not, generally meaning sideway.")
barcolor(enableTrendColors ? ilong==iLP ? #00e2ff99 : na : na, title='Bullish candle color')
barcolor(enableTrendColors ? ishort==iSP ? #ff000099 : na : na, title='Bearish candle color')
barcolor(enableTrendColors ? BULL==0 and BEAR==0 ? #84848d99 : na : na, title='Neutral candle color')
|
Daily Trend | https://www.tradingview.com/script/vndcKGWb-Daily-Trend/ | ZakiBrecht | https://www.tradingview.com/u/ZakiBrecht/ | 64 | 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/
// © matHodl
//@version=5
indicator("Daily Trend", overlay = true)
res = input.timeframe("D", "Time Frame Analysis", group = "Past Candle Price")
lb = input(1, "Bar Lookback", group = "Past Candle Price")
mid0 = request.security(syminfo.tickerid, res, hl2[lb])
showMid0 = input.bool(true, "M", group = "Past Candle Price", inline = "1")
res3 = request.security(syminfo.tickerid, res, high[lb])
showRes3 = input.bool(true, "R3", group = "Past Candle Price", inline = "2")
res2 = request.security(syminfo.tickerid, res, res3-((res3-mid0)/3))
showRes2 = input.bool(true, "R2", group = "Past Candle Price", inline = "2")
res1 = request.security(syminfo.tickerid, res, mid0+((res3-mid0)/3))
showRes1 = input.bool(true, "R2", group = "Past Candle Price", inline = "2")
sup3 = request.security(syminfo.tickerid, res, low[lb])
showSup3 = input.bool(true, "S3", group = "Past Candle Price", inline = "3")
sup2 = request.security(syminfo.tickerid, res, sup3+((mid0-sup3)/3))
showSup2 = input.bool(true, "S2", group = "Past Candle Price", inline = "3")
sup1 = request.security(syminfo.tickerid, res, mid0-((mid0-sup3)/3))
showSup1 = input.bool(true, "S1", group = "Past Candle Price", inline = "3")
res4 = request.security(syminfo.tickerid, res, res3+((res3-mid0)/3))
showRes4 = input.bool(true, "R4", group = "Past Candle Price", inline = "2")
sup4 = request.security(syminfo.tickerid, res, sup3-((mid0-sup3)/3))
showSup4 = input.bool(true, "S4", group = "Past Candle Price", inline = "3")
session = request.security(syminfo.tickerid, res, time[lb])
var label TF_close = na
var line line1 = na
var line line2 = na
var line line3 = na
var line line4 = na
var line line5 = na
var line line6 = na
var line line7 = na
var line line8 = na
var line line9 = na
if mid0 and showMid0
line1 := line.new(bar_index, mid0, bar_index + 10, mid0, color = color.blue, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line1[1])
plot(line.get_price(line1, bar_index), color = color.new(color.blue, 100))
if res1 and showRes1
line4 := line.new(bar_index, res1, bar_index + 10, res1, color = color.green, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line4[1])
plot(line.get_price(line4, bar_index), color = color.new(color.green, 100))
if res2 and showRes2
line3 := line.new(bar_index, res2, bar_index + 10, res2, color = color.green, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line3[1])
plot(line.get_price(line3, bar_index), color = color.new(color.green, 100))
if res3 and showRes3
line2 := line.new(bar_index, res3, bar_index + 10, res3, color = color.green, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line2[1])
plot(line.get_price(line2, bar_index), color = color.new(color.green, 100))
if res4 and showRes4
line8 := line.new(bar_index, res4, bar_index + 10, res4, color = color.green, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line8[1])
plot(line.get_price(line8, bar_index), color = color.new(color.green, 100))
if sup1 and showSup1
line7 := line.new(bar_index, sup1, bar_index + 10, sup1, color = color.red, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line7[1])
plot(line.get_price(line7, bar_index), color = color.new(color.red, 100))
if sup2 and showSup2
line6 := line.new(bar_index, sup2, bar_index + 10, sup2, color = color.red, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line6[1])
plot(line.get_price(line6, bar_index), color = color.new(color.red, 100))
if sup3 and showSup3
line5 := line.new(bar_index, sup3, bar_index + 10, sup3, color = color.red, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line5[1])
plot(line.get_price(line5, bar_index), color = color.new(color.red, 100))
if sup4 and showSup4
line9 := line.new(bar_index, sup4, bar_index + 10, sup4, color = color.red, style = line.style_dotted, extend = extend.left, width = 2)
line.delete(line9[1])
plot(line.get_price(line9, bar_index), color = color.new(color.red, 100))
linefill.new(line2, line8, color = color.new(color.green, 90))
linefill.new(line5, line9, color = color.new(color.red, 90))
//=====Supertrend=====//
atrPeriod = input(10, "ATR Length", group = "SUPERTREND")
factor = input.float(3.0, "Factor", step = 0.01, group = "SUPERTREND")
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
//LTF
resLTF = input.timeframe("15", "LTF Analysis", group = "SUPERTREND")
lbm = request.security(syminfo.tickerid, resLTF, hl2)
lut = request.security(syminfo.tickerid, resLTF, direction < 0 ? supertrend : na)
ldt = request.security(syminfo.tickerid, resLTF, direction < 0? na : supertrend)
lowBodyMiddle = plot(lbm, display = display.none)
lowUpTrend = plot(lut, "Up Trend", color = color.green, style = plot.style_linebr, display = display.none)
lowDownTrend = plot(ldt, "Down Trend", color = color.red, style = plot.style_linebr, display = display.none)
fill(lowBodyMiddle, lowUpTrend, color.new(color.green, 80), fillgaps = false, display = display.none)
fill(lowBodyMiddle, lowDownTrend, color.new(color.red, 80), fillgaps = false, display = display.none)
upLTF = request.security(syminfo.tickerid, resLTF, direction < 0)
downLTF = request.security(syminfo.tickerid, resLTF, direction > 0)
//HTF
resHTF = input.timeframe("60", "HTF Analysis", group = "SUPERTREND")
hbm = request.security(syminfo.tickerid, resHTF, hl2)
hut = request.security(syminfo.tickerid, resHTF, direction < 0 ? supertrend : na)
hdt = request.security(syminfo.tickerid, resHTF, direction < 0? na : supertrend)
highBodyMiddle = plot(hbm, display = display.none)
highUpTrend = plot(hut, "Up Trend", color = color.green, style = plot.style_linebr, display = display.none)
highDownTrend = plot(hdt, "Down Trend", color = color.red, style = plot.style_linebr, display = display.none)
fill(highBodyMiddle, highUpTrend, color.new(color.green, 80), fillgaps = false)
fill(highBodyMiddle, highDownTrend, color.new(color.red, 80), fillgaps = false)
upHTF = request.security(syminfo.tickerid, resHTF, direction < 0)
downHTF = request.security(syminfo.tickerid, resHTF, direction > 0)
up = request.security(syminfo.tickerid, resLTF, ta.change(direction) < 0) and upHTF
down = request.security(syminfo.tickerid, resLTF, ta.change(direction) > 0) and downHTF
plotshape(up, "Up", style = shape.triangleup, textcolor = color.white, color = color.green, size = size.tiny, location = location.belowbar)
plotshape(down, "Down", style = shape.triangledown,textcolor = color.white, color = color.red, size = size.tiny, location = location.abovebar)
var line lineEntry = na
if up
lineEntry := line.new(bar_index, high, bar_index + 1, high, color = color.blue, style = line.style_dotted, extend = extend.right, width = 2)
line.delete(lineEntry[1])
if down
lineEntry := line.new(bar_index, low, bar_index + 1, low, color = color.blue, style = line.style_dotted, extend = extend.right, width = 2)
line.delete(lineEntry[1])
plot(line.get_price(lineEntry, bar_index), color = color.new(color.blue, 100))
barcolor(upHTF ? color.lime : downHTF ? color.red : na) |
Supertrend Targets [ChartPrime] | https://www.tradingview.com/script/SqWrqra4-Supertrend-Targets-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 388 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Supertrend Targets [ChartPrime]", explicit_plot_zorder = true, overlay = true)
source = input.string("HLCC4", "Source", ["Smooth", "Close", "Open", "High", "Low", "Hl2", "HLC3", "OHLC4", "HLCC4"])
stop = input.bool(true, "Show Trailing Stop")
show = input.int(-4, "Levels", minval = -5, maxval = 5)
scale = input.int(80, "Scale", minval = 1, maxval = 100) / 100
window = input.int(0, "Window Length", minval = 0)
unique = input.bool(false, "Unique", "Make sure every data point is unique.")
mult = input.float(3, "Multiplier", minval = 0)
atr = input.int(10, "ATR Length", minval = 1)
average = input.string("Disabled", "Custom Level", ["Average", "Average + STDEV", "Percentile", "Disabled"])
rank = input.int(75, "Percent Rank", minval = 0, maxval = 100)
enable = input.bool(false, "Enable Table")
style = input.string("Bottom Right", "Position",
["Bottom Left","Bottom Middle","Bottom Right","Middle Left","Middle Center","Middle Right",
"Top Left","Top Middle","Top Right"])
type trend
float value
bool state
type risk
float gain
float drawdown
float average_gain
float average_drawdown
float gain_stdev
float drawdown_stdev
float entry
location() =>
switch style
"Bottom Left" => position.bottom_left
"Bottom Middle" => position.bottom_center
"Bottom Right" => position.bottom_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Top Left" => position.top_left
"Top Middle" => position.top_center
"Top Right" => position.top_right
percent(current, previous)=>
(current - previous)/previous
add_percent(source, percent)=>
source * (1 + percent)
logistic(source, bandwidth) =>
1 / (math.exp(source / bandwidth) + 2 + math.exp(-source / bandwidth))
logistic_kernel(source, size = 256, h = 4, r = 0.5) =>
float weight = 0
float weight_sum = 0
for i = 0 to size
src = source[i]
k = math.pow(i, 2) / (math.pow(h, 2) * r)
w = logistic(k, r)
weight := weight + src * w
weight_sum := weight_sum + w
weight / weight_sum
sinc(source, bandwidth) =>
if source == 0
1
else
math.sin(math.pi * source / bandwidth) / (math.pi * source / bandwidth)
sinc_kernel(source, size = 64, h = 4, r = 0.5) =>
float weight = 0
float weight_sum = 0
for i = 0 to size
src = source[i]
k = math.pow(i, 2) / (math.pow(h, 2) * r)
w = sinc(k, r)
weight := weight + src * w
weight_sum := weight_sum + w
weight / weight_sum
supertrend(src, factor, atrPeriod) =>
atr = ta.atr(atrPeriod)
upper_band = src + factor * atr
lower_band = src - factor * atr
prev_lower_band = nz(lower_band[1])
prev_upper_band = nz(upper_band[1])
lower_band := lower_band > prev_lower_band or hl2[1] < prev_lower_band ? lower_band : prev_lower_band
upper_band := upper_band < prev_upper_band or hl2[1] > prev_upper_band ? upper_band : prev_upper_band
bool direction = na
float super_trend = na
prev_super_trend = super_trend[1]
if na(atr[1])
direction := true
else if prev_super_trend == prev_upper_band
direction := hl2 > upper_band ? false : true
else
direction := hl2 < lower_band ? true : false
super_trend := not direction ? lower_band : upper_band
trend.new(super_trend, direction)
method flag(trend self, bool direction)=>
bullish = self.state != self.state[1] and not self.state
bearish = self.state != self.state[1] and self.state
switch direction
true => bullish
false => bearish
method target_percent(trend self, int window, int rank)=>
var bullish_target = array.new<float>()
var bearish_target = array.new<float>()
var bullish_drawdown = array.new<float>()
var bearish_drawdown = array.new<float>()
var high_prices = array.new<float>()
var low_prices = array.new<float>()
array.push(high_prices, high)
array.push(low_prices, low)
var float entry = close
if self.flag(true)
//if close < entry
percent_target = percent(array.min(low_prices), entry)
percent_drawdown = percent(array.max(high_prices), entry)
if not array.includes(bearish_target, percent_target) and unique
array.unshift(bearish_target, percent_target)
else
array.unshift(bearish_target, percent_target)
if not array.includes(bearish_drawdown, percent_drawdown) and unique
array.unshift(bearish_drawdown, percent_drawdown)
else
array.unshift(bearish_drawdown, percent_drawdown)
array.clear(low_prices)
array.clear(high_prices)
entry := close
if self.flag(false)
//if close > entry
percent_target = percent(array.max(high_prices), entry)
percent_drawdown = percent(array.min(low_prices), entry)
if not array.includes(bullish_target, percent_target)
array.unshift(bullish_target, percent_target)
if not array.includes(bullish_drawdown, percent_drawdown)
array.unshift(bullish_drawdown, percent_drawdown)
array.clear(high_prices)
array.clear(low_prices)
entry := close
if array.size(bullish_target) > window and window > 0
array.pop(bullish_target)
array.pop(bullish_drawdown)
if array.size(bearish_target) > window and window > 0
array.pop(bearish_target)
array.pop(bearish_drawdown)
if self.state
risk.new(
add_percent(entry, array.percentile_linear_interpolation(bearish_target, 100 - rank)),
add_percent(entry, array.percentile_linear_interpolation(bearish_drawdown, rank)),
add_percent(entry, array.avg(bearish_target)),
add_percent(entry, array.avg(bearish_drawdown)),
array.stdev(bearish_target),
array.stdev(bearish_drawdown),
entry)
else
risk.new(
add_percent(entry, array.percentile_linear_interpolation(bullish_target, rank)),
add_percent(entry, array.percentile_linear_interpolation(bullish_drawdown, 100 - rank)),
add_percent(entry, array.avg(bullish_target)),
add_percent(entry, array.avg(bullish_drawdown)),
array.stdev(bullish_target),
array.stdev(bullish_drawdown),
entry)
method value_percent(trend self)=>
var float entry = close
if self.flag(true)
entry := close
if self.flag(false)
entry := close
percent(close, entry)
avg = logistic_kernel(sinc_kernel(hlc3, 16, 1.5, 1.5), 16, 1.5, 1.5)
source_switch = switch source
"Smooth" => avg
"Close" => close
"Open" => open
"High" => high
"Low" => low
"Hl2" => hl2
"HLC3" => hlc3
"OHLC4" => ohlc4
"HLCC4" => hlcc4
super_trend = supertrend(source_switch, mult, atr)
custom_rank = super_trend.target_percent(window, rank)
target_25 = super_trend.target_percent(window, 25 * scale)
target_50 = super_trend.target_percent(window, 50 * scale)
target_75 = super_trend.target_percent(window, 75 * scale)
target_90 = super_trend.target_percent(window, 90 * scale)
target_100 = super_trend.target_percent(window, 100 * scale)
custom_gain = str.contains(average, "Average") ? target_50.average_gain : custom_rank.gain
custom_drawdown = str.contains(average, "Average") ? target_50.average_drawdown : custom_rank.drawdown
signal = super_trend.value_percent()
colour = super_trend.state ? (signal > 0 ? color.red : color.green) : (signal > 0 ? color.green : color.red)
target_50_average_gain = plot(average != "Disabled" ? custom_gain : na, "Average Gain", color.new(color.blue, 25), 3, plot.style_steplinebr)
target_50_average_gain_stdev = plot(average == "Average + STDEV" ? add_percent(custom_gain, super_trend.state ? -target_50.gain_stdev : target_50.gain_stdev) : na, "STDEV Gains", color.new(color.blue, 70), 2, plot.style_steplinebr)
target_50_average_drawdown = plot(average != "Disabled" ? custom_drawdown : na, "Average Drawdown", color.new(color.purple, 25), 3, plot.style_steplinebr)
target_50_average_drawdown_stdev = plot(average == "Average + STDEV" ? add_percent(custom_drawdown, super_trend.state ? target_50.drawdown_stdev : -target_50.drawdown_stdev) : na, "STDEV Drawdown", color.new(color.purple, 70), 2, plot.style_steplinebr)
target_100_gain = plot(show >= 5 and show > 0 or show <= -1 ? target_100.gain : na, "Gain 100th", color.new(color.green, 70), 2, plot.style_steplinebr)
target_100_drawdown = plot(show >= 5 and show > 0 or show <= -1 ? target_100.drawdown : na, "Drawdown 100th", color.new(color.red, 70), 2, plot.style_steplinebr)
target_90_gain = plot(show >= 4 and show > 0 or show <= -2 ? target_90.gain : na, "Gain 90th", color.new(color.green, 60), 2, plot.style_steplinebr)
target_90_drawdown = plot(show >= 4 and show > 0 or show <= -2 ? target_90.drawdown : na, "Drawdown 90th", color.new(color.red, 60), 2, plot.style_steplinebr)
target_75_drawdown = plot(show >= 3 and show > 0 or show <= -3 ? target_75.drawdown : na, "Drawdown 75th", color.new(color.red, 50), 2, plot.style_steplinebr)
target_75_gain = plot(show >= 3 and show > 0 or show <= -3 ? target_75.gain : na, "Gain 75th", color.new(color.green, 50), 2, plot.style_steplinebr)
target_50_gain = plot(show >= 2 and show > 0 or show <= -4 ? target_50.gain : na, "Gain 50th", color.new(color.green, 40), 2, plot.style_steplinebr)
target_50_drawdown = plot(show >= 2 and show > 0 or show <= -4 ? target_50.drawdown : na, "Drawdown 50th", color.new(color.red, 40), 2, plot.style_steplinebr)
target_25_drawdown = plot(show >= 1 and show > 0 or show <= -5 ? target_25.drawdown : na, "Drawdown 25th", color.new(color.red, 30), 2, plot.style_steplinebr)
target_25_gain = plot(show >= 1 and show > 0 or show <= -5 ? target_25.gain : na, "Gain 25th", color.new(color.green, 30), 2, plot.style_steplinebr)
center_line = plot(target_25.entry, "Center Line", color.gray)
super_trend_line_bullish = plot(stop and not super_trend.state ? super_trend.value : na, "Super Trend BUllish", color.blue, 2, plot.style_linebr)
super_trend_line_bearish = plot(stop and super_trend.state ? super_trend.value : na, "Super Trend Bearish", color.orange, 2, plot.style_linebr)
alpha_red = color.new(color.red, 98)
alpha_green = color.new(color.green, 98)
fill(target_100_gain, center_line, alpha_green)
fill(target_90_gain, center_line, alpha_green)
fill(target_75_gain, center_line, alpha_green)
fill(target_50_gain, center_line, alpha_green)
fill(target_25_gain, center_line, alpha_green)
fill(target_100_drawdown, center_line, alpha_red)
fill(target_90_drawdown, center_line, alpha_red)
fill(target_75_drawdown, center_line, alpha_red)
fill(target_50_drawdown, center_line, alpha_red)
fill(target_25_drawdown, center_line, alpha_red)
fill(target_50_average_gain, center_line, color.new(color.blue, 90))
fill(target_50_average_drawdown, center_line, color.new(color.purple, 90))
fill(target_50_average_gain_stdev, target_50_average_gain, color.new(color.blue, 95))
fill(target_50_average_drawdown_stdev, target_50_average_drawdown, color.new(color.purple, 95))
tbl = table.new(location(), 4, 7, color.black, color.black, 1, color.black, 1)
if enable
table.cell_set_text(tbl, 0, 0, "Percentile")
table.cell_set_text_color(tbl, 0, 0, color.white)
table.cell_set_text(tbl, 1, 0, "Risk Ratio")
table.cell_set_text_color(tbl, 1, 0, color.white)
table.cell_set_text(tbl, 2, 0, "Take Profit")
table.cell_set_text_color(tbl, 2, 0, color.white)
table.cell_set_text(tbl, 3, 0, "Stop Loss")
table.cell_set_text_color(tbl, 3, 0, color.white)
if (show >= 1 and show > 0) or (show <= -5 and show < 0)
table.cell_set_text(tbl, 0, 1, str.tostring(math.round(25 * scale, 2)) + "'th")
table.cell_set_text_color(tbl, 0, 1, color.white)
table.cell_set_text(tbl, 1, 1, str.tostring(math.round(math.abs(target_25.gain - target_100.entry) / math.abs(target_25.drawdown - target_100.entry), 2)))
table.cell_set_text_color(tbl, 1, 1, color.white)
table.cell_set_text(tbl, 2, 1, str.tostring(math.round_to_mintick(math.abs(target_25.gain))))
table.cell_set_text_color(tbl, 2, 1, color.white)
table.cell_set_text(tbl, 3, 1, str.tostring(math.round_to_mintick(math.abs(target_25.drawdown))))
table.cell_set_text_color(tbl, 3, 1, color.white)
if (show >= 2 and show > 0) or (show <= -4 and show < 0)
table.cell_set_text(tbl, 0, 2, str.tostring(math.round(50 * scale, 2)) + "'th")
table.cell_set_text_color(tbl, 0, 2, color.white)
table.cell_set_text(tbl, 1, 2, str.tostring(math.round(math.abs(target_50.gain - target_100.entry) / math.abs(target_50.drawdown - target_100.entry), 2)))
table.cell_set_text_color(tbl, 1, 2, color.white)
table.cell_set_text(tbl, 2, 2, str.tostring(math.round_to_mintick(math.abs(target_50.gain))))
table.cell_set_text_color(tbl, 2, 2, color.white)
table.cell_set_text(tbl, 3, 2, str.tostring(math.round_to_mintick(math.abs(target_50.drawdown))))
table.cell_set_text_color(tbl, 3, 2, color.white)
if (show >= 3 and show > 0) or (show <= -3 and show < 0)
table.cell_set_text(tbl, 0, 3, str.tostring(math.round(75 * scale, 2)) + "'th")
table.cell_set_text_color(tbl, 0, 3, color.white)
table.cell_set_text(tbl, 1, 3, str.tostring(math.round(math.abs(target_75.gain - target_100.entry) / math.abs(target_75.drawdown - target_100.entry), 2)))
table.cell_set_text_color(tbl, 1, 3, color.white)
table.cell_set_text(tbl, 2, 3, str.tostring(math.round_to_mintick(math.abs(target_75.gain))))
table.cell_set_text_color(tbl, 2, 3, color.white)
table.cell_set_text(tbl, 3, 3, str.tostring(math.round_to_mintick(math.abs(target_75.drawdown))))
table.cell_set_text_color(tbl, 3, 3, color.white)
if (show >= 4 and show > 0) or (show <= -2 and show < 0)
table.cell_set_text(tbl, 0, 4, str.tostring(math.round(90 * scale, 2)) + "'th")
table.cell_set_text_color(tbl, 0, 4, color.white)
table.cell_set_text(tbl, 1, 4, str.tostring(math.round(math.abs(target_90.gain - target_100.entry) / math.abs(target_90.drawdown - target_100.entry), 2)))
table.cell_set_text_color(tbl, 1, 4, color.white)
table.cell_set_text(tbl, 2, 4, str.tostring(math.round_to_mintick(math.abs(target_90.gain))))
table.cell_set_text_color(tbl, 2, 4, color.white)
table.cell_set_text(tbl, 3, 4, str.tostring(math.round_to_mintick(math.abs(target_90.drawdown))))
table.cell_set_text_color(tbl, 3, 4, color.white)
if (show >= 5 and show > 0) or (show <= -1 and show < 0)
table.cell_set_text(tbl, 0, 5, str.tostring(math.round(100 * scale, 2)) + "'th")
table.cell_set_text_color(tbl, 0, 5, color.white)
table.cell_set_text(tbl, 1, 5, str.tostring(math.round(math.abs(target_100.gain - target_100.entry) / math.abs(target_100.drawdown - target_100.entry), 2)))
table.cell_set_text_color(tbl, 1, 5, color.white)
table.cell_set_text(tbl, 2, 5, str.tostring(math.round_to_mintick(math.abs(target_100.gain))))
table.cell_set_text_color(tbl, 2, 5, color.white)
table.cell_set_text(tbl, 3, 5, str.tostring(math.round_to_mintick(math.abs(target_100.drawdown))))
table.cell_set_text_color(tbl, 3, 5, color.white)
if average != "Disabled"
table.cell_set_text(tbl, 0, 6, str.contains(average, "Average") ? "Average" : average == "Percentile" ? str.tostring(rank) + "'th" : "")
table.cell_set_text_color(tbl, 0, 6, color.white)
table.cell_set_text(tbl, 1, 6, str.tostring(math.round(math.abs(custom_gain - target_100.entry) / math.abs(custom_drawdown - target_100.entry), 2)))
table.cell_set_text_color(tbl, 1, 6, color.white)
table.cell_set_text(tbl, 2, 6, str.tostring(math.round_to_mintick(math.abs(custom_gain))))
table.cell_set_text_color(tbl, 2, 6, color.white)
table.cell_set_text(tbl, 3, 6, str.tostring(math.round_to_mintick(math.abs(custom_drawdown))))
table.cell_set_text_color(tbl, 3, 6, color.white)
|
Tetra Trendline Indicator 2.0 | https://www.tradingview.com/script/9WNHoldF/ | egghen | https://www.tradingview.com/u/egghen/ | 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/
// © egghen
//@version=5
indicator(title='Tetra Trendline Indicator 2.0', shorttitle='TTLI 2.0', overlay=true)
// Define input parameters for trendlines
showTrendline1 = input(true, title='Show Trendline 1')
trendlineColor1 = input(color.blue, title='Trendline 1 Color')
trendlineWidth1 = input(1, title='Trendline 1 Width')
trendlineLength1 = input(100, title='Trendline 1 Length')
alertOnTrendline1Break = input(true, title='Alert on Trendline 1 Break')
showTrendline2 = input(true, title='Show Trendline 2')
trendlineColor2 = input(color.red, title='Trendline 2 Color')
trendlineWidth2 = input(1, title='Trendline 2 Width')
trendlineLength2 = input(150, title='Trendline 2 Length')
alertOnTrendline2Break = input(true, title='Alert on Trendline 2 Break')
showTrendline3 = input(true, title='Show Trendline 3')
trendlineColor3 = input(color.green, title='Trendline 3 Color')
trendlineWidth3 = input(1, title='Trendline 3 Width')
trendlineLength3 = input(200, title='Trendline 3 Length')
alertOnTrendline3Break = input(true, title='Alert on Trendline 3 Break')
showTrendline4 = input(true, title='Show Trendline 4')
trendlineColor4 = input(color.orange, title='Trendline 4 Color')
trendlineWidth4 = input(1, title='Trendline 4 Width')
trendlineLength4 = input(250, title='Trendline 4 Length')
alertOnTrendline4Break = input(true, title='Alert on Trendline 4 Break')
// Calculate trendline coordinates for Trendline 1
var float tl1_x1 = na
var float tl1_y1 = na
var float tl1_x2 = na
var float tl1_y2 = na
if showTrendline1
tl1_x1 := bar_index - trendlineLength1
tl1_y1 := ta.lowest(low, trendlineLength1)
tl1_x2 := bar_index
tl1_y2 := ta.lowest(low, 1)
tl1_y2
// Calculate trendline coordinates for Trendline 2
var float tl2_x1 = na
var float tl2_y1 = na
var float tl2_x2 = na
var float tl2_y2 = na
if showTrendline2
tl2_x1 := bar_index - trendlineLength2
tl2_y1 := ta.highest(high, trendlineLength2)
tl2_x2 := bar_index
tl2_y2 := ta.highest(high, 1)
tl2_y2
// Calculate trendline coordinates for Trendline 3
var float tl3_x1 = na
var float tl3_y1 = na
var float tl3_x2 = na
var float tl3_y2 = na
if showTrendline3
tl3_x1 := bar_index - trendlineLength3
tl3_y1 := ta.lowest(low, trendlineLength3)
tl3_x2 := bar_index
tl3_y2 := ta.lowest(low, 1)
tl3_y2
// Calculate trendline coordinates for Trendline 4
var float tl4_x1 = na
var float tl4_y1 = na
var float tl4_x2 = na
var float tl4_y2 = na
if showTrendline4
tl4_x1 := bar_index - trendlineLength4
tl4_y1 := ta.highest(high, trendlineLength4)
tl4_x2 := bar_index
tl4_y2 := ta.highest(high, 1)
tl4_y2
// Plot trendlines using plot function
plot1 = plot(showTrendline1 ? tl1_y1 : na, title='Trendline 1', color=trendlineColor1, linewidth=trendlineWidth1)
plot2 = plot(showTrendline2 ? tl2_y1 : na, title='Trendline 2', color=trendlineColor2, linewidth=trendlineWidth2)
plot3 = plot(showTrendline3 ? tl3_y1 : na, title='Trendline 3', color=trendlineColor3, linewidth=trendlineWidth3)
plot4 = plot(showTrendline4 ? tl4_y1 : na, title='Trendline 4', color=trendlineColor4, linewidth=trendlineWidth4)
// Fill the area between trendlines (optional)
plot(showTrendline1 ? tl1_y1 : na, color=color.new(color.gray, 80), style=plot.style_histogram, linewidth=0)
plot(showTrendline2 ? tl2_y1 : na, color=color.new(color.gray, 80), style=plot.style_histogram, linewidth=0)
plot(showTrendline3 ? tl3_y1 : na, color=color.new(color.gray, 80), style=plot.style_histogram, linewidth=0)
plot(showTrendline4 ? tl4_y1 : na, color=color.new(color.gray, 80), style=plot.style_histogram, linewidth=0)
// Alert conditions for Trendline 1 break
alertcondition(alertOnTrendline1Break and ta.crossover(high, tl1_y1), title='Alert: Trendline 1 Break (Overbought)', message='Trendline 1 has been breached from below (Overbought)')
// Alert conditions for Trendline 2 break
alertcondition(alertOnTrendline2Break and ta.crossunder(low, tl2_y1), title='Alert: Trendline 2 Break (Oversold)', message='Trendline 2 has been breached from above (Oversold)')
// Alert conditions for Trendline 3 break
alertcondition(alertOnTrendline3Break and ta.crossover(high, tl3_y1), title='Alert: Trendline 3 Break (Overbought)', message='Trendline 3 has been breached from below (Overbought)')
// Alert conditions for Trendline 4 break
alertcondition(alertOnTrendline4Break and ta.crossunder(low, tl4_y1), title='Alert: Trendline 4 Break (Oversold)', message='Trendline 4 has been breached from above (Oversold)')
// end code |
Weighted Oscillator Convergence Divergence | https://www.tradingview.com/script/JAZ2GOdu-Weighted-Oscillator-Convergence-Divergence/ | tseddik | https://www.tradingview.com/u/tseddik/ | 38 | 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/
// © tseddik
//@version=5
indicator(title="Weighted Oscillator Convergence Divergence", shorttitle="WOCD", overlay=false, timeframe = '', timeframe_gaps = true)
// Inputs
length = input(9, title="Length")
smooth1 = input(5, title="Smoothing 1")
smooth2 = input(7, title="Smoothing 2")
maTypeInput = input.string("Weighted", title="MA Type", options=["Weighted","NonLag","Wilder"])
src = input.source(close, title= "source")
oscDiff = input(9, title="0sc Diff")
col_length = input(#2962FF, "Length ", group="Color Settings", inline="Length")
col_smooth1 = input(#FF6D00, "Smooth1 ", group="Color Settings", inline="Smooth1")
col_smooth2 = input(#ff00d4, "Smooth2 ", group="Color Settings", inline="Smooth2")
col_grow_above = input(#00ffe5, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#b2dcdf, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#ffcdf0, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#ff52bd, "Fall", group="Histogram", inline="Below")
nonLagEMA(src, length) =>
alpha = 2 / (length + 1)
nonLag = 0.0
nonLag := alpha * src + (1 - alpha) * ta.ema(src, length)
nonLag
Wild_ma(_src, _malength) =>
_wild = 0.0
_wild := nz(_wild[1]) + (_src - nz(_wild[1])) / _malength
_wild
ma(source, length, type) =>
switch type
"NonLag" => nonLagEMA(source, length)
"Wilder" => Wild_ma(source, length)
"Weighted" => ta.wma(source, length)
// Calculate raw oscillator value
diff = close - src[length]
smoothedOscillator = ma(diff, oscDiff, maTypeInput)
// Apply smoothing
smoothedValue1 = ta.ema(smoothedOscillator, smooth1)
smoothedValue2 = ta.sma(smoothedOscillator, smooth2)
hist = smoothedOscillator - smoothedValue1
// Plot oscillator and smoothed values
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(smoothedOscillator, color=col_length, title="WOCD Line")
plot(smoothedValue1, color=col_smooth1, title="Smoothed EMA")
plot(smoothedValue2, color=col_smooth2, title="Smoothed SMA")
// Plot zero line
hline(0, "Zero Line", color=color.gray) |
Fibonacci Ranges (Real-Time) [LuxAlgo] | https://www.tradingview.com/script/td8l5rTE-Fibonacci-Ranges-Real-Time-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,470 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Fibonacci Ranges (Real-Time) [LuxAlgo]", shorttitle='LuxAlgo - Fibonacci Ranges (Real-Time)', max_lines_count=500, max_labels_count=500, overlay=true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
z = ' '
y = ' '
x = ' '
L = input.int ( 5 , 'L' , minval =1 , group = 'Swing Settings' )
R = input.int ( 1 , 'R' , minval =1 , group = 'Swing Settings' )
c_ = input.string( 'Channel + Shadows' , 'Channel' , options=['Channel', 'Channel + Shadows', 'None'], group = 'Fibonacci Channel' )
opt= input.string('0.000 - 1.000', 'Break level' , group = 'Fibonacci Channel'
, options= ['-0.382 - 1.382', '0.000 - 1.000', '0.236 - 0.764', '0.382 - 0.618'] )
c = input.int ( 2 , 'Break count' , minval =0 , group = 'Fibonacci Channel' )
sb = input.bool ( true , z+x+ 'Show breaks' , group = 'Fibonacci Channel' )
sF = input.bool ( false , z+y+ 'Latest Fibonacci' , group = 'Fibonacci' )
F0 = input.color ( #08998164 , ' ' , inline='f' , group = 'Fibonacci' )
F_ = input.color ( #08998180 , '' , inline='f' , group = 'Fibonacci' )
Fm = input.color ( #1e42b070 , '' , inline='f' , group = 'Fibonacci' )
Fp = input.color ( #f2364580 , '' , inline='f' , group = 'Fibonacci' )
F1 = input.color ( #f2364564 , '' , inline='f' , group = 'Fibonacci' )
Fc = c_ != 'None' ? true : false
fl = c_ == 'Channel + Shadows' ? true : false
n = bar_index
//-----------------------------------------------------------------------------}
//User Defined Types
//-----------------------------------------------------------------------------{
type piv
int b
float p
int d
type fib
line n0_382
line _0_000
line _0_236
line _0_382
line _0_500
line _0_618
line _0_764
line _1_000
line _1_382
line diagon
label lab1
label lab2
bool active
int count
type fibLast
linefill lf_0
linefill lfM0
linefill lfM1
linefill lf_1
line ln_0_5
line diagon
label lab
//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
var piv[] pivs = array.new<piv>()
var f = fib .new (
n0_382 = line.new (na, na, na, na, color=F0),
_0_000 = line.new (na, na, na, na, color=F0),
_0_236 = line.new (na, na, na, na, color=F_),
_0_382 = line.new (na, na, na, na, color=F_),
_0_500 = line.new (na, na, na, na, color=Fm),
_0_618 = line.new (na, na, na, na, color=Fp),
_0_764 = line.new (na, na, na, na, color=Fp),
_1_000 = line.new (na, na, na, na, color=F1),
_1_382 = line.new (na, na, na, na, color=F1),
lab1 = label.new(na, na , color=color.gray
,style= label.style_label_center
, yloc= yloc.price , size= size.tiny),
lab2 = label.new(na, na , color=color.gray
,style= label.style_label_center
, yloc= yloc.price , size= size.tiny),
diagon = line.new (na, na, na, na
,color=color.silver ,style=line.style_dashed),
active = false, count = 0
)
var fibLast fLast = fibLast.new(
lf_0 = linefill.new(
line .new(na, na, na, na, color=F0)
, line .new(na, na, na, na, color=F0)
, color .new(F0, 75)
),
lfM0 = linefill.new(
line .new(na, na, na, na, color=F_)
, line .new(na, na, na, na, color=F_)
, color .new(F_, 75)
),
lfM1 = linefill.new(
line .new(na, na, na, na, color=Fp)
, line .new(na, na, na, na, color=Fp)
, color .new(Fp, 75)
),
lf_1 = linefill.new(
line .new(na, na, na, na, color=F1)
, line .new(na, na, na, na, color=F1)
, color .new(F1, 75)
),
ln_0_5 = line.new(na, na, na, na, color=color.blue ),
diagon = line.new(na, na, na, na, color=color.silver
, style=line.style_dashed),
lab = label.new( na, na , color=color.gray )
)
var line ln = line.new(na, na, na, na)
bool brokeU = false
bool brokeD = false
//-----------------------------------------------------------------------------}
//Execution
//-----------------------------------------------------------------------------{
ph = ta.pivothigh(L, R)
pl = ta.pivotlow (L, R)
a1 = switch opt
'-0.382 - 1.382' => -0.382
'0.000 - 1.000' => 0
'0.236 - 0.764' => 0.236
'0.382 - 0.618' => 0.382
a2 = switch opt
'-0.382 - 1.382' => 1.382
'0.000 - 1.000' => 1
'0.236 - 0.764' => 0.764
'0.382 - 0.618' => 0.618
if ph
if pivs.size() > 0
get = pivs.first()
if get.d > 0 and ph > get.p
get.b := n -R
get.p := high[R]
if get.d < 0 and ph > get.p
pivs.unshift(piv.new(n -R, high[R] , 1))
else
pivs .unshift(piv.new(n -R, high[R] , 1))
if pivs.size() > 1 and not f.active and Fc
get1 = pivs.get(1) , idx1 = get1.b , diff = high[R] - get1.p
f.n0_382.set_xy1(n -R, high[R] + (diff * 0.382)), f.n0_382.set_xy2(n + 8, high[R] + (diff * 0.382))
f._0_000.set_xy1(n -R, high[R] ), f._0_000.set_xy2(n + 8, high[R] )
f._0_236.set_xy1(n -R, high[R] - (diff * 0.236)), f._0_236.set_xy2(n + 8, high[R] - (diff * 0.236))
f._0_382.set_xy1(n -R, high[R] - (diff * 0.382)), f._0_382.set_xy2(n + 8, high[R] - (diff * 0.382))
f._0_500.set_xy1(n -R, high[R] - (diff * 0.500)), f._0_500.set_xy2(n + 8, high[R] - (diff * 0.500))
f._0_618.set_xy1(n -R, high[R] - (diff * 0.618)), f._0_618.set_xy2(n + 8, high[R] - (diff * 0.618))
f._0_764.set_xy1(n -R, high[R] - (diff * 0.764)), f._0_764.set_xy2(n + 8, high[R] - (diff * 0.764))
f._1_000.set_xy1(n -R, get1.p ), f._1_000.set_xy2(n + 8, get1.p )
f._1_382.set_xy1(n -R, get1.p - (diff * 0.382)), f._1_382.set_xy2(n + 8, get1.p - (diff * 0.382))
f.lab1 .set_xy (n +8, high[R] - (diff * a1 )), f.lab2 .set_xy (n + 8, high[R] - (diff * a2 ))
f.diagon.set_xy1(idx1, get1.p ), f.diagon.set_xy2(n -R, high[R] )
f.active := true
if pl
if pivs.size() > 0
get = pivs.first()
if get.d < 0 and pl < get.p
get.b := n -R
get.p := low [R]
if get.d > 0 and pl < get.p
pivs.unshift(piv.new(n -R, low [R] ,-1))
else
pivs .unshift(piv.new(n -R, low [R] ,-1))
if pivs.size() > 1 and not f.active and Fc
get1 = pivs.get(1) , idx1 = get1.b , diff = get1.p - low [R]
f.n0_382.set_xy1(n -R, low [R] - (diff * 0.382)), f.n0_382.set_xy2(n + 8, low [R] - (diff * 0.382))
f._0_000.set_xy1(n -R, low [R] ), f._0_000.set_xy2(n + 8, low [R] )
f._0_236.set_xy1(n -R, low [R] + (diff * 0.236)), f._0_236.set_xy2(n + 8, low [R] + (diff * 0.236))
f._0_382.set_xy1(n -R, low [R] + (diff * 0.382)), f._0_382.set_xy2(n + 8, low [R] + (diff * 0.382))
f._0_500.set_xy1(n -R, low [R] + (diff * 0.500)), f._0_500.set_xy2(n + 8, low [R] + (diff * 0.500))
f._0_618.set_xy1(n -R, low [R] + (diff * 0.618)), f._0_618.set_xy2(n + 8, low [R] + (diff * 0.618))
f._0_764.set_xy1(n -R, low [R] + (diff * 0.764)), f._0_764.set_xy2(n + 8, low [R] + (diff * 0.764))
f._1_000.set_xy1(n -R, get1.p ), f._1_000.set_xy2(n + 8, get1.p )
f._1_382.set_xy1(n -R, get1.p + (diff * 0.382)), f._1_382.set_xy2(n + 8, get1.p + (diff * 0.382))
f.lab1 .set_xy (n +8, low [R] + (diff * a1 )), f.lab2 .set_xy (n + 8, low [R] + (diff * a2 ))
f.diagon.set_xy1(idx1, get1.p ), f.diagon.set_xy2(n -R, low [R] )
f.active := true
if pivs.size() >= 2
max = math.max(pivs.first().p, pivs.get(1).p )
min = math.min(pivs.first().p, pivs.get(1).p )
dif = max - min
_0i = pivs.first( ).b, _0p = pivs.first( ).p
_1i = pivs.get (1).b, _1p = pivs.get (1).p
d = _0p < _1p ? -dif : dif
x2 = math.max(last_bar_index , _0i) + 8
l0_1 = fLast. lf_0.get_line1(), l0_2 = fLast. lf_0.get_line2()
lM01 = fLast. lfM0.get_line1(), lM02 = fLast. lfM0.get_line2()
lM11 = fLast. lfM1.get_line1(), lM12 = fLast. lfM1.get_line2()
l1_1 = fLast. lf_1.get_line1(), l1_2 = fLast. lf_1.get_line2()
if (ph or pl) and sF
l0_1 .set_xy1(_0i, _0p + (d * 0.382)), l0_1 .set_xy2( x2, _0p + (d * 0.382))
l0_2 .set_xy1(_0i, _0p ), l0_2 .set_xy2( x2, _0p )
lM01 .set_xy1(_0i, _0p - (d * 0.236)), lM01 .set_xy2( x2, _0p - (d * 0.236))
lM02 .set_xy1(_0i, _0p - (d * 0.382)), lM02 .set_xy2( x2, _0p - (d * 0.382))
lM11 .set_xy1(_0i, _0p - (d * 0.618)), lM11 .set_xy2( x2, _0p - (d * 0.618))
lM12 .set_xy1(_0i, _0p - (d * 0.764)), lM12 .set_xy2( x2, _0p - (d * 0.764))
l1_1 .set_xy1(_0i, _0p - d ), l1_1 .set_xy2( x2, _0p - d )
l1_2 .set_xy1(_0i, _1p - (d * 0.382)), l1_2 .set_xy2( x2, _1p - (d * 0.382))
fLast.ln_0_5.set_xy1(_0i, _0p - (d * 0.5 )), fLast.ln_0_5.set_xy2( x2, _0p - (d * 0.5 ))
fLast.diagon.set_xy1(_0i, _0p ), fLast.diagon.set_xy2(_1i, _1p )
fLast.lab .set_xy (_0i, _0p )
fLast.lab .set_style (_1p > _0p ? label.style_label_up : label.style_label_down )
else
l0_1 .set_x2 ( n + 8 )
l0_2 .set_x2 ( n + 8 )
lM01 .set_x2 ( n + 8 )
lM02 .set_x2 ( n + 8 )
lM11 .set_x2 ( n + 8 )
lM12 .set_x2 ( n + 8 )
l1_1 .set_x2 ( n + 8 )
l1_2 .set_x2 ( n + 8 )
fLast.ln_0_5.set_x2 ( n + 8 )
if f.active
lv1 = opt == '0.000 - 1.000' ? f._0_000 : opt == '0.236 - 0.764' ? f._0_236 : opt == '0.382 - 0.618' ? f._0_382 : f.n0_382
lv2 = opt == '0.000 - 1.000' ? f._1_000 : opt == '0.236 - 0.764' ? f._0_764 : opt == '0.382 - 0.618' ? f._0_618 : f._1_382
max = math.max(lv1.get_y2(), lv2.get_y2())
min = math.min(lv1.get_y2(), lv2.get_y2())
if close < max and close > min
f.count := 0
else
if close > max or close < min
f.count += 1
if f.count > c
f.n0_382.set_xy1(na, na), f.n0_382.set_xy2(na, na)
f._0_000.set_xy1(na, na), f._0_000.set_xy2(na, na)
f._0_236.set_xy1(na, na), f._0_236.set_xy2(na, na)
f._0_382.set_xy1(na, na), f._0_382.set_xy2(na, na)
f._0_500.set_xy1(na, na), f._0_500.set_xy2(na, na)
f._0_618.set_xy1(na, na), f._0_618.set_xy2(na, na)
f._0_764.set_xy1(na, na), f._0_764.set_xy2(na, na)
f._1_000.set_xy1(na, na), f._1_000.set_xy2(na, na)
f._1_382.set_xy1(na, na), f._1_382.set_xy2(na, na)
f.diagon.set_xy1(na, na), f.diagon.set_xy2(na, na)
f.lab1 .set_xy (na, na), f.lab2 .set_xy (na, na)
f.active := false
if close > max
brokeU := true
else
brokeD := true
else
f.n0_382.set_x2(n + 8)
f._0_000.set_x2(n + 8)
f._0_236.set_x2(n + 8)
f._0_382.set_x2(n + 8)
f._0_500.set_x2(n + 8)
f._0_618.set_x2(n + 8)
f._0_764.set_x2(n + 8)
f._1_000.set_x2(n + 8)
f._1_382.set_x2(n + 8)
f.lab1 .set_x (n + 8)
f.lab2 .set_x (n + 8)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plotn0_382 = f.n0_382.get_y2()
plot_0_000 = f._0_000.get_y2()
plot_0_236 = f._0_236.get_y2()
plot_0_382 = f._0_382.get_y2()
plot_0_500 = f._0_500.get_y2()
plot_0_618 = f._0_618.get_y2()
plot_0_764 = f._0_764.get_y2()
plot_1_000 = f._1_000.get_y2()
plot_1_382 = f._1_382.get_y2()
ch = ta.change(plot_0_000)
p1 = plot(ch ? na : plotn0_382 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p2 = plot(ch ? na : plot_0_000 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p3 = plot(ch ? na : plot_0_236 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p4 = plot(ch ? na : plot_0_382 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p5 = plot(ch ? na : plot_0_500 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p6 = plot(ch ? na : plot_0_618 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p7 = plot(ch ? na : plot_0_764 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p8 = plot(ch ? na : plot_1_000 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
p9 = plot(ch ? na : plot_1_382 , color=color.new(color.blue, 100), style=plot.style_steplinebr)
fill(p1, p2, ch or not fl ? na : plot_0_000 , math.avg(plotn0_382, plot_0_000) , F0 , color.new(chart.bg_color, 100) )
fill(p1, p2, ch or not fl ? na : plotn0_382 , math.avg(plotn0_382, plot_0_000) , F0 , color.new(chart.bg_color, 100) )
fill(p3, p4, ch or not fl ? na : plot_0_236 , math.avg(plot_0_382, math.avg(plot_0_382, plot_0_236)), F_ , color.new(chart.bg_color, 100) )
fill(p3, p4, ch or not fl ? na : math.avg(plot_0_236, math.avg(plot_0_382, plot_0_236)), plot_0_382 , color.new(chart.bg_color, 100), F_ )
fill(p4, p5, ch or not fl ? na : plot_0_382 , plot_0_500 , color.new(chart.bg_color, 100), Fm )
fill(p5, p6, ch or not fl ? na : plot_0_500 , plot_0_618 , Fm , color.new(chart.bg_color, 100) )
fill(p6, p7, ch or not fl ? na : plot_0_764 , math.avg(plot_0_618, math.avg(plot_0_618, plot_0_764)), Fp , color.new(chart.bg_color, 100) )
fill(p6, p7, ch or not fl ? na : math.avg(plot_0_764, math.avg(plot_0_618, plot_0_764)), plot_0_618 , color.new(chart.bg_color, 100), Fp )
fill(p8, p9, ch or not fl ? na : plot_1_000 , math.avg(plot_1_382, plot_1_000) , F1 , color.new(chart.bg_color, 100) )
fill(p8, p9, ch or not fl ? na : plot_1_382 , math.avg(plot_1_382, plot_1_000) , F1 , color.new(chart.bg_color, 100) )
plotshape(sb and brokeU and f.active[1] ? high : na, location=location.abovebar, style=shape.labeldown, size=size.tiny, color=#089981)
plotshape(sb and brokeD and f.active[1] ? low : na, location=location.belowbar, style=shape.labelup , size=size.tiny, color=#f23645)
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
alertcondition(brokeU and f.active[1], 'break Up' , 'break Up' )
alertcondition(brokeD and f.active[1], 'break Down', 'break Donw')
//-----------------------------------------------------------------------------} |
🐰Born4Trade | https://www.tradingview.com/script/5OKgLlO6-Born4Trade/ | Born4Trade | https://www.tradingview.com/u/Born4Trade/ | 51 | 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/
// © Born4Trade
//@version=5
indicator("🐰Born4Trade", overlay=true)
High = request.security(syminfo.tickerid, "D", high, lookahead = barmerge.lookahead_on)
Low = request.security(syminfo.tickerid, "D", low, lookahead = barmerge.lookahead_on)
A = (High-Low)
B = A/2
C = A/3
D = (High-B)
N = (High-C)
S = (Low+C)
plot(High, "High", color=#000000,style=plot.style_circles)
plot(Low,"Low",color=#000000,style=plot.style_circles)
plot(N,"0.66",color=#FF0000,style=plot.style_circles)
plot(D,"0.50",color=#000000,style=plot.style_circles)
plot(S,"0.33",color=#0000FF,style=plot.style_circles)
plot(A,"Points",color=#000000) |
Rule of 16 - Lower | https://www.tradingview.com/script/Jy54RqN3-Rule-of-16-Lower/ | thebearfib | https://www.tradingview.com/u/thebearfib/ | 32 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thebearfib
//
//@version=5
//
//a level of 1.8 - Tells vix pricing in for spx move
//According to the rule of 16, if the VIX is trading at 16,
//then the SPX is estimated to see average daily moves up or down of 1% (because 16/16 = 1).
//If the VIX is at 24, the daily moves might be around 1.5%, and at 32, the rule of 16 says the SPX might see 2% daily moves.
//
indicator("Rule of 16 - Lower", format= format.percent, precision = 2, overlay=false)
_barcol = input.bool(defval = true, title = 'Color Bars', group = '➤ Rule of 16 ', inline='1')
_dip = input.float(defval = 1.8, title = 'Buy The Dip Ratio', group = '➤ Rule of 16 ', inline='1')
_src = close
_sN = syminfo.ticker
_sym = input.symbol("CBOE:VIX", " ", group = '➤ Symbol', inline='1')
_tf = input.timeframe("D", " ", group = '➤ Symbol', inline='1')
_cday = request.security(_sym, _tf, _src) / 15.87
_pctMv = _cday *16
color _maxMove = _cday > _dip ? color.rgb(0, 255, 8) : color.rgb(111, 108, 108)
plot(_cday, title= 'vix plot', color= _maxMove, linewidth=2, style = plot.style_line, display = display.all)
hline(1.8, title = 'SPX Threshold', color=color.rgb(119, 120, 125), linewidth = 1, linestyle = hline.style_dashed,display = display.all)
hline(0, title = 'Zeroline', color=color.rgb(70, 70, 71), linewidth = 5, linestyle = hline.style_solid, display = display.all)
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Inputs ——————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
_show = input.bool(defval = true, title = "𝚂𝚑𝚘𝚠 & ", group='➤ Table', inline='1')
_position3c = input.string("Top Center"," Position", options = ["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"], group='➤ Table', inline='1')
_fontSize1 = input.string("Normal","🗚 - Font Size", options = [ "Auto", "Tiny", "Small", "Normal", "Large", "Huge"])
_fontSize = switch _fontSize1
"Normal" => size.normal
"Auto" => size.auto
"Tiny" => size.tiny
"Small" => size.small
"Large" => size.large
"Huge" => size.huge
//
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————— Inputs ——————————————————————————————————————————————————————————————————————————————
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//
tableposGo3 = switch _position3c
"Top Right" => position.top_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Middle Right" => position.middle_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Bottom Right" => position.bottom_right
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
if barstate.islast or barstate.islastconfirmedhistory
var table tabu = table.new(tableposGo3, 99, 99,
bgcolor = color.rgb(45, 44, 44,100),
frame_color=color.rgb(59, 58, 58,100),
frame_width = 3,
border_color =color.rgb(19, 19, 19,100),
border_width = 1)
if _show
table.cell(tabu, 1, 1, 'MOVE of SPX',text_halign = text.align_left,text_color = color.gray,text_size = _fontSize)
table.cell(tabu, 2, 1, 'Annual:',text_halign = text.align_left,text_color = color.gray,text_size = _fontSize)
table.cell(tabu, 3, 1, str.tostring(_pctMv, format.percent),text_halign = text.align_right,text_color = color.rgb(255, 255, 255),text_size = _fontSize)
table.cell(tabu, 4, 1, 'Daily:',text_halign = text.align_left,text_color = color.gray,text_size = _fontSize)
table.cell(tabu, 5, 1, str.tostring(_cday, format.percent),text_halign = text.align_right,text_color = color.rgb(255, 255, 255),text_size = _fontSize)
// barcolor(color, offset, editable, show_last, title, display)
barcolor( _barcol ? _maxMove : na, title='Color Bars - Show Above Threshold', display = display.all)
|
ICT HTF FVGs (fadi) | https://www.tradingview.com/script/Cti9P1Ww-ICT-HTF-FVGs-fadi/ | fadizeidan | https://www.tradingview.com/u/fadizeidan/ | 301 | 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/
// © fadizeidan
//
//@version=5
indicator("ICT HTF FVGs (fadi)", overlay=true, max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
//+------------------------------------------------------------------------------------------------------------+//
//+--- Types ---+//
//+------------------------------------------------------------------------------------------------------------+//
type Settings
bool CE_show
string CE_style
color CE_color
bool Border_show
bool mitigated_show
string mitigated_type
color mitigated_color_bull
color mitigated_color_bear
bool ltf_hide
bool label_show
color label_color
color label_bgcolor
string label_size
int padding
int buffer
type Imbalance_Settings
bool show
string htf
color color_bull
color color_bear
int max_count
type Imbalance
int open_time
int close_time
float open
float middle
float close
bool mitigated
int mitigated_time
line line_middle
label lbl
box box
type ImbalanceStructure
Imbalance[] imbalance
Imbalance_Settings settings
int visible = 0
type Helper
string name = "Helper"
//+------------------------------------------------------------------------------------------------------------+//
//+--- Settings ---+//
//+------------------------------------------------------------------------------------------------------------+//
Settings_Group = "Global Settings"
Settings settings = Settings.new()
Imbalance_Settings HTF_1_Settings = Imbalance_Settings.new()
Imbalance_Settings HTF_2_Settings = Imbalance_Settings.new()
Imbalance_Settings HTF_3_Settings = Imbalance_Settings.new()
Imbalance_Settings HTF_4_Settings = Imbalance_Settings.new()
Imbalance_Settings HTF_5_Settings = Imbalance_Settings.new()
Imbalance_Settings HTF_6_Settings = Imbalance_Settings.new()
string tooltip1 = "HTF FVG Settings:\n\tShow/Hide timeframe\n\tTimeframe to display\n\tBullish FVG Color\n\tBearish FVG Color\n\tMaximum number of FVGs to display"
string tooltip2 = "Mitigated FVG Settings:\n\tShow/Hide mitigated (Applies to all).\n\tBullish FVG Color\n\tBearish FVG Color\n\tWhen to mark it as mitigated (Based on HTF timeframe, not current timeframe)"
HTF_1_Settings.show := input.bool(true, "", inline="htf1")
htf_1 = input.timeframe("5", "", inline="htf1")
HTF_1_Settings.htf := htf_1
HTF_1_Settings.color_bull := input.color(color.new(color.green,90), "", inline="htf1")
HTF_1_Settings.color_bear := input.color(color.new(color.blue,90), "", inline="htf1")
HTF_1_Settings.max_count := input.int(20, "", inline="htf1", tooltip = tooltip1)
HTF_2_Settings.show := input.bool(true, "", inline="htf2")
htf_2 = input.timeframe("15", "", inline="htf2")
HTF_2_Settings.htf := htf_2
HTF_2_Settings.color_bull := input.color(color.new(color.green,90), "", inline="htf2")
HTF_2_Settings.color_bear := input.color(color.new(color.blue,90), "", inline="htf2")
HTF_2_Settings.max_count := input.int(20, "", inline="htf2", tooltip = tooltip1)
HTF_3_Settings.show := input.bool(true, "", inline="htf3")
htf_3 = input.timeframe("60", "", inline="htf3")
HTF_3_Settings.htf := htf_3
HTF_3_Settings.color_bull := input.color(color.new(color.green,90), "", inline="htf3")
HTF_3_Settings.color_bear := input.color(color.new(color.blue,90), "", inline="htf3")
HTF_3_Settings.max_count := input.int(20, "", inline="htf3", tooltip = tooltip1)
HTF_4_Settings.show := input.bool(true, "", inline="htf4")
htf_4 = input.timeframe("240", "", inline="htf4")
HTF_4_Settings.htf := htf_4
HTF_4_Settings.color_bull := input.color(color.new(color.green,90), "", inline="htf4")
HTF_4_Settings.color_bear := input.color(color.new(color.blue,90), "", inline="htf4")
HTF_4_Settings.max_count := input.int(10, "", inline="htf4", tooltip = tooltip1)
HTF_5_Settings.show := input.bool(true, "", inline="htf5")
htf_5 = input.timeframe("1D", "", inline="htf5")
HTF_5_Settings.htf := htf_5
HTF_5_Settings.color_bull := input.color(color.new(color.green,90), "", inline="htf5")
HTF_5_Settings.color_bear := input.color(color.new(color.blue,90), "", inline="htf5")
HTF_5_Settings.max_count := input.int(10, "", inline="htf5", tooltip = tooltip1)
HTF_6_Settings.show := input.bool(true, "", inline="htf6")
htf_6 = input.timeframe("1W", "", inline="htf6")
HTF_6_Settings.htf := htf_6
HTF_6_Settings.color_bull := input.color(color.new(color.green,90), "", inline="htf6")
HTF_6_Settings.color_bear := input.color(color.new(color.blue,90), "", inline="htf6")
HTF_6_Settings.max_count := input.int(2, "", inline="htf6", tooltip = tooltip1)
settings.ltf_hide := input.bool(true, "Hide Lower Timeframes")
settings.Border_show := input.bool(true, "Show Border", group=Settings_Group, inline="4")
settings.mitigated_show := input.bool(true, "Show Mitigated", group=Settings_Group, inline="2")
settings.mitigated_color_bull := input.color(color.new(color.gray,95), "", group=Settings_Group, inline="2")
settings.mitigated_color_bear := input.color(color.new(color.gray,95), "", group=Settings_Group, inline="2")
settings.mitigated_type := input.string('Wick filled', 'when', options = ['None', 'Wick filled', 'Body filled', 'Wick filled half', 'Body filled half'], group=Settings_Group, inline="2", tooltip=tooltip2)
settings.CE_show := input.bool(true, "Show C.E. ", group=Settings_Group, inline="3")
settings.CE_color := input.color(color.new(color.black,60), "", group=Settings_Group, inline="3")
settings.CE_style := input.string('····', ' ', options = ['⎯⎯⎯', '----', '····'], group=Settings_Group, inline="3")
settings.label_show := input.bool(true, "Show Label ", inline="label")
settings.label_color := input.color(color.new(color.black, 10), "", inline='label')
settings.label_bgcolor := input.color(color.new(color.white, 100), "", inline='label')
settings.label_size := input.string(size.small, "", [size.tiny, size.small, size.normal, size.large, size.huge], inline="label")
settings.padding := input.int(4, "Distance from current candle", minval=0)
settings.buffer := input.int(6, "Spacing between timeframes", minval=0)
//+------------------------------------------------------------------------------------------------------------+//
//+--- Variables ---+//
//+------------------------------------------------------------------------------------------------------------+//
color color_transparent = #ffffff00
Helper helper = Helper.new()
var ImbalanceStructure FVG_1 = ImbalanceStructure.new()
var ImbalanceStructure FVG_2 = ImbalanceStructure.new()
var ImbalanceStructure FVG_3 = ImbalanceStructure.new()
var ImbalanceStructure FVG_4 = ImbalanceStructure.new()
var ImbalanceStructure FVG_5 = ImbalanceStructure.new()
var ImbalanceStructure FVG_6 = ImbalanceStructure.new()
var Imbalance[] FVGs_1 = array.new<Imbalance>()
var Imbalance[] FVGs_2 = array.new<Imbalance>()
var Imbalance[] FVGs_3 = array.new<Imbalance>()
var Imbalance[] FVGs_4 = array.new<Imbalance>()
var Imbalance[] FVGs_5 = array.new<Imbalance>()
var Imbalance[] FVGs_6 = array.new<Imbalance>()
FVG_1.imbalance := FVGs_1
FVG_1.settings := HTF_1_Settings
FVG_2.imbalance := FVGs_2
FVG_2.settings := HTF_2_Settings
FVG_3.imbalance := FVGs_3
FVG_3.settings := HTF_3_Settings
FVG_4.imbalance := FVGs_4
FVG_4.settings := HTF_4_Settings
FVG_5.imbalance := FVGs_5
FVG_5.settings := HTF_5_Settings
FVG_6.imbalance := FVGs_6
FVG_6.settings := HTF_6_Settings
//Used internally for padding
var int TF_1 = 0
var int TF_2 = 0
var int TF_3 = 0
var int TF_4 = 0
var int TF_5 = 0
var int TF_6 = 0
var float daily = 0
var float monthly = 0
//+------------------------------------------------------------------------------------------------------------+//
//+--- Methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
method LineStyle(Helper helper, string style) =>
helper.name := style
out = switch style
'----' => line.style_dashed
'····' => line.style_dotted
=> line.style_solid
out
method Gethtftext(Helper helper, string htf) =>
helper.name := htf
formatted = htf
seconds = timeframe.in_seconds(htf)
if seconds < 60
formatted := str.tostring(seconds) + "s"
else if (seconds / 60) < 60
formatted := str.tostring((seconds/60)) + "m"
else if (seconds/60/60) < 24
formatted := str.tostring((seconds/60/60)) + "H"
formatted
method Validtimeframe(Helper helper, tf) =>
helper.name := tf
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(tf)
n1 < n2
method ProximityRange(Helper helper, tf) =>
helper.name := tf
float range_high = 0
float range_low = 0
if timeframe.isseconds or timeframe.isminutes
range_high := close + daily
range_low := close - daily
if timeframe.isdaily
range_high := close + monthly*3
range_low := close - monthly*3
if timeframe.isweekly
range_high := close + monthly*12
range_low := close - monthly*12
[range_low, range_high]
//+------------------------------------------------------------------------------------------------------------+//
//+--- Imbalances Methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
// AddZone is used to display and manage imbalance related boxes
method AddZone(ImbalanceStructure IS, Imbalance imb, int step) =>
if IS.settings.show
int buffer = time+((time-time[1])*(settings.padding+1+(settings.buffer*(step-1))))
if na(imb.box)
imb.box := box.new(imb.open_time, imb.open, buffer, imb.close, settings.Border_show ? imb.open < imb.close ? color.new(IS.settings.color_bull, color.t(IS.settings.color_bull)/ 3) : color.new(IS.settings.color_bear, color.t(IS.settings.color_bear)/ 3) : color_transparent, settings.Border_show ? 1 : 0, bgcolor = imb.open < imb.close ? IS.settings.color_bull : IS.settings.color_bear, xloc=xloc.bar_time)
if settings.label_show
imb.lbl := label.new(buffer, imb.middle, text=helper.Gethtftext(IS.settings.htf), xloc=xloc.bar_time, textcolor=settings.label_color, style=label.style_label_left, color=settings.label_bgcolor, size = settings.label_size)
if settings.CE_show
imb.line_middle := line.new(imb.open_time, imb.middle, buffer, imb.middle, xloc=xloc.bar_time, style=helper.LineStyle(settings.CE_style), color=settings.CE_color)
IS.visible := IS.visible + 1
else
//if mitigated
box.set_right(imb.box, imb.mitigated ? imb.mitigated_time : buffer)
box.set_bgcolor(imb.box, imb.open < imb.close ? imb.mitigated ? settings.mitigated_color_bull : IS.settings.color_bull : imb.mitigated ? settings.mitigated_color_bear : IS.settings.color_bear)
box.set_border_color(imb.box, settings.Border_show ? imb.open < imb.close ? color.new(settings.mitigated_color_bull, color.t(settings.mitigated_color_bull)/ 3) : color.new(settings.mitigated_color_bear, color.t(settings.mitigated_color_bear)/ 3) : color_transparent)
label.set_x(imb.lbl, buffer)
//label.delete(imb.lbl)
if settings.CE_show
line.set_x2(imb.line_middle, imb.mitigated ? imb.mitigated_time : buffer)
if imb.mitigated and not settings.mitigated_show
if not na(imb.box)
IS.visible := IS.visible - 1
box.delete(imb.box)
line.delete(imb.line_middle)
label.delete(imb.lbl)
IS
// AddImbalance adds a newly discovered imbalance. this applies for both FVG and Volume Imbalance
method AddImbalance(ImbalanceStructure IS, float o, float c, int o_time) =>
Imbalance imb = Imbalance.new()
imb.open_time := o_time
imb.open := o
imb.middle := (o+c)/2
imb.close := c
IS.imbalance.unshift(imb)
//IS.AddZone(imb)
if IS.imbalance.size() > 100 //IS.settings.max_count
temp = IS.imbalance.pop()
if not na(temp.box)
IS.visible := IS.visible - 1
box.delete(temp.box)
line.delete(temp.line_middle)
label.delete(temp.lbl)
IS
// CheckMitigated checks if the imbalance has been mitigated based on the settings
method CheckMitigated(ImbalanceStructure IS, o, h, l, c) =>
if IS.imbalance.size() > 0
for i = IS.imbalance.size() - 1 to 0
imb = IS.imbalance.get(i)
if not imb.mitigated
switch settings.mitigated_type
"None" =>
imb.mitigated := false
'Wick filled' =>
imb.mitigated := imb.open <= imb.close ? low <= imb.open : high >= imb.open
'Body filled' =>
imb.mitigated := imb.open < imb.close ? math.min(o, c) <= imb.open : math.max(o, c) >= imb.open
'Wick filled half' =>
imb.mitigated := imb.open <= imb.close ? low <= imb.middle : high >= imb.middle
'Body filled half' =>
imb.mitigated := imb.open <= imb.close ? math.min(o, c) <= imb.middle : math.max(o, c) >= imb.middle
if imb.mitigated
if not settings.mitigated_show
if not na(imb.box)
IS.visible := IS.visible - 1
box.delete(imb.box)
line.delete(imb.line_middle)
label.delete(imb.lbl)
IS.imbalance.remove(i)
else
imb.mitigated_time := time
IS
method AdjustMargins(ImbalanceStructure IS, int step) =>
if IS.imbalance.size() > 0
int buffer = time+((time-time[1])*(settings.padding+1+(settings.buffer*(step-1))))
[rl, rh] = helper.ProximityRange(IS.settings.htf)
for i = 0 to IS.imbalance.size() - 1
imb = IS.imbalance.get(i)
log.info("Adjust Margins: {0} {1}", math.max(imb.open, imb.close), rl)
if ((math.max(imb.open, imb.close) > rl) and (math.min(imb.open, imb.close) < rh)) and IS.visible <= IS.settings.max_count
IS.AddZone(imb, step)
else
if not na(imb.box)
IS.visible := IS.visible -1
box.delete(imb.box)
label.delete(imb.lbl)
line.delete((imb.line_middle))
IS
// FindImbalance looks for imbalances and, if found, adds it to the list
method FindImbalance(ImbalanceStructure IS, o, h, l, c, t, o1, h1, l1, c1, t1, o2, h2, l2, c2, t2) =>
if IS.settings.show and (h < l2 or l > h2)
o = h < l2 ? l2 : h2
c = h < l2 ? h : l
if IS.imbalance.size() == 0
IS.AddImbalance(o, c, t2)
else
if IS.imbalance.first().open_time < t2
IS.AddImbalance(o, c, t2)
IS
method Process(ImbalanceStructure IS, float o, float h, float l, float c, int t, float o1, float h1, float l1, float c1, int t1, float o2, float h2, float l2, float c2, int t2) =>
var int visible = 0
if IS.settings.show
if not settings.ltf_hide or (settings.ltf_hide and helper.Validtimeframe(IS.settings.htf))
if IS.settings.show
IS.FindImbalance(o, h, l, c, t, o1, h1, l1, c1, t1, o2, h2, l2, c2, t2)
visible := 1
IS.CheckMitigated(o, h, l, c)
visible
//+------------------------------------------------------------------------------------------------------------+//
//+--- Main call to start the process ---+//
//+------------------------------------------------------------------------------------------------------------+//
daily := request.security(syminfo.tickerid, "1D", ta.atr(14))
monthly := request.security(syminfo.tickerid, "1M", ta.atr(14))
[o_1, h_1, l_1, c_1, t_1] = request.security(syminfo.tickerid, htf_1, [open[1], high[1], low[1], close[1], time[1]])
[o1_1, h1_1, l1_1, c1_1, t1_1] = request.security(syminfo.tickerid, htf_1, [open[2], high[2], low[2], close[2], time[2]])
[o2_1, h2_1, l2_1, c2_1, t2_1] = request.security(syminfo.tickerid, htf_1, [open[3], high[3], low[3], close[3], time[3]])
TF_1 := FVG_1.Process(o_1, h_1, l_1, c_1, t_1, o1_1, h1_1, l1_1, c1_1, t1_1, o2_1, h2_1, l2_1, c2_1, t2_1)
FVG_1.AdjustMargins(TF_1)
[o_2, h_2, l_2, c_2, t_2] = request.security(syminfo.tickerid, htf_2, [open[1], high[1], low[1], close[1], time[1]])
[o1_2, h1_2, l1_2, c1_2, t1_2] = request.security(syminfo.tickerid, htf_2, [open[2], high[2], low[2], close[2], time[2]])
[o2_2, h2_2, l2_2, c2_2, t2_2] = request.security(syminfo.tickerid, htf_2, [open[3], high[3], low[3], close[3], time[3]])
TF_2 := TF_1 + FVG_2.Process(o_2, h_2, l_2, c_2, t_2, o1_2, h1_2, l1_2, c1_2, t1_2, o2_2, h2_2, l2_2, c2_2, t2_2)
FVG_2.AdjustMargins(TF_2)
[o_3, h_3, l_3, c_3, t_3] = request.security(syminfo.tickerid, htf_3, [open[1], high[1], low[1], close[1], time[1]])
[o1_3, h1_3, l1_3, c1_3, t1_3] = request.security(syminfo.tickerid, htf_3, [open[2], high[2], low[2], close[2], time[2]])
[o2_3, h2_3, l2_3, c2_3, t2_3] = request.security(syminfo.tickerid, htf_3, [open[3], high[3], low[3], close[3], time[3]])
TF_3 := TF_2 + FVG_3.Process(o_3, h_3, l_3, c_3, t_3, o1_3, h1_3, l1_3, c1_3, t1_3, o2_3, h2_3, l2_3, c2_3, t2_3)
FVG_3.AdjustMargins(TF_3)
[o_4, h_4, l_4, c_4, t_4] = request.security(syminfo.tickerid, htf_4, [open[1], high[1], low[1], close[1], time[1]])
[o1_4, h1_4, l1_4, c1_4, t1_4] = request.security(syminfo.tickerid, htf_4, [open[2], high[2], low[2], close[2], time[2]])
[o2_4, h2_4, l2_4, c2_4, t2_4] = request.security(syminfo.tickerid, htf_4, [open[3], high[3], low[3], close[3], time[3]])
TF_4 := TF_3 + FVG_4.Process(o_4, h_4, l_4, c_4, t_4, o1_4, h1_4, l1_4, c1_4, t1_4, o2_4, h2_4, l2_4, c2_4, t2_4)
FVG_4.AdjustMargins(TF_4)
[o_5, h_5, l_5, c_5, t_5] = request.security(syminfo.tickerid, htf_5, [open[1], high[1], low[1], close[1], time[1]])
[o1_5, h1_5, l1_5, c1_5, t1_5] = request.security(syminfo.tickerid, htf_5, [open[2], high[2], low[2], close[2], time[2]])
[o2_5, h2_5, l2_5, c2_5, t2_5] = request.security(syminfo.tickerid, htf_5, [open[3], high[3], low[3], close[3], time[3]])
TF_5 := TF_4 + FVG_5.Process(o_5, h_5, l_5, c_5, t_5, o1_5, h1_5, l1_5, c1_5, t1_5, o2_5, h2_5, l2_5, c2_5, t2_5)
FVG_5.AdjustMargins(TF_5)
[o_6, h_6, l_6, c_6, t_6] = request.security(syminfo.tickerid, htf_6, [open[1], high[1], low[1], close[1], time[1]])
[o1_6, h1_6, l1_6, c1_6, t1_6] = request.security(syminfo.tickerid, htf_6, [open[2], high[2], low[2], close[2], time[2]])
[o2_6, h2_6, l2_6, c2_6, t2_6] = request.security(syminfo.tickerid, htf_6, [open[3], high[3], low[3], close[3], time[3]])
TF_6 := TF_5 + FVG_6.Process(o_6, h_6, l_6, c_6, t_6, o1_6, h1_6, l1_6, c1_6, t1_6, o2_6, h2_6, l2_6, c2_6, t2_6)
FVG_6.AdjustMargins(TF_6)
|
Divergences Refurbished | https://www.tradingview.com/script/XOlWBNuN-Divergences-Refurbished/ | andre_007 | https://www.tradingview.com/u/andre_007/ | 345 | 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/
// @Thanks and credits:
// © LonesomeTheBlue
// Modified by © andre_007
// @description This is a script forked from LonesomeTheBlue's Divergence for Many Indicators v4.
// It is a script that checks for divergence between price and many indicators.
// in this version, I added more indicators to check for divergence.
// I also added 40 symbols to check for divergence.
// More info on the original script can be found here:
// https://www.tradingview.com/script/n8AGnIZd-Divergence-for-Many-Indicators-v4/
//@version=5
indicator('Divergences Refurbished', overlay=true, max_bars_back=1000, max_lines_count=400, max_labels_count=400)
import andre_007/MomentumIndicators/2 as MI
import andre_007/VolumeIndicators/3 as VI
import andre_007/TrendIndicators/3 as TI
import andre_007/VolatilityIndicators/8 as VOL
// Constants
// -------------------------------------------------------------------------------------------------------------- {
// Groups
var string GROUP_DIV = 'Divergence Settings'
var string GROUP_IND = 'Indicators to Check'
var string GROUP_SYM = 'Symbols to Check'
var string GROUP_STYLE = 'Colors and Styles'
var string GROUP_MACD_PARAM = 'MACD Parameters'
var string GROUP_RSI_PARAM = 'RSI Parameters'
var string GROUP_STOC_PARAM = 'Stochastic Parameters'
var string GROUP_CCI_PARAM = 'CCI Parameters'
var string GROUP_MOM_PARAM = 'Momentum Parameters'
var string GROUP_CMF_PARAM = 'Chaikin Money Flow Parameters'
var string GROUP_OBV_PARAM = 'OBV Parameters'
var string GROUP_MFI_PARAM = 'Money Flow Index Parameters'
var string GROUP_VOLUMEOSC_PARAM = 'Volume Oscillator Parameters'
var string GROUP_PVT_PARAM = 'Price Volume Trend Parameters'
var string GROUP_ULTOSC_PARAM = 'Ultimate Oscillator Parameters'
var string GROUP_FISHER_PARAM = 'Fisher Transform Parameters'
var string GROUP_ZSCORE_PARAM = 'Z-Score/T-Score Parameters'
// Moving Average Types
var string TYPE_MA_TOOLTIP = '1 - Simple Moving Average\n' +
'2 - Exponential Moving Average\n' +
'3 - Weighted Moving Average\n' +
'4 - Volume Weighted Moving Average\n' +
'5 - Arnaud Legoux Moving Average\n' +
'6 - Hull Moving Average\n' +
'7 - Least Squares Moving Average\n' +
'8 - Relative Moving Average\n' +
'9 - Median'
// -------------------------------------------------------------------------------------------------------------- }
// Divergence settings
// -------------------------------------------------------------------------------------------------------------- {
prd = input.int(defval=5, title='Pivot Period', minval=1, maxval=50, group=GROUP_DIV)
source = input.string(defval='High/Low', title='Source for Pivot Points', options=['Close', 'High/Low'], group=GROUP_DIV)
searchdiv = input.string(defval='Regular/Hidden', title='Divergence Type', options=['Regular', 'Hidden', 'Regular/Hidden'], group=GROUP_DIV)
showindis = input.string(defval='Don\'t Show', title='Show Indicator Names', options=['Full', 'Abbreviation', 'Don\'t Show'], group=GROUP_DIV)
showlimit = input.int(1, title='Minimum Number of Divergence', minval=1, maxval=11, group=GROUP_DIV)
maxpp = input.int(defval=3, title='Maximum Pivot Points to Check', minval=1, maxval=20, group=GROUP_DIV)
maxbars = input.int(defval=100, title='Maximum Bars to Check', minval=30, maxval=200, group=GROUP_DIV)
shownum = input(defval=true, title='Show Divergence Number', group=GROUP_DIV)
showlast = input(defval=false, title='Show Only Last Divergence', group=GROUP_DIV)
dontconfirm = input(defval=true, title='Don\'t Wait for Confirmation', group=GROUP_DIV)
showlines = input(defval=true, title='Show Divergence Lines', group=GROUP_DIV)
showpivot = input(defval=false, title='Show Pivot Points', group=GROUP_DIV)
show_support_resistance = input(defval=true, title='Show Support/Resistance', group=GROUP_DIV, inline='1', tooltip='Show Support/Resistance for each divergence.')
support_resistance_bars = input.int(defval=13, title='Support/Resistance Length', minval=1, group=GROUP_DIV,
inline='2', tooltip='Number of bars to plot Support/Resistance lines.')
support_resistance_extend = input.string(defval='None', title='Extend Support/Resistance', options=['None', 'Left', 'Right', 'Both'], group=GROUP_DIV,
inline='2', tooltip='Extend Support/Resistance lines to the left, right, both or none.')
// -------------------------------------------------------------------------------------------------------------- }
// Style settings
// -------------------------------------------------------------------------------------------------------------- {
pos_reg_div_col = input(defval=#009606, title='Positive Regular Divergence', group=GROUP_STYLE)
neg_reg_div_col = input(defval=#f23645, title='Negative Regular Divergence', group=GROUP_STYLE)
pos_hid_div_col = input(defval=#2962ff, title='Positive Hidden Divergence', group=GROUP_STYLE)
neg_hid_div_col = input(defval=#9c27b0, title='Negative Hidden Divergence', group=GROUP_STYLE)
pos_div_text_col = input(defval=#000000, title='Positive Divergence Text Color', group=GROUP_STYLE)
neg_div_text_col = input(defval=#000000, title='Negative Divergence Text Color', group=GROUP_STYLE)
reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'], group=GROUP_STYLE)
hid_div_l_style_ = input.string(defval='Dashed', title='Hdden Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'], group=GROUP_STYLE)
reg_div_l_width = input.int(defval=2, title='Regular Divergence Line Width', minval=1, maxval=5, group=GROUP_STYLE)
hid_div_l_width = input.int(defval=1, title='Hidden Divergence Line Width', minval=1, maxval=5, group=GROUP_STYLE)
char_separator = input.string(defval='\n', title='Character Separator', group=GROUP_STYLE)
show_tooltip = input(defval=true, title='Show Tooltip', group=GROUP_STYLE)
yShiftPercent = input(defval=0.0, title='Shift labels in y-axis (%)', group=GROUP_STYLE)
// -------------------------------------------------------------------------------------------------------------- }
// Indicator to check
// -------------------------------------------------------------------------------------------------------------- {
calcmacd = input(defval=true, title='MACD', group=GROUP_IND, inline='macd')
calcmacd_text = input.string(defval='🤥', title='', inline='macd', group=GROUP_IND)
calcmacda = input(defval=true, title='MACD Histogram', group=GROUP_IND, inline='macda')
calcmacda_text = input.string(defval='🤥', title='', inline='macda', group=GROUP_IND)
calcvwmacd = input(true, title='Volume Weighted MACD', group=GROUP_IND, inline='vwmacd')
calcvwmacd_text = input.string(defval='🤥', title='', inline='vwmacd', group=GROUP_IND)
calcrsi = input(defval=true, title='RSI', group=GROUP_IND, inline='rsi')
calcrsi_text = input.string(defval='🤥', title='', inline='rsi', group=GROUP_IND)
calcstoc = input(defval=true, title='Stochastic', group=GROUP_IND, inline='stoc')
calcstoc_text = input.string(defval='🤥', title='', inline='stoc', group=GROUP_IND)
calccci = input(defval=true, title='CCI', group=GROUP_IND, inline='cci')
calccci_text = input.string(defval='🤥', title='', inline='cci', group=GROUP_IND)
calcmom = input(defval=true, title='Momentum', group=GROUP_IND, inline='mom')
calcmom_text = input.string(defval='🤥', title='', inline='mom', group=GROUP_IND)
calcobv = input(defval=true, title='OBV', group=GROUP_IND, inline='obv')
calcobv_text = input.string(defval='🤥', title='', inline='obv', group=GROUP_IND)
calccmf = input(true, title='Chaikin Money Flow', group=GROUP_IND, inline='cmf')
calccmf_text = input.string(defval='🤥', title='', inline='cmf', group=GROUP_IND)
calcmfi = input(true, title='Money Flow Index', group=GROUP_IND, inline='mfi')
calcmfi_text = input.string(defval='🤥', title='', inline='mfi', group=GROUP_IND)
calcStochRSI = input(true, title='Stochastic RSI', group=GROUP_IND, inline='stochrsi')
calcStochRSI_text = input.string(defval='🤥', title='', inline='stochrsi', group=GROUP_IND)
calcVolumeOsc = input(true, title='Volume Oscillator', group=GROUP_IND, inline='volumeosc')
calcVolumeOsc_text = input.string(defval='🤥', title='', inline='volumeosc', group=GROUP_IND)
calcPVT = input(true, title='Price Volume Trend', group=GROUP_IND, inline='pvt')
calcPVT_text = input.string(defval='🤥', title='', inline='pvt', group=GROUP_IND)
calcUltimateOsc = input(true, title='Ultimate Oscillator', group=GROUP_IND, inline='ultosc')
calcUltimateOsc_text = input.string(defval='🤥', title='', inline='ultosc', group=GROUP_IND)
calcFisherTransform = input(true, title='Fisher Transform', group=GROUP_IND, inline='fisher')
calcFisherTransform_text = input.string(defval='🤥', title='', inline='fisher', group=GROUP_IND)
calcZscore = input(true, title='Z-Score/T-Score', group=GROUP_IND, inline='zscore')
calcZscore_text = input.string(defval='🤥', title='', inline='zscore', group=GROUP_IND)
calcExt_1 = input(false, title='', group=GROUP_IND, inline='ext1')
externalIndicator_1 = input(defval=close, title='External Indicator 1', group=GROUP_IND, inline='ext1')
externalIndicator_1_text = input.string(defval='External Indicator 1🔎', title='', inline='ext1', group=GROUP_IND)
calcExt_2 = input(false, title='', group=GROUP_IND, inline='ext2')
externalIndicator_2 = input(defval=close, title='External Indicator 2', group=GROUP_IND, inline='ext2')
externalIndicator_2_text = input.string(defval='External Indicator 2🔎', title='', inline='ext2', group=GROUP_IND)
calcExt_3 = input(false, title='', group=GROUP_IND, inline='ext3')
externalIndicator_3 = input(defval=close, title='External Indicator 3', group=GROUP_IND, inline='ext3')
externalIndicator_3_text = input.string(defval='External Indicator 3🔎', title='', inline='ext3', group=GROUP_IND)
calcExt_4 = input(false, title='', group=GROUP_IND, inline='ext4')
externalIndicator_4 = input(defval=close, title='External Indicator 4', group=GROUP_IND, inline='ext4')
externalIndicator_4_text = input.string(defval='External Indicator 4🔎', title='', inline='ext4', group=GROUP_IND)
// -------------------------------------------------------------------------------------------------------------- }
// Indicator parameters
// -------------------------------------------------------------------------------------------------------------- {
// MACD
macd_source = input.source(defval=close, title='MACD Source', group=GROUP_MACD_PARAM)
macd_fast = input.int(defval=12, title='MACD Fast Length', minval=1, maxval=50, group=GROUP_MACD_PARAM)
macd_slow = input.int(defval=26, title='MACD Slow Length', minval=1, maxval=50, group=GROUP_MACD_PARAM)
macd_signal = input.int(defval=9, title='MACD Signal Length', minval=1, maxval=50, group=GROUP_MACD_PARAM)
macd_type_ma = input.int(defval=1, title='MACD Type of Moving Average', minval=1, maxval=9, tooltip=TYPE_MA_TOOLTIP, group=GROUP_MACD_PARAM)
// RSI
rsi_source = input.source(defval=close, title='RSI Source', group=GROUP_RSI_PARAM)
rsi_length = input.int(defval=14, title='RSI Length', minval=1, maxval=50, group=GROUP_RSI_PARAM)
// Stochastic
stoc_source = input.source(defval=close, title='Stochastic Source', group=GROUP_STOC_PARAM)
stoc_k = input.int(defval=14, title='Stochastic K', minval=1, maxval=50, group=GROUP_STOC_PARAM)
stoc_d = input.int(defval=3, title='Stochastic D', minval=1, maxval=50, group=GROUP_STOC_PARAM)
stoc_dSmoothing = input.int(defval=3, title='Stochastic D Smoothing', minval=1, maxval=50, group=GROUP_STOC_PARAM)
stoc_type_ma = input.int(defval=1, title='Stochastic Type of Moving Average', minval=1, maxval=9, tooltip=TYPE_MA_TOOLTIP, group=GROUP_STOC_PARAM)
// CCI
cci_source = input.source(defval=close, title='CCI Source', group=GROUP_CCI_PARAM)
cci_length = input.int(defval=10, title='CCI Length', minval=1, maxval=50, group=GROUP_CCI_PARAM)
cci_type_ma = input.int(defval=1, title='CCI Type of Moving Average', minval=1, maxval=9, tooltip=TYPE_MA_TOOLTIP, group=GROUP_CCI_PARAM)
// Momentum
mom_source = input.source(defval=close, title='Momentum Source', group=GROUP_MOM_PARAM)
mom_length = input.int(defval=10, title='Momentum Length', minval=1, maxval=50, group=GROUP_MOM_PARAM)
// Chaikin Money Flow
cmf_length = input.int(defval=21, title='Chaikin Money Flow Length', minval=1, maxval=50, group=GROUP_CMF_PARAM)
// OBV
obv_source = input.source(defval=close, title='OBV Source', group=GROUP_OBV_PARAM)
// Money Flow Index
mfi_source = input.source(defval=close, title='Money Flow Index Source', group=GROUP_MFI_PARAM)
mfi_length = input.int(defval=14, title='Money Flow Index Length', minval=1, maxval=50, group=GROUP_MFI_PARAM)
// Volume Oscillator
sourceVolumeOsc = input(close, title='Volume Oscillator Source', group=GROUP_VOLUMEOSC_PARAM)
shortLengthVolumeOsc = input.int(5, title='Volume Oscillator Short Length', minval=1, group=GROUP_VOLUMEOSC_PARAM)
longLengthVolumeOsc = input.int(10, title='Volume Oscillator Long Length', minval=1, group=GROUP_VOLUMEOSC_PARAM)
// PVT
sourcePVT = input(close, title='Price Volume Trend Source', group=GROUP_PVT_PARAM)
// Ultimate Oscillator
ultosc_source = input.source(defval=close, title='Ultimate Oscillator Source', group=GROUP_ULTOSC_PARAM)
ultosc_length1 = input.int(defval=7, title='Ultimate Oscillator Fast Length', minval=1, maxval=50, group=GROUP_ULTOSC_PARAM)
ultosc_length2 = input.int(defval=14, title='Ultimate Oscillator Middle Length', minval=1, maxval=50, group=GROUP_ULTOSC_PARAM)
ultosc_length3 = input.int(defval=28, title='Ultimate Oscillator Slow Length', minval=1, maxval=50, group=GROUP_ULTOSC_PARAM)
// Fisher Transform
fisher_source = input.string(defval='High/Low', title='Fisher Transform Source', options=['Close', 'High/Low'], group=GROUP_FISHER_PARAM)
fisher_length = input.int(defval=10, title='Fisher Transform Length', minval=1, maxval=50, group=GROUP_FISHER_PARAM)
// Z-Score/T-Score
zscore_source = input.source(defval=hl2, title='Z-Score/T-Score Source', group=GROUP_ZSCORE_PARAM)
zscore_length = input.int(defval=21, title='Z-Score/T-Score Length for Standard Deviation', minval=1, maxval=50, group=GROUP_ZSCORE_PARAM)
zscore_mean_length = input.int(defval=21, title='Z-Score/T-Score Length for Mean', group=GROUP_ZSCORE_PARAM)
zscore_mean_type = input.int(defval=2, title='Z-Score/T-Score Type of Moving Average for Mean', minval=1, maxval=9, tooltip=TYPE_MA_TOOLTIP, group=GROUP_ZSCORE_PARAM)
// -------------------------------------------------------------------------------------------------------------- }
// Symbols to check
// -------------------------------------------------------------------------------------------------------------- {
sourceSymbols = input.string(defval='High/Low', title='Source for Pivot Points', options=['Close', 'High/Low'], group=GROUP_SYM)
// -----------------
// U.S. Market
// -----------------
// Russell 3000
useSym1 = input(true, '', inline = 'sym1', group=GROUP_SYM)
sym1 = input.symbol('AMEX:IWV', '', inline = 'sym1', group=GROUP_SYM)
sym1_text = input.string(defval = '📈', title = '', inline = 'sym1', group=GROUP_SYM)
// Nasdaq
useSym2 = input(true, '', inline = 'sym2', group=GROUP_SYM)
sym2 = input.symbol('NASDAQ:QQQ', '', inline = 'sym2', group=GROUP_SYM)
sym2_text = input.string(defval = '📈', title = '', inline = 'sym2', group=GROUP_SYM)
// S&P 500 Equal Weight
useSym3 = input(true, '', inline = 'sym3', group=GROUP_SYM)
sym3 = input.symbol('AMEX:RSP', '', inline = 'sym3', group=GROUP_SYM)
sym3_text = input.string(defval = '📈', title = '', inline = 'sym3', group=GROUP_SYM)
// -----------------
// Europe Market
// -----------------
// Germany 40
useSym4 = input(true, '', inline = 'sym4', group=GROUP_SYM)
sym4 = input.symbol('CAPITALCOM:DE40', '', inline = 'sym4', group=GROUP_SYM)
sym4_text = input.string(defval ='📉', title = '', inline = 'sym4', group=GROUP_SYM)
// UK 100
useSym5 = input(true, '', inline = 'sym5', group=GROUP_SYM)
sym5 = input.symbol('TVC:UKX', '', inline = 'sym5', group=GROUP_SYM)
sym5_text = input.string(defval = '📉', title = '', inline = 'sym5', group=GROUP_SYM)
// Euro Stoxx 600
useSym6 = input(true, '', inline = 'sym6', group=GROUP_SYM)
sym6 = input.symbol('TVC:SXXP', '', inline = 'sym6', group=GROUP_SYM)
sym6_text = input.string(defval = '📉', title = '', inline = 'sym6', group=GROUP_SYM)
// -----------------
// Asia Market
// -----------------
// Japan
useSym7 = input(true, '', inline = 'sym7', group=GROUP_SYM)
sym7 = input.symbol('TVC:NI225', '', inline = 'sym7', group=GROUP_SYM)
sym7_text = input.string(defval = '📉', title = '', inline = 'sym7', group=GROUP_SYM)
// China (Hong Kong)
useSym8 = input(true, '', inline = 'sym8', group=GROUP_SYM)
sym8 = input.symbol('TVC:HSI', '', inline = 'sym8', group=GROUP_SYM)
sym8_text = input.string(defval = '📉', title = '', inline = 'sym8', group=GROUP_SYM)
// -----------------
// Oceanic Market
// -----------------
// Australia
useSym9 = input(true, '', inline = 'sym9', group=GROUP_SYM)
sym9 = input.symbol('EIGHTCAP:ASX200', '', inline = 'sym9', group=GROUP_SYM)
sym9_text = input.string(defval = '📉', title = '', inline = 'sym9', group=GROUP_SYM)
// -----------------
// Latin America
// -----------------
// Brazil
useSym10 = input(true, '', inline = 'sym10', group=GROUP_SYM)
sym10 = input.symbol('AMEX:EWZ', '', inline = 'sym10', group=GROUP_SYM)
sym10_text = input.string(defval = '📉', title = '', inline = 'sym10', group=GROUP_SYM)
// -----------------
// World
// -----------------
useSym11 = input(true, '', inline = 'sym11', group=GROUP_SYM)
sym11 = input.symbol('AMEX:VT', '', inline = 'sym11', group=GROUP_SYM)
sym11_text = input.string(defval = '🌎', title = '', inline = 'sym11', group=GROUP_SYM)
// -----------------
// Commodities: Metals
// -----------------
// Gold
useSym12 = input(true, '', inline = 'sym12', group=GROUP_SYM)
sym12 = input.symbol('TVC:GOLD', '', inline = 'sym12', group=GROUP_SYM)
sym12_text = input.string(defval = '🥇', title = '', inline = 'sym12', group=GROUP_SYM)
// Silver
useSym13 = input(true, '', inline = 'sym13', group=GROUP_SYM)
sym13 = input.symbol('TVC:SILVER', '', inline = 'sym13', group=GROUP_SYM)
sym13_text = input.string(defval = '🥈', title = '', inline = 'sym13', group=GROUP_SYM)
// Copper
useSym14 = input(true, '', inline = 'sym14', group=GROUP_SYM)
sym14 = input.symbol('CAPITALCOM:COPPER', '', inline = 'sym14', group=GROUP_SYM)
sym14_text = input.string(defval = '🏭', title = '', inline = 'sym14', group=GROUP_SYM)
//---------------------------------------
// Commodities: Energy
//---------------------------------------
// Crude Oil
useSym15 = input(true, '', inline = 'sym15', group=GROUP_SYM)
sym15 = input.symbol('TVC:USOIL', '', inline = 'sym15', group=GROUP_SYM)
sym15_text = input.string(defval = '🛢️', title = '', inline = 'sym15', group=GROUP_SYM)
// Natural Gas
useSym16 = input(true, '', inline = 'sym16', group=GROUP_SYM)
sym16 = input.symbol('PEPPERSTONE:NATGAS', '', inline = 'sym16', group=GROUP_SYM)
sym16_text = input.string(defval ='🔥', title = '', inline = 'sym16', group=GROUP_SYM)
// Uranium
useSym17 = input(true, '', inline = 'sym17', group=GROUP_SYM)
sym17 = input.symbol('AMEX:URA', '', inline = 'sym17', group=GROUP_SYM)
sym17_text = input.string(defval ='☢️', title = '', inline = 'sym17', group=GROUP_SYM)
// -----------------
// Commodities: Agriculture and Livestock
// -----------------
// Corn
useSym18 = input(true, '', inline = 'sym18', group=GROUP_SYM)
sym18 = input.symbol('AMEX:CORN', '', inline = 'sym18', group=GROUP_SYM)
sym18_text = input.string(defval = '🌽', title = '', inline = 'sym18', group=GROUP_SYM)
// Wheat
useSym19 = input(true, '', inline = 'sym19', group=GROUP_SYM)
sym19 = input.symbol('PEPPERSTONE:WHEAT', '', inline = 'sym19', group=GROUP_SYM)
sym19_text = input.string(defval = '🌾', title = '', inline = 'sym19', group=GROUP_SYM)
// Cattle
useSym20 = input(true, '', inline = 'sym20', group=GROUP_SYM)
sym20 = input.symbol('PEPPERSTONE:CATTLE', '', inline = 'sym20', group=GROUP_SYM)
sym20_text = input.string(defval = '🐂', title = '', inline = 'sym20', group=GROUP_SYM)
// -----------------
// FOREX
// -----------------
// U.S. Dollar Index (inverted)
// Currencies in DXY:
// 1. Euro (EUR) 57.6% weight
// 2. Japanese yen (JPY) 13.6% weight
// 3. Pound sterling (GBP) 11.9% weight
// 4. Canadian dollar (CAD) 9.1% weight
// 5. Swedish krona (SEK) 4.2% weight
// 6. Swiss franc (CHF) 3.6% weight
useSym21 = input(true, '', inline = 'sym21', group=GROUP_SYM)
sym21 = input.symbol('1/TVC:DXY', '', inline = 'sym21', group=GROUP_SYM)
sym21_text = input.string(defval ='💵 (inverse)', title = '', inline = 'sym21', group=GROUP_SYM)
// Taiwan Dollar
useSym22 = input(true, '', inline = 'sym22', group=GROUP_SYM)
sym22 = input.symbol('FX_IDC:TWDUSD', '', inline = 'sym22', group=GROUP_SYM)
sym22_text = input.string(defval = ' 🇹🇼', title = '', inline = 'sym22', group=GROUP_SYM)
// South Korean Won
useSym23 = input(true, '', inline = 'sym23', group=GROUP_SYM)
sym23 = input.symbol('FX_IDC:KRWUSD', '', inline = 'sym23', group=GROUP_SYM)
sym23_text = input.string(defval = ' 🇰🇷', title = '', inline = 'sym23', group=GROUP_SYM)
// Chinese Yuan
useSym24 = input(true, '', inline = 'sym24', group=GROUP_SYM)
sym24 = input.symbol('FX_IDC:CNYUSD', '', inline = 'sym24', group=GROUP_SYM)
sym24_text = input.string(defval = ' 🇨🇳', title = '', inline = 'sym24', group=GROUP_SYM)
// Indian Rupee
useSym25 = input(true, '', inline = 'sym25', group=GROUP_SYM)
sym25 = input.symbol('FX_IDC:INRUSD', '', inline = 'sym25', group=GROUP_SYM)
sym25_text = input.string(defval = ' 🇮🇳', title = '', inline = 'sym25', group=GROUP_SYM)
// Brazilian Real
useSym26 = input(true, '', inline = 'sym26', group=GROUP_SYM)
sym26 = input.symbol('FX_IDC:BRLUSD', '', inline = 'sym26', group=GROUP_SYM)
sym26_text = input.string(defval = ' 🇧🇷', title = '', inline = 'sym26', group=GROUP_SYM)
// -----------------
// Treasuries Bonds
// -----------------
// USA 1-Year Treasury Note Yield
useSym27 = input(true, '', inline = 'sym27', group=GROUP_SYM)
sym27 = input.symbol('TVC:US01Y', '', inline = 'sym27', group=GROUP_SYM)
sym27_text = input.string(defval ='🏦', title = '', inline = 'sym27', group=GROUP_SYM)
// USA 10-Year Treasury Note Yield
useSym28 = input(true, '', inline = 'sym28', group=GROUP_SYM)
sym28 = input.symbol('TVC:US10Y', '', inline = 'sym28', group=GROUP_SYM)
sym28_text = input.string(defval = '🏦', title = '', inline = 'sym28', group=GROUP_SYM)
// Japan 10-Year Treasury Note Yield
useSym29 = input(true, '', inline = 'sym29', group=GROUP_SYM)
sym29 = input.symbol('TVC:JP10Y', '', inline = 'sym29', group=GROUP_SYM)
sym29_text = input.string(defval = '🏦', title = '', inline = 'sym29', group=GROUP_SYM)
// Brazil 10-Year Treasury Note Yield
useSym30 = input(true, '', inline = 'sym30', group=GROUP_SYM)
sym30 = input.symbol('TVC:BR10Y', '', inline = 'sym30', group=GROUP_SYM)
sym30_text = input.string(defval = '🏦', title = '', inline = 'sym30', group=GROUP_SYM)
// -----------------
// Misc: Volatility and Fear
// -----------------
// VIX: CBOE Volatility Index (inverted)
useSym31 = input(true, '', inline = 'sym31', group=GROUP_SYM)
sym31 = input.symbol('1/TVC:VIX', '', inline = 'sym31', group=GROUP_SYM)
sym31_text = input.string(defval = '😱 (inverse)', title = '', inline = 'sym31', group=GROUP_SYM)
// -----------------
// Cryptocurrencies
// -----------------
// Total Market Cap
useSym32 = input(true, '', inline = 'sym32', group=GROUP_SYM)
sym32 = input.symbol('CRYPTOCAP:TOTAL', '', inline = 'sym32', group=GROUP_SYM)
sym32_text = input.string(defval = '🚀', title = '', inline = 'sym32', group=GROUP_SYM)
// TOTAL2: Market capitalization of the top-125 cryptocurrencies, excluding BTC
useSym33 = input(true, '', inline = 'sym33', group=GROUP_SYM)
sym33 = input.symbol('CRYPTOCAP:TOTAL2', '', inline = 'sym33', group=GROUP_SYM)
sym33_text = input.string(defval = '🚀', title = '', inline = 'sym33', group=GROUP_SYM)
// TOTAL3: Market capitalization of the top-125 cryptocurrencies, excluding BTC and ETH
useSym34 = input(true, '', inline = 'sym34', group=GROUP_SYM)
sym34 = input.symbol('CRYPTOCAP:TOTAL3', '', inline = 'sym34', group=GROUP_SYM)
sym34_text = input.string(defval = '🚀', title = '', inline = 'sym34', group=GROUP_SYM)
// OTHERS: Market capitalization of the top-125 cryptocurrencies, excluding top 11 listed on
// https://www.tradingview.com/markets/cryptocurrencies/global-charts/
useSym35 = input(true, '', inline = 'sym35', group=GROUP_SYM)
sym35 = input.symbol('CRYPTOCAP:OTHERS', '', inline = 'sym35', group=GROUP_SYM)
sym35_text = input.string(defval = '🚀', title = '', inline = 'sym35', group=GROUP_SYM)
// Market Cap in DeFi
useSym36 = input(true, '', inline = 'sym36', group=GROUP_SYM)
sym36 = input.symbol('CRYPTOCAP:TOTALDEFI', '', inline = 'sym36', group=GROUP_SYM)
sym36_text = input.string(defval = '🚀', title = '', inline = 'sym36', group=GROUP_SYM)
// BTC INDEX: perpetual contract
useSym37 = input(true, '', inline = 'sym37', group=GROUP_SYM)
sym37 = input.symbol('BITFINEX:BTCUSDLONGS', '', inline = 'sym37', group=GROUP_SYM)
sym37_text = input.string(defval = '🚀', title = '', inline = 'sym37', group=GROUP_SYM)
// BTC INDEX: futures contract
useSym38 = input(true, '', inline = 'sym38', group=GROUP_SYM)
sym38 = input.symbol('BITFINEX:BTCF0USTF0LONGS', '', inline = 'sym38', group=GROUP_SYM)
sym38_text = input.string(defval = '🚀', title = '', inline = 'sym38', group=GROUP_SYM)
// ARK Innovation ETF
// Top 10 holdings:
// 1. Tesla (TSLA)
// 2. Roku (ROKU)
// 3. Coinbase (COIN)
// 4. Zoom (ZM)
// 5. Path (UIPATH INC - CLASS A)
// 6. Block Inc (SQ)
// 7. DRAFTKINGS INC-CL A (DKNG UW)
// 8. TWILIO INC - A (TWLO)
// 9. Unity Software (U)
// 10. Shopfy (SHOP)
useSym39 = input(true, '', inline = 'sym39', group=GROUP_SYM)
sym39 = input.symbol('AMEX:ARKK', '', inline = 'sym39', group=GROUP_SYM)
sym39_text = input.string(defval = '🚀', title = '', inline = 'sym39', group=GROUP_SYM)
// Amplify Transformational Data Sharing ETF
// Top 10 holdings:
// 1. Coinbase (COIN)
// 2. MicroStrategy (MSTR)
// 3. SBI HOLDINGS INC (8473 JT)
// 4. ACCENTURE PLC IRELAND CLASS A (ACN)
// 5. GALAXY DIGITAL HOLDINGS LTD (GLXY CN)
// 6. CLEANSPARK INC (CLSK UW)
// 7. GMO INTERNET GROUP (9449 JT)
// 8. PAYPAL HLDGS INC (PYPL UW)
// 9. RIOT PLATFORMS INC (RIOT UW)
// 10. OVERSTOCK COM INC DEL (OSTK UW)
useSym40 = input(true, '', inline = 'sym40', group=GROUP_SYM)
sym40 = input.symbol('AMEX:BLOK', '', inline = 'sym40', group=GROUP_SYM)
sym40_text = input.string(defval = '🚀', title = '', inline = 'sym40', group=GROUP_SYM)
// -------------------------------------------------------------------------------------------------------------- }
//■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
// Begin Calculations
//■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
// Set line styles
// -------------------------------------------------------------------------------------------------------------- {
var reg_div_l_style = reg_div_l_style_ == 'Solid' ? line.style_solid : reg_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
var hid_div_l_style = hid_div_l_style_ == 'Solid' ? line.style_solid : hid_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
// -------------------------------------------------------------------------------------------------------------- }
// Get indicators
// -------------------------------------------------------------------------------------------------------------- {
// RSI
rsi = MI.rsi(source=rsi_source, length=rsi_length)
// MACD
[macd, signalMACD, deltamacd] = MI.macd(source=macd_source, fastLength=macd_fast, slowLength=macd_slow,
signalLength=macd_signal, maTypeFast=macd_type_ma, maTypeSlow=macd_type_ma, maTypeMACD=macd_type_ma)
// Volume weighted MACD
[vwmacd, vwsignalMACD, vwmacdHistogram] = MI.macd(source=macd_source, fastLength=macd_fast, slowLength=macd_slow,
signalLength=macd_signal, maTypeFast=macd_type_ma, maTypeSlow=macd_type_ma, maTypeMACD=4)
// Momentum
moment = ta.mom(mom_source, mom_length)
// CCI
cci = MI.cci(source=cci_source, length=cci_length, maType=cci_type_ma)
// OBV
obv = VI.obv(source=obv_source)
// Stoch
[stk, signalStoch] = MI.stoch(source=stoc_source, kLength=stoc_k, kSmoothing=stoc_d, dSmoothing=stoc_dSmoothing, maTypeK=stoc_type_ma, maTypeD=stoc_type_ma)
// Chaikin money flow
cmf = VI.cmf(length=cmf_length)
// Moneyt Flow Index
mfi = VI.mfi(source=mfi_source, length=mfi_length)
// Stochastic RSI
[stochRSI, signalStochRSI] = MI.stoch(source=rsi, kLength=stoc_k, kSmoothing=stoc_d, dSmoothing=stoc_dSmoothing, maTypeK=stoc_type_ma, maTypeD=stoc_type_ma)
// Volume Oscillator
volumeOsc = VI.vo(shortLen=shortLengthVolumeOsc, longLen=longLengthVolumeOsc)
// Price Volume Trend
pvt = VI.pvt(source=sourcePVT)
// Ultimate Oscillator
ultosc = MI.ultimateOscillator(source=ultosc_source, fastLength=ultosc_length1, middleLength=ultosc_length2, slowLength=ultosc_length3)
// Fisher Transform
[fisher, fisher_signal] = if fisher_source == 'Close'
MI.fisher(length=fisher_length)
else
MI.fisher(sourceHigh=high, sourceLow=low, length=fisher_length)
// Z-Score/T-Score
mean_zscore = switch zscore_mean_type
1 => ta.sma(zscore_source, zscore_mean_length)
2 => ta.ema(zscore_source, zscore_mean_length)
3 => ta.wma(zscore_source, zscore_mean_length)
4 => ta.vwma(zscore_source, zscore_mean_length)
5 => ta.alma(zscore_source, zscore_mean_length, 0.85, 6)
6 => ta.hma(zscore_source, zscore_mean_length)
7 => ta.linreg(zscore_source, zscore_mean_length, na)
8 => ta.rma(zscore_source, zscore_mean_length)
9 => ta.median(zscore_source, zscore_mean_length)
zt_score = if zscore_length < 30
VOL.tscore(src=zscore_source, mean=mean_zscore, length=zscore_length, degreesOfFreedom=zscore_length-1)
else
VOL.zscore(src=zscore_source, mean=mean_zscore, length=zscore_length)
// -------------------------------------------------------------------------------------------------------------- }
// Get symbols
// -------------------------------------------------------------------------------------------------------------- {
get_hl() => sourceSymbols == 'Close' ? close : hl2
// Symbols
sym_1 = request.security(sym1, timeframe.period, get_hl())
sym_2 = request.security(sym2, timeframe.period, get_hl())
sym_3 = request.security(sym3, timeframe.period, get_hl())
sym_4 = request.security(sym4, timeframe.period, get_hl())
sym_5 = request.security(sym5, timeframe.period, get_hl())
sym_6 = request.security(sym6, timeframe.period, get_hl())
sym_7 = request.security(sym7, timeframe.period, get_hl())
sym_8 = request.security(sym8, timeframe.period, get_hl())
sym_9 = request.security(sym9, timeframe.period, get_hl())
sym_10 = request.security(sym10, timeframe.period, get_hl())
sym_11 = request.security(sym11, timeframe.period, get_hl())
sym_12 = request.security(sym12, timeframe.period, get_hl())
sym_13 = request.security(sym13, timeframe.period, get_hl())
sym_14 = request.security(sym14, timeframe.period, get_hl())
sym_15 = request.security(sym15, timeframe.period, get_hl())
sym_16 = request.security(sym16, timeframe.period, get_hl())
sym_17 = request.security(sym17, timeframe.period, get_hl())
sym_18 = request.security(sym18, timeframe.period, get_hl())
sym_19 = request.security(sym19, timeframe.period, get_hl())
sym_20 = request.security(sym20, timeframe.period, get_hl())
sym_21 = request.security(sym21, timeframe.period, get_hl())
sym_22 = request.security(sym22, timeframe.period, get_hl())
sym_23 = request.security(sym23, timeframe.period, get_hl())
sym_24 = request.security(sym24, timeframe.period, get_hl())
sym_25 = request.security(sym25, timeframe.period, get_hl())
sym_26 = request.security(sym26, timeframe.period, get_hl())
sym_27 = request.security(sym27, timeframe.period, get_hl())
sym_28 = request.security(sym28, timeframe.period, get_hl())
sym_29 = request.security(sym29, timeframe.period, get_hl())
sym_30 = request.security(sym30, timeframe.period, get_hl())
sym_31 = request.security(sym31, timeframe.period, get_hl())
sym_32 = request.security(sym32, timeframe.period, get_hl())
sym_33 = request.security(sym33, timeframe.period, get_hl())
sym_34 = request.security(sym34, timeframe.period, get_hl())
sym_35 = request.security(sym35, timeframe.period, get_hl())
sym_36 = request.security(sym36, timeframe.period, get_hl())
sym_37 = request.security(sym37, timeframe.period, get_hl())
sym_38 = request.security(sym38, timeframe.period, get_hl())
sym_39 = request.security(sym39, timeframe.period, get_hl())
sym_40 = request.security(sym40, timeframe.period, get_hl())
// -------------------------------------------------------------------------------------------------------------- }
// Keep indicators names and colors in arrays
// -------------------------------------------------------------------------------------------------------------- {
var indicators_name = array.new_string(60)
var div_colors = array.new_color(4)
var tooltip_names = array.new_string(60)
if barstate.isfirst
// Names
array.set(indicators_name, 0, showindis == 'Full' ? 'MACD' + calcmacd_text : 'MACD')
array.set(indicators_name, 1, showindis == 'Full' ? 'MACD Histogram' + calcmacda_text : 'HIS')
array.set(indicators_name, 2, showindis == 'Full' ? 'RSI' + calcrsi_text : 'RSI')
array.set(indicators_name, 3, showindis == 'Full' ? 'Stochastic' + calcstoc_text : 'STOC')
array.set(indicators_name, 4, showindis == 'Full' ? 'CCI' + calccci_text : 'CCI')
array.set(indicators_name, 5, showindis == 'Full' ? 'Momentum' + calcmom_text : 'MOM')
array.set(indicators_name, 6, showindis == 'Full' ? 'On Balance Volume' + calcobv_text: 'OBV')
array.set(indicators_name, 7, showindis == 'Full' ? 'Volume Weighted MACD' + calcvwmacd_text : 'VMACD')
array.set(indicators_name, 8, showindis == 'Full' ? 'Chaikin Money Flow' + calccmf_text : 'CMF')
array.set(indicators_name, 9, showindis == 'Full' ? 'Money Flow Index' + calcmfi_text : 'MFI')
array.set(indicators_name, 10, showindis == 'Full' ? 'Stochastic RSI' + calcStochRSI_text : 'SRSI')
array.set(indicators_name, 11, showindis == 'Full' ? 'Volume Oscillator' + calcVolumeOsc_text : 'VO')
array.set(indicators_name, 12, showindis == 'Full' ? 'Price Volume Trend' + calcPVT_text : 'PVT')
array.set(indicators_name, 13, showindis == 'Full' ? 'Ultimate Oscillator' + calcUltimateOsc_text : 'UO')
array.set(indicators_name, 14, showindis == 'Full' ? 'Fisher Transform' + calcFisherTransform_text : 'FT')
array.set(indicators_name, 15, showindis == 'Full' ? (zscore_length < 30 ? 'T-Score' : 'Z-Score') + calcZscore_text : 'ZSC')
array.set(indicators_name, 16, showindis == 'Full' ? externalIndicator_1_text : 'EX1')
array.set(indicators_name, 17, showindis == 'Full' ? externalIndicator_2_text : 'EX2')
array.set(indicators_name, 18, showindis == 'Full' ? externalIndicator_3_text : 'EX3')
array.set(indicators_name, 19, showindis == 'Full' ? externalIndicator_4_text : 'EX4')
array.set(indicators_name, 20, showindis == 'Full' ? syminfo.ticker(sym1) + sym1_text : 'S1')
array.set(indicators_name, 21, showindis == 'Full' ? syminfo.ticker(sym2) + sym2_text: 'S2')
array.set(indicators_name, 22, showindis == 'Full' ? syminfo.ticker(sym3) + sym3_text: 'S3')
array.set(indicators_name, 23, showindis == 'Full' ? syminfo.ticker(sym4) + sym4_text: 'S4')
array.set(indicators_name, 24, showindis == 'Full' ? syminfo.ticker(sym5) + sym5_text: 'S5')
array.set(indicators_name, 25, showindis == 'Full' ? syminfo.ticker(sym6) + sym6_text: 'S6')
array.set(indicators_name, 26, showindis == 'Full' ? syminfo.ticker(sym7) + sym7_text: 'S7')
array.set(indicators_name, 27, showindis == 'Full' ? syminfo.ticker(sym8) + sym8_text: 'S8')
array.set(indicators_name, 28, showindis == 'Full' ? syminfo.ticker(sym9) + sym9_text: 'S9')
array.set(indicators_name, 29, showindis == 'Full' ? syminfo.ticker(sym10) + sym10_text : 'S10')
array.set(indicators_name, 30, showindis == 'Full' ? syminfo.ticker(sym11) + sym11_text : 'S11')
array.set(indicators_name, 31, showindis == 'Full' ? syminfo.ticker(sym12) + sym12_text : 'S12')
array.set(indicators_name, 32, showindis == 'Full' ? syminfo.ticker(sym13) + sym13_text : 'S13')
array.set(indicators_name, 33, showindis == 'Full' ? syminfo.ticker(sym14) + sym14_text : 'S14')
array.set(indicators_name, 34, showindis == 'Full' ? syminfo.ticker(sym15) + sym15_text : 'S15')
array.set(indicators_name, 35, showindis == 'Full' ? syminfo.ticker(sym16) + sym16_text : 'S16')
array.set(indicators_name, 36, showindis == 'Full' ? syminfo.ticker(sym17) + sym17_text : 'S17')
array.set(indicators_name, 37, showindis == 'Full' ? syminfo.ticker(sym18) + sym18_text : 'S18')
array.set(indicators_name, 38, showindis == 'Full' ? syminfo.ticker(sym19) + sym19_text : 'S19')
array.set(indicators_name, 39, showindis == 'Full' ? syminfo.ticker(sym20) + sym20_text : 'S20')
array.set(indicators_name, 40, showindis == 'Full' ? syminfo.ticker(sym21) + sym21_text : 'S21')
array.set(indicators_name, 41, showindis == 'Full' ? syminfo.ticker(sym22) + sym22_text : 'S22')
array.set(indicators_name, 42, showindis == 'Full' ? syminfo.ticker(sym23) + sym23_text : 'S23')
array.set(indicators_name, 43, showindis == 'Full' ? syminfo.ticker(sym24) + sym24_text : 'S24')
array.set(indicators_name, 44, showindis == 'Full' ? syminfo.ticker(sym25) + sym25_text : 'S25')
array.set(indicators_name, 45, showindis == 'Full' ? syminfo.ticker(sym26) + sym26_text : 'S26')
array.set(indicators_name, 46, showindis == 'Full' ? syminfo.ticker(sym27) + sym27_text : 'S27')
array.set(indicators_name, 47, showindis == 'Full' ? syminfo.ticker(sym28) + sym28_text : 'S28')
array.set(indicators_name, 48, showindis == 'Full' ? syminfo.ticker(sym29) + sym29_text : 'S29')
array.set(indicators_name, 49, showindis == 'Full' ? syminfo.ticker(sym30) + sym30_text : 'S30')
array.set(indicators_name, 50, showindis == 'Full' ? syminfo.ticker(sym31) + sym31_text : 'S31')
array.set(indicators_name, 51, showindis == 'Full' ? syminfo.ticker(sym32) + sym32_text : 'S32')
array.set(indicators_name, 52, showindis == 'Full' ? syminfo.ticker(sym33) + sym33_text : 'S33')
array.set(indicators_name, 53, showindis == 'Full' ? syminfo.ticker(sym34) + sym34_text : 'S34')
array.set(indicators_name, 54, showindis == 'Full' ? syminfo.ticker(sym35) + sym35_text : 'S35')
array.set(indicators_name, 55, showindis == 'Full' ? syminfo.ticker(sym36) + sym36_text : 'S36')
array.set(indicators_name, 56, showindis == 'Full' ? syminfo.ticker(sym37) + sym37_text : 'S37')
array.set(indicators_name, 57, showindis == 'Full' ? syminfo.ticker(sym38) + sym38_text : 'S38')
array.set(indicators_name, 58, showindis == 'Full' ? syminfo.ticker(sym39) + sym39_text : 'S39')
array.set(indicators_name, 59, showindis == 'Full' ? syminfo.ticker(sym40) + sym40_text : 'S40')
// Tooltips
array.set(tooltip_names, 0, 'MACD' + calcmacd_text)
array.set(tooltip_names, 1, 'MACD Histogram' + calcmacda_text)
array.set(tooltip_names, 2, 'RSI' + calcrsi_text)
array.set(tooltip_names, 3, 'Stochastic' + calcstoc_text)
array.set(tooltip_names, 4, 'CCI' + calccci_text)
array.set(tooltip_names, 5, 'Momentum' + calcmom_text)
array.set(tooltip_names, 6, 'On Balance Volume' + calcobv_text)
array.set(tooltip_names, 7, 'Volume Weighted MACD' + calcvwmacd_text)
array.set(tooltip_names, 8, 'Chaikin Money Flow' + calccmf_text)
array.set(tooltip_names, 9, 'Money Flow Index' + calcmfi_text)
array.set(tooltip_names, 10, 'Stochastic RSI' + calcStochRSI_text)
array.set(tooltip_names, 11, 'Volume Oscillator' + calcVolumeOsc_text)
array.set(tooltip_names, 12, 'Price Volume Trend' + calcPVT_text)
array.set(tooltip_names, 13, 'Ultimate Oscillator' + calcUltimateOsc_text)
array.set(tooltip_names, 14, 'Fisher Transform' + calcFisherTransform_text)
array.set(tooltip_names, 15, (zscore_length < 30 ? 'T-Score' : 'Z-Score') + calcZscore_text)
array.set(tooltip_names, 16, externalIndicator_1_text)
array.set(tooltip_names, 17, externalIndicator_2_text)
array.set(tooltip_names, 18, externalIndicator_3_text)
array.set(tooltip_names, 19, externalIndicator_4_text)
array.set(tooltip_names, 20, syminfo.ticker(sym1) + sym1_text)
array.set(tooltip_names, 21, syminfo.ticker(sym2) + sym2_text)
array.set(tooltip_names, 22, syminfo.ticker(sym3) + sym3_text)
array.set(tooltip_names, 23, syminfo.ticker(sym4) + sym4_text)
array.set(tooltip_names, 24, syminfo.ticker(sym5) + sym5_text)
array.set(tooltip_names, 25, syminfo.ticker(sym6) + sym6_text)
array.set(tooltip_names, 26, syminfo.ticker(sym7) + sym7_text)
array.set(tooltip_names, 27, syminfo.ticker(sym8) + sym8_text)
array.set(tooltip_names, 28, syminfo.ticker(sym9) + sym9_text)
array.set(tooltip_names, 29, syminfo.ticker(sym10) + sym10_text)
array.set(tooltip_names, 30, syminfo.ticker(sym11) + sym11_text)
array.set(tooltip_names, 31, syminfo.ticker(sym12) + sym12_text)
array.set(tooltip_names, 32, syminfo.ticker(sym13) + sym13_text)
array.set(tooltip_names, 33, syminfo.ticker(sym14) + sym14_text)
array.set(tooltip_names, 34, syminfo.ticker(sym15) + sym15_text)
array.set(tooltip_names, 35, syminfo.ticker(sym16) + sym16_text)
array.set(tooltip_names, 36, syminfo.ticker(sym17) + sym17_text)
array.set(tooltip_names, 37, syminfo.ticker(sym18) + sym18_text)
array.set(tooltip_names, 38, syminfo.ticker(sym19) + sym19_text)
array.set(tooltip_names, 39, syminfo.ticker(sym20) + sym20_text)
array.set(tooltip_names, 40, syminfo.ticker(sym21) + sym21_text)
array.set(tooltip_names, 41, syminfo.ticker(sym22) + sym22_text)
array.set(tooltip_names, 42, syminfo.ticker(sym23) + sym23_text)
array.set(tooltip_names, 43, syminfo.ticker(sym24) + sym24_text)
array.set(tooltip_names, 44, syminfo.ticker(sym25) + sym25_text)
array.set(tooltip_names, 45, syminfo.ticker(sym26) + sym26_text)
array.set(tooltip_names, 46, syminfo.ticker(sym27) + sym27_text)
array.set(tooltip_names, 47, syminfo.ticker(sym28) + sym28_text)
array.set(tooltip_names, 48, syminfo.ticker(sym29) + sym29_text)
array.set(tooltip_names, 49, syminfo.ticker(sym30) + sym30_text)
array.set(tooltip_names, 50, syminfo.ticker(sym31) + sym31_text)
array.set(tooltip_names, 51, syminfo.ticker(sym32) + sym32_text)
array.set(tooltip_names, 52, syminfo.ticker(sym33) + sym33_text)
array.set(tooltip_names, 53, syminfo.ticker(sym34) + sym34_text)
array.set(tooltip_names, 54, syminfo.ticker(sym35) + sym35_text)
array.set(tooltip_names, 55, syminfo.ticker(sym36) + sym36_text)
array.set(tooltip_names, 56, syminfo.ticker(sym37) + sym37_text)
array.set(tooltip_names, 57, syminfo.ticker(sym38) + sym38_text)
array.set(tooltip_names, 58, syminfo.ticker(sym39) + sym39_text)
array.set(tooltip_names, 59, syminfo.ticker(sym40) + sym40_text)
// Colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)
// -------------------------------------------------------------------------------------------------------------- }
// Pivots Highs and Lows
// -------------------------------------------------------------------------------------------------------------- {
// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh(source == 'Close' ? close : high, prd, prd)
float pl = ta.pivotlow(source == 'Close' ? close : low, prd, prd)
plotshape(ph and showpivot, text='H', style=shape.labeldown, color=color.new(color.white, 100), textcolor=color.new(color.red, 0),
location=location.abovebar, offset=-prd, size=size.small, editable=true)
plotshape(pl and showpivot, text='L', style=shape.labelup, color=color.new(color.white, 100), textcolor=color.new(color.lime, 0),
location=location.belowbar, offset=-prd, size=size.small, editable=true)
// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
// add PHs to the array
if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)
// add PLs to the array
if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)
// -------------------------------------------------------------------------------------------------------------- }
// Functions to check Regular Divergences and Hidden Divergences
// -------------------------------------------------------------------------------------------------------------- {
// @function Check positive regular or negative hidden divergence
// @param {float} src - source value
// @param {int} cond - condition. 1 => positive regular, 2 => negative hidden
// @returns {int} divergence length
positive_regular_positive_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : low
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src > src[1] or close > close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x))) or
(cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - close[len]) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// @function Check negative regular or positive hidden divergence
// @param {float} src - source value
// @param {int} cond - condition. 1 => negative regular, 2 => positive hidden
// @returns {int} divergence length
negative_regular_negative_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : high
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src < src[1] or close < close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and
((cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x))) or
(cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x))))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1
if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
arrived := false
break
virtual_line1 := virtual_line1 - slope1
virtual_line2 := virtual_line2 - slope2
if arrived
divlen := len
break
divlen
// -------------------------------------------------------------------------------------------------------------- }
// Start to check divergences
// -------------------------------------------------------------------------------------------------------------- {
// @function Calculate 4 types of divergence if enabled in the options and return divergences in an array
// @param {bool} cond - condition to check divergence
// @param {float} indicator - indicator value
calculate_divs(cond, indicator)=>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator, 1) : 0)
array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator, 1) : 0)
array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator, 2) : 0)
array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator, 2) : 0)
divs
// array to keep all divergences
var all_divergences = array.new_int(240) // 60 indicators * 4 divergence = 240
// set related array elements
array_set_divs(div_pointer, index) =>
for x = 0 to 3 by 1
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// set divergences array
array_set_divs(calculate_divs(calcmacd, macd), 0)
array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
array_set_divs(calculate_divs(calcrsi, rsi), 2)
array_set_divs(calculate_divs(calcstoc, stk), 3)
array_set_divs(calculate_divs(calccci, cci), 4)
array_set_divs(calculate_divs(calcmom, moment), 5)
array_set_divs(calculate_divs(calcobv, obv), 6)
array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
array_set_divs(calculate_divs(calccmf, cmf), 8)
array_set_divs(calculate_divs(calcmfi, mfi), 9)
array_set_divs(calculate_divs(calcStochRSI, stochRSI), 10)
array_set_divs(calculate_divs(calcVolumeOsc, volumeOsc), 11)
array_set_divs(calculate_divs(calcPVT, pvt), 12)
array_set_divs(calculate_divs(calcUltimateOsc, ultosc), 13)
array_set_divs(calculate_divs(calcFisherTransform, fisher), 14)
array_set_divs(calculate_divs(calcZscore, zt_score), 15)
array_set_divs(calculate_divs(calcExt_1, externalIndicator_1), 16)
array_set_divs(calculate_divs(calcExt_2, externalIndicator_2), 17)
array_set_divs(calculate_divs(calcExt_3, externalIndicator_3), 18)
array_set_divs(calculate_divs(calcExt_4, externalIndicator_4), 19)
array_set_divs(calculate_divs(useSym1, sym_1), 20)
array_set_divs(calculate_divs(useSym2, sym_2), 21)
array_set_divs(calculate_divs(useSym3, sym_3), 22)
array_set_divs(calculate_divs(useSym4, sym_4), 23)
array_set_divs(calculate_divs(useSym5, sym_5), 24)
array_set_divs(calculate_divs(useSym6, sym_6), 25)
array_set_divs(calculate_divs(useSym7, sym_7), 26)
array_set_divs(calculate_divs(useSym8, sym_8), 27)
array_set_divs(calculate_divs(useSym9, sym_9), 28)
array_set_divs(calculate_divs(useSym10, sym_10), 29)
array_set_divs(calculate_divs(useSym11, sym_11), 30)
array_set_divs(calculate_divs(useSym12, sym_12), 31)
array_set_divs(calculate_divs(useSym13, sym_13), 32)
array_set_divs(calculate_divs(useSym14, sym_14), 33)
array_set_divs(calculate_divs(useSym15, sym_15), 34)
array_set_divs(calculate_divs(useSym16, sym_16), 35)
array_set_divs(calculate_divs(useSym17, sym_17), 36)
array_set_divs(calculate_divs(useSym18, sym_18), 37)
array_set_divs(calculate_divs(useSym19, sym_19), 38)
array_set_divs(calculate_divs(useSym20, sym_20), 39)
array_set_divs(calculate_divs(useSym21, sym_21), 40)
array_set_divs(calculate_divs(useSym22, sym_22), 41)
array_set_divs(calculate_divs(useSym23, sym_23), 42)
array_set_divs(calculate_divs(useSym24, sym_24), 43)
array_set_divs(calculate_divs(useSym25, sym_25), 44)
array_set_divs(calculate_divs(useSym26, sym_26), 45)
array_set_divs(calculate_divs(useSym27, sym_27), 46)
array_set_divs(calculate_divs(useSym28, sym_28), 47)
array_set_divs(calculate_divs(useSym29, sym_29), 48)
array_set_divs(calculate_divs(useSym30, sym_30), 49)
array_set_divs(calculate_divs(useSym31, sym_31), 50)
array_set_divs(calculate_divs(useSym32, sym_32), 51)
array_set_divs(calculate_divs(useSym33, sym_33), 52)
array_set_divs(calculate_divs(useSym34, sym_34), 53)
array_set_divs(calculate_divs(useSym35, sym_35), 54)
array_set_divs(calculate_divs(useSym36, sym_36), 55)
array_set_divs(calculate_divs(useSym37, sym_37), 56)
array_set_divs(calculate_divs(useSym38, sym_38), 57)
array_set_divs(calculate_divs(useSym39, sym_39), 58)
array_set_divs(calculate_divs(useSym40, sym_40), 59)
// check minimum number of divergence, if less than showlimit then delete all divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1
total_div += math.round(math.sign(array.get(all_divergences, x)))
total_div
if total_div < showlimit
array.fill(all_divergences, 0)
// keep line in an array
var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
var pos_div_support_resistance = array.new_line(0)
var neg_div_support_resistance = array.new_line(0)
// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines() =>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1
line.delete(array.get(pos_div_lines, j))
array.clear(pos_div_lines)
delete_old_neg_div_lines() =>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1
line.delete(array.get(neg_div_lines, j))
array.clear(neg_div_lines)
delete_old_pos_div_labels() =>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)
delete_old_pos_div_support_resistance() =>
if array.size(pos_div_support_resistance) > 0
for j = 0 to array.size(pos_div_support_resistance) - 1
line.delete(array.get(pos_div_support_resistance, j))
array.clear(pos_div_support_resistance)
delete_old_neg_div_labels() =>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)
delete_old_neg_div_support_resistance() =>
if array.size(neg_div_support_resistance) > 0
for j = 0 to array.size(neg_div_support_resistance) - 1
line.delete(array.get(neg_div_support_resistance, j))
array.clear(neg_div_support_resistance)
// delete last creted lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n) =>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n) =>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)
delete_last_pos_div_support_resistance(n) =>
if n > 0 and array.size(pos_div_support_resistance) >= n
asz = array.size(pos_div_support_resistance)
for j = 1 to n
line.delete(array.get(pos_div_support_resistance, asz - j))
array.pop(pos_div_support_resistance)
delete_last_neg_div_support_resistance(n) =>
if n > 0 and array.size(neg_div_support_resistance) >= n
asz = array.size(neg_div_support_resistance)
for j = 1 to n
line.delete(array.get(neg_div_support_resistance, asz - j))
array.pop(neg_div_support_resistance)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false
// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
// draw divergences lines and labels
divergence_text_top = ''
divergence_text_bottom = ''
divergence_tooltip_top = ''
divergence_tooltip_bottom = ''
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
_extend = switch support_resistance_extend
'Both' => extend.both
'Right' => extend.right
'Left' => extend.left
'None' => extend.none
for x = 0 to 59 by 1
div_type = -1
for y = 0 to 3
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if (y % 2) == 1
dnumdiv_top := dnumdiv_top + 1
top_label_col := array.get(div_colors, y)
if (y % 2) == 0
dnumdiv_bottom := dnumdiv_bottom + 1
bottom_label_col := array.get(div_colors, y)
if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = if showlines
line.new(
x1 = bar_index - array.get(all_divergences, x * 4 + y),
y1 = (source == "Close" ? close[array.get(all_divergences, x * 4 + y)] : (y % 2) == 0 ? low[array.get(all_divergences, x * 4 + y)] : high[array.get(all_divergences, x * 4 + y)]),
x2 = bar_index,
y2 = (source == "Close" ? close : (y % 2) == 0 ? low : high),
color = array.get(div_colors, y),
style = y < 2 ? reg_div_l_style : hid_div_l_style,
width = y < 2 ? reg_div_l_width : hid_div_l_width)
else
na
new_support_resistance = if show_support_resistance
_new_support_resistance = line.new(
x1 = bar_index,
y1 = (source == "Close" ? close : (y % 2) == 0 ? low : high),
x2 = bar_index+support_resistance_bars,
y2 = (source == "Close" ? close : (y % 2) == 0 ? low : high),
extend = _extend,
color = array.get(div_colors, y),
style = y < 2 ? reg_div_l_style : hid_div_l_style,
width = y < 2 ? reg_div_l_width : hid_div_l_width)
else
na
if (y % 2) == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
if show_support_resistance
delete_last_pos_div_support_resistance(last_pos_div_lines)
last_pos_div_lines := 0
if showlast
delete_old_pos_div_lines()
if show_support_resistance
delete_old_pos_div_support_resistance()
array.push(pos_div_lines, new_line)
array.push(pos_div_support_resistance, new_support_resistance)
last_pos_div_lines := last_pos_div_lines + 1
remove_last_pos_divs := true
if (y % 2) == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
if show_support_resistance
delete_last_neg_div_support_resistance(last_neg_div_lines)
last_neg_div_lines := 0
if showlast
delete_old_neg_div_lines()
if show_support_resistance
delete_old_neg_div_support_resistance()
array.push(neg_div_lines, new_line)
array.push(neg_div_support_resistance, new_support_resistance)
last_neg_div_lines := last_neg_div_lines + 1
remove_last_neg_divs := true
// set variables for alerts
if y == 0
pos_reg_div_detected := true
if y == 1
neg_reg_div_detected := true
if y == 2
pos_hid_div_detected := true
if y == 3
neg_hid_div_detected := true
// Get text for labels
if div_type >= 0
_char_separator_top = str.length(divergence_text_top) > 0 ? char_separator : ''
_char_separator_bottom = str.length(divergence_text_bottom) > 0 ? char_separator : ''
// Labels
divergence_text_top += (div_type % 2 == 1 ? showindis != 'Don\'t Show' ? _char_separator_top + array.get(indicators_name, x) : '' : '')
divergence_text_bottom += (div_type % 2 == 0 ? showindis != 'Don\'t Show' ? _char_separator_bottom + array.get(indicators_name, x) : '' : '')
// Tooltips
_tooltip_separator_top = str.length(divergence_tooltip_top) > 0 ? char_separator : ''
_tooltip_separator_bottom = str.length(divergence_tooltip_bottom) > 0 ? char_separator : ''
divergence_tooltip_top += (div_type % 2 == 1 ? _tooltip_separator_top + array.get(tooltip_names, x) : '')
divergence_tooltip_bottom += (div_type % 2 == 0 ? _tooltip_separator_bottom + array.get(tooltip_names, x) : '')
// Plot labels and tooltips
if showindis != 'Don\'t Show' or shownum
// Concatenate number of divergences
if shownum and dnumdiv_top > 0
divergence_text_top := divergence_text_top + (showindis=='Full' or showindis=='Abbreviation' ? '\n' : '') + str.tostring(dnumdiv_top)
if shownum and dnumdiv_bottom > 0
divergence_text_bottom := divergence_text_bottom + (showindis=='Full' or showindis=='Abbreviation' ? '\n' : '') + str.tostring(dnumdiv_bottom)
// Draw labels and tooltips (top)
if divergence_text_top != ''
if showlast
delete_old_neg_div_labels()
yShift = yShiftPercent/100 * high
label_top = label.new(x = bar_index, y = math.max(high, high[1]) + yShift, text = divergence_text_top, color = top_label_col,
textcolor = neg_div_text_col, style = label.style_label_down)
array.push(neg_div_labels, label_top)
if show_tooltip
label.set_tooltip(id=label_top, tooltip=divergence_tooltip_top)
// Draw labels and tooltips (bottom)
if divergence_text_bottom != ''
if showlast
delete_old_pos_div_labels()
yShift = yShiftPercent/100 * low
label_bottom = label.new(x = bar_index, y = math.min(low, low[1]) - yShift, text = divergence_text_bottom, color = bottom_label_col,
textcolor = pos_div_text_col, style = label.style_label_up)
array.push(pos_div_labels, label_bottom)
if show_tooltip
label.set_tooltip(id=label_bottom, tooltip=divergence_tooltip_bottom)
// -------------------------------------------------------------------------------------------------------------- }
// Alerts
// -------------------------------------------------------------------------------------------------------------- {
// Individual Divergence Alerts
alertcondition(pos_reg_div_detected, title='Positive Regular Divergence Detected', message='Positive Regular Divergence Detected')
alertcondition(neg_reg_div_detected, title='Negative Regular Divergence Detected', message='Negative Regular Divergence Detected')
alertcondition(pos_hid_div_detected, title='Positive Hidden Divergence Detected', message='Positive Hidden Divergence Detected')
alertcondition(neg_hid_div_detected, title='Negative Hidden Divergence Detected', message='Negative Hidden Divergence Detected')
// Combined Divergence Alerts
alertcondition(pos_reg_div_detected or pos_hid_div_detected, title='Positive Divergence Detected', message='Positive Divergence Detected')
alertcondition(neg_reg_div_detected or neg_hid_div_detected, title='Negative Divergence Detected', message='Negative Divergence Detected')
// All Divergence Alerts
alertcondition(pos_reg_div_detected or neg_reg_div_detected or pos_hid_div_detected or neg_hid_div_detected, title='Divergence Detected', message='Divergence Detected')
// -------------------------------------------------------------------------------------------------------------- }
|
Bollinger RSI Bands | https://www.tradingview.com/script/hPKHu9UA-Bollinger-RSI-Bands/ | tseddik | https://www.tradingview.com/u/tseddik/ | 46 | 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/
// © tseddik
//@version=5
indicator(title="Bollinger RSI Bands", shorttitle="BRSIB", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
// RSI Settings
rsiLength = input.int(14, minval=1, title="RSI Length")
rsiSource = input.source(close, "Source")
candlesMAType = input.string("EMA", title="Candles MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
candleLength = input.int(5, minval=1, title="Candle Length")
candleMALength = input.int(5, minval=1, title="Candle MA Length")
bollingerMAType = input.string("SMA", title="Bollinger MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
bollingerMALength = input.int(14, title="MA Length")
bbStdDev = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev")
RSIma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"WMA" => ta.wma(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"VWMA" => ta.vwma(source, length)
bbma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"WMA" => ta.wma(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"VWMA" => ta.vwma(source, length)
rsio = ta.rsi(open, candleLength)
rsih = ta.rsi(high, candleLength)
rsil = ta.rsi(low, candleLength)
rsic = ta.rsi(close, candleLength)
s_rsio = RSIma(rsio, candleMALength,candlesMAType)
s_rsih = RSIma(rsih, candleMALength,candlesMAType)
s_rsil = RSIma(rsil, candleMALength,candlesMAType)
s_rsic = RSIma(rsic, candleMALength,candlesMAType)
up = ta.rma(math.max(ta.change(rsiSource), 0), rsiLength)
down = ta.rma(-math.min(ta.change(rsiSource), 0), rsiLength)
rsiValue = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMAMovAvg = bbma(rsiValue, bollingerMALength , bollingerMAType)
// Plot Candle Colors
candleColor = s_rsic >= s_rsio ? #056656 : #ec407a
plotcandle(s_rsio,s_rsih,s_rsil,s_rsic, color=candleColor)
// Plot RSI and RSI-Based MA
rsiPlot = plot(rsiValue, "RSI", color=#000000)
plot(rsiMAMovAvg, "RSI-based MA", color=#787B86)
// Plot RSI Bands
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=#ff000014, title="RSI Background Fill")
// Plot Bollinger Bands
bbUpperBand = plot(rsiMAMovAvg + ta.stdev(rsiValue, bollingerMALength) * bbStdDev, title="Upper Bollinger Band", color=#f7525f)
bbLowerBand = plot(rsiMAMovAvg - ta.stdev(rsiValue, bollingerMALength) * bbStdDev, title="Lower Bollinger Band", color=#f7525f)
fill(bbUpperBand, bbLowerBand, color=color.new(color.green, 90), title="Bollinger Bands Background Fill")
|
Super SMA 5 8 13 | https://www.tradingview.com/script/MX8EUksX/ | tamerbozoglu | https://www.tradingview.com/u/tamerbozoglu/ | 116 | 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/
// © tamerbozoglu
//@version=4
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
//# *
//# * Study : SMA 5 8 13 Buy / Sell Signal
//# * Author : @BozzTamer
//# * Strategist : @xtrader_
//# * Revision History
//# * Release : Sep 17, 2023
//# *
//# *
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //
//
//This indicator is based on the 5 8 13 simple moving average strategy of strategist Selcuk Gonencler.
//The indicator shows buy and sell signals when favorable conditions occur.
// ══ H O W T O U S E ══════════════════════════════════════════════════════════════════════════ //
// Above 5-8-13 - Confirmed hold/buy
// 5 below (8-13 above) - Be careful, lose weight but don't run away.
// Below 5-8 (above 13) - Risk has begun. Don't be stubborn. 13 is your last castle.
// 5-8-13 below. Don't fight! Wait until it rises above 5-8 again.
study(title="Super SMA 5 8 13", overlay=true)
src = close
ma5 = sma(src, 5)
ma8 = sma(src, 8)
ma13 = sma(src, 13)
buy_cond = cross(ma5, ma13) and ma5 > ma13
sell_cond = cross(ma5, ma13) and ma5 < ma8 and ma5 < ma13
plot( ma5, color=color.rgb(0, 255, 8), style=plot.style_line, title="SMA 5", linewidth=2, transp = 0)
plot( ma8, color=color.rgb(255, 230, 0), style=plot.style_line, title="SMA 8", linewidth=2, transp = 0)
plot( ma13, color=color.rgb(255, 0, 0), style=plot.style_line, title="SMA 13", linewidth=2, transp = 0)
plotarrow(buy_cond ? 1 : 0, colordown=color.rgb(0, 255, 8), title="BUY SIGNAL",maxheight=50, minheight=50, transp = 0)
plotarrow(sell_cond ? -1 : 0, colorup=color.rgb(255, 0, 0), title="SELL SIGNAL",maxheight=50, minheight=50, transp = 0)
alertcondition(buy_cond, title = "Buy Condition", message = "Buy Alert!")
alertcondition(sell_cond, title = "Sell Condition", message = "Sell Alert!") |
Buy/Sell Box | https://www.tradingview.com/script/Q0pX4Ddc-Buy-Sell-Box/ | AleSaira | https://www.tradingview.com/u/AleSaira/ | 72 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AleSaira
//@version=5
indicator(title="Buy/Sell Box", shorttitle="Buy/Sell Box", overlay=true)
//================================================================================================}
// Input for the number of horizontal candles in the box
boxWidth = input.int (5, title="Box Width", minval=1)
// Input for the box lines color
boxLineColor = input.color (color.rgb(85, 59, 255), title="Box Line Color")
// Input for the box lines width
boxLine = input.int (2, title="Box Lines", minval=1)
// Input for the doji size
sizeDoji = input.float (0.15, title="Doji Size", minval=0.05)
//================================================================================================}
// Calculate the size of the doji's body
dojiSize = math.abs(open - close)
// Identify a doji if the body size is very small compared to the entire range
isDoji = dojiSize < (high - low) * sizeDoji
//================================================================================================}
// Calculate rectangle coordinates
rectTop = math.max(high[1], low[1])
rectBottom = math.min(high[1], low[1])
rectLeft = bar_index[1]
rectRight = bar_index + boxWidth
//================================================================================================}
// Draw rectangle lines if it's a doji
if isDoji
line.new(x1=rectLeft, y1=rectTop, x2=rectRight, y2=rectTop, width=boxLine, color=boxLineColor)
line.new(x1=rectRight, y1=rectTop, x2=rectRight, y2=rectBottom, width=boxLine, color=boxLineColor)
line.new(x1=rectLeft, y1=rectBottom, x2=rectRight, y2=rectBottom, width=boxLine, color=boxLineColor)
line.new(x1=rectLeft, y1=rectTop, x2=rectLeft, y2=rectBottom, width=boxLine, color=boxLineColor)
//================================================================================================}
// Calculate the 200-period Exponential Moving Average (EMA)
ema150 = ta.ema(close, 150)
// Condition for "buy" signal
buy_condition = close > rectTop and close[1] < rectTop and close[1] > close[2] and close > close[1] and close > ema150
sell_condition = close <= rectBottom and close[1] > rectBottom and close[1] < close[2] and close < close[1] and close < ema150
buy_condition1 = buy_condition[1] ? (close[1] < close) : false
sell_condition1 = sell_condition[1] ? (close[1] > close) : false
//================================================================================================}
//================================================================================================}
// Plot signals on the chart
plotshape(series=sell_condition1, location=location.abovebar, color=color.rgb(204, 23, 135), style=shape.circle, title="Sell Signal", text="Sell", textcolor=color.black)
plotshape(series=buy_condition1, location=location.belowbar, color=color.rgb(18, 189, 205), style=shape.circle, title="Buy Signal", text="Buy", textcolor=color.white)
//================================================================================================}
//================================================================================================}
highestHigh = ta.highest(high, 20)[1]
lowestLow = ta.lowest(low, 20)[1]
//================================================================================================}
// Plot the extreme prices for confirmation
plot(highestHigh, color=color.rgb(222, 13, 233), linewidth=1)
plot(lowestLow, color=color.rgb(15, 195, 198), linewidth=1)
//================================================================================================}
alertcondition(buy_condition, title="Buy Out_of_box", message="Buy out")
alertcondition(sell_condition, title="Sell Out_of_box", message="Sell out")
//================================================================================================}
|
Forex & Stock Daily WatchList And Screener [M] | https://www.tradingview.com/script/7LWKEIkk-Forex-Stock-Daily-WatchList-And-Screener-M/ | Milvetti | https://www.tradingview.com/u/Milvetti/ | 43 | 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/
// © Milvetti
//@version=5
indicator("Forex & Stock Daily WatchList And Screener [M]",overlay = true)
gI = "Indices"
openIndices = input(true,"Show Indices Table",inline = "Ind",group = gI)
indPos = input.string("Top Right","",["Top Left","Top Center","Top Right","Middle Left","Middle Center","Middle Right","Bottom Left","Bottom Center","Bottom Right"],inline = "Ind",group = gI)
a01 = input.bool(true, title = "", group = gI, inline = 'i01')
a02 = input.bool(true, title = "", group = gI, inline = 'i02')
a03 = input.bool(true, title = "", group = gI, inline = 'i03')
a04 = input.bool(true, title = "", group = gI, inline = 'i04')
a05 = input.bool(true, title = "", group = gI, inline = 'i05')
a06 = input.bool(true, title = "", group = gI, inline = 'i06')
a07 = input.bool(true, title = "", group = gI, inline = 'i07')
a08 = input.bool(true, title = "", group = gI, inline = 'i08')
a09 = input.bool(true, title = "", group = gI, inline = 'i09')
a10 = input.bool(true, title = "", group = gI, inline = 'i10')
a11 = input.bool(true, title = "", group = gI, inline = 'i11')
a12 = input.bool(true, title = "", group = gI, inline = 'i12')
a13 = input.bool(true, title = "", group = gI, inline = 'i13')
a14 = input.bool(true, title = "", group = gI, inline = 'i14')
i01 = input.symbol('DXY', "",group = gI, inline = 'i01')
i02 = input.symbol('VIX', "",group = gI, inline = 'i02')
i03 = input.symbol('US05Y/US10Y', "",group = gI, inline = 'i03')
i04 = input.symbol('SP500',"", group = gI, inline = 'i04')
i05 = input.symbol('DJI', "",group = gI, inline = 'i05')
i06 = input.symbol('NASDAQ', "", group = gI, inline = 'i06')
i07 = input.symbol('BDI',"", group = gI, inline = 'i07')
i08 = input.symbol('FTSE', "", group = gI, inline = 'i08')
i09 = input.symbol('Nikkei', "", group = gI, inline = 'i09')
i10 = input.symbol('FESX1!', "", group = gI, inline = 'i10')
i11 = input.symbol('hsi', "", group = gI, inline = 'i11')
i12 = input.symbol('brent', "", group = gI, inline = 'i12')
i13 = input.symbol('wti', "", group = gI, inline = 'i13')
i14 = input.symbol('XAUXAG', "", group = gI, inline = 'i14')
gS = 'Symbols'
openSymbols = input(true,"Show Fx Table",inline = "Sym",group = gS)
symPos = input.string("Bottom Right","",["Top Left","Top Center","Top Right","Middle Left","Middle Center","Middle Right","Bottom Left","Bottom Center","Bottom Right"],inline = "Sym",group = gS)
u01 = input.bool(true, title = "", group = gS, inline = 's01')
u02 = input.bool(true, title = "", group = gS, inline = 's02')
u03 = input.bool(true, title = "", group = gS, inline = 's03')
u04 = input.bool(true, title = "", group = gS, inline = 's04')
u05 = input.bool(true, title = "", group = gS, inline = 's05')
u06 = input.bool(true, title = "", group = gS, inline = 's06')
u07 = input.bool(true, title = "", group = gS, inline = 's07')
u08 = input.bool(false, title = "", group = gS, inline = 's08')
u09 = input.bool(true, title = "", group = gS, inline = 's09')
u10 = input.bool(true, title = "", group = gS, inline = 's10')
u11 = input.bool(false, title = "", group = gS, inline = 's11')
u12 = input.bool(true, title = "", group = gS, inline = 's12')
u13 = input.bool(false, title = "", group = gS, inline = 's13')
u14 = input.bool(false, title = "", group = gS, inline = 's14')
u15 = input.bool(false, title = "", group = gS, inline = 's15')
u16 = input.bool(false, title = "", group = gS, inline = 's16')
u17 = input.bool(true, title = "", group = gS, inline = 's17')
u18 = input.bool(true, title = "", group = gS, inline = 's18')
u19 = input.bool(true, title = "", group = gS, inline = 's19')
u20 = input.bool(false, title = "", group = gS, inline = 's20')
s01 = input.symbol('EURUSD', "",group = gS, inline = 's01')
s02 = input.symbol('USDJPY', "",group = gS, inline = 's02')
s03 = input.symbol('GBPUSD', "",group = gS, inline = 's03')
s04 = input.symbol('USDCHF',"", group = gS, inline = 's04')
s05 = input.symbol('AUDUSD', "",group = gS, inline = 's05')
s06 = input.symbol('USDCAD', "", group = gS, inline = 's06')
s07 = input.symbol('NZDUSD',"", group = gS, inline = 's07')
s08 = input.symbol('EURJPY', "", group = gS, inline = 's08')
s09 = input.symbol('EURGBP', "", group = gS, inline = 's09')
s10 = input.symbol('GBPJPY', "", group = gS, inline = 's10')
s11 = input.symbol('EURAUD', "", group = gS, inline = 's11')
s12 = input.symbol('AUDJPY', "", group = gS, inline = 's12')
s13 = input.symbol('EURCAD', "", group = gS, inline = 's13')
s14 = input.symbol('USDSGD', "", group = gS, inline = 's14')
s15 = input.symbol('USDHKD', "",group = gS, inline = 's15')
s16 = input.symbol('EURNZD', "", group = gS, inline = 's16')
s17 = input.symbol('META', "", group = gS, inline = 's17')
s18 = input.symbol('GOOGL', "",group = gS, inline = 's18')
s19 = input.symbol('MSFT', "",group = gS, inline = 's19')
s20 = input.symbol('BABA', "",group = gS, inline = 's20')
getDataI()=>
prePrice = close-ta.change(close)
change = ta.change(close)/prePrice*100
trend = close>ta.sma(close,50) ? "Up" : "Down"
stoch = math.round(ta.stoch(close,high,low,30),2)
price = str.tostring(close,format.mintick)
[price,change,trend,stoch]
StochSrc = input.source(close,"Source",inline="Stoch",group = "Stochastic")
stochLen = input.int(30,"Length",inline="Stoch",group = "Stochastic")
rsiSrc = input.source(close,"Source",inline="RSI",group = "RSI")
rsiLen = input.int(14,"Length",inline="RSI",group = "RSI")
movSrc = input.source(close,"Source",inline="MOV",group = "Trend(Mov)")
movLen = input.int(50,"Length",inline="MOV",group = "Trend(Mov)")
macdSrc = input.source(close,"Source",group = "MACD")
macdFlen = input.int(12,"Fast Length",group = "MACD")
macdSlen = input.int(26,"Slow Length",group = "MACD")
macdSmooth = input.int(9,"Signal Smoothing",group = "MACD")
getMacd()=>
[macd,sig,hist] = ta.macd(macdSrc,macdFlen,macdSlen,macdSmooth)
sigText = hist>=0 ? (hist[1] < hist ? "Strong\nBullish" : "Bullish") : (hist[1] < hist ? "Strong\nBearish" : "Bearish")
sigText
getDataS()=>
price = str.tostring(close,format.mintick)
vol = str.tostring(volume,format.volume)
prePrice = close-ta.change(close)
change = ta.change(close)/prePrice*100
trend = close>ta.sma(movSrc,movLen) ? "Up" : "Down"
macdText = getMacd()
rsi = math.round(ta.rsi(rsiSrc,rsiLen),2)
stoch = math.round(ta.stoch(StochSrc,high,low,stochLen),2)
[price,vol,change,trend,stoch,rsi,macdText]
getPos(x)=>
pos = switch x
"Top Right" => position.top_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Middle Right" => position.middle_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Bottom Right" => position.bottom_right
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
pos
getSize(x)=>
oPut = switch x
"Tiny" => size.tiny
"Small" => size.small
"Medium" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
oPut
[prI1,chI1,trendI1,stochI1] = request.security(i01,"1D",getDataI(),lookahead = barmerge.lookahead_on)
[prI2,chI2, trendI2, stochI2] = request.security(i02, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI3,chI3, trendI3, stochI3] = request.security(i03, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI4,chI4, trendI4, stochI4] = request.security(i04, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI5,chI5, trendI5, stochI5] = request.security(i05, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI6,chI6, trendI6, stochI6] = request.security(i06, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI7,chI7, trendI7, stochI7] = request.security(i07, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI8,chI8, trendI8, stochI8] = request.security(i08, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI9,chI9, trendI9, stochI9] = request.security(i09, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI10,chI10, trendI10, stochI10] = request.security(i10, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI11,chI11, trendI11, stochI11] = request.security(i11, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI12,chI12, trendI12, stochI12] = request.security(i12, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI13,chI13, trendI13, stochI13] = request.security(i13, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prI14,chI14, trendI14, stochI14] = request.security(i14, "1D", getDataI(), lookahead=barmerge.lookahead_on)
[prS1, volS1, chS1, trendS1, stochS1, rsiS1, macdS1] = request.security(s01, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS2, volS2, chS2, trendS2, stochS2, rsiS2, macdS2] = request.security(s02, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS3, volS3, chS3, trendS3, stochS3, rsiS3, macdS3] = request.security(s03, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS4, volS4, chS4, trendS4, stochS4, rsiS4, macdS4] = request.security(s04, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS5, volS5, chS5, trendS5, stochS5, rsiS5, macdS5] = request.security(s05, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS6, volS6, chS6, trendS6, stochS6, rsiS6, macdS6] = request.security(s06, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS7, volS7, chS7, trendS7, stochS7, rsiS7, macdS7] = request.security(s07, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS8, volS8, chS8, trendS8, stochS8, rsiS8, macdS8] = request.security(s08, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS9, volS9, chS9, trendS9, stochS9, rsiS9, macdS9] = request.security(s09, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS10, volS10, chS10, trendS10, stochS10, rsiS10, macdS10] = request.security(s10, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS11, volS11, chS11, trendS11, stochS11, rsiS11, macdS11] = request.security(s11, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS12, volS12, chS12, trendS12, stochS12, rsiS12, macdS12] = request.security(s12, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS13, volS13, chS13, trendS13, stochS13, rsiS13, macdS13] = request.security(s13, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS14, volS14, chS14, trendS14, stochS14, rsiS14, macdS14] = request.security(s14, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS15, volS15, chS15, trendS15, stochS15, rsiS15, macdS15] = request.security(s15, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS16, volS16, chS16, trendS16, stochS16, rsiS16, macdS16] = request.security(s16, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS17, volS17, chS17, trendS17, stochS17, rsiS17, macdS17] = request.security(s17, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS18, volS18, chS18, trendS18, stochS18, rsiS18, macdS18] = request.security(s18, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS19, volS19, chS19, trendS19, stochS19, rsiS19, macdS19] = request.security(s19, "1D", getDataS(), lookahead = barmerge.lookahead_on)
[prS20, volS20, chS20, trendS20, stochS20, rsiS20, macdS20] = request.security(s20, "1D", getDataS(), lookahead = barmerge.lookahead_on)
var checkIndArray = array.new_bool()
priceIndArray = array.new_string()
var symbolIndArray = array.new_string()
changeIndArray = array.new_float()
trendIndArray = array.new_string()
stochIndArray = array.new_float()
var checkSArray = array.new_bool()
priceSArray = array.new_string()
volSArray = array.new_string()
var symbolSArray = array.new_string()
changeSArray = array.new_float()
trendSArray = array.new_string()
stochSArray = array.new_float()
rsiSArray = array.new_float()
macdSArray = array.new_string()
if barstate.isfirst
array.push(checkIndArray, a01)
array.push(checkIndArray, a02)
array.push(checkIndArray, a03)
array.push(checkIndArray, a04)
array.push(checkIndArray, a05)
array.push(checkIndArray, a06)
array.push(checkIndArray, a07)
array.push(checkIndArray, a08)
array.push(checkIndArray, a09)
array.push(checkIndArray, a10)
array.push(checkIndArray, a11)
array.push(checkIndArray, a12)
array.push(checkIndArray, a13)
array.push(checkIndArray, a14)
array.push(symbolIndArray, i01)
array.push(symbolIndArray, i02)
array.push(symbolIndArray, i03)
array.push(symbolIndArray, i04)
array.push(symbolIndArray, i05)
array.push(symbolIndArray, i06)
array.push(symbolIndArray, i07)
array.push(symbolIndArray, i08)
array.push(symbolIndArray, i09)
array.push(symbolIndArray, i10)
array.push(symbolIndArray, i11)
array.push(symbolIndArray, i12)
array.push(symbolIndArray, i13)
array.push(symbolIndArray, i14)
array.push(checkSArray, u01)
array.push(checkSArray, u02)
array.push(checkSArray, u03)
array.push(checkSArray, u04)
array.push(checkSArray, u05)
array.push(checkSArray, u06)
array.push(checkSArray, u07)
array.push(checkSArray, u08)
array.push(checkSArray, u09)
array.push(checkSArray, u10)
array.push(checkSArray, u11)
array.push(checkSArray, u12)
array.push(checkSArray, u13)
array.push(checkSArray, u14)
array.push(checkSArray, u15)
array.push(checkSArray, u16)
array.push(checkSArray, u17)
array.push(checkSArray, u18)
array.push(checkSArray, u19)
array.push(checkSArray, u20)
array.push(symbolSArray, s01)
array.push(symbolSArray, s02)
array.push(symbolSArray, s03)
array.push(symbolSArray, s04)
array.push(symbolSArray, s05)
array.push(symbolSArray, s06)
array.push(symbolSArray, s07)
array.push(symbolSArray, s08)
array.push(symbolSArray, s09)
array.push(symbolSArray, s10)
array.push(symbolSArray, s11)
array.push(symbolSArray, s12)
array.push(symbolSArray, s13)
array.push(symbolSArray, s14)
array.push(symbolSArray, s15)
array.push(symbolSArray, s16)
array.push(symbolSArray, s17)
array.push(symbolSArray, s18)
array.push(symbolSArray, s19)
array.push(symbolSArray, s20)
array.push(priceIndArray, prI1)
array.push(priceIndArray, prI2)
array.push(priceIndArray, prI3)
array.push(priceIndArray, prI4)
array.push(priceIndArray, prI5)
array.push(priceIndArray, prI6)
array.push(priceIndArray, prI7)
array.push(priceIndArray, prI8)
array.push(priceIndArray, prI9)
array.push(priceIndArray, prI10)
array.push(priceIndArray, prI11)
array.push(priceIndArray, prI12)
array.push(priceIndArray, prI13)
array.push(priceIndArray, prI14)
array.push(changeIndArray,chI1)
array.push(changeIndArray, chI2)
array.push(changeIndArray, chI3)
array.push(changeIndArray, chI4)
array.push(changeIndArray, chI5)
array.push(changeIndArray, chI6)
array.push(changeIndArray, chI7)
array.push(changeIndArray, chI8)
array.push(changeIndArray, chI9)
array.push(changeIndArray, chI10)
array.push(changeIndArray, chI11)
array.push(changeIndArray, chI12)
array.push(changeIndArray, chI13)
array.push(changeIndArray, chI14)
array.push(trendIndArray,trendI1)
array.push(trendIndArray, trendI2)
array.push(trendIndArray, trendI3)
array.push(trendIndArray, trendI4)
array.push(trendIndArray, trendI5)
array.push(trendIndArray, trendI6)
array.push(trendIndArray, trendI7)
array.push(trendIndArray, trendI8)
array.push(trendIndArray, trendI9)
array.push(trendIndArray, trendI10)
array.push(trendIndArray, trendI11)
array.push(trendIndArray, trendI12)
array.push(trendIndArray, trendI13)
array.push(trendIndArray, trendI14)
array.push(stochIndArray,stochI1)
array.push(stochIndArray, stochI2)
array.push(stochIndArray, stochI3)
array.push(stochIndArray, stochI4)
array.push(stochIndArray, stochI5)
array.push(stochIndArray, stochI6)
array.push(stochIndArray, stochI7)
array.push(stochIndArray, stochI8)
array.push(stochIndArray, stochI9)
array.push(stochIndArray, stochI10)
array.push(stochIndArray, stochI11)
array.push(stochIndArray, stochI12)
array.push(stochIndArray, stochI13)
array.push(stochIndArray, stochI14)
array.push(priceSArray, prS1)
array.push(priceSArray, prS2)
array.push(priceSArray, prS3)
array.push(priceSArray, prS4)
array.push(priceSArray, prS5)
array.push(priceSArray, prS6)
array.push(priceSArray, prS7)
array.push(priceSArray, prS8)
array.push(priceSArray, prS9)
array.push(priceSArray, prS10)
array.push(priceSArray, prS11)
array.push(priceSArray, prS12)
array.push(priceSArray, prS13)
array.push(priceSArray, prS14)
array.push(priceSArray, prS15)
array.push(priceSArray, prS16)
array.push(priceSArray, prS17)
array.push(priceSArray, prS18)
array.push(priceSArray, prS19)
array.push(priceSArray, prS20)
array.push(volSArray, volS1)
array.push(volSArray, volS2)
array.push(volSArray, volS3)
array.push(volSArray, volS4)
array.push(volSArray, volS5)
array.push(volSArray, volS6)
array.push(volSArray, volS7)
array.push(volSArray, volS8)
array.push(volSArray, volS9)
array.push(volSArray, volS10)
array.push(volSArray, volS11)
array.push(volSArray, volS12)
array.push(volSArray, volS13)
array.push(volSArray, volS14)
array.push(volSArray, volS15)
array.push(volSArray, volS16)
array.push(volSArray, volS17)
array.push(volSArray, volS18)
array.push(volSArray, volS19)
array.push(volSArray, volS20)
array.push(changeSArray,chS1)
array.push(changeSArray, chS2)
array.push(changeSArray, chS3)
array.push(changeSArray, chS4)
array.push(changeSArray, chS5)
array.push(changeSArray, chS6)
array.push(changeSArray, chS7)
array.push(changeSArray, chS8)
array.push(changeSArray, chS9)
array.push(changeSArray, chS10)
array.push(changeSArray, chS11)
array.push(changeSArray, chS12)
array.push(changeSArray, chS13)
array.push(changeSArray, chS14)
array.push(changeSArray, chS15)
array.push(changeSArray, chS16)
array.push(changeSArray, chS17)
array.push(changeSArray, chS18)
array.push(changeSArray, chS19)
array.push(changeSArray, chS20)
array.push(trendSArray,trendS1)
array.push(trendSArray, trendS2)
array.push(trendSArray, trendS3)
array.push(trendSArray, trendS4)
array.push(trendSArray, trendS5)
array.push(trendSArray, trendS6)
array.push(trendSArray, trendS7)
array.push(trendSArray, trendS8)
array.push(trendSArray, trendS9)
array.push(trendSArray, trendS10)
array.push(trendSArray, trendS11)
array.push(trendSArray, trendS12)
array.push(trendSArray, trendS13)
array.push(trendSArray, trendS14)
array.push(trendSArray, trendS15)
array.push(trendSArray, trendS16)
array.push(trendSArray, trendS17)
array.push(trendSArray, trendS18)
array.push(trendSArray, trendS19)
array.push(trendSArray, trendS20)
array.push(stochSArray,stochS1)
array.push(stochSArray, stochS2)
array.push(stochSArray, stochS3)
array.push(stochSArray, stochS4)
array.push(stochSArray, stochS5)
array.push(stochSArray, stochS6)
array.push(stochSArray, stochS7)
array.push(stochSArray, stochS8)
array.push(stochSArray, stochS9)
array.push(stochSArray, stochS10)
array.push(stochSArray, stochS11)
array.push(stochSArray, stochS12)
array.push(stochSArray, stochS13)
array.push(stochSArray, stochS14)
array.push(stochSArray, stochS15)
array.push(stochSArray, stochS16)
array.push(stochSArray, stochS17)
array.push(stochSArray, stochS18)
array.push(stochSArray, stochS19)
array.push(stochSArray, stochS20)
array.push(rsiSArray, rsiS1)
array.push(rsiSArray, rsiS2)
array.push(rsiSArray, rsiS3)
array.push(rsiSArray, rsiS4)
array.push(rsiSArray, rsiS5)
array.push(rsiSArray, rsiS6)
array.push(rsiSArray, rsiS7)
array.push(rsiSArray, rsiS8)
array.push(rsiSArray, rsiS9)
array.push(rsiSArray, rsiS10)
array.push(rsiSArray, rsiS11)
array.push(rsiSArray, rsiS12)
array.push(rsiSArray, rsiS13)
array.push(rsiSArray, rsiS14)
array.push(rsiSArray, rsiS15)
array.push(rsiSArray, rsiS16)
array.push(rsiSArray, rsiS17)
array.push(rsiSArray, rsiS18)
array.push(rsiSArray, rsiS19)
array.push(rsiSArray, rsiS20)
array.push(macdSArray, macdS1)
array.push(macdSArray, macdS2)
array.push(macdSArray, macdS3)
array.push(macdSArray, macdS4)
array.push(macdSArray, macdS5)
array.push(macdSArray, macdS6)
array.push(macdSArray, macdS7)
array.push(macdSArray, macdS8)
array.push(macdSArray, macdS9)
array.push(macdSArray, macdS10)
array.push(macdSArray, macdS11)
array.push(macdSArray, macdS12)
array.push(macdSArray, macdS13)
array.push(macdSArray, macdS14)
array.push(macdSArray, macdS15)
array.push(macdSArray, macdS16)
array.push(macdSArray, macdS17)
array.push(macdSArray, macdS18)
array.push(macdSArray, macdS19)
array.push(macdSArray, macdS20)
selectSize = input.string("Small","Size",["Tiny","Small","Medium","Large","Huge","Auto"],group = "Customize")
titleTextColor =input.color(color.white,"Title Text Color",group = "Customize")
titleColor =input.color(#0b183d,"Title Background Color",group = "Customize")
textColor =input.color(color.white,"Text Color",group = "Customize")
backColor = input.color(#131722,"Background Color",group = "Customize")
borderColor = input.color(color.new(color.white,88),"Border Color",group = "Customize")
frameColor = input.color(#aaaaaa,"Frame Color",group = "Customize")
positiveColor = input.color(color.new(color.green,60),"Positive Color",group = "Customize")
neutralColor = input.color(#131722,"Neutral Color",group = "Customize")
negativeColor = input.color(color.new(color.red,60),"Negative Color",group = "Customize")
var indTab = table.new(getPos(indPos),5,15,bgcolor = backColor,frame_color = frameColor,border_color = borderColor,frame_width = 1,border_width = 1 )
var symTab = table.new(getPos(symPos),8,21,bgcolor = backColor,frame_color = frameColor,border_color = borderColor,frame_width = 1,border_width = 1 )
if barstate.isfirst
if openIndices
table.cell(indTab,0,0,"Pair",text_color = titleTextColor,bgcolor = titleColor)
table.cell(indTab,1,0,"Price",text_color = titleTextColor,bgcolor = titleColor)
table.cell(indTab,2,0,"Change",text_color = titleTextColor,bgcolor = titleColor,tooltip="Daily Change(%)")
table.cell(indTab,3,0,"Stoch",text_color = titleTextColor,bgcolor = titleColor)
table.cell(indTab,4,0,"Trend",text_color = titleTextColor,bgcolor = titleColor)
//Symbol Table
if openSymbols
table.cell(symTab,0,0,"Pair",text_color = titleTextColor,bgcolor = titleColor)
table.cell(symTab,1,0,"Price",text_color = titleTextColor,bgcolor = titleColor)
table.cell(symTab,2,0,"Volume",text_color = titleTextColor,bgcolor = titleColor)
table.cell(symTab,3,0,"Change",text_color = titleTextColor,bgcolor = titleColor,tooltip="Daily Change(%)")
table.cell(symTab,4,0,"Stoch",text_color = titleTextColor,bgcolor = titleColor)
table.cell(symTab,5,0,"Rsi",text_color = titleTextColor,bgcolor = titleColor)
table.cell(symTab,6,0,"Trend",text_color = titleTextColor,bgcolor = titleColor)
table.cell(symTab,7,0,"Macd",text_color = titleTextColor,bgcolor = titleColor)
for i=0 to array.size(checkSArray)-1
if i+1<=array.size(checkIndArray) and openIndices
check = array.get(checkIndArray,i)
if check
sym = syminfo.ticker(array.get(symbolIndArray,i))
sym := sym=="US05Y/TVC:US10Y" ? "US05Y/US10Y" : sym
price = array.get(priceIndArray,i)
change = array.get(changeIndArray,i)
trend = array.get(trendIndArray,i)
stoch = array.get(stochIndArray,i)
changeColor = change>0 ? positiveColor : negativeColor
trendColor = trend=="Up" ? positiveColor : negativeColor
stochColor = stoch<=25 ? positiveColor : stoch>75 ? negativeColor : neutralColor
table.cell(indTab,0,i+1,sym,text_color = textColor,text_size =getSize(selectSize))
table.cell(indTab,1,i+1,price,text_color = textColor,text_size =getSize(selectSize))
table.cell(indTab,2,i+1,str.tostring(change,format.percent),text_color = textColor,text_size =getSize(selectSize),bgcolor = changeColor)
table.cell(indTab,3,i+1,str.tostring(stoch),text_color = textColor,text_size =getSize(selectSize),bgcolor = stochColor)
table.cell(indTab,4,i+1,trend,text_color = textColor,text_size =getSize(selectSize),bgcolor = trendColor)
if i+1<=array.size(checkSArray) and openSymbols
check = array.get(checkSArray,i)
if check
sym = syminfo.ticker(array.get(symbolSArray,i))
price = array.get(priceSArray,i)
vol = array.get(volSArray,i)
change = array.get(changeSArray,i)
trend = array.get(trendSArray,i)
stoch = array.get(stochSArray,i)
rsi = array.get(rsiSArray,i)
macd = array.get(macdSArray,i)
changeColor = change>0 ? positiveColor : negativeColor
trendColor = trend=="Up" ? positiveColor : negativeColor
stochColor = stoch<=25 ? positiveColor : stoch>75 ? negativeColor : neutralColor
rsiColor = rsi<=35 ? positiveColor : rsi>=65 ? negativeColor : neutralColor
macdColor = macd=="Strong\nBullish" ? positiveColor : macd=="Bullish" ? color.new(positiveColor,50) : macd=="Strong\nBearish" ? negativeColor : macd=="Bearish" ? color.new(negativeColor,50) : neutralColor
table.cell(symTab,0,i+1,sym,text_color = textColor,text_size =getSize(selectSize))
table.cell(symTab,1,i+1,price,text_color = textColor,text_size =getSize(selectSize))
table.cell(symTab,2,i+1,vol,text_color = changeColor,text_size =getSize(selectSize))
table.cell(symTab,3,i+1,str.tostring(change,format.percent),text_color = textColor,text_size =getSize(selectSize),bgcolor = changeColor)
table.cell(symTab,4,i+1,str.tostring(stoch),text_color = textColor,text_size =getSize(selectSize),bgcolor = stochColor)
table.cell(symTab,5,i+1,str.tostring(rsi),text_color = textColor,text_size =getSize(selectSize),bgcolor = rsiColor)
table.cell(symTab,6,i+1,trend,text_color = textColor,text_size =getSize(selectSize),bgcolor = trendColor)
table.cell(symTab,7,i+1,macd,text_color = textColor,text_size =getSize(selectSize),bgcolor = macdColor)
|
Smart Money Indicator | https://www.tradingview.com/script/k5XOwvdC-Smart-Money-Indicator/ | hiren147 | https://www.tradingview.com/u/hiren147/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hiren147
//@version=5
indicator("Smart Money Indicator", overlay = true)
// Input for the length of the volume moving average
length = input.int(20, title = "Volume MA Length")
// Calculate the volume moving average
smaVolume = ta.sma(volume, length)
// Plot a line on the chart when the current volume is significantly above the moving average
plotshape(series = volume > smaVolume * 1.5, title = "Smart Money", location = location.belowbar, color = color.green, style = shape.triangleup, size = size.small)
// Plot a line on the chart when the current volume is significantly below the moving average
plotshape(series = volume < smaVolume * 0.5, title = "Dumb Money", location = location.abovebar, color = color.red, style = shape.triangledown, size = size.small)
|
RSI Trend Detector PSAR Based | https://www.tradingview.com/script/5nliVT2q-RSI-Trend-Detector-PSAR-Based/ | traderharikrishna | https://www.tradingview.com/u/traderharikrishna/ | 103 | 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/
// © traderharikrishna
//@version=5
indicator("RSI Trend Detector PSAR Based")
rsilen=input.int(14,"RSI Length")
src=input.source(close,"Source")
rsi=ta.rsi(src,rsilen)
u=hline(60,display=display.none)
d=hline(40,display=display.none)
f=hline(50)
fill(u,d,color=color.rgb(80, 81, 83, 60))
sar=ta.sar(0.02,0.02,0.2)
//plot(sar, color=rsi>60?color.green:rsi<40?color.red:color.gray,linewidth=3)
r=plot(rsi, color=close>sar?color.rgb(0, 209, 7):color.rgb(252, 5, 5),linewidth=3)
rsim=ta.sma(rsi,14)
s=plot(rsim,color=color.yellow,linewidth=2)
fill(r,s,color=rsi>rsim?color.rgb(3, 243, 11, 81):color.rgb(243, 7, 7, 70))
up=ta.crossover(rsi,rsim)
dn=ta.crossunder(rsi,rsim)
alertcondition(up,title="RSI Cross Up",message="RSI Cross Up")
alertcondition(dn,title="RSI Cross Dn",message="RSI Cross Down") |
HTF Candle Insights (Expo) | https://www.tradingview.com/script/tG4HXiE1-HTF-Candle-Insights-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 648 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman
//@version=5
indicator("HTF Candle Insights (Expo)",overlay = true,max_bars_back = 500, max_boxes_count = 500)
// ~~ Inputs {
tf = input.timeframe("60","Timeframe", group="Higher Timeframe Candles")
numb = input.int(4,"Amount of Candles",minval=0, maxval=20, group="Higher Timeframe Candles")+1
dn_col = input.color(color.new(color.red,10), title="Dn", inline="Candles", group="Higher Timeframe Candles")
dn_wick = input.color(color.new(color.red,0), title="Wick", inline="Candles", group="Higher Timeframe Candles")
up_col = input.color(color.new(color.lime,10), title="Up",inline="Candles", group="Higher Timeframe Candles")
up_wick = input.color(color.new(color.lime,0), title="Wick", inline="Candles", group="Higher Timeframe Candles")
Range = input.bool(false,"Range High/Low", inline="range", group="Range")
Mid = input.bool(true,"Range Mid", inline="range", group="Range")
high_col = input.color(color.red, title="High", inline="range 1", group="Range")
low_col = input.color(color.lime, title="Low",inline="range 1", group="Range")
mid_col = input.color(color.rgb(20, 69, 246), title="Mid",inline="range 1", group="Range")
loc = input.int(1,"Location", group="Location Settings")
// ~~ Table Inputs {
showTable = input.bool(true,title="Show Table", inline="tbl", group="Table")
TblSize = input.string(size.normal,title="",options=[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],inline="tbl", group="Table")
pos = input.string(position.top_right, title="",options =[position.top_right,position.top_center,
position.top_left,position.bottom_right,position.bottom_center,position.bottom_left,position.middle_right,position.middle_left],inline="tbl", group="Table")
textcolor = input.color(color.white, title="Text",inline="tbl_col", group="Table")
bgcolor = input.color(color.new(color.blue,30), title="Bg",inline="tbl_col", group="Table")
//~~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ HTF Error Message {
tfs = str.tonumber(tf)
if str.tostring(tf) == "1D"
tfs := 1440
error = str.tonumber(timeframe.period)>=tfs
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ UDT {
type HTF
array<box> candle
array<line> wickH
array<line> wickL
array<float> hl
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
b = bar_index
var candle = HTF.new(array.new<box>(numb),array.new<line>(numb),array.new<line>(numb),array.new<float>(numb*2))
[o,h,l,c] = request.security(syminfo.ticker,tf,[open,high,low,close],lookahead=barmerge.lookahead_on)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Code {
if ta.change(o) //New candle declaration
candle.candle.shift().delete()
candle.wickH.shift().delete()
candle.wickL.shift().delete()
candle.hl.shift()
candle.hl.shift()
candle.candle.push(box.new(b+numb*4+loc,math.max(o,c),b+numb*4+loc+2,math.min(o,c),color(na),bgcolor=o>c?dn_col:up_col))
candle.wickH.push(line.new(b+numb*4+loc+1,math.max(o,c),b+numb*4+loc+1,h,color=o>c?dn_col:up_col))
candle.wickL.push(line.new(b+numb*4+loc+1,math.min(o,c),b+numb*4+loc+1,l,color=o>c?dn_col:up_col))
candle.hl.push(h)
candle.hl.push(l)
else // Relocate previous & current candles
d = loc
for [i,x] in candle.candle
if i<numb-1
x.set_left(b+d*2)
x.set_right(b+d*2+2)
candle.wickH.get(i).set_x1(b+d*2+1)
candle.wickH.get(i).set_x2(b+d*2+1)
candle.wickL.get(i).set_x1(b+d*2+1)
candle.wickL.get(i).set_x2(b+d*2+1)
else
x.set_lefttop(b+d*2,math.max(o,c))
x.set_rightbottom(b+d*2+2,math.min(o,c))
x.set_bgcolor(o>c?dn_col:up_col)
candle.wickH.get(i).set_xy1(b+d*2+1,math.max(o,c))
candle.wickH.get(i).set_xy2(b+d*2+1,h)
candle.wickH.get(i).set_color(o>c?dn_wick:up_wick)
candle.wickL.get(i).set_xy1(b+d*2+1,math.min(o,c))
candle.wickL.get(i).set_xy2(b+d*2+1,l)
candle.wickL.get(i).set_color(o>c?dn_wick:up_wick)
candle.hl.set(numb*2-2,h)
candle.hl.set(numb*2-1,l)
d += 2
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Range {
if Range
RangeHigh = line.new(b,candle.hl.max(),b+numb*4+loc+2,candle.hl.max(),color=high_col,extend=extend.none)
RangeLow = line.new(b,candle.hl.min(),b+numb*4+loc+2,candle.hl.min(),color=low_col,extend=extend.none)
(RangeHigh[1]).delete()
(RangeLow[1]).delete()
if Mid
RangeMid = line.new(b,math.avg(candle.hl.max(),candle.hl.min()),b+numb*4+loc+2,math.avg(candle.hl.max(),candle.hl.min()),color=mid_col,extend=extend.none)
(RangeMid[1]).delete()
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Table {
tbl = table.new(pos, 2, 11, frame_color=chart.bg_color, frame_width=2, border_width=2, border_color=chart.bg_color)
if barstate.islast and showTable
tbl.cell(0, 0, text=error?"Error":"TF", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
tbl.cell(0, 1, text=error?"The chart's timeframe must be less than the HTF '"+tf+"' timeframe. \n\nor please select a higher timeframe in the setting panel of the indicator.":str.tostring(timeframe.period), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize)
tbl.cell(1, 0, text="HTF", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
tbl.cell(1, 1, text=str.tostring(tf), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Double MACD Pattern 1.0 | https://www.tradingview.com/script/rIBsVI8Z/ | egghen | https://www.tradingview.com/u/egghen/ | 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/
// © egghen
//@version=5
indicator('Double MACD Pattern 1.0', shorttitle='D-MACD-P 1.0')
// MACD Settings
slowLength_1 = input(title='MACD 1 Fast Length', defval=12, group="MACD 1")
fastLength_1 = input(title='MACD 1 Slow Length', defval=26, group="MACD 1")
signalLength_1 = input(title='MACD 1 Signal Length', defval=9, group="MACD 1")
fastLength_2 = input(title='MACD 2 Fast Length', defval=12, group="MACD 2")
slowLength_2 = input(title='MACD 2 Slow Length', defval=26, group="MACD 2")
signalLength_2 = input(title='MACD 2 Signal Length', defval=9, group="MACD 2")
// Define Calculation
macdLine_1 = ta.ema(hl2, fastLength_1) - ta.ema(hl2, slowLength_1)
macdLine_2 = ta.ema(hl2, fastLength_2) - ta.ema(hl2, slowLength_2)
signalLine_1 = ta.ema(macdLine_1, signalLength_1)
signalLine_2 = ta.ema(macdLine_2, signalLength_2)
// Calculate MACD Histograms
histogram_1 = macdLine_1 - signalLine_1
histogram_2 = macdLine_2 - signalLine_2
// Plot MACD Line
plot(macdLine_1, color=color.new(#6a71ed, 0), linewidth=2, title='MACD Line 1')
plot(signalLine_1, color=color.rgb(235, 96, 68), title='Signal Line 1')
plot(macdLine_2, color=color.new(#b3d0e7, 40), linewidth=2, title='MACD Line 2')
plot(signalLine_2, color=color.rgb(117, 243, 33), title='Signal Line 2')
// Plot Histograms
plot(histogram_1, color=color.new(#f41d1d, 0), style=plot.style_histogram, title='Histogram 1')
plot(histogram_2, color=color.new(#0788f1, 0), style=plot.style_histogram, title='Histogram 2')
hline(0, color=#787B86, linestyle=hline.style_dashed, title="Trend Line")
// Alert on MACD Crossover and Crossunder
long_signal = ta.crossunder(macdLine_1, signalLine_1) and ta.crossover(macdLine_2, signalLine_2) and ta.crossover(histogram_1, histogram_2)
short_signal = ta.crossover(macdLine_1, signalLine_1) and ta.crossunder(macdLine_2, signalLine_2) and ta.crossunder(histogram_1, histogram_2)
potential_long = ta.crossover(macdLine_2, signalLine_2) and ta.crossunder(macdLine_1, signalLine_1)
potential_short = ta.crossunder(macdLine_2, signalLine_2) and ta.crossover(macdLine_1, signalLine_1)
up_trend = ta.crossover(macdLine_2, macdLine_1)
down_trend = ta.crossover(macdLine_1, macdLine_2)
// Send an Alert
if long_signal
alert('D-MACD+p 1.1 - Long Signal.')
if short_signal
alert('D-MACD+p 1.1 - Short Signal.')
if up_trend
alert('D-MACD+p 1.1 - Up Trend Signal.')
if down_trend
alert('D-MACD+p 1.1 - Down Trend Signal.')
if potential_long
alert('D-MACD+p 1.1 - Potential Long Signal.')
if potential_short
alert('D-MACD+p 1.1 - Potential Short Signal.')
//
// end code |
SMI Ergodic Indicator + Oscillator | https://www.tradingview.com/script/eP4Z46mQ-SMI-Ergodic-Indicator-Oscillator/ | The_Estonian_ | https://www.tradingview.com/u/The_Estonian_/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © The_Estonian_
//@version=5
indicator(title="SMI Ergodic Indicator+Oscillator", shorttitle="SMIIO", format=format.price, precision=4, timeframe="", timeframe_gaps=true)
longlen = input.int(20, minval=1, title="Long Length")
shortlen = input.int(5, minval=1, title="Short Length")
siglen = input.int(5, minval=1, title="Signal Line Length")
erg = ta.tsi(close, shortlen, longlen)
sig = ta.ema(erg, siglen)
osc = erg - sig
plot(osc, color=#FF5252, style=plot.style_histogram, title="SMI Ergodic Oscillator")
plot(erg, color=#e700fc, title="SMI")
plot(sig, color=#ffd102, title="Signal")
plot(ta.cross(erg, sig) ? erg : na, color= #ffffff, style = plot.style_circles, linewidth = 3)
TopLine = hline(.70, "MAX", color.red)
OB = .40
OverboughtLine = hline(OB, "Overbought", color.red)
fill(TopLine, OverboughtLine, color.new(color.red, 80))
BottomLine = hline(-.70, "MAX", color.green)
OS = -.40
OverSoldLine = hline(OS, "OverSold", color=color.green)
fill(BottomLine, OverSoldLine, color.new(color.green, 80))
MiddleLine = hline(0.0, "Middle", color.white) |
Kawasaki_MFI | https://www.tradingview.com/script/UDxvdk0b/ | KAWASAKI-AXIS | https://www.tradingview.com/u/KAWASAKI-AXIS/ | 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/
// © KAWASAKI-AXIS
//@version=5
indicator(title="Kawasaki_MFI", overlay=true)
my_high = request.security(syminfo.tickerid, "D", high)
my_low = request.security(syminfo.tickerid, "D", low)
my_close = request.security(syminfo.tickerid, "D", close)
my_volume = request.security(syminfo.tickerid, "D", volume)
adl = ta.cum(na(my_volume) ? na : ((my_close - my_low) - (my_high - my_close)) / (my_high - my_low) * my_volume)
plot(adl, title="ADL", color=color.new(color.blue, 0))
|
Supply Demand Profiles [LuxAlgo] | https://www.tradingview.com/script/0UysVHbl-Supply-Demand-Profiles-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,115 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Supply Demand Profiles [LuxAlgo]", "LuxAlgo - Supply Demand Profiles", true, max_bars_back = 5000, max_boxes_count = 500, max_lines_count = 500)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
clGR = 'Calculation Settings'
pVDST = 'This charting tool allows usage of different volume data sources and different polarity options'
vdT1 = 'Volume - Bar Polarity'
vdT2 = 'Volume - Bar Buying/Selling Pressure'
vdT7 = 'Volume - Heikin Ashi Bar Polarity'
vdT3 = 'Volume - Intrabar Polarity (LTF)'
vdT4 = 'Volume - Intrabar Buying/Selling Pressure (LTF)'
vdT5 = 'Volume Delta - Intrabar Polarity (LTF)'
vdT6 = 'Volume Delta - Intrabar Buying/Selling Pressure (LTF)'
pVDS = input.string(vdT1, 'Volume Data Source', options = [vdT1, vdT2, vdT7, vdT3, vdT4, vdT5, vdT6], group = clGR, tooltip = pVDST)
tfTP = 'This option is applicable when any of the \'Intrabar (LTF)\' option is selected and if so then this opton sets the indicator Precision. ' +
'If the Lower Timeframe Precision is set to AUTO, then the Lower Timeframe is determined by the following algorithm:\n\n' +
' - Chart Timeframe, Lower Timeframe\n' +
' <= 1 min 1 Sec\n' +
' <= 2 min 5 Sec\n' +
' <= 3 min 10 Sec\n' +
' <= 5 min 15 Sec\n' +
' <= 15 min 30 Sec\n' +
' <= 1 hour 1 min\n' +
' <= 2 hour 3 min\n' +
' <= 4 hour 5 min\n' +
' <= 1 day 15 min\n' +
' <= 1 week 1 hour\n' +
' > 1 week 1 day'
vdLT = input.string('Auto', 'Lower Timeframe Precision',
options=['Auto', '1 Sec', '5 Sec', '10 Sec', '15 Sec', '30 Sec', '1 Min', '3 Min', '5 Min', '15 Min', '30 Min', '1 Hour', '4 Hour', '1 Day'],
group = clGR, tooltip = tfTP)
isVA = input.float(68, "Value Area Volume %", minval = 0, maxval = 100, group = clGR) / 100
prGR = 'Presentation Settings'
sdTT = 'Defines the relationship between the price of a given asset and the willingness of traders to either buy or sell it'
sdSH = input.bool(true, 'Supply & Demand Zones', group = prGR, tooltip = sdTT)
vpTT = 'Volume profile displays total trading activity (both buying and selling activity) over a specified time period at specific price levels'
vpSH = input.bool(true, 'Volume Profile', group = prGR, tooltip = vpTT)
spTT = 'Sentiment profile displays the dominat party at the specific price levels\n' +
' - orange rows : selling pressure is higher\n' +
' - green rows : buying pressure is higher\n\n' +
'narrow rows does not mean no interest at that price levels but equlibrium between selling and buying trading activity'
spSH = input.bool(true, 'Sentiment Profile', group = prGR, tooltip = spTT)
vspGR = 'Presentation, Others'
vaHTT = 'Value Area High (VAH)\n the highest price level within the value area'
vaHL = input.bool(true, 'Value Area High (VAH)', inline = 'VAH', group = vspGR, tooltip = vaHTT)
vaHC = input.color(color.new(#2962ff, 0), '', inline = 'VAH', group = vspGR)
pocTT = 'Point of Control (POC)\n displays developing POC, the changes of the price levels with the highest traded activity'
pocL = input.bool(true, 'Point of Control (POC)', inline = 'PoC', group = vspGR, tooltip = pocTT)
pocC = input.color(color.new(#ff0000, 0), '', inline = 'PoC', group = vspGR)
vaLTT = 'Value Area Low (VAL)\n the lowest price level within the value area'
vaLL = input.bool(true, 'Value Area Low (VAL) ', inline = 'VAL', group = vspGR, tooltip = vaLTT)
vaLC = input.color(color.new(#2962ff, 0), '', inline = 'VAL', group = vspGR)
sdOT = 'Supply & Demand, Others'
sdTH = input.int(15, 'Supply & Demand Threshold %', minval = 0, maxval = 41, group = sdOT) / 100
sdSC = input.color(color.new(#2157f3, 50), 'Supply Zones', inline = 'SD', group = sdOT)
sdDC = input.color(color.new(#ff5d00, 50), 'Demand Zones', inline = 'SD', group = sdOT)
vpGR = 'Volume Profile, Others'
vpUVC = input.color(color.new(#2962ff, 75), 'Profile, Up Volume', inline = 'ZZ2', group = vpGR)
vpDVC = input.color(color.new(#fbc02d, 75), 'Down Volume', inline = 'ZZ2' , group = vpGR)
vaUVC = input.color(color.new(#2962ff, 25), 'Value Area, Up Volume', inline = 'ZZ1', group = vpGR)
vaDVC = input.color(color.new(#fbc02d, 25), 'Down Volume', inline = 'ZZ1' , group = vpGR)
spGR = 'Sentiment Profile, Others'
vsUVC = input.color(color.new(#089981, 75), 'Sentiment, Bullish', inline = 'BB', group = spGR)
vsDVC = input.color(color.new(#ff5d00, 75), 'Bearish', inline = 'BB', group = spGR)
spUVC = input.color(color.new(#089981, 25), 'Value Area, Bullish', inline = 'BB1', group = spGR)
spDVC = input.color(color.new(#ff5d00, 25), 'Bearish', inline = 'BB1', group = spGR)
othGR = 'Others'
pLVL = input.int(100, 'Number of Rows', minval = 10, maxval = 150, step = 5, group = othGR)
pPLC = input.string('Left', 'Placment', options = ['Right', 'Left'], group = othGR)
pWDH = input.int(30, 'Profile Width %', minval = 0, maxval = 100, group = othGR) / 100
pLB = input.bool(true, 'Profile Price Levels', group = othGR)
pBG = input.bool(false, 'Profile Background ', inline = 'BG', group = othGR)
pBGC = input.color(color.new(#37a6ef, 95), '', inline = 'BG', group = othGR)
vaBG = input.bool(true, 'Value Area Background', inline ='vBG', group = othGR)
vaBGC = input.color(color.new(#37a6ef, 95), '', inline ='vBG', group = othGR)
pSCT = input.time(timestamp("23 Jul 2023"), "Start Calculation", confirm = true, inline = 'wa1', group = othGR)
pECT = input.time(timestamp("21 Aug 2023"), "End Calculation " , confirm = true, inline = 'wa2', group = othGR)
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field o (float) open price of the bar
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field c (float) close price of the bar
// @field v (float) volume of the bar
// @field i (int) index of the bar
type bar
float o = open
float h = high
float l = low
float c = close
float v = volume
int i = bar_index
// @type maintain volume profile data
//
// @field vsT (array<float>) array maintains tolal traded volume
// @field vsB (array<float>) array maintains bullish traded volume
// @field vsD (array<float>) array maintains delta traded volume
// @field vp (array<box>) array maintains visual object of each price level
// @field pc (array<box>) array maintains visual object of poc
type VP
float [] vsT
float [] vsB
float [] vsD
box [] vp
line [] pc
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
VP aVP = VP.new(
array.new <float> (pLVL + 1, 0.),
array.new <float> (pLVL + 1, 0.),
array.new <float> (pLVL + 1, 0.),
array.new <box> (na),
array.new <line> (na)
)
nzV = nz(b.v)
mInMS = 60 * 1000
var laP = 0
var lbP = 0
//-----------------------------------------------------------------------------}
// Functions / Methods
//-----------------------------------------------------------------------------{
// @function Calculates the volume of up and down bars
//
// @returns [float, float] the volume of up bars, and the volume of down bars
f_calcV() =>
uV = 0., dV = 0.
switch
(pVDS == vdT4 or pVDS == vdT6) and (b.c - b.l) > (b.h - b.c) => uV += nzV
(pVDS == vdT4 or pVDS == vdT6) and (b.c - b.l) < (b.h - b.c) => dV -= nzV
(pVDS == vdT3 or pVDS == vdT5) and b.c > b.o => uV += nzV
(pVDS == vdT3 or pVDS == vdT5) and b.c < b.o => dV -= nzV
b.c > nz(b.c[1]) => uV += nzV
b.c < nz(b.c[1]) => dV -= nzV
nz(uV[1]) > 0 => uV += nzV
nz(dV[1]) < 0 => dV -= nzV
[uV, dV]
// @function Calculates the Lower Timeframe based on the Input or Chart Resolution
//
// @param _tf chart Timeframe string
//
// @returns [string] Lower Timeframe string
f_calcLTF(_tf) =>
int tfInMs = timeframe.in_seconds() * 1000
switch _tf
'Auto' => tfInMs <= 1 * mInMS ? '1S' :
tfInMs <= 2 * mInMS ? '5S' :
tfInMs <= 3 * mInMS ? '10S' :
tfInMs <= 5 * mInMS ? '15S' :
tfInMs <= 15 * mInMS ? '30S' :
tfInMs <= 60 * mInMS ? '1' :
tfInMs <= 120 * mInMS ? '3' :
tfInMs <= 240 * mInMS ? '5' :
tfInMs <= 1440 * mInMS ? '15' :
tfInMs <= 7 * 1440 * mInMS ? '60' : 'D'
'1 Sec' => '1S'
'5 Sec' => '5S'
'10 Sec' => '10S'
'15 Sec' => '15S'
'30 Sec' => '30S'
'1 Min' => '1'
'3 Min' => '3'
'5 Min' => '5'
'15 Min' => '15'
'30 Min' => '30'
'1 Hour' => '60'
'4 Hour' => '240'
'1 Day' => '1D'
// @function creates new line object, updates existing line objects
//
// @param details in Pine Script™ language reference manual
//
// @returns id of the line
f_drawLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)
line.set_xy1(id, _x1, _y1)
line.set_xy2(id, _x2, _y2)
line.set_color(id, _color)
id
// @function creates new label object, updates existing label objects
//
// @param details in Pine Script™ language reference manual
//
// @returns none
f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>
var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)
label.set_xy(id, _x, _y)
label.set_text(id, _text)
label.set_tooltip(id, _tooltip)
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
sBX = ta.valuewhen(time == pSCT, b.i, 0)
eBX = ta.valuewhen(time == pECT, b.i, 0)
[sB, eB] = if sBX < eBX
[sBX, eBX]
else
[eBX, sBX]
pLN = eB - sB
pHST = ta.highest(high, pLN > 0 ? pLN + 1 : 200)
pLST = ta.lowest (low , pLN > 0 ? pLN + 1 : 200)
pSTP = (pHST - pLST) / pLVL
[uV, dV] = request.security_lower_tf(syminfo.tickerid, f_calcLTF(vdLT), f_calcV())
tuV = uV.sum()
tdV = dV.sum()
vd = tuV + tdV
tV = tuV - tdV
haP = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close > open)
nzV := pVDS == vdT1 or pVDS == vdT2 or pVDS == vdT7 ? nzV : pVDS == vdT3 or pVDS == vdT4 ? tV : math.abs(vd)
bCON = pVDS == vdT3 or pVDS == vdT4 or pVDS == vdT5 or pVDS == vdT6 ? tuV > math.abs(tdV) : pVDS == vdT2 ? (b.c - b.l) > (b.h - b.c) : pVDS == vdT7 ? haP : b.c > b.o
var pir = 0.
if (b.i == eB) and nzV and (pLN > 0)
for bI = pLN to 0
l = 0
for pL = pLST to pHST by pSTP
if b.h[bI] >= pL and b.l[bI] < pL + pSTP
aVP.vsT.set(l, aVP.vsT.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])))
if bCON[bI]
aVP.vsB.set(l, aVP.vsB.get(l) + nzV[bI] * ((b.h[bI] - b.l[bI]) == 0 ? 1 : pSTP / (b.h[bI] - b.l[bI])))
l += 1
if pocL
if bI == pLN
pir := pLST + (aVP.vsT.indexof(aVP.vsT.max()) + .50) * pSTP
else
aVP.pc.push(line.new(b.i[bI] - 1, pir, b.i[bI], pLST + (aVP.vsT.indexof(aVP.vsT.max()) + .50) * pSTP, color = pocC, width = 2))
pir := pLST + (aVP.vsT.indexof(aVP.vsT.max()) + .50) * pSTP
for l = 0 to pLVL - 1
bbp = 2 * aVP.vsB.get(l) - aVP.vsT.get(l)
aVP.vsD.set(l, aVP.vsD.get(l) + bbp * (bbp > 0 ? 1 : -1) )
pcL = aVP.vsT.indexof(aVP.vsT.max())
ttV = aVP.vsT.sum() * isVA
va = aVP.vsT.get(pcL)
laP := pcL
lbP := pcL
while va < ttV
if lbP == 0 and laP == pLVL - 1
break
vaP = 0.
if laP < pLVL - 1
vaP := aVP.vsT.get(laP + 1)
vbP = 0.
if lbP > 0
vbP := aVP.vsT.get(lbP - 1)
if vaP >= vbP
va += vaP
laP += 1
else
va += vbP
lbP -= 1
vah = f_drawLineX(b.i - pLN, pLST + (laP + 1.00) * pSTP, b.i, pLST + (laP + 1.00) * pSTP, xloc.bar_index, extend.none, vaHL ? vaHC : color(na), line.style_solid, 2)
//f_drawLineX(b.i - pLN, pLST + (pcL + 0.50) * pSTP, b.i, pLST + (pcL + 0.50) * pSTP, xloc.bar_index, extend.none, pocL ? pocC : color(na), line.style_solid, 2)
val = f_drawLineX(b.i - pLN, pLST + (lbP + 0.00) * pSTP, b.i, pLST + (lbP + 0.00) * pSTP, xloc.bar_index, extend.none, vaLL ? vaLC : color(na), line.style_solid, 2)
if pLB
f_drawLabelX((pPLC == 'Right' ? math.min(sBX, eBX) : math.max(sBX, eBX)), pHST, str.tostring(pHST, format.mintick),
xloc.bar_index, yloc.price, color.new(chart.fg_color, 89), label.style_label_down, chart.fg_color, size.normal, text.align_left,
'Profile High\n %' + str.tostring((pHST - pLST) / pLST * 100, '#.##') + ' higher than the Profile Low\n number of bars ' + str.tostring(pLN))
f_drawLabelX((pPLC == 'Right' ? math.min(sBX, eBX) : math.max(sBX, eBX)), pLST, str.tostring(pLST, format.mintick),
xloc.bar_index, yloc.price, color.new(chart.fg_color, 89), label.style_label_up , chart.fg_color, size.normal, text.align_left,
'Profile Low\n %' + str.tostring((pHST - pLST) / pHST * 100, '#.##') + ' lower than the Profile High\n number of bars ' + str.tostring(pLN))
f_drawLabelX((pPLC == 'Right' ? math.min(sBX, eBX) : math.max(sBX, eBX)), pLST + (laP + 1.) * pSTP, str.tostring(pLST + (laP + 1.) * pSTP, format.mintick),
xloc.bar_index, yloc.price, color.new(chart.fg_color, 89), (pPLC == 'Right' ? label.style_label_right : label.style_label_left), chart.fg_color,
size.normal, text.align_left, 'Value Area High Price')
f_drawLabelX((pPLC == 'Right' ? math.min(sBX, eBX) : math.max(sBX, eBX)), pLST + (pcL + .5) * pSTP, str.tostring(pLST + (pcL + .5) * pSTP, format.mintick),
xloc.bar_index, yloc.price, color.new(chart.fg_color, 89), (pPLC == 'Right' ? label.style_label_right : label.style_label_left), chart.fg_color,
size.normal, text.align_left, 'Point Of Control Price')
f_drawLabelX((pPLC == 'Right' ? math.min(sBX, eBX) : math.max(sBX, eBX)), pLST + (lbP + .0) * pSTP, str.tostring(pLST + (lbP + .0) * pSTP, format.mintick),
xloc.bar_index, yloc.price, color.new(chart.fg_color, 89), (pPLC == 'Right' ? label.style_label_right : label.style_label_left), chart.fg_color,
size.normal, text.align_left, 'Value Area Low Price')
if vaBG
linefill.new(vah, val, vaBGC)
if pBG
aVP.vp.push(box.new(b.i - pLN, pLST, b.i, pHST, pBGC, 1, line.style_dotted, bgcolor = pBGC))
for l = 0 to pLVL - 1
if vpSH
sBI = pPLC == 'Right' ? b.i - int(aVP.vsB.get(l) / aVP.vsT.max() * pLN * pWDH) : b.i - pLN
eBI = pPLC == 'Right' ? b.i : sBI + int( aVP.vsB.get(l) / aVP.vsT.max() * pLN * pWDH)
aVP.vp.push(box.new(sBI, pLST + (l + 0.9) * pSTP, eBI, pLST + (l + 0.1) * pSTP, l >= lbP and l <= laP ? vaUVC : vpUVC, bgcolor = l >= lbP and l <= laP ? vaUVC : vpUVC))
sBI := pPLC == 'Right' ? sBI : eBI
eBI := sBI + (pPLC == 'Right' ? -1 : 1) * int( (aVP.vsT.get(l) - aVP.vsB.get(l) )/ aVP.vsT.max() * pLN * pWDH)
aVP.vp.push(box.new(sBI, pLST + (l + 0.9) * pSTP, eBI, pLST + (l + 0.1) * pSTP, l >= lbP and l <= laP ? vaDVC : vpDVC, bgcolor = l >= lbP and l <= laP ? vaDVC : vpDVC))
if spSH
bbp = 2 * aVP.vsB.get(l) - aVP.vsT.get(l)
sBI = pPLC == 'Right' ? b.i + int( aVP.vsD.get(l) / aVP.vsD.max() * pLN * pWDH / 2) : b.i - pLN
eBI = pPLC == 'Right' ? b.i : sBI - int(aVP.vsD.get(l) / aVP.vsD.max() * pLN * pWDH / 2)
spC = bbp > 0 ? l >= lbP and l <= laP ? spUVC : vsUVC : l >= lbP and l <= laP ? spDVC : vsDVC
aVP.vp.push(box.new(sBI, pLST + (l + 0.9) * pSTP, eBI, pLST + (l + 0.1) * pSTP, spC, bgcolor = spC))
if sdSH and aVP.vsT.get(l) / aVP.vsT.max() < sdTH
sdC = pLST + (l + 0.50) * pSTP > pLST + (pcL + .5) * pSTP ? sdSC : sdDC
aVP.vp.push(box.new(eB - pLN, pLST + (l + 1.00) * pSTP, eB, pLST + (l + 0.00) * pSTP, color(na), bgcolor = sdC))
//-----------------------------------------------------------------------------} |
TTP PNR filter | https://www.tradingview.com/script/mDvBlwsG-TTP-PNR-filter/ | TheTradingParrot | https://www.tradingview.com/u/TheTradingParrot/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheTradingParrot
//@version=5
indicator("TTP PNR filter v0.1.2",overlay=false)
length = input(150)
plow = input.float(0.0,"Percentile low",minval=0,maxval=100, inline = "a")
phigh = input.float(1.0,"Percentile high",minval=0,maxval=100, inline = "a")
src = input(close)
enableTime = input.bool(false, "Enable", tooltip = "When enabled it will analise time passed since last time certain value was reached. Use it to measure time PNR of signals. Example: connect any signal that prints 1 whenever it triggers, then select low 98 and high 100, then enable time analysis. You will see how long it tends to pass between one signal and the next in average. You can then apply similar PNR analysis to time and frequency.", group = "time analysis")
valueTime = input.float(1.0, "Value")
s = ta.barssince(src == valueTime)
if enableTime
src := s
valuelow = ta.percentile_nearest_rank(src, length , plow)
valuehigh = ta.percentile_nearest_rank(src, length , phigh)
a = plot(valuelow,"% low", color=na)
b = plot(valuehigh, "% high" , color=na)
fill(a, b, valuelow, valuehigh, top_color = color.new(color.green,50), bottom_color =color.new(color.red,30))
plot(src, "src", color=color.white)
signaldirection = input.string("X over", "Direction", options = ["X over", "X under", "Below", "Above"], group = "signal")
signalsource = input.string("% low", options = ["% low", "% high"], group = "signal") == "% low" ? valuelow : valuehigh
bool signal = switch signaldirection
"X over" => ta.crossover(src, signalsource)
"X under" => ta.crossunder(src, signalsource)
"Below" => src < signalsource
"Above" => src > signalsource
=> false
plot(signal ? 1 : na, "signal", display = display.data_window)
long = signaldirection == "X over" or signaldirection == "Above"
short = not long
indicatorCondition = signal
indicatorValue = src
plotIndicator = true
indicatorName = "PNR"
plotSignal = true
plotBackground = true
signalValue = src
color triggerColor = long ? color.lime : color.red
// Plot Character
plotchar( series = signal and long ? src : na,
title = "Entry long",
char = ".",
location = location.absolute,
color = triggerColor,
textcolor = color.white,
size = size.large,
display = display.all - display.data_window)
plotchar( series = signal and short ? src : na,
title = "Entry short",
char = ".",
location = location.absolute,
color = triggerColor,
textcolor = color.white,
size = size.large,
display = display.all - display.data_window)
alertcondition(signal,"PNR Signal") |
Returns Model by Tenozen | https://www.tradingview.com/script/tYtLFMDU-Returns-Model-by-Tenozen/ | Tenozen | https://www.tradingview.com/u/Tenozen/ | 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/
// © Tenozen
//@version=5
indicator("Returns Model by Tenozen", overlay= false, precision = 7)
true_log = input.bool(false, "Log on?")
ret_len = input.int(20, "Return Gap Length")
true_period = input.bool(false, "Use Array Period?")
n = input.int(20, "Array Period")
log_val = math.log(close)
//Returns
ret = true_log? (log_val[ret_len] - log_val)/log_val*-1 :(close[ret_len] - close)/close*-1 //
//MA
ma_len = input.int(9, "MA Length")
smo_len = input.int(5, "Smoothing Length")
ma = ta.sma(ret, ma_len)
smoothing = ta.sma(ma, smo_len)
//Returns Array
var float [] ret_array = array.new_float()
array.push(ret_array, ret[1])
//Average Return
ret_av = array.avg(ret_array) //
//STD
t_ret = (ret[1] - ret_av)*(ret[1] - ret_av) //
var float [] array_t_ret = array.new_float()
array_p_ret = array.new_float()
if true_period
for i = 0 to n - 1
array.push(array_p_ret, t_ret[i])
else
array.push(array_t_ret, t_ret)
dev_av = true_period? array.sum(array_p_ret)/(array.size(array_p_ret)-1): array.sum(array_t_ret)/(array.size(array_t_ret)-1)
pos_std_ret = math.sqrt(dev_av)
pos_std_ret_2 = math.sqrt(dev_av)*2
neg_std_ret = math.sqrt(dev_av)*-1
neg_std_ret_2 = math.sqrt(dev_av)*2*-1
//Plot
plot(ret, "Return", color.new(#ffffff, 0))
plot(ret_av, "Average Return", color.new(color.purple, 50))
plot(ma, "Moving Average", color=color.new(color.aqua, 0), linewidth=2)
plot(smoothing, "Smoothed Average", color=color.new(color.orange, 0), linewidth=1)
p1 = plot(pos_std_ret, "Standard Deviation +1", color.new(color.red, 50))
n2 = plot(neg_std_ret, "Standard Deviation -1", color.new(color.aqua, 50))
n1 = plot(pos_std_ret_2, "Standard Deviation +2", color.new(color.red, 50))
p2 = plot(neg_std_ret_2, "Standard Deviation -2", color.new(color.aqua, 50))
hline(0, "Zero Line", color.new(color.white, 50), linestyle = hline.style_dotted)
fill(p1,n1,color.new(color.aqua, 90))
fill(p2,n2,color.new(color.red, 90))
// |
Reversal Confirmations [QuantVue] | https://www.tradingview.com/script/3SuZmC5o-Reversal-Confirmations-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 380 | 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/
// © QuantVue
//@version=5
indicator('Reversal Confirmations [QuantVue]', overlay = true)
//----------inputs----------//
lookback = input.int(50, 'Lookback Period', minval = 1, step = 1)
downColor = input(color.red, 'Shape Color Down')
upColor = input(color.green, 'Shape Color Up')
showChannels = input.bool(defval = true, title = 'Show Channel Lines')
showMean = input.bool(defval = true, title = 'Show Mean', inline = '1')
emaColor = input.color(color.orange, ' ', inline = '1')
find_highest = ta.highest(high, lookback)
find_lowest = ta.lowest(low, lookback)
ema = ta.ema(close, lookback)
var dnRv = 0.0
var dnRv_trigger = false
var upRv = 0.0
var upRv_trigger = false
if high == find_highest
dnRv_trigger := false
if low == find_lowest
upRv_trigger := false
for i = 0 to lookback - 1
if high[i] == find_highest
dnRv := low[i]
for i = 0 to lookback - 1
if low[i] == find_lowest
upRv := high[i]
dnRv_signal = close < dnRv and dnRv_trigger == false
upRv_signal = close > upRv and upRv_trigger == false
if dnRv_signal
dnRv_trigger := true
if upRv_signal
upRv_trigger := true
//plots
plot(showChannels ? find_highest : na , 'Upper Channel', color = upColor)
plot(showChannels ? find_lowest : na , 'Lower Channel', color = downColor)
plot(showMean ? ema : na , 'Mean', color = emaColor)
plotshape(dnRv_signal ? 1 : 0, style = shape.triangledown, location = location.abovebar, color = downColor, display = display.pane)
plotshape(upRv_signal ? 1 : 0, style = shape.triangleup, location = location.belowbar, color = upColor, display = display.pane)
//alerts
if upRv_signal
alert('Upside Reversal', alert.freq_once_per_bar_close)
else if dnRv_signal
alert('Downside Reversal', alert.freq_once_per_bar_close) |
Position calculator [krazke] | https://www.tradingview.com/script/uJDgv6tl-Position-calculator-krazke/ | krazke | https://www.tradingview.com/u/krazke/ | 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/
// © krazke
//@version=5
indicator("Position calculator", overlay = true)
// MARK: - Constants
LIQUIDATION_PERCENT = 100.0
LIQUIDATION_SL_PRICE_GAP = 3.0 // In percent
DIRECTION_G_TITLE = "Direction"
POSITION_G_TITLE = "Position"
// MARK: - Types
type LeaverageResult
int leaverage
float liquidation_price
// MARK: - Functions
f_liquidation_price(src, is_long, percent) =>
p = is_long ? -percent : percent
liquidation_price = src * (1.0 + p / 100.0)
f_normalized_float(value) =>
int precision = str.length(str.tostring(syminfo.mintick))-2
pow = math.pow(10, precision)
int(value * pow) / pow
f_find_nearest_liquidation(stop_loss, max_leverage, is_long, src) =>
float nearest_liquidation_price = na
float nearest_diff = na
int leaverage = na
for i = 1 to max_leverage
liquidation_percent = LIQUIDATION_PERCENT / i
liquidation_price = f_liquidation_price(src, is_long, liquidation_percent)
// Calculate the absolute difference between the stop loss and liquidation price
diff = math.abs(stop_loss - liquidation_price)
// Update nearest liquidation price if it's closer
if (na(nearest_liquidation_price) or diff < nearest_diff)
nearest_liquidation_price := liquidation_price
nearest_diff := diff
leaverage := i
LeaverageResult.new(leaverage, nearest_liquidation_price)
// MARK: - Inputs
is_long = input(true, title = "LONG", group = DIRECTION_G_TITLE)
is_fixed_entry = input(true, title = "FIXED ENTRY", inline = "0", group = POSITION_G_TITLE)
fixed_entry = input.float(1630.0, title = "", minval = 0.00000000001, step = 1.0, inline = "0", group = POSITION_G_TITLE)
stop_loss = input.float(1600.0, title = "Stop loss", minval = 0.000000001, step = 1.0, group = POSITION_G_TITLE)
potential_loss = input.float(50.0, title = "Potential loss (USD)", minval = 1.0, step = 1.0, group = POSITION_G_TITLE)
max_leaverage = input.int(50, title = "Max leaverage", minval = 0, step = 1, group = POSITION_G_TITLE)
// MARK: - Global Properties
var table dealTable = table.new(position.bottom_right, 2, 8, bgcolor = color.gray, frame_width = 2, frame_color = color.black, border_width = 1, border_color = color.black)
var int leaverage = 1
var float liquidation_price = 0.0
var float sl_lq_diff = 9999999999999.0
var float margin = 100.0
// MARK: - Local Properties
src = is_fixed_entry ? fixed_entry : close
// MARK: - Calculate Leaverage
for i = 1 to max_leaverage
liquidation_percent = LIQUIDATION_PERCENT / i
_liquidation_price = f_liquidation_price(src, is_long, liquidation_percent)
if is_long
// diff = _liquidation_price - stop_loss
// if diff < 0 and diff < sl_lq_diff and _liquidation_price > 0
// leaverage := i
// sl_lq_diff := diff
// liquidation_price := _liquidation_price
diff = (100.0 - (_liquidation_price * 100.0) / stop_loss)
if diff > 0 and diff <= LIQUIDATION_SL_PRICE_GAP
leaverage := i
break
else
diff = ((_liquidation_price * 100.0) / stop_loss - 100.0)
if diff > 0 and diff <= LIQUIDATION_SL_PRICE_GAP
leaverage := i
break
// leaverage_result = f_find_nearest_liquidation(stop_loss, max_leaverage, is_long, src)
// leaverage := leaverage_result.leaverage
// liquidation_price := leaverage_result.liquidation_price
// MARK: - Calculate Margin Size
e_sl_diff_percent = math.abs(math.abs((stop_loss * 100) / src) - 100.0)
stop_loss_roe = e_sl_diff_percent * leaverage
margin := (potential_loss * 100) / stop_loss_roe
// MARK: - Calculate Liquidation Price
liquidation_percent = LIQUIDATION_PERCENT / leaverage
liquidation_price := is_long ? src * (1.0 - liquidation_percent / 100.0) : src * (1.0 + liquidation_percent / 100.0)
// MARK: - Plots
red_color = color.red
green_color = color.green
clear_color = color.new(red_color, 100)
target_index = bar_index + 10
entry_line = line.new(bar_index, src, target_index, src, extend=extend.left, color=green_color)
entry_label = label.new(target_index, src, 'ENTRY: ' + str.tostring(f_normalized_float(src)), textcolor=green_color, color=clear_color, style=label.style_label_left)
stop_loss_line = line.new(bar_index, stop_loss, target_index, stop_loss, extend=extend.left, color=red_color)
stop_loss_label = label.new(target_index, stop_loss, 'STOP: ' + str.tostring(f_normalized_float(stop_loss)), textcolor=red_color, color=clear_color, style=label.style_label_left)
liquidation_loss_line = line.new(bar_index, liquidation_price, target_index, liquidation_price, extend=extend.left, color=red_color, width = 3)
liquidation_loss_label = label.new(target_index, liquidation_price, 'LIQUIDATION: ~' + str.tostring(f_normalized_float(liquidation_price)), textcolor=red_color, color=clear_color, style=label.style_label_left)
line.delete (entry_line[1])
label.delete(entry_label[1])
line.delete (stop_loss_line[1])
label.delete(stop_loss_label[1])
line.delete (liquidation_loss_line[1])
label.delete(liquidation_loss_label[1])
// MARK: - Table Setup
if barstate.isfirst
table.cell(dealTable, 0, 0, "D", tooltip = "Position direction")
table.cell(dealTable, 0, 1, "E", tooltip = "Entry price")
table.cell(dealTable, 0, 2, "M", tooltip = "Margin size (USD)")
table.cell(dealTable, 0, 3, "P", tooltip = "Position size with included leaverage (USD)")
table.cell(dealTable, 0, 4, "L", tooltip = "Leaverage size")
table.cell(dealTable, 0, 5, "SL", tooltip = "Stop loss price (USD)")
table.cell(dealTable, 0, 6, "LP", tooltip = "Liquidation price (USD)")
table.cell(dealTable, 0, 7, "PL", tooltip = "Potential loss size (USD)")
if barstate.islast
position_direction_str = is_long ? "LONG" : "SHORT"
entry_price_str = str.tostring(f_normalized_float(src)) + "$"
margin_str = str.tostring(f_normalized_float(margin)) + "$"
position_size_str = str.tostring(f_normalized_float(margin * leaverage)) + "$"
leaverage_str = str.tostring(f_normalized_float(leaverage))
stop_loss_str = str.tostring(f_normalized_float(stop_loss)) + "$"
liquidation_price_str = str.tostring(f_normalized_float(liquidation_price)) + "$"
potential_loss_str = str.tostring(f_normalized_float(potential_loss)) + "$"
table.cell(dealTable, 1, 0, position_direction_str)
table.cell(dealTable, 1, 1, entry_price_str)
table.cell(dealTable, 1, 2, margin_str)
table.cell(dealTable, 1, 3, position_size_str)
table.cell(dealTable, 1, 4, leaverage_str)
table.cell(dealTable, 1, 5, stop_loss_str)
table.cell(dealTable, 1, 6, liquidation_price_str)
table.cell(dealTable, 1, 7, potential_loss_str)
|
Trend Lines [AstroHub] | https://www.tradingview.com/script/nlVXBeqg-trend-lines-astrohub/ | AstroHub | https://www.tradingview.com/u/AstroHub/ | 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/
//@version=5
indicator("Trend Lines [AstroHub]", overlay=true)
// Input parameters
lookback = input(20, "Period")
// Determining the high and low prices
highs = ta.highest(high, lookback)
lows = ta.lowest(low, lookback)
// Determining the trend lines
trendLineUp = ta.valuewhen(high == highs, high, 0)
trendLineDown = ta.valuewhen(low == lows, low, 0)
// Determining the bar color
barColor = close > (trendLineUp + trendLineDown) / 2 ? color.green : color.red
// Drawing the lines and changing the bar color
plot(trendLineUp, color=color.green, linewidth=2)
plot(trendLineDown, color=color.red, linewidth=2)
barcolor(barColor)
// RSI indicator
rsiLength = input(13, "RSI Length")
overboughtLevel = input(70, "Overbought Level")
oversoldLevel = input(20, "Oversold Level")
rsi = ta.rsi(close, rsiLength)
// Determine the RSI signal for trend reversal
rsiSignal = rsi > overboughtLevel ? 1 : rsi < oversoldLevel ? -1 : 0
// Plot the RSI signal on the chart
plotshape(rsiSignal == 1 ? low : na, style=shape.triangledown, color=color.red, size=size.small)
plotshape(rsiSignal == -1 ? high : na, style=shape.triangleup, color=color.green, size=size.small)
|
Hosoda Waves ABCDE | https://www.tradingview.com/script/eiR9SQX1/ | WD_GANN | https://www.tradingview.com/u/WD_GANN/ | 87 | 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/
// © WD_GANN
//@version=5
indicator("Hosoda Waves ABCDE",shorttitle="Hosoda Waves ABCDE", overlay=true)
priceA = input.price(100, inline="PointA", confirm=true)
timeA = input.time(timestamp("2020-02-20"), inline="PointA", confirm=true)
AllColor=input.color(color.blue, "Labels, Wave and TPs color")
priceB = input.price(100, inline="PointB", confirm=true)
timeB = input.time(timestamp("2020-02-20"), inline="PointB", confirm=true)
line.new(timeA,priceA,timeB,priceB, xloc = xloc.bar_time,color=AllColor)
priceC = input.price(100, inline="PointC", confirm=true)
timeC = input.time(timestamp("2020-02-20"), inline="PointC", confirm=true)
line.new(timeB,priceB,timeC,priceC, xloc = xloc.bar_time,color=AllColor)
priceD = input.price(100, inline="PointD", confirm=true)
timeD = input.time(timestamp("2020-02-20"), inline="PointD", confirm=true)
line.new(timeC,priceC,timeD,priceD, xloc = xloc.bar_time,color=AllColor)
priceE = input.price(100, inline="PointE", confirm=true)
timeE = input.time(timestamp("2020-02-20"), inline="PointE", confirm=true)
line.new(timeD,priceD,timeE,priceE, xloc = xloc.bar_time,color=AllColor)
multiply= (priceB> priceA)? 1:-1
//label.new(timeA, priceA, "A", xloc=xloc.bar_time,yloc=(multiply>0)?yloc.belowbar:yloc.abovebar, style=label.style_none,color=AllColor)
//label.new(timeB, priceB, "B", xloc=xloc.bar_time,yloc=(multiply<0)?yloc.belowbar:yloc.abovebar, style=label.style_none,color=AllColor)
//label.new(timeC, priceC, "C", xloc=xloc.bar_time,yloc=(multiply>0)?yloc.belowbar:yloc.abovebar, style=label.style_none,color=AllColor)
//label.new(timeD, priceD, "D", xloc=xloc.bar_time,yloc=(multiply<0)?yloc.belowbar:yloc.abovebar, style=label.style_none,color=AllColor)
//label.new(timeE, priceE, "E", xloc=xloc.bar_time,yloc=(multiply>0)?yloc.belowbar:yloc.abovebar, style=label.style_none,color=AllColor)
//SWING ABC
HosodaTpEabcprice=priceB + (multiply * math.abs(priceB-priceA))
line.new(timeA,HosodaTpEabcprice,timeA+1,HosodaTpEabcprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(130, 192, 243), width=2)
label.new(timeA, HosodaTpEabcprice, "E-A=" +str.tostring(HosodaTpEabcprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(202, 231, 255))
HosodaTpNabcprice=priceC + (multiply * math.abs(priceB-priceA))
line.new(timeA,HosodaTpNabcprice,timeA+1,HosodaTpNabcprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(130, 192, 243), width=2)
label.new(timeA, HosodaTpNabcprice, "N-A="+str.tostring(HosodaTpNabcprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(202, 231, 255))
HosodaTpVabcprice=priceB + (multiply * math.abs(priceB-priceC))
line.new(timeA,HosodaTpVabcprice,timeA+1,HosodaTpVabcprice, xloc = xloc.bar_time,extend=extend.right,color=color.lime, width=2)
label.new(timeA, HosodaTpVabcprice,"V-A=" +str.tostring(HosodaTpVabcprice) , xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(179, 255, 218))
HosodaTpNTabcprice=priceC + (multiply * math.abs(priceC-priceA))
line.new(timeA,HosodaTpNTabcprice,timeA+1,HosodaTpNTabcprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(245, 115, 115), width=2)
label.new(timeA, HosodaTpNTabcprice, "NT-A="+str.tostring(HosodaTpNTabcprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(255, 200, 200))
//SWING BCD
HosodaTpEbcdprice=priceC - (multiply * math.abs(priceC-priceB))
line.new(timeC,HosodaTpEbcdprice,timeC+1,HosodaTpEbcdprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(130, 192, 243), width=1)
label.new(timeC, HosodaTpEbcdprice, "E-B=" +str.tostring(HosodaTpEbcdprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(202, 231, 255))
HosodaTpNbcdprice=priceD - (multiply * math.abs(priceC-priceB))
line.new(timeC,HosodaTpNbcdprice,timeC+1,HosodaTpNbcdprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(130, 192, 243), width=1)
label.new(timeC, HosodaTpNbcdprice, "N-B="+str.tostring(HosodaTpNbcdprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(202, 231, 255))
HosodaTpVbcdprice=priceC - (multiply * math.abs(priceC-priceD))
line.new(timeC,HosodaTpVbcdprice,timeC+1,HosodaTpVbcdprice, xloc = xloc.bar_time,extend=extend.right,color=color.lime, width=1)
label.new(timeC, HosodaTpVbcdprice,"V-B=" +str.tostring(HosodaTpVbcdprice) , xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(179, 255, 218))
HosodaTpNTbcdprice=priceD - (multiply * math.abs(priceD-priceB))
line.new(timeC,HosodaTpNTbcdprice,timeC+1,HosodaTpNTbcdprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(245, 115, 115), width=1)
label.new(timeC, HosodaTpNTbcdprice, "NT-B="+str.tostring(HosodaTpNTbcdprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(255, 200, 200))
//SWING CDE
HosodaTpEcdeprice=priceD + (multiply * math.abs(priceD-priceC))
line.new(timeE,HosodaTpEcdeprice,timeE+1,HosodaTpEcdeprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(130, 192, 243), width=0)
label.new(timeE, HosodaTpEcdeprice, "E-C=" +str.tostring(HosodaTpEcdeprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(202, 231, 255))
HosodaTpNcdeprice=priceE + (multiply * math.abs(priceD-priceC))
line.new(timeE,HosodaTpNcdeprice,timeE+1,HosodaTpNcdeprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(130, 192, 243), width=0)
label.new(timeE, HosodaTpNcdeprice, "N-C="+str.tostring(HosodaTpNcdeprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(202, 231, 255))
HosodaTpVcdeprice=priceD + (multiply * math.abs(priceD-priceE))
line.new(timeE,HosodaTpVcdeprice,timeE+1,HosodaTpVcdeprice, xloc = xloc.bar_time,extend=extend.right,color=color.lime, width=0)
label.new(timeE, HosodaTpVcdeprice,"V-C=" +str.tostring(HosodaTpVcdeprice) , xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(179, 255, 218))
HosodaTpNTcdeprice=priceE + (multiply * math.abs(priceE-priceC))
line.new(timeE,HosodaTpNTcdeprice,timeE+1,HosodaTpNTcdeprice, xloc = xloc.bar_time,extend=extend.right,color=color.rgb(245, 115, 115), width=0)
label.new(timeE, HosodaTpNTcdeprice, "NT-C="+str.tostring(HosodaTpNTcdeprice), xloc=xloc.bar_time,yloc=yloc.price, style=label.style_text_outline,color=color.rgb(255, 200, 200))
|
Percentage Range Consolidation Histogram | https://www.tradingview.com/script/XEybKoh8-Percentage-Range-Consolidation-Histogram/ | Honestcowboy | https://www.tradingview.com/u/Honestcowboy/ | 41 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Honestcowboy
//@version=5
indicator("Percentage Range Consolidation", overlay=false)
//tooltips
consolidationLengthTip = "The amount of bars script will use to measure width from highest high to lowest low in percentage"
percentageFilterTip = "The maximum % the zone can be currently for it to be valid (coloring means it's consolidating at low volatility)"
consolidationLengthCheckTip = "The script will plot on each bar percentage value that the range is. This is the amount of bars back it will look at zone % to calculate averages"
ConsolidationLengthCheckPercentage = "After checking amount of bars back at zone % this is the percentage used for the white line. At default this is set to 15% meaning that if zone is ranked in bottom 15% of zone widths it will highlight (coloring means it's consolidating at low volatility)"
//use inputs
consolidationStrictness = input.string(title='consolidation filters', defval='all', options=['percentage', 'median', 'all'], group="settings")
consolidationLength1 = input.int(defval=10, minval=1, title="percentage zone length", group="consolidation check 1", tooltip = consolidationLengthTip)
percentageFilter1 = input.float(defval=15, minval=0, maxval=100, title="percentage zone % filter", group="consolidation check 1", tooltip = percentageFilterTip)
ConsolidationLengthCheckLength1 = input.int(defval=50, minval=1, title="percentage zone PNR length", group="consolidation check 1", tooltip = consolidationLengthCheckTip)
ConsolidationLengthCheckPercentage1 = input.float(defval=20, minval=0, maxval=100, title="percentage zone PNR %", group="consolidation check 1", tooltip = ConsolidationLengthCheckPercentage)
consolidationLength2 = input.int(defval=30, minval=1, title="percentage zone length", group="consolidation check 2", tooltip = consolidationLengthTip)
percentageFilter2 = input.float(defval=15, minval=0, maxval=100, title="percentage zone % filter", group="consolidation check 2", tooltip = percentageFilterTip)
ConsolidationLengthCheckLength2 = input.int(defval=50, minval=1, title="percentage zone PNR length", group="consolidation check 2", tooltip = consolidationLengthCheckTip)
ConsolidationLengthCheckPercentage2 = input.float(defval=20, minval=0, maxval=100, title="percentage zone PNR %", group="consolidation check 2", tooltip = ConsolidationLengthCheckPercentage)
consolidationLength3 = input.int(defval=80, minval=1, title="percentage zone length", group="consolidation check 3", tooltip = consolidationLengthTip)
percentageFilter3 = input.float(defval=15, minval=0, maxval=100, title="percentage zone % filter", group="consolidation check 3", tooltip = percentageFilterTip)
ConsolidationLengthCheckLength3 = input.int(defval=50, minval=1, title="percentage zone PNR length", group="consolidation check 3", tooltip = consolidationLengthCheckTip)
ConsolidationLengthCheckPercentage3 = input.float(defval=20, minval=0, maxval=100, title="percentage zone PNR %", group="consolidation check 3", tooltip = ConsolidationLengthCheckPercentage)
transparancy1 = input.int(defval=30, minval=0, maxval=100, title="color transparancy", group="visuals")
transparancy2 = input.int(defval=80, minval=0, maxval=100, title="grays transparancy", group="visuals")
transparancy3 = input.int(defval=50, minval=0, maxval=100, title="percentage zone PNR line transparancy", group="visuals")
useBarColoring = input.bool(true, title="", group="bar coloring", inline = "1")
consolidationNumberForColoring = input.string(defval = "3", options = ["1", "2", "3"], title="consolidation filters needed", group="bar coloring", inline = "1")
barColor = input.color(defval=color.rgb(215, 0, 0), title="", group="bar coloring", inline = "1")
//Consolidation Function
f_consolidationZone(consolidationStrictness, consolidationLength, percentageFilter, ConsolidationLengthCheckLength, ConsolidationLengthCheckPercentage) =>
bandsTop = ta.percentile_nearest_rank(close,consolidationLength,100) // you can change these so the zone will % will not be created from top and bottom but more middle values
bandsBottom = ta.percentile_nearest_rank(close,consolidationLength,0) // you can change these so the zone will % will not be created from top and bottom but more middle values
percentageZone = ((bandsTop-bandsBottom)/bandsBottom)*100
percentageZonePNR = ta.percentile_nearest_rank(percentageZone, ConsolidationLengthCheckLength, ConsolidationLengthCheckPercentage)
consolidating = consolidationStrictness=="all"?percentageZone<percentageZonePNR and percentageZone<percentageFilter:
consolidationStrictness=="percentage"?percentageZone<percentageFilter:
consolidationStrictness=="median"?percentageZone<percentageZonePNR:false
[percentageZone,percentageZonePNR,consolidating]
//get values
[percentageZone1,percentageZonePNR1,consolidating1] = f_consolidationZone(consolidationStrictness, consolidationLength1, percentageFilter1, ConsolidationLengthCheckLength1, ConsolidationLengthCheckPercentage1)
[percentageZone2,percentageZonePNR2,consolidating2] = f_consolidationZone(consolidationStrictness, consolidationLength2, percentageFilter2, ConsolidationLengthCheckLength2, ConsolidationLengthCheckPercentage2)
[percentageZone3,percentageZonePNR3,consolidating3] = f_consolidationZone(consolidationStrictness, consolidationLength3, percentageFilter3, ConsolidationLengthCheckLength3, ConsolidationLengthCheckPercentage3)
//coloring
zoneColor1= consolidating1?color.new(color.yellow,transparancy1):color.new(color.gray,transparancy2)
zoneColor2= consolidating2?color.new(color.orange,transparancy1):color.new(color.gray,transparancy2)
zoneColor3= consolidating3?color.new(color.blue,transparancy1):color.new(color.gray,transparancy2)
//Bar coloring
numberOfConsolidations = 0
numberOfConsolidations := consolidating1 ? numberOfConsolidations+1 : numberOfConsolidations
numberOfConsolidations := consolidating2 ? numberOfConsolidations+1 : numberOfConsolidations
numberOfConsolidations := consolidating3 ? numberOfConsolidations+1 : numberOfConsolidations
isConsolidating = consolidationNumberForColoring == "1" ? numberOfConsolidations>=1 : consolidationNumberForColoring == "2" ? numberOfConsolidations>=2 : numberOfConsolidations>=3
barcolor(isConsolidating ? barColor : na)
//Breakout Logic
float breakTop = na
float breakBottom = na
breakTop := (isConsolidating and not isConsolidating[1]) ? high : (isConsolidating and isConsolidating[1] and high>breakTop[1]) ? high : breakTop[1]
breakBottom := (isConsolidating and not isConsolidating[1]) ? low : (isConsolidating and isConsolidating[1] and low<breakBottom[1]) ? low : breakBottom[1]
breaksTop = close>breakTop
breaksBottom = close<breakBottom
breakTop := (breaksTop or breaksBottom) and (not isConsolidating) ? na : breakTop
breakBottom := (breaksTop or breaksBottom) and (not isConsolidating) ? na : breakBottom
//plotting
plot(percentageZone3, color=zoneColor3, style=plot.style_columns, title="Percentage zone 3")
plot(percentageZonePNR3, color=color.new(color.white,transparancy3), linewidth=3, title="percentage zone PNR 3")
plot(percentageZone2, color=zoneColor2, style=plot.style_columns, title="Percentage zone 2")
plot(percentageZonePNR2, color=color.new(color.white,transparancy3), linewidth=3, title="percentage zone PNR 2")
plot(percentageZone1, color=zoneColor1, style=plot.style_columns, title="Percentage zone 1")
plot(percentageZonePNR1, color=color.new(color.white,transparancy3), linewidth=3, title="percentage zone PNR 1")
//Alerts
bgcolor(breaksTop ? color.rgb(0, 158, 8) : breaksBottom ? color.rgb(215, 0, 0) : na)
alertcondition(isConsolidating and not isConsolidating[1],title="Consolidation start")
alertcondition(breaksTop,title="break top of rane")
alertcondition(breaksBottom,title="breaks bottom of range") |
MTF - Zigzag + Tech Indicators | https://www.tradingview.com/script/qyJipOeN-MTF-Zigzag-Tech-Indicators/ | Sharad_Gaikwad | https://www.tradingview.com/u/Sharad_Gaikwad/ | 67 | 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
//#region General functions
var tab = table.new(position=position.top_right, columns=7, rows=30,frame_color = color.yellow, frame_width = 1)
msg(int row, int col, string msg_str, clr=color.blue) =>
if(barstate.islast)
table.cell(table_id=tab, column=col, row=row, text=msg_str, text_color=clr)
t(val) => str.tostring(val)
method f(float f) => str.tostring(f)
method f(int i) => str.tostring(i)
method f(bool b) => str.tostring(b)
method f(string s) => str.tostring(s)
method fd(int t, string format = "dd-MM-yy HH:mm") => str.format_time(t, format, syminfo.timezone)
dt(val, format = "dd-MM-yy HH:mm") => str.format_time(val, format, syminfo.timezone)
var debug = array.new<string>(1, "")
method clear_log(string [] s) =>
s.clear()
s.unshift("")
method log(string [] s, string msg, bool on_last_bar = false) =>
if((not on_last_bar) or (on_last_bar and barstate.islast))
if(str.length(s.get(0)) + str.length(msg) < 4095)
s.set(0, s.get(0) + msg + "\n")
method display(string [] s, where = 'B') =>
if(not na(s.get(0)))
if(where == 'B')
label.new(bar_index, low, yloc = yloc.belowbar, style = label.style_diamond, tooltip = s.get(0), size = size.tiny)
else
label.new(bar_index, high, yloc = yloc.abovebar, style = label.style_diamond, tooltip = s.get(0), size = size.tiny)
debug.clear_log()
//#endregion General functions
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//@version=5
indicator('MTF - Zigzag + Tech Indicators', overlay=true, max_lines_count = 500, max_labels_count = 500)
//#region Input Parameters
start_time = input.time(timestamp("01 Jan 1900"))
g1 = 'High high, Lower low Setup'
lb = input.int(title = 'Left bars', defval = 10, group = g1, inline = 'g11')
rb = input.int(title = 'Right bars', defval = 10, group = g1, inline = 'g11')
g2 = 'Chart timeframe Zigzag Setup'
color_ctf = input.color(title = 'Zigzag color', defval = color.blue, group = g2, inline = 'g21')
width_ctf = input.int(title = 'Width', defval = 1, group = g2, inline = 'g21')
plot_ctf_zigzag = input.bool(title = 'Plot Zigzag', defval = true, group = g2, inline = 'g22')
plot_ctf_hhll_labels = input.bool(title = 'Plot HHLL labels', defval = true, group = g2, inline = 'g22')
g3 = 'Higher timeframe Zigzag Setup'
htf = input.timeframe(title = 'HTF', defval = 'D', group = g3, inline = 'g31')
htf_offset = input.int(title = 'Offset', defval = 1, minval = 0, maxval = 1, group = g3, inline = 'g31')
color_htf = input.color(title = 'Zigzag color', defval = color.yellow, group = g3, inline = 'g32')
width_htf = input.int(title = 'Width', defval = 1, group = g3, inline = 'g32')
plot_htf_zigzag = input.bool(title = 'Plot Zigzag', defval = true, group = g3, inline = 'g33')
plot_htf_hhll_labels = input.bool(title = 'Plot HHLL labels', defval = true, group = g3, inline = 'g33')
g4 = 'Higher timeframe Zigzag Setup 1'
htf1 = input.timeframe(title = 'HTF', defval = 'W', group = g4, inline = 'g41')
htf1_offset = input.int(title = 'Offset', defval = 1, minval = 0, maxval = 1, group = g4, inline = 'g41')
color_htf1 = input.color(title = 'Zigzag color', defval = color.purple, group = g4, inline = 'g42')
width_htf1 = input.int(title = 'Width', defval = 1, group = g4, inline = 'g42')
plot_htf1_zigzag = input.bool(title = 'Plot Zigzag', defval = false, group = g4, inline = 'g43')
plot_htf1_hhll_labels = input.bool(title = 'Plot HHLL labels', defval = false, group = g4, inline = 'g43')
//#endregion Input Parameters
//#region Definitions and functios
var tf_info = table.new(position=position.bottom_right, columns=1, rows=1,frame_color = na, frame_width = 1)
show_tf(int row = 0, int col = 0, string msg_str, clr=color.blue) =>
if(barstate.islast)
table.cell(table_id=tf_info, column=col, row=row, text=msg_str, text_color=clr, text_size = size.tiny)
var ctf = t(timeframe.period)
show_tf(0, 0, "TF: "+t(ctf)+"/"+t(htf)+"/"+t(htf1))
type class_visuals
bool plot_line = false
bool plot_label = false
color clr
int width
var visuals = map.new<string, class_visuals>()
if(bar_index == 0)
visuals.put('CTF', class_visuals.new(plot_ctf_zigzag, plot_ctf_hhll_labels, color_ctf, width_ctf))
visuals.put('HTF', class_visuals.new(plot_htf_zigzag, plot_htf_hhll_labels, color_htf, width_htf))
visuals.put('HTF1', class_visuals.new(plot_htf1_zigzag, plot_htf1_hhll_labels, color_htf1, width_htf1))
//objects
type class_hhll
string group //H or l
string sub_group // HH, LL, LH, HL
int bar_id
int bar_time
float pivot_pp
line ln
label lbl
float rsi
float stoc
float adx
float sma20
float sma50
float sma100
float sma200
float price_move
float price_change
float cum_volume
float swing_volume
string tf
bool is_new = false
var array<class_hhll> hhll_ctf = array.new<class_hhll>()
var array<class_hhll> hhll_htf = array.new<class_hhll>()
var array<class_hhll> hhll_htf1 = array.new<class_hhll>()
type class_ohlc
bool pivot
float pp
int bar_id
int bar_time
float rsi
float stoc
float adx
float sma20
float sma50
float sma100
float sma200
float cum_volume
//
rsi = math.round(ta.rsi(close, 14), 2)
stoc = math.round(ta.stoch(close, high, low, 14), 2)
[diplus, diminus, _adx] = ta.dmi(14, 14)
adx = math.round(_adx, 2)
sma20 = math.round(ta.sma(close, 20), 2)
sma50 = math.round(ta.sma(close, 50), 2)
sma100 = math.round(ta.sma(close, 100), 2)
sma200 = math.round(ta.sma(close, 200), 2)
vol_sum = ta.cum(volume)
//
get_ph_pl(i) =>
ph = class_ohlc.new(pivot = false)
pl = class_ohlc.new(pivot = false)
_ph = ta.pivothigh(high[i], lb, rb)
_pl = ta.pivotlow(low[i], lb, rb)
// __ph = ta.pivothigh(high[i], lb, rb)
// __pl = ta.pivotlow(low[i], lb, rb)
// _ph = __ph != 0 ? true : false
// _pl = __pl != 0 ? true : false
if((_ph > 0 or _pl > 0) and time >= start_time)
rec = class_ohlc.new(
pivot = true,
pp = _ph > 0 ? high[rb+i] : low[rb+i],
bar_id = bar_index[rb+i],
bar_time = time[rb+i],
rsi = rsi[rb+i],
stoc = stoc[rb+i],
adx = adx[rb+i],
sma20 = sma20[rb+i],
sma50 = sma50[rb+i],
sma100 = sma100[rb+i],
sma200 = sma200[rb+i],
cum_volume = vol_sum[rb+i])
ph := not na(_ph) ? rec : ph
pl := not na(_pl) ? rec : pl
[ph, pl]
//
method get_tt(class_hhll hhll) =>
tt = "Tag = "+ hhll.sub_group + " (" + dt(hhll.bar_time) +")\n" +
"Timeframe = "+ hhll.tf + "\n" +
"Price point = "+ t(hhll.pivot_pp) + "\n" +
"Price change = "+ t(hhll.price_change) + " ("+t(hhll.price_move) + " %)\n" +
"Swing volume = "+ t(math.round(hhll.swing_volume/1000000, 2)) + " M\n" +
"---- Technical Indicators ----" +"\n"+
"RSI = "+ t(hhll.rsi) + "\n" +
"Stochastic = "+ t(hhll.stoc) + "\n" +
"ADX = "+ t(hhll.adx) + "\n" +
"SMA20 = "+ t(hhll.sma20) + "\n" +
"SMA50 = "+ t(hhll.sma50) + "\n" +
"SMA100 = "+ t(hhll.sma100) + "\n" +
"SMA200 = "+ t(hhll.sma200)
//
method get(array<class_hhll> hhll, id) => hhll.size() > id ? hhll.get(id) : class_hhll.new()
//
method add_ph(array<class_hhll> hhll, class_ohlc ph, class_visuals v, tf) =>
if(ph.pivot)
pp = ph.pp
bar_id = ph.bar_id
bar_time = ph.bar_time
vol = ph.cum_volume
class_hhll prev = hhll.get(0)
rec_deleted = false
if(prev.group == 'H')
if(pp > prev.pivot_pp)
rec_deleted := true
prev.ln.delete()
prev.lbl.delete()
hhll.shift()
prev := hhll.get(0)
if(prev.group != 'H')
move = math.round((pp - nz(prev.pivot_pp, 0)) / pp * 100, 2)
change = math.round_to_mintick(pp - nz(prev.pivot_pp))
swing_vol = vol - prev.cum_volume
new_rec = class_hhll.new(group = 'H', bar_id = bar_id, bar_time = bar_time, pivot_pp = pp, rsi = ph.rsi,
stoc = ph.stoc, adx = ph.adx, sma20 = ph.sma20, sma50 = ph.sma50, sma100 = ph.sma100, sma200 = ph.sma200, price_move = move, price_change = change,
cum_volume = ph.cum_volume, swing_volume = swing_vol, tf = t(tf), is_new = true)
if(na(prev.group))
new_rec.sub_group := 'HH'
if(v.plot_line)
new_rec.ln := line.new(bar_time, pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny,
color = v.clr, tooltip = tt)
else
class_hhll prev_ph = hhll.get(1)
new_rec.sub_group := pp > prev_ph.pivot_pp ? 'HH' : 'LH'
if(v.plot_line)
new_rec.ln := line.new(prev.bar_time, prev.pivot_pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny, color = v.clr, tooltip = tt)
hhll.unshift(new_rec)
true
//
method add_pl(array<class_hhll> hhll, class_ohlc pl, class_visuals v, tf) =>
if(pl.pivot)
pp = pl.pp
bar_id = pl.bar_id
bar_time = pl.bar_time
vol = pl.cum_volume
class_hhll prev = hhll.get(0)
rec_deleted = false
if(prev.group == 'L')
if(pp < prev.pivot_pp)
rec_deleted := true
prev.ln.delete()
prev.lbl.delete()
hhll.shift()
prev := hhll.get(0)
if(prev.group != 'L')
move = math.round((pp - nz(prev.pivot_pp, 0)) / pp * 100, 2)
change = math.round_to_mintick(pp - nz(prev.pivot_pp))
swing_vol = vol - prev.cum_volume
new_rec = class_hhll.new(group = 'L', bar_id = bar_id, bar_time = bar_time, pivot_pp = pp, rsi = pl.rsi,
stoc = pl.stoc, adx = pl.adx, sma20 = pl.sma20, sma50 = pl.sma50, sma100 = pl.sma100, sma200 = pl.sma200, price_move = move, price_change = change,
cum_volume = pl.cum_volume, swing_volume = swing_vol, tf = t(tf), is_new = true)
if(na(prev.group))
new_rec.sub_group := 'LL'
if(v.plot_line)
new_rec.ln := line.new(bar_time, pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny, color = v.clr, tooltip = tt)
else
class_hhll prev_pl = hhll.get(1)
new_rec.sub_group := pp < prev_pl.pivot_pp ? 'LL' : 'HL'
if(v.plot_line)
new_rec.ln := line.new(prev.bar_time, prev.pivot_pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny, color = v.clr, tooltip = tt)
hhll.unshift(new_rec)
true
//#endregion Definitions and functios
//#region Main
//main code
[ph_ctf, pl_ctf] = get_ph_pl(0)
hhll_ctf.add_ph(ph_ctf, visuals.get('CTF'), ctf)
hhll_ctf.add_pl(pl_ctf, visuals.get('CTF'), ctf)
//HTF code
new_htf = timeframe.change(htf)
[ph_htf, pl_htf] = request.security('', htf, get_ph_pl(htf_offset))
if(na(ph_htf) or not new_htf)
ph_htf := class_ohlc.new(false)
if(na(pl_htf) or not new_htf)
pl_htf := class_ohlc.new(false)
hhll_htf.add_ph(ph_htf, visuals.get('HTF'), htf)
hhll_htf.add_pl(pl_htf, visuals.get('HTF'), htf)
//HTF 1 code
new_htf1 = timeframe.change(htf1)
[ph_htf1, pl_htf1] = request.security('', htf1, get_ph_pl(htf1_offset))
if(na(ph_htf1) or not new_htf1)
ph_htf1 := class_ohlc.new(false)
if(na(pl_htf1) or not new_htf1)
pl_htf1 := class_ohlc.new(false)
hhll_htf1.add_ph(ph_htf1, visuals.get('HTF1'), htf1)
hhll_htf1.add_pl(pl_htf1, visuals.get('HTF1'), htf1)
//#endregion Main
|
Intraday Session Table | https://www.tradingview.com/script/R5QGfsOz-Intraday-Session-Table/ | avsr90 | https://www.tradingview.com/u/avsr90/ | 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/
// © avsr90
//@version=5
/// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © avsr90
indicator("Intraday Session Table ",overlay =false,max_bars_back=5000,precision=2)
Table=input.bool(defval=true,title="Table")
Multi=input.string(defval="ROC",options=["ROC","CLOSE","RSI","MA20","MA50","MOM","CL-OP","NetB","NetV"])
To_View_individual_Charts_Check_Out_Above_Table_Check_in_Box=input.string("Check out above 'TABLE' inputCheck in Box ")
//Resolution,"RedB","Net B"
Resn1=input.timeframe(defval="D",title="Resolution")
//INTRADAY LENGTH
Cle=math.round_to_mintick(close)
Open= request.security(syminfo.tickerid ,Resn1,close[1],barmerge.gaps_off, barmerge.lookahead_on)
opcl=math.round_to_mintick(Cle-Open)
//length from Day open
Nifnum= ta.change(Open)
Lb=int(math.max(1, nz(ta.barssince(Nifnum)) + 1))
// Date and Timer
Named=str.tostring(dayofweek(timenow))
Named1=Named=="1" ? "SUNDAY":Named=="2" ? "MONDAY":Named=="3" ? "TUESDAY":Named=="4" ? "WEDNESDAY":
Named=="5" ?"THURSDAY": Named=="6" ? "FRIDAY":Named=="7" ?"SATURDAY":na
Years=year(timenow)
Months=month(timenow)
Days= dayofmonth (timenow)
pr=str.tostring(hour(timenow), "00:") + str.tostring(minute(timenow), "00:") + str.tostring(second(timenow), "00")
prd=str.tostring((Days),"00/") + str.tostring((Months),"00/") + str.tostring((Years),"0000")
prd1=str.tostring(Named1)
//Lengths
L_rsi=input(defval=14,title="L for RSI")
L_mom=input(defval=10,title="L for Mom")
Intra_bars_count() =>
greenBars = 0.00
redBars = 0.00
for i=1 to Lb
if ( close[i]*volume[i]>open[i]*volume[i])
greenBars:= greenBars+1
if not (close[i]*volume[i] > open[i]*volume[i])
redBars := redBars+1
[greenBars,redBars]
[greenB, redB] = Intra_bars_count()
NetB=greenB-redB
//Session
ses1 = input.session("0915-0929")
ses2 = input.session("0930-0944")
ses3 = input.session("0945-0959")
ses4 = input.session("1000-1014")
ses5 = input.session("1015-1029")
ses6 = input.session("1030-1044")
ses7 = input.session("1045-1059")
ses8 = input.session("1100-1114")
ses9 = input.session("1115-1129")
ses10 = input.session("1130-1144")
ses11 = input.session("1145-1159")
ses12 = input.session("1200-1214")
ses13 = input.session("1215-1229")
ses14 = input.session("1230-1244")
ses15 = input.session("1245-1259")
ses16 = input.session("1300-1314")
ses17 = input.session("1315-1329")
ses18 = input.session("1330-1344")
ses19 = input.session("1345-1359")
ses20 = input.session("1400-1414")
ses21 = input.session("1415-1429")
ses22 = input.session("1430-1444")
ses23 = input.session("1445-1459")
ses24 = input.session("1500-1514")
ses25 = input.session("1515-1529")
ses26 = input.session("1530-1544")
ses27 = input.session("1545-1559")
ses28 = input.session("1600-1614")
ses29 = input.session("1615-1629")
ses30 = input.session("1630-1644")
ses31 = input.session("1645-1659")
ses32 = input.session("1700-1714")
IsLastBarSession(sessionTime, sessionTimeZone=syminfo.timezone) =>
var int lastBarHour = na
var int lastBarMinute = na
var int lastBarSecond = na
inSess = not na(time(timeframe.period, sessionTime, sessionTimeZone))
if not inSess and inSess[1]
lastBarHour := hour[1]
lastBarMinute := minute[1]
lastBarSecond := second[1]
hour == lastBarHour and minute == lastBarMinute and second == lastBarSecond
//New Day
t1 = ta.change(time("D","0915-1630",syminfo.timezone))
var float o1 = 0
if IsLastBarSession(ses1, sessionTimeZone=syminfo.timezone)
o1:= opcl
var float o2 = 0
if t1
o2:=0
if IsLastBarSession(ses2, sessionTimeZone=syminfo.timezone)
o2:= opcl
var float o3 = 0
if t1
o3:=0
if IsLastBarSession(ses3, sessionTimeZone=syminfo.timezone)
o3:= opcl
var float o4 = 0
if t1
o4:=0
if IsLastBarSession(ses4, sessionTimeZone=syminfo.timezone)
o4:= opcl
var float o5 = 0
if t1
o5:=0
if IsLastBarSession(ses5, sessionTimeZone=syminfo.timezone)
o5:= opcl
var float o6 = 0
if t1
o6:=0
if IsLastBarSession(ses6, sessionTimeZone=syminfo.timezone)
o6:= opcl
var float o7 = 0
if t1
o7:=0
if IsLastBarSession(ses7, sessionTimeZone=syminfo.timezone)
o7:= opcl
var float o8 = 0
if t1
o8:=0
if IsLastBarSession(ses8, sessionTimeZone=syminfo.timezone)
o8:= opcl
var float o9 = 0
if t1
o9:=0
if IsLastBarSession(ses9, sessionTimeZone=syminfo.timezone)
o9:= opcl
var float o10 = 0
if t1
o10:=0
if IsLastBarSession(ses10, sessionTimeZone=syminfo.timezone)
o10:= opcl
var float o11 = 0
if t1
o11:=0
if IsLastBarSession(ses11, sessionTimeZone=syminfo.timezone)
o11:= opcl
var float o12 = 0
if t1
o12:=0
if IsLastBarSession(ses12, sessionTimeZone=syminfo.timezone)
o12:= opcl
var float o13 = 0
if t1
o13:=0
if IsLastBarSession(ses13, sessionTimeZone=syminfo.timezone)
o13:= opcl
var float o14 = 0
if IsLastBarSession(ses14, sessionTimeZone=syminfo.timezone)
o14:= opcl
if t1
o14:=0
var float o15 = 0
if t1
o15:=0
if IsLastBarSession(ses15, sessionTimeZone=syminfo.timezone)
o15:= opcl
var float o16 = 0
if t1
o16:= 0
if IsLastBarSession(ses16, sessionTimeZone=syminfo.timezone)
o16:= opcl
var float o17 = 0
float o17a=0
if t1
o17:=0
if IsLastBarSession(ses17, sessionTimeZone=syminfo.timezone)
o17:= opcl
var float o18 = 0
if t1
o18:=0
if IsLastBarSession(ses18, sessionTimeZone=syminfo.timezone)
o18:= opcl
var float o19 = 0
if t1
o19:=0
if IsLastBarSession(ses19, sessionTimeZone=syminfo.timezone)
o19:= opcl
var float o20 = 0
if t1
o20:=0
if IsLastBarSession(ses20, sessionTimeZone=syminfo.timezone)
o20:= opcl
var float o21 = 0
if t1
o21:=0
if IsLastBarSession(ses21, sessionTimeZone=syminfo.timezone)
o21:= opcl
var float o22 = 0
if t1
o22:=0
if IsLastBarSession(ses22, sessionTimeZone=syminfo.timezone)
o22:= opcl
var float o23 = 0
if t1
o23:=0
if IsLastBarSession(ses23, sessionTimeZone=syminfo.timezone)
o23:= opcl
var float o24=0
if t1
o24:=0
if IsLastBarSession(ses24, sessionTimeZone=syminfo.timezone)
o24:= opcl
var float o25 = 0
if t1
o25:=0
if IsLastBarSession(ses25, sessionTimeZone=syminfo.timezone)
o25:= opcl
var float o26 = 0
if t1
o26:=0
if IsLastBarSession(ses26, sessionTimeZone=syminfo.timezone)
o26:= opcl
var float o27 = 0
if t1
o27:=0
if IsLastBarSession(ses27, sessionTimeZone=syminfo.timezone)
o27:= opcl
var float o28 = 0
if t1
o28:=0
if IsLastBarSession(ses28, sessionTimeZone=syminfo.timezone)
o28:= opcl
var float o29 = 0
if t1
o29:=0
if IsLastBarSession(ses29, sessionTimeZone=syminfo.timezone)
o29:= opcl
var float o30 = 0
if t1
o30:=0
if IsLastBarSession(ses30, sessionTimeZone=syminfo.timezone)
o30:= opcl
var float o31 = 0
if t1
o31:=0
if IsLastBarSession(ses31, sessionTimeZone=syminfo.timezone)
o31:= opcl
var float o32=0
if t1
o32:=0
if IsLastBarSession(ses32, sessionTimeZone=syminfo.timezone)
o32:= opcl
//Increase/Decrease in OP-Cl
var float v1 = 0
if IsLastBarSession(ses1,sessionTimeZone=syminfo.timezone)
v1 := 0
var float v2 = 0
if IsLastBarSession(ses2,sessionTimeZone=syminfo.timezone) and ( o2>o1)
v2:=o2-o1
if IsLastBarSession(ses2,sessionTimeZone=syminfo.timezone) and ( o2<o1)
v2 := o1-o2
if t1
v2:=0
var float v3 = 0
if IsLastBarSession(ses3,sessionTimeZone=syminfo.timezone) and ( o3>o2)
v3:=o3-o2
if IsLastBarSession(ses3,sessionTimeZone=syminfo.timezone) and ( o3<o2)
v3 := o2-o3
if t1
v3:=0
var float v4 = 0
if IsLastBarSession(ses4,sessionTimeZone=syminfo.timezone) and ( o4>o3)
v4:=o4-o3
if IsLastBarSession(ses4,sessionTimeZone=syminfo.timezone) and ( o4<o3)
v4 := o3-o4
if t1
v4:=0
var float v5 = 0
if IsLastBarSession(ses5,sessionTimeZone=syminfo.timezone) and ( o5>o4)
v5:=o5-o4
if IsLastBarSession(ses5,sessionTimeZone=syminfo.timezone) and ( o5<o4)
v5 := o4-o5
if t1
v5:=0
var float v6 = 0
if IsLastBarSession(ses6,sessionTimeZone=syminfo.timezone) and ( o6>o5)
v6:=o6-o5
if IsLastBarSession(ses6,sessionTimeZone=syminfo.timezone) and ( o6<o5)
v6 := o5-o6
if t1
v6:=0
var float v7 = 0
if IsLastBarSession(ses7,sessionTimeZone=syminfo.timezone) and ( o7>o6)
v7:=o7-o6
if IsLastBarSession(ses7,sessionTimeZone=syminfo.timezone) and ( o7<o6)
v7 := o6-o7
if t1
v7:=0
var float v8 = 0
if IsLastBarSession(ses8,sessionTimeZone=syminfo.timezone) and ( o8>o7)
v8:=o8-o7
if IsLastBarSession(ses8,sessionTimeZone=syminfo.timezone) and ( o8<o7)
v8 := o7-o8
if t1
v8:=0
var float v9 = 0
if IsLastBarSession(ses9,sessionTimeZone=syminfo.timezone) and ( o9>o8)
v9:=o9-o8
if IsLastBarSession(ses9,sessionTimeZone=syminfo.timezone) and ( o9<o8)
v9 := o8-o9
if t1
v9:=0
var float v10 = 0
if IsLastBarSession(ses10,sessionTimeZone=syminfo.timezone) and ( o10>o9)
v10:=o10-o9
if IsLastBarSession(ses10,sessionTimeZone=syminfo.timezone) and ( o10<o9)
v10 := o9-o10
if t1
v10:=0
var float v11 = 0
if IsLastBarSession(ses11,sessionTimeZone=syminfo.timezone) and ( o11>o10)
v11:=o11-o10
if IsLastBarSession(ses11,sessionTimeZone=syminfo.timezone) and ( o11<o10)
v11 := o10-o11
if t1
v11:=0
var float v12 = 0
if IsLastBarSession(ses12,sessionTimeZone=syminfo.timezone) and ( o12>o11)
v12:=o12-o11
if IsLastBarSession(ses12,sessionTimeZone=syminfo.timezone) and ( o12<o11)
v12 := o11-o12
if t1
v12:=0
var float v13 = 0
if IsLastBarSession(ses13,sessionTimeZone=syminfo.timezone) and ( o13>o12)
v13:=o13-o12
if IsLastBarSession(ses13,sessionTimeZone=syminfo.timezone) and ( o13<o12)
v13 := o12-o13
if t1
v13:=0
var float v14 = 0
if IsLastBarSession(ses14,sessionTimeZone=syminfo.timezone) and ( o14>o13)
v14:=o14-o13
if IsLastBarSession(ses14,sessionTimeZone=syminfo.timezone) and ( o14<o13)
v14 := o13-o14
if t1
v14:=0
var float v15 = 0
if IsLastBarSession(ses15,sessionTimeZone=syminfo.timezone) and ( o15>o14)
v15:=o15-o14
if IsLastBarSession(ses15,sessionTimeZone=syminfo.timezone) and ( o15<o14)
v15 := o14-o15
if t1
v15:=0
var float v16 = 0
if IsLastBarSession(ses16,sessionTimeZone=syminfo.timezone) and ( o16>o15)
v16:=o16-o15
if IsLastBarSession(ses16,sessionTimeZone=syminfo.timezone) and ( o16<o15)
v16 := o15-o16
if t1
v16:=0
var float v17 = 0
if IsLastBarSession(ses17,sessionTimeZone=syminfo.timezone) and ( o17>o16)
v17:=o17-o16
if IsLastBarSession(ses17,sessionTimeZone=syminfo.timezone) and ( o17<o16)
v17 := o16-o17
if t1
v17:=0
var float v18 = 0
if IsLastBarSession(ses18,sessionTimeZone=syminfo.timezone) and ( o18>o17)
v18:=o18-o17
if IsLastBarSession(ses18,sessionTimeZone=syminfo.timezone) and ( o18<o17)
v18 := o17-o18
if t1
v18:=0
var float v19 = 0
if IsLastBarSession(ses19,sessionTimeZone=syminfo.timezone) and ( o19>o18)
v19:=o19-o18
if IsLastBarSession(ses19,sessionTimeZone=syminfo.timezone) and ( o19<o18)
v19 := o18-o19
if t1
v19:=0
var float v20 = 0
if IsLastBarSession(ses20,sessionTimeZone=syminfo.timezone) and ( o20>o19)
v20:=o20-o19
if IsLastBarSession(ses20,sessionTimeZone=syminfo.timezone) and ( o20<o19)
v20 := o19-o20
if t1
v20:=0
var float v21 = 0
if IsLastBarSession(ses21,sessionTimeZone=syminfo.timezone) and ( o21>o20)
v21:=o21-o20
if IsLastBarSession(ses21,sessionTimeZone=syminfo.timezone) and ( o21<o20)
v21 := o20-o21
if t1
v21:=0
var float v22 = 0
if IsLastBarSession(ses22,sessionTimeZone=syminfo.timezone) and ( o22>o21)
v22:=o22-o21
if IsLastBarSession(ses22,sessionTimeZone=syminfo.timezone) and ( o22<o21)
v22 := o21-o22
if t1
v22:=0
var float v23 = 0
if IsLastBarSession(ses23,sessionTimeZone=syminfo.timezone) and ( o23>o22)
v23:=o23-o22
if IsLastBarSession(ses23,sessionTimeZone=syminfo.timezone) and ( o23<o22)
v23 := o22-o23
if t1
v23:=0
var float v24 = 0
if IsLastBarSession(ses24,sessionTimeZone=syminfo.timezone) and ( o24>o23)
v24:=o24-o23
if IsLastBarSession(ses24,sessionTimeZone=syminfo.timezone) and ( o24<o23)
v24 := o23-o24
if t1
v24:=0
var float v25 = 0
if IsLastBarSession(ses25,sessionTimeZone=syminfo.timezone) and ( o25>o24)
v25:=o25-o24
if IsLastBarSession(ses25,sessionTimeZone=syminfo.timezone) and ( o25<o24)
v25 := o24-o25
if t1
v25:=0
var float v26 = 0
if IsLastBarSession(ses26,sessionTimeZone=syminfo.timezone) and ( o26>o25)
v26:=o26-o25
if IsLastBarSession(ses26,sessionTimeZone=syminfo.timezone) and ( o26<o25)
v26 := o25-o26
if t1
v26:=0
var float v27 = 0
if IsLastBarSession(ses27,sessionTimeZone=syminfo.timezone) and ( o27>o26)
v27:=o27-o26
if IsLastBarSession(ses27,sessionTimeZone=syminfo.timezone) and ( o27<o26)
v27 := o26-o27
if t1
v27:=0
var float v28 = 0
if IsLastBarSession(ses28,sessionTimeZone=syminfo.timezone) and ( o28>o27)
v28:=o28-o27
if IsLastBarSession(ses28,sessionTimeZone=syminfo.timezone) and (o28<o27)
v28 := o27-o28
if t1
v28:=0
var float v29 = 0
if IsLastBarSession(ses29,sessionTimeZone=syminfo.timezone) and ( o29>o28)
v29:=o29-o28
if IsLastBarSession(ses29,sessionTimeZone=syminfo.timezone) and ( o29<o28)
v29 := o28-o29
if t1
v29:=0
var float v30 = 0
if IsLastBarSession(ses30,sessionTimeZone=syminfo.timezone) and ( o30>o29)
v30:=o30-o29
if IsLastBarSession(ses30,sessionTimeZone=syminfo.timezone) and ( o30<o29)
v30 := o29-o30
if t1
v30:=0
var float v31 = 0
if IsLastBarSession(ses31,sessionTimeZone=syminfo.timezone) and ( o31>o30)
v31:=o31-o30
if IsLastBarSession(ses31,sessionTimeZone=syminfo.timezone) and ( o31<o30)
v31 := o30-o31
if t1
v31:=0
var float v32 = 0
if IsLastBarSession(ses32,sessionTimeZone=syminfo.timezone) and ( o32>o31)
v32:=o32-o31
if IsLastBarSession(ses32,sessionTimeZone=syminfo.timezone) and ( o32<o31)
v32 := o31-o32
if t1
v32:=0
//Sum Increase/Decrease in Op-Cl
v1a=0
v2a=o2<o1?v2*-1:v2
v3a=o3<o2?v3*-1:v3
v4a=o4<o3?v4*-1:v4
v5a=o5<o4?v5*-1:v5
v6a=o6<o5?v6*-1:v6
v7a=o7<o6?v7*-1:v7
v8a=o8<o7?v8*-1:v8
v9a=o9<o8?v9*-1:v9
v10a=o10<o9?v10*-1:v10
v11a=o11<o10?v11*-1:v11
v12a=o12<o11?v12*-1:v12
v13a=o13<o12?v13*-1:v13
v14a=o14<o13?v14*-1:v14
v15a=o15<o14?v15*-1:v15
v16a=o16<o15?v16*-1:v16
v17a=o17<o16?v17*-1:v17
v18a=o18<o17?v18*-1:v18
v19a=o19<o18?v19*-1:v19
v20a=o20<o19?v20*-1:v20
v21a=o21<o20?v21*-1:v21
v22a=o22<o21?v22*-1:v22
v23a=o23<o22?v23*-1:v23
v24a=o24<o23?v24*-1:v24
v25a=o25<o24?v25*-1:v25
v26a=o26<o25?v26*-1:v26
v27a=o27<o26?v27*-1:v27
v28a=o28<o27?v28*-1:v28
Sumv=o1+v1a+v2a+v3a+v4a+v5a+v6a+v7a+v8a+v9a+v10a+v11a+v12a+v13a+v14a+v15a+v16a+v17a+v18a+v19a+v20a+v21a+v22a+v23a+v24a+v25a+v26a+v27a+v28a
Rocp=math.round_to_mintick(ta.roc(close,Lb))
MA20p=math.round_to_mintick(ta.sma(close,20))
MA50p=math.round_to_mintick(ta.sma(close,50))
Momp=math.round_to_mintick(ta.mom(close,L_mom))
Rsip=math.round_to_mintick(ta.mom(close,L_rsi))
Closep=math.round_to_mintick(close)
Buyvol= (high==low)? 0: volume*(close-low)/(high-low)
Sellvol = (high==low) ? 0: volume*(high-close)/(high-low)
Netvol= (Buyvol-Sellvol)
Buyvol_Intra=math.sum(Buyvol,Lb)
Sellvol_Intra=math.sum(Sellvol,Lb)
Netvol_Intra=Buyvol_Intra-Sellvol_Intra
//Calculations nof ROC,MA20,MA50,CLOSE,RSI,Op-CL
rr15=Multi=="ROC" ? math.round_to_mintick(ta.roc(close,Lb)):Multi=="MA20" ? math.round_to_mintick(ta.sma(close,20)):Multi=="RSI" ? math.round_to_mintick(ta.rsi(close,L_rsi)):
Multi=="CLOSE" ? math.round_to_mintick(close):Multi=="MOM" ? math.round_to_mintick(ta.mom(close,L_mom)):Multi=="MA50" ? math.round_to_mintick(ta.sma(close,50)):
Multi=="CL-OP" ? Sumv:Multi=="NetB" ? NetB:Multi=="NetV" ? math.round_to_mintick(Netvol_Intra/1000000):na
//Header Change
change=Multi=="ROC" ? "ROC":Multi=="RSI" ?"RSI":Multi=="MA20" ?"MA20":Multi=="CLOSE" ?"CLOSE":Multi=="MA50" ?"MA50":Multi=="MOM" ?"MOM":Multi=="CL-OP"?
"CL-OP":Multi=="NetB" ? "NetB":Multi=="NetV"?"NetV(M)":na
colmulti=Multi=="ROC" ?color.rgb(8, 100, 56):Multi=="RSI" ? color.rgb(86, 35, 95):Multi=="MA20" ? color.navy:Multi=="CLOSE" ? color.rgb(51, 86, 114):
Multi=="MOM" ? color.rgb(124, 71, 99): Multi=="MA50" ?color.rgb(49, 39, 94):Multi=="CL-OP"?color.rgb(124, 71, 99):Multi=="NetB"?color.navy:
Multi=="NetV"?color.navy: na
//Plots
plot(Sumv,title="Cl-OP ses wise Plot",color=Sumv>Sumv[1] ? color.green:color.red,display=not Table and Multi=="CL-OP" ? display.all:display.none)
plot(Rocp,title="ROC Plot",color=Rocp>0 ? color.green:color.red,display=not Table and Multi=="ROC"? display.all:display.none)
plot(MA20p,title="MA 20 Plot",color=color.orange,display=not Table and Multi=="MA20"? display.all:display.none)
plot(MA50p,title="MA50 Plot ",color=color.red,display=not Table and Multi=="MA50"? display.all:display.none)
plot(Momp,title="MOM plot",color=Momp>0 ? color.green:color.red,display=not Table and Multi=="MOM"? display.all:display.none)
plot(Rsip,title="RSI Plot",color=color.blue,display=not Table and Multi=="RSI"? display.all:display.none)
plot(Closep,title="ClosePlot",color=close>close[1]? color.green:color.red,display=not Table and Multi=="CLOSE"? display.all:display.none)
plot(math.round_to_mintick(Netvol_Intra/1000000),title="NetVol_Intra(M)", color=Netvol_Intra>0 ?color.green:color.red,display=not Table and Multi=="NetV"? display.all:display.none)
plot(NetB,title="Green Bars - Red Bars", color=Netvol_Intra>0 ?color.green:color.red,display=not Table and Multi=="NetB"? display.all:display.none)
//ROC,MA20,MA50,CLOSE,RSI
var float don1 = 0
if IsLastBarSession(ses1, sessionTimeZone=syminfo.timezone)
don1 :=math.round_to_mintick(rr15)
if t1
don1:=0
var float don2=0
if IsLastBarSession(ses2, sessionTimeZone=syminfo.timezone)
don2 := math.round_to_mintick(rr15)
if t1
don2:=0
var float don3 = 0
if IsLastBarSession(ses3, sessionTimeZone=syminfo.timezone)
don3 :=math.round_to_mintick(rr15)
if t1
don3:=0
var float don4 = 0
if IsLastBarSession(ses4, sessionTimeZone=syminfo.timezone)
don4 := math.round_to_mintick(rr15)
if t1
don4:=0
var float don5 = 0
if IsLastBarSession(ses5, sessionTimeZone=syminfo.timezone)
don5 := math.round_to_mintick(rr15)
if t1
don5:=0
var float don6 = 0
if IsLastBarSession(ses6, sessionTimeZone=syminfo.timezone)
don6 := math.round_to_mintick(rr15)
if t1
don6:=0
var float don7 = 0
if IsLastBarSession(ses7, sessionTimeZone=syminfo.timezone)
don7 :=math.round_to_mintick(rr15)
if t1
don7:=0
var float don8 = 0
if IsLastBarSession(ses8, sessionTimeZone=syminfo.timezone)
don8 := math.round_to_mintick(rr15)
if t1
don8:=0
var float don9 = 0
if IsLastBarSession(ses9, sessionTimeZone=syminfo.timezone)
don9 := math.round_to_mintick(rr15)
if t1
don9:=0
var float don10 = 0
if IsLastBarSession(ses10, sessionTimeZone=syminfo.timezone)
don10 := math.round_to_mintick(rr15)
if t1
don10:=0
var float don11 = 0
if IsLastBarSession(ses11, sessionTimeZone=syminfo.timezone)
don11 := math.round_to_mintick(rr15)
if t1
don11:=0
var float don12 = 0
if IsLastBarSession(ses12, sessionTimeZone=syminfo.timezone)
don12 := math.round_to_mintick(rr15)
if t1
don12:=0
var float don13 = 0
if IsLastBarSession(ses13, sessionTimeZone=syminfo.timezone)
don13 := math.round_to_mintick(rr15)
if t1
don13:=0
var float don14 = 0
if IsLastBarSession(ses14, sessionTimeZone=syminfo.timezone)
don14 := math.round_to_mintick(rr15)
if t1
don14:=0
var float don15 = 0
if IsLastBarSession(ses15, sessionTimeZone=syminfo.timezone)
don15 := math.round_to_mintick(rr15)
if t1
don15:=0
var float don16 = 0
if IsLastBarSession(ses16, sessionTimeZone=syminfo.timezone)
don16 := math.round_to_mintick(rr15)
if t1
don16:=0
var float don17 = 0
if IsLastBarSession(ses17, sessionTimeZone=syminfo.timezone)
don17 := math.round_to_mintick(rr15)
if t1
don17:=0
var float don18 = 0
if IsLastBarSession(ses18, sessionTimeZone=syminfo.timezone)
don18 := math.round_to_mintick(rr15)
if t1
don18:=0
var float don19 = 0
if IsLastBarSession(ses19, sessionTimeZone=syminfo.timezone)
don19 := math.round_to_mintick(rr15)
if t1
don19:=0
var float don20 = 0
if IsLastBarSession(ses20, sessionTimeZone=syminfo.timezone)
don20 := math.round_to_mintick(rr15)
if t1
don20:=0
var float don21 = 0
if IsLastBarSession(ses21, sessionTimeZone=syminfo.timezone)
don21 := math.round_to_mintick(rr15)
if t1
don21:=0
var float don22 = 0
if IsLastBarSession(ses22, sessionTimeZone=syminfo.timezone)
don22 := math.round_to_mintick(rr15)
if t1
don22:=0
var float don23 = 0
if IsLastBarSession(ses23, sessionTimeZone=syminfo.timezone)
don23 := math.round_to_mintick(rr15)
if t1
don23:=0
var float don24 = 0
if IsLastBarSession(ses24, sessionTimeZone=syminfo.timezone)
don24 := math.round_to_mintick(rr15)
if t1
don24:=0
var float don25 = 0
if IsLastBarSession(ses25, sessionTimeZone=syminfo.timezone)
don25 := math.round_to_mintick(rr15)
if t1
don25:=0
var float don26 = 0
if IsLastBarSession(ses26, sessionTimeZone=syminfo.timezone)
don26 := math.round_to_mintick(rr15)
if t1
don26:=0
var float don27 = 0
if IsLastBarSession(ses27, sessionTimeZone=syminfo.timezone)
don27 := math.round_to_mintick(rr15)
if t1
don27:=0
var float don28 = 0
if IsLastBarSession(ses28, sessionTimeZone=syminfo.timezone)
don28 := math.round_to_mintick(rr15)
if t1
don28:=0
var float don29 = 0
if IsLastBarSession(ses29, sessionTimeZone=syminfo.timezone)
don29 := math.round_to_mintick(rr15)
if t1
don29:=0
var float don30 = 0
if IsLastBarSession(ses30, sessionTimeZone=syminfo.timezone)
don30 := math.round_to_mintick(rr15)
if t1
don30:=0
var float don31 = 0
if IsLastBarSession(ses31, sessionTimeZone=syminfo.timezone)
don31 := math.round_to_mintick(rr15)
if t1
don31:=0
var float don32 = 0
if IsLastBarSession(ses32, sessionTimeZone=syminfo.timezone)
don32 := math.round_to_mintick(rr15)
if t1
don32:=0
//TABLE
BorderThickness = 1
TableWidth = 0
Tableheight=0
TableLocation = input.string("top_left", title='Select Table Position',options=["top_left","top_center","top_right",
"middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"] ,
tooltip="Default location is at top_ left")
//RoundingPrecision = input.int(title='Indicator Rounding Precision', defval=2, minval=0, maxval=5)
TableTextSize = input.string("Auto", title='Select Table Text Size',options=["Auto","Huge","Large","Normal","Small",
"Tiny"] , tooltip="Default Text Size is Auto")
celltextsize = switch TableTextSize
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
"Tiny" => size.tiny
TBGcol=input.color(defval=color.new(#ffffff,0),title="BG color")
cellcol=color.new(#ffffff,0)
cellcolin=input.color(defval=color.new(#e10043,20),title="headercolor")
cellcol1=color.new(#ffffff,0)
cellcol1in=input.color(defval=color.new(#e10043,20),title="column headercolor")
ctexcol=input.color(defval=color.new(#000000,0),title="column header textcolor")
var table t = table.new (position=TableLocation,columns=30,rows= 50, bgcolor=colmulti,frame_color=color.black,frame_width=2,
border_color=color.black,border_width=BorderThickness)
if barstate.islast
if Table
//Headers
table.cell(t, 1, 1,str.tostring(pr)+"\n"+"TIME" ,text_size=size.normal, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,
text_halign=text.align_left)
table.cell(t, 2, 1,str.tostring(prd)+"\n"+"(DATE)" ,text_size=size.small, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,
text_halign=text.align_left)
table.cell(t, 3, 1,str.tostring(prd1)+"\n"+"(DAY)" ,text_size=size.small, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,
text_halign=text.align_left)
table.cell(t, 4, 1,text_size=size.normal, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,text_halign=text.align_left)
table.cell(t, 5, 1,text_size=size.normal, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,text_halign=text.align_left)
table.cell(t, 6, 1,"SESSION" ,text_size=size.normal, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,text_halign=text.align_left)
table.cell(t, 7, 1,"WISE",text_size=size.normal, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,text_halign=text.align_left)
table.cell(t, 8, 1,"MOVEMENT",text_size=size.normal, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,text_halign=text.align_left)
table.cell(t, 9, 1,text_size=size.normal, width=TableWidth,height=Tableheight,text_color=ctexcol,bgcolor=cellcol,text_halign=text.align_left)
table.cell(t, 1, 2,"Session",text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=ctexcol)
table.cell(t, 2, 2,"CL-OP",text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=ctexcol)
table.cell(t, 3, 2,"CL-OP"+"\n"+ "Inc/Dec",text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=ctexcol)
table.cell(t, 4, 2,str.tostring(change),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=colmulti)
table.cell(t, 6,2,"Session",text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=ctexcol)
table.cell(t, 7,2,"CL-OP",text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=ctexcol)
table.cell(t, 8,2,"CL-OP"+"\n"+ "Inc/Dec",text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=ctexcol)
table.cell(t, 9,2,str.tostring(change),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=colmulti)
// //Session
table.cell(t, 1, 3, str.tostring(ses1),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 1, 4, str.tostring(ses2),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 1, 5, str.tostring(ses3),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 1, 6, str.tostring(ses4),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,text_color=color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 1, 7, str.tostring(ses5),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,text_color=color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 1, 8, str.tostring(ses6),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,text_color= color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 1, 9, str.tostring(ses7),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,text_color=color.blue, height=Tableheight,text_halign=text.align_right)
table.cell(t, 1, 10, str.tostring(ses8),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 1, 11, str.tostring(ses9),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 1, 12, str.tostring(ses10),text_size=celltextsize, width=TableWidth,bgcolor=cellcol, text_color=color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 1, 13, str.tostring(ses11),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue, height=Tableheight, text_halign=text.align_right)
table.cell(t, 1, 14, str.tostring(ses12),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue, height=Tableheight, text_halign=text.align_right)
table.cell(t, 1, 15, str.tostring(ses13),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue, height=Tableheight, text_halign=text.align_right)
table.cell(t, 1, 16, str.tostring(ses14),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 1, 17, str.tostring(ses15),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 1, 18, str.tostring(ses16),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 6, 3, str.tostring(ses17),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 6, 4, str.tostring(ses18),text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,bgcolor=cellcol,text_color=color.blue,
text_halign=text.align_right)
table.cell(t, 6, 5, str.tostring(ses19),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,bgcolor=cellcol,text_color=color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 6, 6, str.tostring(ses20),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,bgcolor=cellcol,text_color=color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 6, 7, str.tostring(ses21),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,bgcolor=cellcol,text_color= color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 6, 8, str.tostring(ses22),text_size=celltextsize, width=TableWidth,bgcolor=cellcol,bgcolor=cellcol,text_color=color.blue, height=Tableheight,text_halign=text.align_right)
table.cell(t, 6, 9, str.tostring(ses23),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,bgcolor=cellcol,text_color=color.blue,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 6, 10, str.tostring(ses24),text_size=celltextsize, width=TableWidth,bgcolor=cellcol, text_color=color.blue,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 6, 11, str.tostring(ses25),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue,height=Tableheight,text_halign=text.align_right)
table.cell(t, 6, 12, str.tostring(ses26),text_size=celltextsize, width=TableWidth,bgcolor=cellcol, text_color=color.blue, height=Tableheight, text_halign=text.align_right)
table.cell(t, 6, 13, str.tostring(ses27),text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue, height=Tableheight, text_halign=text.align_right)
table.cell(t, 6, 14, text_size=celltextsize, width=TableWidth, bgcolor=cellcol,text_color=color.blue, height=Tableheight, text_halign=text.align_right)
table.cell(t, 6, 15, text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue, text_halign=text.align_right)
table.cell(t, 6, 16, text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,text_halign=text.align_right)
table.cell(t, 6, 17, text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,text_halign=text.align_right)
table.cell(t, 6, 18, text_size=celltextsize, width=TableWidth,height=Tableheight,bgcolor=cellcol,text_color=color.blue,text_halign=text.align_right)
// Opcl
table.cell(t, 2, 3, str.tostring(o1),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o1>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 2, 4,str.tostring(o2) ,text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o2>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 2, 5, str.tostring(o3),text_size=celltextsize, width=TableWidth,text_color=o3>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 2, 6, str.tostring(o4),text_size=celltextsize, width=TableWidth,text_color=o4>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 2, 7, str.tostring(o5),text_size=celltextsize, width=TableWidth, text_color=o5>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 2, 8, str.tostring(o6),text_size=celltextsize, width=TableWidth,text_color=o6>0 ? color.green: color.red, height=Tableheight,text_halign=text.align_right)
table.cell(t, 2, 9, str.tostring(o7),text_size=celltextsize, width=TableWidth, text_color=o7>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 2, 10, str.tostring(o8),text_size=celltextsize, width=TableWidth, text_color=o8>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 2, 11, str.tostring(o9),text_size=celltextsize, width=TableWidth, text_color=o9>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 2, 12, str.tostring(o10),text_size=celltextsize, width=TableWidth, text_color=o10>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 2, 13, str.tostring(o11),text_size=celltextsize, width=TableWidth, text_color=o11>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 2, 14, str.tostring(o12),text_size=celltextsize, width=TableWidth, text_color=o12>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 2, 15, str.tostring(o13),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o13>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 2, 16, str.tostring(o14),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o14>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 2, 17, str.tostring(o15),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o15>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 2, 18,str.tostring(o16) ,text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o16>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 7, 3, str.tostring(o17 ),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o17>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 7, 4, str.tostring(o18 ),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o18>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 7, 5, str.tostring(o19),text_size=celltextsize, width=TableWidth,text_color=o19>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 7, 6, str.tostring(o20),text_size=celltextsize, width=TableWidth,text_color=o20>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 7, 7, str.tostring(o21),text_size=celltextsize, width=TableWidth, text_color=o21>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 7, 8, str.tostring(o22),text_size=celltextsize, width=TableWidth,text_color=o22>0 ? color.green: color.red, height=Tableheight,text_halign=text.align_right)
table.cell(t, 7, 9, str.tostring(o23 ),text_size=celltextsize, width=TableWidth, text_color=o23>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 7, 10, str.tostring(o24 ),text_size=celltextsize, width=TableWidth, text_color=o24>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 7, 11, str.tostring(o25 ),text_size=celltextsize, width=TableWidth, text_color=o25>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 7, 12, str.tostring(o26),text_size=celltextsize, width=TableWidth, text_color=o26>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 7, 13, str.tostring(o27),text_size=celltextsize, width=TableWidth, text_color=o27>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
//Increase/Decrease in Op-Cl
table.cell(t, 3, 3, str.tostring(v1),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=v1>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 3, 4, str.tostring(v2 ),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color= o2<o1 ? color.red: color.green,
text_halign=text.align_right)
table.cell(t, 3, 5, str.tostring(v3),text_size=celltextsize, width=TableWidth,text_color=o3<o2 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 3, 6, str.tostring(v4),text_size=celltextsize, width=TableWidth,text_color=o4<o3 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 3, 7, str.tostring(v5),text_size=celltextsize, width=TableWidth, text_color=o5<o4 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 3, 8, str.tostring(v6),text_size=celltextsize, width=TableWidth,text_color=o6<o5 ? color.red: color.green, height=Tableheight,text_halign=text.align_right)
table.cell(t, 3, 9, str.tostring(v7),text_size=celltextsize, width=TableWidth, text_color=o7<o6 ? color.red: color.green,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 3, 10, str.tostring(v8),text_size=celltextsize, width=TableWidth, text_color=o8<o7 ? color.red: color.green,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 3, 11, str.tostring(v9),text_size=celltextsize, width=TableWidth, text_color=o9<o8 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 3, 12, str.tostring(v10),text_size=celltextsize, width=TableWidth, text_color=o10<o9 ? color.red: color.green, height=Tableheight, text_halign=text.align_right)
table.cell(t, 3, 13, str.tostring(v11),text_size=celltextsize, width=TableWidth, text_color=o11<o10 ? color.red: color.green, height=Tableheight, text_halign=text.align_right)
table.cell(t, 3, 14, str.tostring(v12),text_size=celltextsize, width=TableWidth, text_color=o12<o11 ? color.red: color.green, height=Tableheight, text_halign=text.align_right)
table.cell(t, 3, 15, str.tostring(v13),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o13<o12 ? color.red: color.green,
text_halign=text.align_right)
table.cell(t, 3, 16, str.tostring(v14),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o14<o13 ? color.red: color.green,
text_halign=text.align_right)
table.cell(t, 3, 17, str.tostring(v15),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o15<o14 ? color.red: color.green,
text_halign=text.align_right)
table.cell(t, 3, 18, str.tostring(v16),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o16<o15 ? color.red: color.green,
text_halign=text.align_right)
table.cell(t, 8, 3, str.tostring(v17),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o17<o16 ? color.red: color.green,
text_halign=text.align_right)
table.cell(t, 8, 4, str.tostring(v18),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=o18<o17 ? color.red: color.green,
text_halign=text.align_right)
table.cell(t, 8, 5, str.tostring(v19),text_size=celltextsize, width=TableWidth,text_color=o19<o18 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 8, 6, str.tostring(v20),text_size=celltextsize, width=TableWidth,text_color=o20<o19 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 8, 7, str.tostring(v21),text_size=celltextsize, width=TableWidth, text_color=o21<o20 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 8, 8, str.tostring(v22),text_size=celltextsize, width=TableWidth,text_color=o22<o21 ? color.red: color.green, height=Tableheight,text_halign=text.align_right)
table.cell(t, 8, 9, str.tostring(v23),text_size=celltextsize, width=TableWidth, text_color=o23<o22 ? color.red: color.green,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 8, 10, str.tostring(v24),text_size=celltextsize, width=TableWidth, text_color=o24<o23 ? color.red: color.green,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 8, 11, str.tostring(v25),text_size=celltextsize, width=TableWidth, text_color=o25<o24 ? color.red: color.green,height=Tableheight,text_halign=text.align_right)
table.cell(t, 8, 12, str.tostring(v26),text_size=celltextsize, width=TableWidth, text_color=o26<o25 ? color.red: color.green, height=Tableheight, text_halign=text.align_right)
table.cell(t, 8, 13, str.tostring(v27),text_size=celltextsize, width=TableWidth, text_color=o27<o26 ? color.red: color.green, height=Tableheight, text_halign=text.align_right)
//ROC,MA20,MA50,CLOSE,RSI,Op-CL
table.cell(t, 4, 3, str.tostring(don1),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color= don1>0 ? color.green:color.red,text_halign=text.align_right)
table.cell(t, 4, 4, str.tostring(don2),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=don2>0 ?color.green:color.red, text_halign=text.align_right)
table.cell(t, 4, 5, str.tostring(don3),text_size=celltextsize, width=TableWidth,text_color=don3>0 ? color.green:color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 4, 6, str.tostring(don4),text_size=celltextsize, width=TableWidth,text_color= don4>0 ? color.green:color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 4, 7, str.tostring(don5),text_size=celltextsize, width=TableWidth, text_color=don5>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 4, 8, str.tostring(don6),text_size=celltextsize, width=TableWidth,text_color=don6>0 ? color.green: color.red, height=Tableheight,text_halign=text.align_right)
table.cell(t, 4, 9, str.tostring(don7),text_size=celltextsize, width=TableWidth, text_color=don7>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 4, 10, str.tostring(don8),text_size=celltextsize, width=TableWidth, text_color=don8>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 4, 11, str.tostring(don9),text_size=celltextsize, width=TableWidth, text_color=don9>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 4, 12, str.tostring(don10),text_size=celltextsize, width=TableWidth, text_color=don10>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 4, 13, str.tostring(don11),text_size=celltextsize, width=TableWidth, text_color=don11>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 4, 14, str.tostring(don12),text_size=celltextsize, width=TableWidth, text_color=don12>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 4, 15, str.tostring(don13),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=don13>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 4, 16, str.tostring(don14),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=don14>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 4, 17, str.tostring(don15),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=don15>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 4, 18, str.tostring(don16),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=don16>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 9, 3, str.tostring(don17),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=don17>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 9, 4, str.tostring(don18),text_size=celltextsize, width=TableWidth,height=Tableheight,text_color=don18>0 ? color.green: color.red,
text_halign=text.align_right)
table.cell(t, 9, 5, str.tostring(don19),text_size=celltextsize, width=TableWidth,text_color=don19>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 9, 6, str.tostring(don20),text_size=celltextsize, width=TableWidth,text_color=don20>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 9, 7, str.tostring(don21),text_size=celltextsize, width=TableWidth, text_color=don21>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 9, 8, str.tostring(don22),text_size=celltextsize, width=TableWidth,text_color=don22>0 ? color.green: color.red, height=Tableheight,text_halign=text.align_right)
table.cell(t, 9, 9, str.tostring(don23),text_size=celltextsize, width=TableWidth, text_color=don23>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 9, 10, str.tostring(don24),text_size=celltextsize, width=TableWidth, text_color=don24>0 ? color.green: color.red,height=Tableheight,
text_halign=text.align_right)
table.cell(t, 9, 11, str.tostring(don25),text_size=celltextsize, width=TableWidth, text_color=don25>0 ? color.green: color.red,height=Tableheight,text_halign=text.align_right)
table.cell(t, 9, 12, str.tostring(don26),text_size=celltextsize, width=TableWidth, text_color=don26>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
table.cell(t, 9, 13, str.tostring(don27),text_size=celltextsize, width=TableWidth, text_color=don27>0 ? color.green: color.red, height=Tableheight, text_halign=text.align_right)
|
Alxuse MACD for tutorial | https://www.tradingview.com/script/bMMWr2L4-Alxuse-MACD-for-tutorial/ | zarafshani20 | https://www.tradingview.com/u/zarafshani20/ | 25 | 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/
// © zarafshani20
//@version=5
indicator(title="Alxuse MACD for tutorial", timeframe = "")
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
upper_Band = input(title = "Upper Band", defval = 100)
lower_Band = input(title = "Lower Band", defval = -100)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
col_grow_above = input(#40af72, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#bdfacc, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#fac7cc, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#ca5b5b, "Fall", group="Histogram", inline="Below")
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
hline(0, "Middle Band", color=color.new(#787B86, 50))
hline(upper_Band, "Upper Band", color=color.new(#fc0202, 50))
hline(lower_Band, "Lower Band", color=color.new(#fc0202, 50))
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(macd, title="MACD", color=color.red)
plot(signal, title="Signal", color=color.green)
Buy_Macd = ta.crossover(macd, signal) ? signal : na
Sell_Macd = ta.crossunder(macd, signal) ? signal : na
Long_Macd = Buy_Macd and Buy_Macd <= lower_Band
Short_Macd = Sell_Macd and Sell_Macd >= upper_Band
plot(Buy_Macd, title="Buy", color=color.green, style=plot.style_circles, linewidth=4)
plot(Sell_Macd, title="Sell", color=color.red, style=plot.style_circles, linewidth=4)
plotchar(Long_Macd, 'Long', '△', location.bottom, color.new(color.lime, 0), size=size.tiny)
plotchar(Short_Macd, 'Short', '▽', location.top, color.new(color.red, 0), size=size.tiny)
alertcondition(Long_Macd, 'Circle Green and Lower Band (Long)', 'Long, Crossover MACD <= Lower Band (Triangles Green)')
alertcondition(Short_Macd, 'Circle Red and Upper Band (Short)', 'Short, Crossunder MACD >= Upper Band (Triangles Red)')
alertcondition(Buy_Macd, 'Circle Green(Buy)', 'Buy, Crossover MACD')
alertcondition(Sell_Macd, 'Circle Red (Sell)', 'Sell, Crossunder MACD')
|
Alxuse Stochastic RSI for tutorial | https://www.tradingview.com/script/orlYeJFy-Alxuse-Stochastic-RSI-for-tutorial/ | zarafshani20 | https://www.tradingview.com/u/zarafshani20/ | 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/
// © zarafshani20
//@version=5
indicator(title="Alxuse Stochastic RSI for tutorial ", timeframe="")
smoothK = input.int(3, "K", minval=1)
smoothD = input.int(3, "D", minval=1)
upper_Band = input(title = "Upper Band", defval = 95)
lower_Band = input(title = "Lower Band", defval = 5)
lengthRSI = input.int(14, "RSI Length", minval=1)
lengthStoch = input.int(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
plot(k, "K", color=color.red)
plot(d, "D", color=color.green)
h0 = hline(upper_Band, "Upper Band", color=color.new(#fc0202, 50))
hline(50, "Middle Band", color=color.new(#787B86, 50))
h1 = hline(lower_Band, "Lower Band", color=color.new(#fc0202, 50))
Buy_SRsi = ta.crossover(k, d) ? d : na
Sell_SRsi = ta.crossunder(k, d) ? d : na
plot(Buy_SRsi, title="Buy", color=color.green, style=plot.style_circles, linewidth=4)
plot(Sell_SRsi, title="Sell", color=color.red, style=plot.style_circles, linewidth=4)
Long_SRsi = Buy_SRsi and Buy_SRsi <= lower_Band
Short_SRsi = Sell_SRsi and Sell_SRsi >= upper_Band
plotchar(Long_SRsi, 'Long', '△', location.bottom, color.new(color.lime, 0), size=size.tiny)
plotchar(Short_SRsi, 'Short', '▽', location.top, color.new(color.red, 0), size=size.tiny)
alertcondition(Long_SRsi, 'Circle Green and Lower Band (Long)', 'Long, Crossover SRsi <= Lower Band')
alertcondition(Short_SRsi, 'Circle Red and Upper Band (Short)', 'Short, Crossunder >= Upper Band')
alertcondition(Buy_SRsi, 'Circle Green (Buy)', 'Buy, Crossover SRsi (Triangles Green)')
alertcondition(Sell_SRsi, 'Circle Red (Sell)', 'Sell, Crossunder SRsi (Triangles Red)') |
Fibonacci Trailing Stop [LuxAlgo] | https://www.tradingview.com/script/yOGnpadz-Fibonacci-Trailing-Stop-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,192 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("Fibonacci Trailing Stop [LuxAlgo]", "LuxAlgo - Fibonacci Trailing Stop", max_lines_count=500, max_labels_count=500, overlay=true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
L = input.int ( 20 , 'L' , group= 'swings' , minval= 1 )
R = input.int ( 1 , 'R' , group= 'swings' , minval= 1 )
lb= input.bool ( false , ' Swings labels', group= 'swings' )
F = input.float ( -0.382 , 'Level ' , inline='_', group='Fibonacci Trailing Stop', options= [-0.5, -0.382, -0.236 , 0, 0.236, 0.382, 0.5, 0.618] )
i = input.bool ( false , '' , inline='_', group='Fibonacci Trailing Stop' )
f = input.float ( 1.618 , '' , inline='_', group='Fibonacci Trailing Stop', step = 0.001 )
c = input.string( 'close' , 'Trigger' , group='Fibonacci Trailing Stop', options= ['close', 'wick'] )
cU= input.color ( #089981 , ' ' , inline='c', group='Fibonacci Trailing Stop' )
cD= input.color ( #f23645 , '' , inline='c', group='Fibonacci Trailing Stop' )
sF= input.bool ( true , ' Latest Fibonacci', group= 'Fibonacci' )
F0= input.color (#08998164 , ' ' , inline='f', group= 'Fibonacci' )
Fm= input.color (#1e42b070 , '' , inline='f', group= 'Fibonacci' )
F1= input.color (#f2364564 , '' , inline='f', group= 'Fibonacci' )
fl= input.bool ( true , ' Shadows' )
Ls= math.max(1, math.ceil(L / 2))
Rs= math.max(1, math.ceil(R / 2))
n = bar_index
iF=i ? f : F
//-----------------------------------------------------------------------------}
//User Defined Types
//-----------------------------------------------------------------------------{
type piv
int b
float p
int d
label l
type fib
linefill lf_0
linefill lfMd
linefill lf_1
line ln_0_5
line diagon
//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
var int dir = 0
var float st = close
var float max = high
var float min = low
var float dif = na
var float other_side = na
var piv[] pivs = array.new<piv>()
var fib fib = fib.new(
lf_0 = linefill.new(
line .new(na, na, na, na, color=sF ? F0 : color.new(color.blue, 100))
, line .new(na, na, na, na, color=sF ? F0 : color.new(color.blue, 100))
, color .new(F0 , fl ? 100: 85)
),
lfMd = linefill.new(
line .new(na, na, na, na, color=sF ? Fm : color.new(color.blue, 100))
, line .new(na, na, na, na, color=sF ? Fm : color.new(color.blue, 100))
, color .new(Fm , fl ? 100: 85)
),
lf_1 = linefill.new(
line .new(na, na, na, na, color=sF ? F1 : color.new(color.blue, 100))
, line .new(na, na, na, na, color=sF ? F1 : color.new(color.blue, 100))
, color .new(F1 , fl ? 100: 85)
),
ln_0_5 = line.new(na, na, na, na, color=sF ? color.blue : color.new(color.blue, 100)),
diagon = line.new(na, na, na, na, color=sF ? color.silver : color.new(color.blue, 100)
, style= line.style_dashed ))
var line_0 = line.new(na, na, na, na)
var line_1 = line.new(na, na, na, na)
//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
flab(i, x, y) => label.new(x, y, style=i == 1 ? label.style_label_down : label.style_label_up, color=color.gray)
//-----------------------------------------------------------------------------}
//Execution
//-----------------------------------------------------------------------------{
ph = ta.pivothigh(L , R )
pl = ta.pivotlow (L , R )
ph_= ta.pivothigh(Ls, Rs) // used for fill ~ ST
pl_= ta.pivotlow (Ls, Rs) // used for fill ~ ST
if ph
if pivs.size() > 0
get = pivs.first()
if get.d > 0 and ph > get.p
get.b := n -R
get.p := high[R]
get.l.set_xy(n -R, high[R])
if get.d < 0 and ph > get.p
pivs.unshift(piv.new(n -R, high[R] , 1, lb ? flab( 1, n -R, high[R]) : na))
else
pivs .unshift(piv.new(n -R, high[R] , 1, lb ? flab( 1, n -R, high[R]) : na))
if pl
if pivs.size() > 0
get = pivs.first()
if get.d < 0 and pl < get.p
get.b := n -R
get.p := low [R]
get.l.set_xy(n -R, low [R])
if get.d > 0 and pl < get.p
pivs.unshift(piv.new(n -R, low [R] ,-1, lb ? flab(-1, n -R, low [R]) : na))
else
pivs .unshift(piv.new(n -R, low [R] ,-1, lb ? flab(-1, n -R, low [R]) : na))
if pivs.size() >= 2
max := math.max(pivs.first().p, pivs.get(1).p)
min := math.min(pivs.first().p, pivs.get(1).p)
if pivs.size() == 2
st := math.avg(max, min)
other_side := math.avg(max, min)
dif := max - min
max += dif * iF
min -= dif * iF
_0i = pivs.first( ).b, _0p = pivs.first( ).p
_1i = pivs.get (1).b, _1p = pivs.get (1).p
d = _0p < _1p ? -dif : dif
l0_1 = fib. lf_0.get_line1(), l0_2 = fib. lf_0.get_line2()
lMd1 = fib. lfMd.get_line1(), lMd2 = fib. lfMd.get_line2()
l1_1 = fib. lf_1.get_line1(), l1_2 = fib. lf_1.get_line2()
if (ph or pl) and (sF or fl)
l0_1 .set_xy1(_0i, _0p ), l0_1 .set_xy2( n + 3 , _0p )
l0_2 .set_xy1(_0i, _0p - (d * 0.236)), l0_2 .set_xy2( n + 3 , _0p - (d * 0.236))
lMd1 .set_xy1(_0i, _0p - (d * 0.382)), lMd1 .set_xy2( n + 3 , _0p - (d * 0.382))
lMd2 .set_xy1(_0i, _0p - (d * 0.618)), lMd2 .set_xy2( n + 3 , _0p - (d * 0.618))
l1_1 .set_xy1(_0i, _0p - (d * 0.786)), l1_1 .set_xy2( n + 3 , _0p - (d * 0.786))
l1_2 .set_xy1(_0i, _1p ), l1_2 .set_xy2( n + 3 , _1p )
fib.ln_0_5.set_xy1(_0i, _0p - (d * 0.5 )), fib.ln_0_5.set_xy2( n + 3 , _0p - (d * 0.5 ))
fib.diagon.set_xy1(_0i, _0p ), fib.diagon.set_xy2(_1i , _1p )
else
l0_1 .set_x2 ( n + 3 )
l0_2 .set_x2 ( n + 3 )
lMd1 .set_x2 ( n + 3 )
lMd2 .set_x2 ( n + 3 )
l1_1 .set_x2 ( n + 3 )
l1_2 .set_x2 ( n + 3 )
fib.ln_0_5.set_x2 ( n + 3 )
price = c == 'close' ? close : dir < 1 ? high : low
if dir < 1
if price > st
st := min
dir := 1
else
st := math.min(st, max)
if dir > -1
if price < st
st := max
dir := -1
else
st := math.max(st, min)
col = dir < 1 ? cD : cU
other_side := switch
dir < 1 and ph_ => math.min(other_side, ph_, st)
dir < 1 => math.min(other_side , st)
dir > -1 and pl_ => math.max(other_side, pl_, st)
dir > -1 => math.max(other_side , st)
=> other_side
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot0 = fib.lf_0.get_line1().get_y2()
plot_236 = fib.lf_0.get_line2().get_y2()
plot_382 = fib.lfMd.get_line1().get_y2()
plot_500 = fib.ln_0_5 .get_y2()
plot_618 = fib.lfMd.get_line2().get_y2()
plot_786 = fib.lf_1.get_line1().get_y2()
plot1 = fib.lf_1.get_line2().get_y2()
ch = ta.change(plot0) or ta.change(plot1) // when lines change
p1 = plot(not ch ? plot0 : na, color=color.new(color.blue, 100), style=plot.style_circles, display=display.none)
p2 = plot(not ch ? plot_236 : na, color=color.new(color.blue, 100), style=plot.style_circles, display=display.none)
p3 = plot(not ch ? plot_382 : na, color=color.new(color.blue, 100), style=plot.style_circles, display=display.none)
p4 = plot(not ch ? plot_618 : na, color=color.new(color.blue, 100), style=plot.style_circles, display=display.none)
p5 = plot(not ch ? plot_786 : na, color=color.new(color.blue, 100), style=plot.style_circles, display=display.none)
p6 = plot(not ch ? plot1 : na, color=color.new(color.blue, 100), style=plot.style_circles, display=display.none)
fill(p1, p2, ch or not fl ? na : math.avg(plot0, plot_236), plot_236, color.new(chart.bg_color, 100), F0)
fill(p3, p4, ch or not fl ? na : plot_382 , plot_500, Fm, color.new(chart.bg_color, 100) )
fill(p3, p4, ch or not fl ? na : plot_500 , plot_618, color.new(chart.bg_color, 100), Fm)
fill(p5, p6, ch or not fl ? na : math.avg(plot1, plot_786), plot_786, color.new(chart.bg_color, 100), F1)
s = plot( st , 'Fib Trailing Stop', color= col , display=display.pane + display.data_window)
o = plot(fl ? na : other_side, 'other side' , color=color.new(col , 75), display=display.pane + display.data_window)
fill ( o , s , color=color.new(col, 90))
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
alertcondition(ta.change(dir) and dir == 1, 'Uptrend' , 'Uptrend' )
alertcondition(ta.change(dir) and dir == -1, 'Downtrend' , 'Downtrend' )
alertcondition(ta.change(dir) , 'Trend change', 'Trend change')
//-----------------------------------------------------------------------------} |
Kviatek - Multi Hour VWAP | https://www.tradingview.com/script/B9bTJSVQ-Kviatek-Multi-Hour-VWAP/ | hundredtoamillion | https://www.tradingview.com/u/hundredtoamillion/ | 73 | 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/
// © hundredtoamillion
//@version=5
indicator('Kviatek - Multi Hour VWAP', overlay=true, max_boxes_count = 500)
resolution1 = input.timeframe("D", "VWAP resolution")
source = input.source(ohlc4, "VWAP source")
session1 = input.session(defval = "0000-0000", title = "VWAP 1 Anchor")
session2 = input.session(defval = "0100-0000", title = "VWAP 2 Anchor")
session3 = input.session(defval = "0200-0000", title = "VWAP 3 Anchor")
session4 = input.session(defval = "0300-0000", title = "VWAP 4 Anchor")
session5 = input.session(defval = "0400-0000", title = "VWAP 4 Anchor")
session6 = input.session(defval = "0500-0000", title = "VWAP 4 Anchor")
session7 = input.session(defval = "0600-0000", title = "VWAP 4 Anchor")
session8 = input.session(defval = "0700-0000", title = "VWAP 4 Anchor")
session9 = input.session(defval = "0800-0000", title = "VWAP 4 Anchor")
session10 = input.session(defval = "0900-0000", title = "VWAP 4 Anchor")
session11 = input.session(defval = "1000-0000", title = "VWAP 4 Anchor")
session12 = input.session(defval = "1100-0000", title = "VWAP 4 Anchor")
session13 = input.session(defval = "1200-0000", title = "VWAP 4 Anchor")
session14 = input.session(defval = "1300-0000", title = "VWAP 4 Anchor")
session15 = input.session(defval = "1400-0000", title = "VWAP 4 Anchor")
session16 = input.session(defval = "1500-0000", title = "VWAP 4 Anchor")
session17 = input.session(defval = "1600-0000", title = "VWAP 4 Anchor")
session18 = input.session(defval = "1700-0000", title = "VWAP 4 Anchor")
session19 = input.session(defval = "1800-0000", title = "VWAP 4 Anchor")
session20 = input.session(defval = "1900-0000", title = "VWAP 4 Anchor")
session21 = input.session(defval = "2000-0000", title = "VWAP 4 Anchor")
session22 = input.session(defval = "2100-0000", title = "VWAP 4 Anchor")
session23 = input.session(defval = "2200-0000", title = "VWAP 4 Anchor")
session24 = input.session(defval = "2300-0000", title = "VWAP 4 Anchor")
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
H1 = time(resolution1, session1)
H2 = time(resolution1, session2)
H3 = time(resolution1, session3)
H4 = time(resolution1, session4)
H5 = time(resolution1, session5)
H6 = time(resolution1, session6)
H7 = time(resolution1, session7)
H8 = time(resolution1, session8)
H9 = time(resolution1, session9)
H10 = time(resolution1, session10)
H11 = time(resolution1, session11)
H12 = time(resolution1, session12)
H13 = time(resolution1, session13)
H14 = time(resolution1, session14)
H15 = time(resolution1, session15)
H16 = time(resolution1, session16)
H17 = time(resolution1, session17)
H18 = time(resolution1, session18)
H19 = time(resolution1, session19)
H20 = time(resolution1, session20)
H21 = time(resolution1, session21)
H22 = time(resolution1, session22)
H23 = time(resolution1, session23)
H24 = time(resolution1, session24)
open_bar(t) => na(t[1]) and not na(t) or t[1] < t ? 1 : 0
tf_switch1 = ta.change(open_bar(H1)) > 0
tf_switch2 = ta.change(open_bar(H2)) > 0
tf_switch3 = ta.change(open_bar(H3)) > 0
tf_switch4 = ta.change(open_bar(H4)) > 0
tf_switch5 = ta.change(open_bar(H5)) > 0
tf_switch6 = ta.change(open_bar(H6)) > 0
tf_switch7 = ta.change(open_bar(H7)) > 0
tf_switch8 = ta.change(open_bar(H8)) > 0
tf_switch9 = ta.change(open_bar(H9)) > 0
tf_switch10 = ta.change(open_bar(H10)) > 0
tf_switch11 = ta.change(open_bar(H11)) > 0
tf_switch12 = ta.change(open_bar(H12)) > 0
tf_switch13 = ta.change(open_bar(H13)) > 0
tf_switch14 = ta.change(open_bar(H14)) > 0
tf_switch15 = ta.change(open_bar(H15)) > 0
tf_switch16 = ta.change(open_bar(H16)) > 0
tf_switch17 = ta.change(open_bar(H17)) > 0
tf_switch18 = ta.change(open_bar(H18)) > 0
tf_switch19 = ta.change(open_bar(H19)) > 0
tf_switch20 = ta.change(open_bar(H20)) > 0
tf_switch21 = ta.change(open_bar(H21)) > 0
tf_switch22 = ta.change(open_bar(H22)) > 0
tf_switch23 = ta.change(open_bar(H23)) > 0
tf_switch24 = ta.change(open_bar(H24)) > 0
vwap1 = ta.vwap(source, tf_switch1)
vwap2 = ta.vwap(source, tf_switch2)
vwap3 = ta.vwap(source, tf_switch3)
vwap4 = ta.vwap(source, tf_switch4)
vwap5 = ta.vwap(source, tf_switch5)
vwap6 = ta.vwap(source, tf_switch6)
vwap7 = ta.vwap(source, tf_switch7)
vwap8 = ta.vwap(source, tf_switch8)
vwap9 = ta.vwap(source, tf_switch9)
vwap10 = ta.vwap(source, tf_switch10)
vwap11 = ta.vwap(source, tf_switch11)
vwap12 = ta.vwap(source, tf_switch12)
vwap13 = ta.vwap(source, tf_switch13)
vwap14 = ta.vwap(source, tf_switch14)
vwap15 = ta.vwap(source, tf_switch15)
vwap16 = ta.vwap(source, tf_switch16)
vwap17 = ta.vwap(source, tf_switch17)
vwap18 = ta.vwap(source, tf_switch18)
vwap19 = ta.vwap(source, tf_switch19)
vwap20 = ta.vwap(source, tf_switch20)
vwap21 = ta.vwap(source, tf_switch21)
vwap22 = ta.vwap(source, tf_switch22)
vwap23 = ta.vwap(source, tf_switch23)
vwap24 = ta.vwap(source, tf_switch24)
color1 = close > vwap1 ? color.green : color.red
color2 = close > vwap2 ? color.green : color.red
color3 = close > vwap3 ? color.green : color.red
color4 = close > vwap4 ? color.green : color.red
color5 = close > vwap5 ? color.green : color.red
color6 = close > vwap6 ? color.green : color.red
color7 = close > vwap7 ? color.green : color.red
color8 = close > vwap8 ? color.green : color.red
color9 = close > vwap9 ? color.green : color.red
color10 = close > vwap10 ? color.green : color.red
color11 = close > vwap11 ? color.green : color.red
color12 = close > vwap12 ? color.green : color.red
color13 = close > vwap13 ? color.green : color.red
color14 = close > vwap14 ? color.green : color.red
color15 = close > vwap15 ? color.green : color.red
color16 = close > vwap16 ? color.green : color.red
color17 = close > vwap17 ? color.green : color.red
color18 = close > vwap18 ? color.green : color.red
color19 = close > vwap19 ? color.green : color.red
color20 = close > vwap20 ? color.green : color.red
color21 = close > vwap21 ? color.green : color.red
color22 = close > vwap22 ? color.green : color.red
color23 = close > vwap23 ? color.green : color.red
color24 = close > vwap24 ? color.green : color.red
plot(vwap1, color = tf_switch1 ? na :color1, linewidth = 1)
plot(vwap2, color = tf_switch2 ? na :color2, linewidth = 1)
plot(vwap3, color = tf_switch3 ? na :color3, linewidth = 1)
plot(vwap4, color = tf_switch4 ? na :color4, linewidth = 1)
plot(vwap5, color = tf_switch5 ? na :color5, linewidth = 1)
plot(vwap6, color = tf_switch6 ? na :color6, linewidth = 1)
plot(vwap7, color = tf_switch7 ? na :color7, linewidth = 1)
plot(vwap8, color = tf_switch8 ? na :color8, linewidth = 1)
plot(vwap9, color = tf_switch9 ? na :color9, linewidth = 1)
plot(vwap10, color = tf_switch10 ? na :color10, linewidth = 1)
plot(vwap11, color = tf_switch11 ? na :color11, linewidth = 1)
plot(vwap12, color = tf_switch12 ? na :color12, linewidth = 1)
plot(vwap13, color = tf_switch13 ? na :color13, linewidth = 1)
plot(vwap14, color = tf_switch14 ? na :color14, linewidth = 1)
plot(vwap15, color = tf_switch15 ? na :color15, linewidth = 1)
plot(vwap16, color = tf_switch16 ? na :color16, linewidth = 1)
plot(vwap17, color = tf_switch17 ? na :color17, linewidth = 1)
plot(vwap18, color = tf_switch18 ? na :color18, linewidth = 1)
plot(vwap19, color = tf_switch19 ? na :color19, linewidth = 1)
plot(vwap20, color = tf_switch20 ? na :color20, linewidth = 1)
plot(vwap21, color = tf_switch21 ? na :color21, linewidth = 1)
plot(vwap22, color = tf_switch22 ? na :color22, linewidth = 1)
plot(vwap23, color = tf_switch23 ? na :color23, linewidth = 1)
plot(vwap24, color = tf_switch24 ? na :color24, linewidth = 1) |
Search for consolidations - AstroHub | https://www.tradingview.com/script/RWibEU8M-search-for-consolidations-astrohub/ | AstroHub | https://www.tradingview.com/u/AstroHub/ | 34 | 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/
// © AstroHub
//@version=5
indicator("Search for consolidations", overlay=true)
// Входные параметры
consol_length = input(20, "consolidation")
// Математическая модель для поиска консолидаций
isConsolidation(high, low, length) =>
range1 = high - low
avg_range = ta.sma(range1, length)
consolidation = ta.sma(ta.rma(avg_range, length), length)
range1 < consolidation
// Расчет результатов
consolidation = isConsolidation(high, low, consol_length)
// Отображение на графике
plotshape(consolidation, "Консолидация", color=color.blue, style=shape.labelup, location=location.belowbar)
|
Alxuse Supertrend 4EMA Buy and Sell for tutorial | https://www.tradingview.com/script/TpC5acre-Alxuse-Supertrend-4EMA-Buy-and-Sell-for-tutorial/ | zarafshani20 | https://www.tradingview.com/u/zarafshani20/ | 46 | 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/
// © zarafshani20
//@version=5
indicator('Alxuse Supertrend 4EMA Buy and Sell for tutorial', overlay=true, timeframe = "")
MAprice = input(close)
MAL1 = input.int(20, step=1, title='EMA 1')
MAL2 = input.int(50, step=1, title='EMA 2')
MAL3 = input.int(100, step=1, title='EMA 3')
MAL4 = input.int(200, step=1, title='EMA 4')
switchema = input(true, title='SEMA??')
MA1 = ta.ema(MAprice, MAL1)
MA2 = ta.ema(MAprice, MAL2)
MA3 = ta.ema(MAprice, MAL3)
MA4 = ta.ema(MAprice, MAL4)
change_1 = ta.change(MA1)
MA1_col = ta.change(MA1) > 0 ? #ffed4b : change_1 < 0 ? #ffed4b83 : #ffed4b
change_2 = ta.change(MA2)
MA2_col = ta.change(MA2) > 0 ? #f32121 : change_2 < 0 ? #f321218a : #f32121
change_3 = ta.change(MA3)
MA3_col = ta.change(MA3) > 0 ? #1c3dfd : change_3 < 0 ? #1c3efd8a : #1c3dfd
change_4 = ta.change(MA4)
MA4_col = ta.change(MA4) > 0 ? #3aff20 : change_4 < 0 ? #3aff208c : #3aff20
EMA1 = plot(switchema ? MA1 : na, title='EMA 1', style=plot.style_linebr, linewidth=1, color=MA1_col)
EMA2 = plot(switchema ? MA2 : na, title='EMA 2', style=plot.style_linebr, linewidth=1, color=MA2_col)
EMA3 = plot(switchema ? MA3 : na, title='EMA 3', style=plot.style_linebr, linewidth=1, color=MA3_col)
EMA4 = plot(switchema ? MA4 : na, title='EMA 4', style=plot.style_linebr, linewidth=1, color=MA4_col)
Sourcebs = input(close, 'Buy&Sell Source Type')
FAP = input(5, 'Buy&Sell Fap')
FAM = input(0.5, 'Buy&Sell Fam')
FAPFAM = FAM * ta.atr(FAP)
Trailing = 0.0
iff_11 = Sourcebs > nz(Trailing[1], 0) ? Sourcebs - FAPFAM : Sourcebs + FAPFAM
iff_2 = Sourcebs < nz(Trailing[1], 0) and Sourcebs[1] < nz(Trailing[1], 0) ? math.min(nz(Trailing[1], 0), Sourcebs + FAPFAM) : iff_11
Trailing := Sourcebs > nz(Trailing[1], 0) and Sourcebs[1] > nz(Trailing[1], 0) ? math.max(nz(Trailing[1], 0), Sourcebs - FAPFAM) : iff_2
SAP = input(21, 'Buy&Sell Sap')
SAM = input.float(7, 'Buy&Sell Sam')
SAPSAM = SAM * ta.atr(SAP)
Trailing1 = 0.0
iff_3 = Sourcebs > nz(Trailing1[1], 0) ? Sourcebs - SAPSAM : Sourcebs + SAPSAM
iff_4 = Sourcebs < nz(Trailing1[1], 0) and Sourcebs[1] < nz(Trailing1[1], 0) ? math.min(nz(Trailing1[1], 0), Sourcebs + SAPSAM) : iff_3
Trailing1 := Sourcebs > nz(Trailing1[1], 0) and Sourcebs[1] > nz(Trailing1[1], 0) ? math.max(nz(Trailing1[1], 0), Sourcebs - SAPSAM) : iff_4
Buy = ta.crossover(Trailing, Trailing1)
Sell = ta.crossunder(Trailing, Trailing1)
plotshape(Buy, 'BUY', shape.labelup, location.belowbar, color.new(color.green, 0), text='BUY', textcolor=color.new(color.black, 0))
plotshape(Sell, 'SELL', shape.labeldown, location.abovebar, color.new(color.red, 0), text='SELL', textcolor=color.new(color.black, 0))
alertcondition(Buy, 'Buy Superrend Signal', 'Buy Signal')
alertcondition(Sell, 'Sell Superrend Signal', 'Sell Signal')
//x = ta.crossover(MA2, MA3) and MA1 < MA4
x1 = MA1 < MA2 and MA2 < MA3 and MA3 < MA4 and ta.crossunder(MA3, MA4)
x2 = MA1 < MA2 and MA2 < MA3 and MA3 < MA4 and ta.crossunder(MA2, MA3)
x3 = MA1 < MA2 and MA2 < MA3 and MA3 < MA4 and ta.crossunder(MA1, MA2)
y1 = MA4 < MA3 and MA3 < MA2 and MA2 < MA1 and ta.crossover(MA3, MA4)
y2 = MA4 < MA3 and MA3 < MA2 and MA2 < MA1 and ta.crossover(MA2, MA3)
y3 = MA4 < MA3 and MA3 < MA2 and MA2 < MA1 and ta.crossover(MA1, MA2)
plotshape(x1, title="X1", color=color.red, location=location.abovebar , style = shape.triangledown, size = size.small)
plotshape(x2, title="X12", color=color.red, location=location.abovebar , style = shape.triangledown, size = size.small)
plotshape(x3, title="X3", color=color.red, location=location.abovebar , style = shape.triangledown, size = size.small)
plotshape(y1, title="y1", color=color.green, location=location.belowbar , style = shape.triangleup, size = size.small)
plotshape(y2, title="y2", color=color.green, location=location.belowbar , style = shape.triangleup, size = size.small)
plotshape(y3, title="y3", color=color.green, location=location.belowbar , style = shape.triangleup, size = size.small)
alertcondition(x1 or x2 or x3, 'Sell 4EMA Signal', 'Sell Signal 4EMA (Red Triangle)')
alertcondition(y1 or y2 or y3, 'Buy 4EMA Signal', 'Buy Signal 4EMA (Green Triangle)') |
Ruth Buy/Sell Signal for Day Trade and Swing Trade | https://www.tradingview.com/script/hHnrUDk8-Ruth-Buy-Sell-Signal-for-Day-Trade-and-Swing-Trade/ | akselanil | https://www.tradingview.com/u/akselanil/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Bu kaynak kod Ref Kafe İşletmeciliği Mimarlık ve Yazılım LTD. ŞTİ.'nin mülküdür. izinsiz kopyalamalarda cezai şartlar uygulanacaktır.
// © akselanil
//@version=5
indicator( title = "Ruthito, Free version Ruthito's Buy/Sell Signal for Day Trade and Swing Trade", shorttitle = "Ref_Ruth", overlay = true, format = format.price, precision = 2 )
import TradingView/ta/5
// ---> VARIABLES
var shortPos = 0, var shortPosTP2 = 0, var shortPosTP3 = 0, var shortPosTP4 = 0, var shortPosTP5 = 0
var shortPosStop = false, var shortPosTakeProfit1 = false, var shortPosTakeProfit2 = false, var shortPosTakeProfit3 = false, var shortPosTakeProfit4 = false, var shortPosTakeProfit5 = false
var shortSL = 0.0, var shortEP = 0.0, var shortTP1 = 0.0, var shortTP2 = 0.0, var shortTP3 = 0.0, var shortTP4 = 0.0, var shortTP5 = 0.0
var longPos = 0, var longPosTP2 = 0, var longPosTP3 = 0, var longPosTP4 = 0, var longPosTP5 = 0
var longPosStop = false, var longPosTakeProfit1 = false, var longPosTakeProfit2 = false, var longPosTakeProfit3 = false, var longPosTakeProfit4 = false, var longPosTakeProfit5 = false
var longSL = 0.0, var longEP = 0.0, var longTP1 = 0.0, var longTP2 = 0.0, var longTP3 = 0.0, var longTP4 = 0.0, var longTP5 = 0.0
date = time >= timestamp( syminfo.timezone, 2023, 1, 1, 0, 0 )
var longAlpEP = 0, var longAlpSL = 0, var longAlpTP1 = 0, var longAlpTP2 = 0, var longAlpTP3 = 0, var longAlpTP4 = 0, var longAlpTP5 = 0, var longIndex = 0
var longTP1Ln = 0, var longTP2Ln = 0, var longTP3Ln = 0, var longTP4Ln = 0, var longTP5Ln = 0, var longSLLn = 0
var longBGtp1TR = 100, var longBGtp2TR = 0, var longBGtp3TR = 0, var longBGtp4TR = 0, var longBGtp5TR = 0, var longBGslTR = 0
var shortAlpEP = 0, var shortAlpSL = 0, var shortAlpTP1 = 0, var shortAlpTP2 = 0, var shortAlpTP3 = 0, var shortAlpTP4 = 0, var shortAlpTP5 = 0, var shortIndex = 0
var shortTP1Ln = 0, var shortTP2Ln = 0, var shortTP3Ln = 0, var shortTP4Ln = 0, var shortTP5Ln = 0, var shortSLLn = 0
var shortBGtp1TR = 100, var shortBGtp2TR = 0, var shortBGtp3TR = 0, var shortBGtp4TR = 0, var shortBGtp5TR = 0, var shortBGslTR = 0
// <--- VARIABLES
// ---> TA
[ kc1Median, kc1Upper, kc1Lower ] = ta.kc( series = close, length = 20, mult = 1 )
[ kc2Median, kc2Upper, kc2Lower ] = ta.kc( series = close, length = 20, mult = 2 )
[ kc3Median, kc3Upper, kc3Lower ] = ta.kc( series = close, length = 20, mult = 3 )
[ kc4Median, kc4Upper, kc4Lower ] = ta.kc( series = close, length = 20, mult = 4 )
[ kc5Median, kc5Upper, kc5Lower ] = ta.kc( series = close, length = 20, mult = 5 )
cci = ta.cci( source = close, length = 20 )
roc = ta.roc( source = close, length = 9 )
rsi = ta.rsi( source = close, length = 14 )
sar = ta.sar( start = 0.02, inc = 0.02, max = 0.2 )
bop = ( close - open ) / ( high - low )
dema = ta.dema( src = close, length = 200 )
// <--- TA
// ---> LONG STRATEGY
upCondtion1 = ta.crossunder( low, kc3Lower )
upCondtion2 = ta.crossunder( cci, -95.0 )
upCondtion3 = -0.1 < roc and roc > -0.2
upCondtion4 = ta.crossunder( bop, -0.9 )
upCondtion5 = ta.crossunder( 18, rsi )
upCondtion6 = kc1Median < sar
upCondtion7 = ohlc4 < kc1Median
longSignal = upCondtion1 and upCondtion2 and upCondtion3 and upCondtion4 and upCondtion6 and upCondtion7
if longSignal
longLbl = label.new( x = bar_index, y = kc5Lower, text = "Long Signal\n\nTP1: " + str.tostring( kc1Lower, "#.##" ) + "\nTP2: " + str.tostring( kc1Median, "#.##" ) + "\nTP3: " + str.tostring( kc1Upper, "#.##" ) + "\nTP4: " + str.tostring( kc2Upper, "#.##" ) + "\nTP5: " + str.tostring( kc3Upper, "#.##" ) + "\n\nSL: " + str.tostring( kc5Lower, "#.##" ), style = label.style_label_up, color = color.rgb( 221, 240, 58 ), textcolor = color.black, textalign = text.align_center, text_font_family = font.family_monospace, size = size.normal )
longEP := kc3Lower
longSL := kc5Lower
longTP1 := kc1Lower
longTP2 := kc1Median
longTP3 := kc1Upper
longTP4 := kc2Upper
longTP5 := kc3Upper
longPos := 1
longPosTP2 := 1
longPosTP3 := 1
longPosTP4 := 1
longPosTP5 := 1
longAlpEP := 0
longAlpSL := 0
longAlpTP1 := 0
longAlpTP2 := 0
longAlpTP3 := 0
longAlpTP4 := 0
longAlpTP5 := 0
longTP1Ln := 1
longTP2Ln := 1
longTP3Ln := 1
longTP4Ln := 1
longTP5Ln := 1
longSLLn := 1
longBGtp1TR := 100
longBGtp2TR := 100
longBGtp3TR := 100
longBGtp4TR := 100
longBGtp5TR := 100
longBGslTR := 100
if longPos == 1 and low < longSL
longPosStop := true
longPos := 0
longPosTP2 := 0
longPosTP3 := 0
longPosTP4 := 0
longPosTP5 := 0
else
longPosStop := false
if longPos == 1 and high > longTP1
longPosTakeProfit1 := true
longPos := 0
else
longPosTakeProfit1 := false
if longPosTP2 == 1 and high > longTP2
longPosTakeProfit2 := true
longPosTP2 := 0
else
longPosTakeProfit2 := false
if longPosTP3 == 1 and high > longTP3
longPosTakeProfit3 := true
longPosTP3 := 0
else
longPosTakeProfit3 := false
if longPosTP4 == 1 and high > longTP4
longPosTakeProfit4 := true
longPosTP4 := 0
else
longPosTakeProfit4 := false
if longPosTP5 == 1 and high > longTP5
longPosTakeProfit5 := true
longPosTP5 := 0
else
longPosTakeProfit5 := false
if high > longTP1 == true and longTP1Ln == 1
longAlpTP1 := na, longBGtp1TR := 0
if high > longTP2 == true and longTP2Ln == 1
longTP2Ln := 0, longAlpTP2 := na, longBGtp2TR := 0
if high > longTP3 == true and longTP3Ln == 1
longTP3Ln := 0, longAlpTP3 := na, longBGtp3TR := 0
if high > longTP4 == true and longTP4Ln == 1
longTP4Ln := 0, longAlpTP4 := na, longBGtp4TR := 0
if high > longTP5 == true and longTP5Ln == 1
longTP5Ln := 0, longAlpEP := na, longAlpSL := na, longAlpTP1 := na, longAlpTP2 := na, longAlpTP3 := na, longAlpTP4 := na, longAlpTP5 := na, longBGtp5TR := 0
if low < longSL == true and longSLLn == 1
longSLLn := 0, longAlpEP := na, longAlpSL := na, longAlpTP1 := na, longAlpTP2 := na, longAlpTP3 := na, longAlpTP4 := na, longAlpTP5 := na, longBGslTR := 0
// <--- LONG STRATEGY
// ---> SHORT STRATEGY
downCondtion1 = ta.crossover( kc3Upper, high )
downCondtion2 = ta.crossover( 165.0, cci )
downCondtion3 = 0.7 > roc and roc < 0.9
downCondtion4 = ta.crossunder( bop, -0.4 )
downCondtion5 = ta.crossover( rsi, 76 )
downCondtion6 = kc1Median > sar
downCondtion7 = ohlc4 > kc1Median
shortSignal = downCondtion1 and downCondtion2 and downCondtion3 and downCondtion4 and downCondtion6 and downCondtion7
if shortSignal
shortLbl = label.new( x = bar_index, y = kc5Upper, text = "Short Signal\n\nTP1: " + str.tostring( kc1Upper, "#.##" ) + "\nTP2: " + str.tostring( kc1Median, "#.##" ) + "\nTP3: " + str.tostring( kc1Lower, "#.##" ) + "\nTP4: " + str.tostring( kc2Lower, "#.##" ) + "\nTP5: " + str.tostring( kc3Lower, "#.##" ) + "\n\nSL: " + str.tostring( kc5Upper, "#.##" ), style = label.style_label_down, color = color.rgb( 221, 240, 58 ), textcolor = color.black, textalign = text.align_center, text_font_family = font.family_monospace, size = size.normal )
shortEP := kc3Upper
shortSL := kc5Upper
shortTP1 := kc1Upper
shortTP2 := kc1Median
shortTP3 := kc1Lower
shortTP4 := kc2Lower
shortTP5 := kc3Lower
shortPos := 1
shortPosTP2 := 1
shortPosTP3 := 1
shortPosTP4 := 1
shortPosTP5 := 1
shortAlpEP := 0
shortAlpSL := 0
shortAlpTP1 := 0
shortAlpTP2 := 0
shortAlpTP3 := 0
shortAlpTP4 := 0
shortAlpTP5 := 0
shortTP1Ln := 1
shortTP2Ln := 1
shortTP3Ln := 1
shortTP4Ln := 1
shortTP5Ln := 1
shortSLLn := 1
shortBGtp1TR := 100
shortBGtp2TR := 100
shortBGtp3TR := 100
shortBGtp4TR := 100
shortBGtp5TR := 100
shortBGslTR := 100
if shortPos == 1 and high > shortSL
shortPosStop := true
shortPos := 0
shortPosTP2 := 0
shortPosTP3 := 0
shortPosTP4 := 0
shortPosTP5 := 0
else
shortPosStop := false
if shortPos == 1 and low < shortTP1
shortPosTakeProfit1 := true
shortPos := 0
else
shortPosTakeProfit1 := false
if shortPosTP2 == 1 and low < shortTP2
shortPosTakeProfit2 := true
shortPosTP2 := 0
else
shortPosTakeProfit2 := false
if shortPosTP3 == 1 and low < shortTP3
shortPosTakeProfit3 := true
shortPosTP3 := 0
else
shortPosTakeProfit3 := false
if shortPosTP4 == 1 and low < shortTP4
shortPosTakeProfit4 := true
shortPosTP4 := 0
else
shortPosTakeProfit4 := false
if shortPosTP5 == 1 and low < shortTP5
shortPosTakeProfit5 := true
shortPosTP5 := 0
else
shortPosTakeProfit5 := false
if low < shortTP1 == true and shortTP1Ln == 1
shortAlpTP1 := na, shortBGtp1TR := 0
if low < shortTP2 == true and shortTP2Ln == 1
shortTP2Ln := 0, shortAlpTP2 := na, shortBGtp2TR := 0
if low < shortTP3 == true and shortTP3Ln == 1
shortTP3Ln := 0, shortAlpTP3 := na, shortBGtp3TR := 0
if low < shortTP4 == true and shortTP4Ln == 1
shortTP4Ln := 0, shortAlpTP4 := na, shortBGtp4TR := 0
if low < shortTP5 == true and shortTP5Ln == 1
shortTP5Ln := 0, shortAlpEP := na, shortAlpSL := na, shortAlpTP1 := na, shortAlpTP2 := na, shortAlpTP3 := na, shortAlpTP4 := na, shortAlpTP5 := na, shortBGtp5TR := 0
if high > shortSL == true and shortSLLn == 1
shortSLLn := 0, shortAlpEP := na, shortAlpSL := na, shortAlpTP1 := na, shortAlpTP2 := na, shortAlpTP3 := na, shortAlpTP4 := na, shortAlpTP5 := na, shortBGslTR := 0
// <--- SHORT STRATEGY
// ---> PLOT
demaPlot = plot( series = dema, color = color.rgb( red = 202, green = 204, blue = 202 ), linewidth = 1, display = display.all, title = "DEMA", editable = false )
// <--- PLOT
// ---> STRATEGY PLOT
bgcolor( longSignal ? color.new( color = color.lime, transp = 60 ) : na, title = "Background color for Long Signals", editable = false )
bgcolor( shortSignal ? color.rgb( red = 255, green = 0, blue = 0 ) : na, title = "Background color for Short Signals", editable = false )
plotshape( longSignal, title = "Long Signal", style = shape.triangleup, color = color.green, location = location.belowbar, text = "Long Signal", textcolor = color.white, size = size.normal )
plotshape( shortSignal, title = "Short Signal", style = shape.triangledown, color = color.red, location = location.abovebar, text = "Short Signal", textcolor = color.white, size = size.normal )
bgcolor( shortPosTakeProfit1 ? color.rgb( red = 116, green = 173,blue = 237 ) : na, title = "Background color for Short Signal TP", editable = false )
plotshape( shortPosTakeProfit1, title = "Short Signal TP1", style = shape.triangleup, color = color.rgb( red = 116, green = 173, blue = 237 ), location = location.belowbar, text = "Short Signal\nTP1", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( shortPosTakeProfit2 ? color.rgb( red = 132, green = 113, blue = 209 ) : na, title = "Background color for Short Signal TP", editable = false )
plotshape( shortPosTakeProfit2, title = "Short Signal TP2", style = shape.triangleup, color = color.rgb( red = 116, green = 221, blue = 237 ), location = location.belowbar, text = "Short Signal\nTP2", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( shortPosTakeProfit3 ? color.rgb( red = 75, green = 0, blue = 130 ) : na, title = "Background color for Short Signal TP", editable = false )
plotshape( shortPosTakeProfit3, title = "Short Signal TP3", style = shape.triangleup, color = color.rgb( red = 116, green = 221, blue = 237 ), location = location.belowbar, text = "Short Signal\nTP3", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( shortPosTakeProfit4 ? color.rgb( red = 177, green = 113, blue = 209 ) : na, title = "Background color for Short Signal TP", editable = false )
plotshape( shortPosTakeProfit4, title = "Short Signal TP4", style = shape.triangleup, color = color.rgb( red = 116, green = 221, blue = 237 ), location = location.belowbar, text = "Short Signal\nTP4", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( shortPosTakeProfit5 ? color.rgb( red = 238, green = 130, blue = 238 ) : na, title = "Background color for Short Signal TP", editable = false )
plotshape( shortPosTakeProfit5, title = "Short Signal TP5", style = shape.triangleup, color = color.rgb( red = 116, green = 221, blue = 237 ), location = location.belowbar, text = "Short Signal\nTP5", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( shortPosStop ? color.new( color = #d976ec, transp = 60 ) : na, title = "Background color for Short Signal SL", editable = false )
plotshape( shortPosStop, title = "Short Signal Stop-Loss", style = shape.triangleup, color = color.rgb( red = 116, green = 221, blue = 237 ), location = location.belowbar, text = "Short Signal Stopped", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( longPosTakeProfit1 ? color.rgb( red = 221, green = 240, blue = 58, transp = longBGtp1TR ) : na, title = "Background color for Long Signal TP", editable = false )
plotshape( longPosTakeProfit1, title = "Long Signal TP1", style = shape.triangledown, color = color.rgb( red = 116, green = 221, blue = 237, transp = longBGtp1TR ), location = location.abovebar, text = "Long Signal\nTP1", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( longPosTakeProfit2 ? color.rgb( red = 255, green = 255, blue = 0, transp = longBGtp2TR ) : na, title = "Background color for Long Signal TP", editable = false )
plotshape( longPosTakeProfit2, title = "Long Signal TP2", style = shape.triangledown, color = color.rgb( red = 116, green = 221, blue = 237, transp = longBGtp2TR ), location = location.abovebar, text = "Long Signal\nTP2", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( longPosTakeProfit3 ? color.rgb( red = 240, green = 218, blue = 58, transp = longBGtp3TR ) : na, title = "Background color for Long Signal TP", editable = false )
plotshape( longPosTakeProfit3, title = "Long Signal TP3", style = shape.triangledown, color = color.rgb( red = 116, green = 221, blue = 237, transp = longBGtp3TR ), location = location.abovebar, text = "Long Signal\nTP3", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( longPosTakeProfit4 ? color.rgb( red = 255, green = 165, blue = 0, transp = longBGtp4TR ) : na, title = "Background color for Long Signal TP", editable = false )
plotshape( longPosTakeProfit4, title = "Long Signal TP4", style = shape.triangledown, color = color.rgb( red = 116, green = 221, blue = 237, transp = longBGtp4TR ), location = location.abovebar, text = "Long Signal\nTP4", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( longPosTakeProfit5 ? color.rgb( red = 240, green = 133, blue = 8, transp = longBGtp5TR ) : na, title = "Background color for Long Signal TP", editable = false )
plotshape( longPosTakeProfit5, title = "Long Signal TP5", style = shape.triangledown, color = color.rgb( red = 116, green = 221, blue = 237, transp = longBGtp5TR ), location = location.abovebar, text = "Long Signal\nTP5", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
bgcolor( longPosStop ? color.new( color = #d976ec, transp = longBGslTR ) : na, title = "Background color for Long Signal SL", editable = false )
plotshape( longPosStop, title = "Long Signal Stop-Loss", style = shape.triangledown, color = color.rgb( red = 116, green = 221, blue = 237, transp = longBGslTR ), location = location.abovebar, text = "Long Signal Stopped", textcolor = color.rgb( red = 255, green = 255, blue = 255 ), size = size.normal )
plot( shortEP, color = color.rgb( red = 116, green = 221, blue = 237, transp = shortAlpEP ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Short Signal Stop Loss level", editable = false, display = display.all )
plot( shortSL, color = color.rgb( red = 255, green = 0, blue = 0, transp = shortAlpSL ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Short Signal Stop Loss level", editable = false, display = display.all )
plot( shortTP1, color = color.rgb( red = 116, green = 173, blue = 237, transp = shortAlpTP1 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Short Signal Stop Loss level", editable = false, display = display.all )
plot( shortTP2, color = color.rgb( red = 132, green = 113, blue = 209, transp = shortAlpTP2 ) , style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Short Signal Stop Loss level", editable = false, display = display.all )
plot( shortTP3, color = color.rgb( red = 75, green = 0, blue = 130, transp = shortAlpTP3 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Short Signal Stop Loss level", editable = false, display = display.all )
plot( shortTP4, color = color.rgb( red = 177, green = 113, blue = 209, transp = shortAlpTP4 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Short Signal Stop Loss level", editable = false, display = display.all )
plot( shortTP5, color = color.rgb( red = 238, green = 130, blue = 238, transp = shortAlpTP5 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Short Signal Stop Loss level", editable = false, display = display.all )
plot( longEP, color = color.rgb( red = 116, green = 221, blue = 237, transp = longAlpEP ) , style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Long Signal Entry Level", editable = false, display = display.all )
plot( longSL, color = color.rgb( red = 255, green = 0, blue = 0, transp = longAlpSL ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Long Signal Stop Loss level", editable = false, display = display.all )
plot( longTP1, color = color.rgb( red = 221, green = 240, blue = 58, transp = longAlpTP1 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Long Signal Take Profit 1 Level", editable = false, display = display.all )
plot( longTP2, color = color.rgb( red = 255, green = 255, blue = 0, transp = longAlpTP2 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Long Signal Take Profit 2 Level", editable = false, display = display.all )
plot( longTP3, color = color.rgb( red = 240, green = 218, blue = 58, transp = longAlpTP3 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Long Signal Take Profit 3 Level", editable = false, display = display.all )
plot( longTP4, color = color.rgb( red = 255, green = 165, blue = 0, transp = longAlpTP4 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Long Signal Take Profit 4 Level", editable = false, display = display.all )
plot( longTP5, color = color.rgb( red = 240,green = 133, blue = 8, transp = longAlpTP5 ), style = plot.style_steplinebr, linewidth = 3, offset = 0, title = "Long Signal Take Profit 5 Level", editable = false, display = display.all )
// <--- STRATEGY PLOT |
Encapsulation Box | https://www.tradingview.com/script/08Nflwm3-Encapsulation-Box/ | AleSaira | https://www.tradingview.com/u/AleSaira/ | 114 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AleSaira
//@version=5
indicator("Encapsulation Box", shorttitle = "Encapsulation Box", overlay = true)
// Input for the number of horizontal candles in the box and box lines color
boxWidth = input.int (5, title="Box Width", minval=1)
boxLineColor = input.color (color.rgb(220, 220, 8), title="Box Line Color")
boxLColor = input.color (color.rgb(181, 220, 8, 74), title="Box Color")
line = input.color (color.rgb(237, 241, 4), title="Line Color")
lineWidth = input.int (2, title="Box Width", minval=1)
boxLine = input.int (1, title="Box Line", minval=1)
// Calculate rectangle coordinates
var float rectTop = na
var float rectBottom = na
var float rectLeft = na
var float rectRight = na
var float rectLine = na
// Update rectangle coordinates only when new max/min is reached
newHigh = high >= ta.highest(high, boxWidth)
newLow = low <= ta.lowest(low, boxWidth)
if newHigh or newLow
rectTop := high
rectBottom := low
rectLeft := float(bar_index)
rectRight := float(bar_index) + float(boxWidth)
rectLine := rectRight + 20
// Initialize buy and sell signals
var bool buySignal = na
var bool sellSignal = na
// Draw rectangle lines
if bar_index >= 3
if high <= high[4] and high <= high[3] and high <= high[2] and high <= high[1] and high and high[4] >= high[3] and low[4] <= low and low[3] <= low[2] and low[3] <= low and low[4] <= low [3]
// Draw the box using box.new for both border and fill
box.new(left=int(rectLeft), right=int(rectRight), top=rectTop, bottom=rectBottom, border_width=boxLine, border_color=boxLineColor, bgcolor=boxLColor)
// Calculate midpoint of the box
midpointPrice = (rectTop + rectBottom) / 2
line.new(x1=int(rectLeft), y1=midpointPrice, x2=int(rectLine), y2=midpointPrice, width=lineWidth, color=line)
// Define the alert
alert("Encapsulation Box: New box formed at bar " + str.tostring(bar_index))
|
Moving Averages w/Signals [CSJ7] | https://www.tradingview.com/script/jTPqlwAd-Moving-Averages-w-Signals-CSJ7/ | gtellezgiron2009 | https://www.tradingview.com/u/gtellezgiron2009/ | 107 | 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/
// © gtellezgiron2009
//@version=5
indicator("Moving Averages w/Signals [CSJ7]", shorttitle = 'CSJ7 Moving Averages', overlay = true)
//==================================
// CONSTANTS
//==================================
// Titles for input groups
string GR_MOVING_AVERAGES = "Moving Averages ===================================="
string GR_SIGNALS = "Buy & Sell Signals ================================="
// Define color constants for various scenarios and states
color COL_BEARGR = color.rgb(133, 17, 17) // Bearish Growing
color COL_BULLGR = color.green // Bullish Growing
color COL_BEARSH = color.red // Bearish Shrinking
color COL_BULLSH = color.rgb(27, 96, 29) // Bullish Shrinking
color COL_TRANSP = color.new(color.blue,100) // Transparent color
color COLOR_UP = color.green // Color for upward movement
color COLOR_DOWN = color.red // Color for downward movement
color COLOR_BUY = color.rgb(0, 255, 8) // Buy signal color
color COLOR_SELL = color.rgb(255, 0, 0) // Sell signal color
color COLOR_NEUTRAL = color.gray // Neutral color
int MA_TRANSPARENCY = 0 // Transparency level for moving averages
// Define line widths for the moving averages
int FAST_LINE_WIDTH = 1
int MEDIUM_LINE_WIDTH = 3
int SLOW_LINE_WIDTH = 5
//==================================
// INPUTS
//==================================
// User input for type of moving average
string ma_type_input = input.string('Exponential','Type of moving average',options = ['Simple', 'Exponential'], group = GR_MOVING_AVERAGES)
// User input for lengths of moving averages
int length_fast_input = input(50, "Fast: Length", group = GR_MOVING_AVERAGES)
int length_medium_input = input(100, "Medium: Length", group = GR_MOVING_AVERAGES)
int length_slow_input = input(500, "Slow: Length", group = GR_MOVING_AVERAGES)
// User input for Buy signal configuration
string buy_crosser_input = input.string('Medium MA','Buy: ',options=['Fast MA','Medium MA','Slow MA'], inline = '1', group = GR_SIGNALS)
string buy_crossType_input = input.string('Over','crosses',options = ['Over', 'Under'], inline = '1', group = GR_SIGNALS)
string buy_crossed_input = input.string('Slow MA','',options=['Fast MA','Medium MA','Slow MA'], inline = '1', group = GR_SIGNALS)
// User input for Sell signal configuration
string sell_crosser_input = input.string('Medium MA','Sell: ',options=['Fast MA','Medium MA','Slow MA'], inline = '2', group = GR_SIGNALS)
string sell_crossType_input = input.string('Under','crosses',options = ['Over', 'Under'], inline = '2', group = GR_SIGNALS)
string sell_crossed_input = input.string('Slow MA','',options=['Fast MA','Medium MA','Slow MA'], inline = '2', group = GR_SIGNALS)
// User input to decide if areas should be filled or not
bool fill_areas_input = input.bool(true, 'Fill areas')
//==================================
// FUNCTIONS
//==================================
// Function to calculate moving averages based on user's choice of type and lengths
get_mas(source, length_fast_input, length_medium_input, length_slow_input, ma_type_input) =>
float ma_fast = 0.0
float ma_med = 0.0
float ma_slow = 0.0
if ma_type_input == "Simple"
ma_fast := ta.sma(source, length_fast_input)
ma_med := ta.sma(source, length_medium_input)
ma_slow := ta.sma(source, length_slow_input)
else if ma_type_input == "Exponential"
ma_fast := ta.ema(source, length_fast_input)
ma_med := ta.ema(source, length_medium_input)
ma_slow := ta.ema(source, length_slow_input)
[ma_fast, ma_med, ma_slow]
// Function to determine color based on direction of the data
get_color_by_direction(source,lookback, col_up,col_dn, transp) =>
col_p = source > source[lookback] ? col_up : source < source[lookback] ? col_dn : COLOR_NEUTRAL
col = color.new(col_p, transp)
// Function to determine various market scenarios based on the relationship between fast and slow signals
get_scenarios(signal_fast,signal_slow) =>
trend_bull = signal_fast > signal_slow
trend_bear = signal_fast < signal_slow
dif_ma = math.abs(signal_fast - signal_slow)
signal_fast_up = signal_fast > signal_fast[1]
signal_fast_dn = signal_fast < signal_fast[1]
signal_slow_up = signal_slow > signal_slow[1]
signal_slow_dn = signal_slow < signal_slow[1]
trend_shrinking = dif_ma < dif_ma[1] and not(trend_bull ? signal_fast_up and signal_slow_up : signal_fast_dn and signal_slow_dn)
trend_growing = not(trend_shrinking)
bullGr = trend_bull and trend_growing
bullSh = trend_bull and trend_shrinking
bearGr = trend_bear and trend_growing
bearSh = trend_bear and trend_shrinking
[bullGr,bullSh,bearGr,bearSh, signal_fast_up, signal_fast_dn, signal_slow_up, signal_slow_dn]
// Calculate moving averages
[ma_fast, ma_med, ma_slow] = get_mas(close, length_fast_input, length_medium_input, length_slow_input, ma_type_input)
// Determine market scenarios based on moving averages
[bullGr,bullSh,bearGr,bearSh, signal_fast_up, signal_fast_dn, signal_slow_up, signal_slow_dn] = get_scenarios(ma_fast,ma_slow)
// Define super bullish and super bearish scenarios
superBull = ma_fast > ma_med and ma_med > ma_slow
superBear = ma_fast < ma_med and ma_med < ma_slow
//==================================
// CROSSES
//==================================
// Determine crossing levels based on user input
float buy_crosser = switch buy_crosser_input
'Fast MA' => ma_fast
'Medium MA' => ma_med
'Slow MA' => ma_slow
float buy_crossed = switch buy_crossed_input
'Fast MA' => ma_fast
'Medium MA' => ma_med
'Slow MA' => ma_slow
float sell_crosser = switch sell_crosser_input
'Fast MA' => ma_fast
'Medium MA' => ma_med
'Slow MA' => ma_slow
float sell_crossed = switch sell_crossed_input
'Fast MA' => ma_fast
'Medium MA' => ma_med
'Slow MA' => ma_slow
// Determine buy and sell signals based on crossing scenarios
buy_signal = buy_crossType_input == 'Over' ? ta.crossover(buy_crosser, buy_crossed) : ta.crossunder(buy_crosser, buy_crossed)
sell_signal = sell_crossType_input == 'Over' ? ta.crossover(buy_crosser, buy_crossed) : ta.crossunder(buy_crosser, buy_crossed)
// Plot buy and sell signals on the chart
plotshape(buy_signal,'Buy Signal', shape.triangleup,location.belowbar, COLOR_BUY,0,'Buy',COLOR_BUY,true,size.small)
plotshape(sell_signal,'Sell Signal', shape.triangledown,location.abovebar, COLOR_SELL,0,'Sell',COLOR_SELL,true,size.small)
//==================================
// PLOTS
//==================================
// Configuration for plot transparency
int ma_transparency_fill = 50
int transp_superBull_fill = 40
int transp_superBear_fill = 20
int div = 5
// Determine lookback periods for moving averages
ma_slow_lookback = int(math.round(length_slow_input / div,0))
ma_medium_lookback = int(math.round(length_medium_input / div,0))
ma_fast_lookback = int(math.round(length_fast_input / div,0))
// Determine trend color based on scenarios
col_trend = bullGr ? COL_BULLGR : bullSh ? COL_BULLSH : bearGr ? COL_BEARGR : bearSh ? COL_BEARSH : color.yellow
// Adjust transparency based on user input
if not(fill_areas_input)
ma_transparency_fill := 100
transp_superBull_fill := 100
transp_superBear_fill := 100
// Plot moving averages on the chart with respective colors and widths
ln_ma_fast = plot(ma_fast, title="Fast", color=get_color_by_direction(ma_fast,ma_fast_lookback, COLOR_UP,COLOR_DOWN, MA_TRANSPARENCY), linewidth = FAST_LINE_WIDTH)
ln_ma_medium = plot(ma_med, title="Medium", color=get_color_by_direction(ma_med,ma_medium_lookback, COLOR_UP,COLOR_DOWN, MA_TRANSPARENCY), linewidth = MEDIUM_LINE_WIDTH)
ln_ma_slow = plot(ma_slow, title="Slow", color=get_color_by_direction(ma_slow,ma_slow_lookback, COLOR_UP,COLOR_DOWN, MA_TRANSPARENCY), linewidth = SLOW_LINE_WIDTH)
// Fill the area between Medium and Slow moving averages based on trend color
fill(ln_ma_medium, ln_ma_slow, color = color.new(col_trend,ma_transparency_fill), fillgaps = true)
|
True Range Moving Average Deviation | https://www.tradingview.com/script/HDbBPnRS-True-Range-Moving-Average-Deviation/ | gabasco | https://www.tradingview.com/u/gabasco/ | 45 | 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/
// © gabasco
//@version=5
indicator(title="True Range Moving Average Deviation", shorttitle="TRMAD", precision=2, timeframe="", overlay=false)
// 1. Input
themeInput = input.string("Standard", title="Theme ", options=["Standard", "Light"], inline = 'theme', group="General Settings", display=display.none)
colorLineInput = input.color(color.new(color.black, 10), title= "", inline = 'theme', group="General Settings", display=display.none)
obValueInput = input.float(3, title="Overbought", inline = 'ob', group="General Settings", display=display.none)
obColorInput = input(#089981, title="", inline = 'ob', group="General Settings", display=display.none)
osValueInput = input.float(-3, title="Oversold ", inline = 'os', group="General Settings", display=display.none)
osColorInput = input(#f23645, title="", inline = 'os', group="General Settings", display=display.none)
trTypeInput = input.string("SMA", title="TR Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="TR Settings", display=display.none)
trLengthInput = input.int(14, "TR Length", minval=2, group="TR Settings", display=display.none)
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings", display=display.none)
maLengthInput = input.int(20, "MA Length", minval=2, group="MA Settings", display=display.none)
// 2. Formula
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)
// 3. Calculation
atr = ma(ta.tr(true), trLengthInput, trTypeInput)
distance = close - ma(close, maLengthInput, maTypeInput)
trmad = nz(distance/atr)
// 4. Drawings
// a. TRMAD
trmadPlot = plot(trmad, "TRMAD", themeInput == "Standard" ? trmad > obValueInput ? obColorInput : trmad < osValueInput ? osColorInput : colorLineInput : colorLineInput, editable = false)
// b. Zero line
zeroPlot = plot(0, editable=false, display=display.none)
obPlot = plot(trmad > obValueInput ? trmad : na, editable=false, display=display.none)
osPlot = plot(trmad < osValueInput ? trmad : na, editable=false, display=display.none)
// c. Fills
// - Above/below zero line
fill(zeroPlot, trmadPlot, themeInput == "Standard" ? trmad < 0 ? color.new(osColorInput,90) : color.new(obColorInput, 90) : chart.bg_color, title = "Area Fill")
// - Overbought / oversold zone
fill(zeroPlot, obPlot, obValueInput * 1.5, obValueInput, top_color = themeInput == "Standard" ? color.new(obColorInput, 50) : na, bottom_color = themeInput == "Standard" ? color.new(obColorInput, 100) : na, title = "Overbought Gradient Fill")
fill(zeroPlot, osPlot, osValueInput, osValueInput * 1.5, top_color = themeInput == "Standard" ? color.new(osColorInput, 100) : na, bottom_color = themeInput == "Standard" ? color.new(osColorInput, 0) : na, title = "Oversold Gradient Fill")
// d. Levels
// - Hidden
obLevel = plot(obValueInput, color = na, editable = false, display=display.none)
midLevel = plot(0, color = na, editable = false, display=display.none)
osLevel = plot(osValueInput, color = na, editable = false, display=display.none)
// - Displayed
hline(obValueInput, 'Overbought')
hline(0, 'Midline')
hline(osValueInput, 'Oversold') |
Nadaraya-Watson Envelope: Modified by Yosiet | https://www.tradingview.com/script/DoOd6evK-Nadaraya-Watson-Envelope-Modified-by-Yosiet/ | yosietserga | https://www.tradingview.com/u/yosietserga/ | 289 | 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/
// Inspired by LuxAlgo Nadaraya-Watson Envelope
//@version=5
indicator("Nadaraya-Watson Envelope: Modified by Yosiet",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.float(500,'Window Size',maxval=500,minval=0)
h = input.float(10.,'Bandwidth')
mult = input.float(3.)
srcUpperBand = input.source(low,'Source Upper Band')
src = input.source(high,'Source Lower Band')
up_col = input.color(#ff1100,'Colors',inline='col')
dn_col = input.color(#39ff14,'',inline='col')
show_bands = input(false, 'Show Bands')
show_sma_7_low_1 = input(false, 'Show SMA 7 LOW +1')
show_sma_7_low_7 = input(false, 'Show SMA 7 LOW -7')
show_sma_30_high = input(false, 'Show SMA 30 HIGH')
//----
n = bar_index
var k = 2
var upper = array.new_line(0)
var lower = array.new_line(0)
sma7_low = ta.sma(low, 7)
sma30_high = ta.sma(high, 30)
strDownArrows = "▼"
strUpArrows = "▲"
RoundUp(number, decimals) =>
factor = math.pow(10, decimals)
math.ceil(number * factor) / factor
plot(show_sma_7_low_1?sma7_low:na, color=color.rgb(255, 235, 59, 81), title="SMA 7 LOW +1", offset=+1, linewidth=1)
plot(show_sma_7_low_7?sma7_low:na, color=color.rgb(255, 235, 59, 81), title="7 sma", offset=-7, linewidth=1)
plot(show_sma_30_high ? sma30_high:na, color=color.purple, title="SMA 30 High", linewidth=1)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length/k-1
array.push(upper,line.new(na,na,na,na))
array.push(lower,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)
yUpper = array.new_float(0)
sum_upper_e = 0.
sum_e = 0.
for i = 0 to length-1
sum_upper = 0.
sumw_upper = 0.
sum = 0.
sumw = 0.
for j = 0 to length-1
w = math.exp(-(math.pow(i-j,2)/(h*h*2)))
sum_upper += srcUpperBand[j]*w
sum += src[j]*w
sumw += w
y_upper_2 = sum_upper/sumw
sum_upper_e += math.abs(srcUpperBand[i] - y_upper_2)
array.push(yUpper,y_upper_2)
y2 = sum/sumw
sum_e += math.abs(src[i] - y2)
array.push(y,y2)
mae_upper = sum_upper_e/length*mult
mae = sum_e/length*mult
for i = 1 to length-1
upper_y2 = array.get(yUpper,i)
upper_y1 = array.get(yUpper,i-1)
y2 = array.get(y,i)
y1 = array.get(y,i-1)
up := array.get(upper,i/k)
dn := array.get(lower,i/k)
//draw borders bands
if show_bands
lset(up,n-i+1,upper_y1 + mae_upper,n-i,upper_y2 + mae_upper,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)
//draw fractals
//if src[i] > y1 + mae and src[i+1] < y1 + mae
// label.new(n-i,src[i],strDownArrows,color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
//if src[i] < y1 - mae and src[i+1] > y1 - mae
// label.new(n-i,src[i],strUpArrows,color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
//draw sma 30 high signals
if sma30_high[i] > upper_y1 + mae_upper and sma30_high[i+1] < upper_y2 + mae_upper
label.new(n-i,srcUpperBand[i]+mae_upper,strDownArrows,color=#00000000,style=label.style_label_down,textcolor=#ec05af,textalign=text.align_center)
//if sma30_high[i] < y1 - mae and sma30_high[i+1] > y2 - mae
// label.new(n-i,src[i+1],strUpArrows,color=#00000000,style=label.style_label_down,textcolor=#ec05af,textalign=text.align_center)
//draw sma 7 low signals
if sma7_low[i] > upper_y1 + mae_upper and sma7_low[i+1] < upper_y2 + mae_upper
label.new(n-i,src[i],strDownArrows,color=#00000000,style=label.style_label_down,textcolor=color.orange,textalign=text.align_center)
if sma7_low[i] < y1 - mae and sma7_low[i+1] > y2 - mae
label.new(n-i,src[i]-mae,strUpArrows,color=#00000000,style=label.style_label_up,textcolor=color.orange,textalign=text.align_center)
cross_up := array.get(yUpper,0) + mae_upper
cross_dn := array.get(y,0) - mae
sma7_crossover = ta.crossover(sma7_low,cross_up)
sma7_crossunder = ta.crossunder(sma7_low,cross_dn)
sma30_crossover = ta.crossover(sma30_high,cross_up)
sma30_crossunder = ta.crossunder(sma30_high,cross_dn)
alertcondition(sma30_crossunder or sma7_crossunder,title="LONG", message='LONG: {{ticker}}/{{interval}} at price {{close}} on {{exchange}}' )
alertcondition(sma7_crossover or sma30_crossover,title="SHORT", message='SHORT: {{ticker}}/{{interval}} at price {{close}} on {{exchange}}' ) |
Nitin Swing Trading | https://www.tradingview.com/script/bphw8qjA-Nitin-Swing-Trading/ | ShareTrading_ | https://www.tradingview.com/u/ShareTrading_/ | 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/
// © ShareTrading_
//@version=5
indicator(title='Swing Trading Nitin', shorttitle='SwingTradeNitin', overlay=true)
//defaultTimeFrame = ((isintraday) ? "D" : ((isdaily) ? "W" : ((isweekly) ? "M" : "3M")))
//inputTimeFrame = input(title="Time Frame", type=string, defval="D")
//chosenTimeFrame = (inputTimeFrame == "D") ? defaultTimeFrame : inputTimeFrame
getSeries(e, timeFrame) =>
request.security(syminfo.tickerid, timeFrame, e, lookahead=barmerge.lookahead_on)
H = getSeries(high[1], 'M')
L = getSeries(low[1], 'M')
C = getSeries(close[1], 'M')
// Main Pivot
P = (H + L + C) / 3
BC = (H + L) / 2
TC = P - BC + P
// Resistence Levels
// R3 = H + 2 * (P - L)
//R2 = P + H - L
R1 = P * 2 - L
// Support Levels
S1 = P * 2 - H
// S2 = P - (H - L)
// S3 = L - 2 * (H - P)
//UX Input Arguments
bColor = color.navy
rColor = color.orange
sColor = color.green
myWidthMainLevels = input.int(title='Line width for Main levels', defval=2, minval=1)
myStyle = plot.style_circles
plot(R1, title='R1', color=color.new(rColor, 0), linewidth=myWidthMainLevels, style=myStyle)
//plot(R2, title="R2", color=rColor, linewidth=myWidthMainLevels, style=myStyle)
//plot(R3, title="R3", color=rColor, linewidth=myWidthMainLevels, style=myStyle)
plot(P, title='P', color=color.new(bColor, 0), linewidth=2, style=plot.style_circles)
p1 = plot(BC, title='BC', color=color.new(bColor, 0), linewidth=2, style=plot.style_circles)
p2 = plot(TC, title='TC', color=color.new(bColor, 0), linewidth=2, style=plot.style_circles)
plot(S1, title='S1', color=color.new(sColor, 0), linewidth=myWidthMainLevels, style=myStyle)
//plot(S2, title="S2", color=sColor, linewidth=myWidthMainLevels, style=myStyle)
//plot(S3, title="S3", color=sColor, linewidth=myWidthMainLevels, style=myStyle)
|
Rolling VWAP Oscillator | https://www.tradingview.com/script/xP8ihbDe-Rolling-VWAP-Oscillator/ | Daniel_Ge | https://www.tradingview.com/u/Daniel_Ge/ | 61 | 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 - modified by Daniel_Ge
// Creds to TradingView - I simply turned the existing indicator into a centered oscillator
//@version=5
indicator("Rolling VWAP Oscillator", "RVWAP Oscillator", false)
// Rolling VWAP
// v3, 2022.07.24
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
import PineCoders/ConditionalAverages/1 as pc
// ———————————————————— Constants and Inputs {
// ————— Constants
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int MS_IN_DAY = MS_IN_HOUR * 24
string TT_SRC = "The source used to calculate the VWAP. The default is the average of the high, low and close prices."
string TT_WINDOW = "By default, the time period used to calculate the RVWAP automatically adjusts with the chart's timeframe.
Check this to use a fixed-size time period instead, which you define with the following three values."
string TT_MINBARS = "The minimum number of last values to keep in the moving window, even if these values are outside the time period.
This avoids situations where a large time gap between two bars would cause the time window to be empty."
string TT_STDEV = "The multiplier for the standard deviation bands offset above and below the RVWAP. Example: 1.0 is 100% of the offset value.
\n\nNOTE: A value of 0.0 will hide the bands."
string TT_TABLE = "Displays the time period of the rolling window."
// ————— Inputs
float srcInput = input.source(hlc3, "Source", tooltip = TT_SRC)
bool show_candles = input.bool(false, "Show Candles", tooltip = "Switch between candles and line")
string GRP2 = '═══════════ Time Period ═══════════'
bool fixedTfInput = input.bool(false, "Use a fixed time period", group = GRP2, tooltip = TT_WINDOW)
int daysInput = input.int(1, "Days", group = GRP2, minval = 0, maxval = 90) * MS_IN_DAY
int hoursInput = input.int(0, "Hours", group = GRP2, minval = 0, maxval = 23) * MS_IN_HOUR
int minsInput = input.int(0, "Minutes", group = GRP2, minval = 0, maxval = 59) * MS_IN_MIN
string GRP3 = '═════════ Deviation Bands ═════════'
float stdevMult1 = input.float(0.5, "Bands Multiplier 1", group = GRP3, inline = "31", minval = 0.0, step = 0.5, tooltip = TT_STDEV)
float stdevMult2 = input.float(1.0, "Bands Multiplier 2", group = GRP3, inline = "32", minval = 0.0, step = 0.5, tooltip = TT_STDEV)
float stdevMult3 = input.float(1.5, "Bands Multiplier 3", group = GRP3, inline = "33", minval = 0.0, step = 0.5, tooltip = TT_STDEV)
float stdevMult4 = input.float(2, "Bands Multiplier 4", group = GRP3, inline = "34", minval = 0.0, step = 0.5, tooltip = TT_STDEV)
color stdevColor1 = input.color(color(#005e76), "", group = GRP3, inline = "31")
color stdevColor2 = input.color(color(#0095bb), "", group = GRP3, inline = "32")
color stdevColor3 = input.color(color(#00a7d1), "", group = GRP3, inline = "33")
color stdevColor4 = input.color(color(#00a7d1), "", group = GRP3, inline = "34")
string GRP4 = '════════ Minimum Window Size ════════'
int minBarsInput = input.int(10, "Bars", group = GRP4, tooltip = TT_MINBARS)
// }
// ———————————————————— Functions {
// @function Determines a time period from the chart's timeframe.
// @returns (int) A value of time in milliseconds that is appropriate for the current chart timeframe. To be used in the RVWAP calculation.
timeStep() =>
int tfInMs = timeframe.in_seconds() * 1000
float step =
switch
tfInMs <= MS_IN_MIN => MS_IN_HOUR
tfInMs <= MS_IN_MIN * 5 => MS_IN_HOUR * 4
tfInMs <= MS_IN_HOUR => MS_IN_DAY * 1
tfInMs <= MS_IN_HOUR * 4 => MS_IN_DAY * 3
tfInMs <= MS_IN_HOUR * 12 => MS_IN_DAY * 7
tfInMs <= MS_IN_DAY => MS_IN_DAY * 30.4375
tfInMs <= MS_IN_DAY * 7 => MS_IN_DAY * 90
=> MS_IN_DAY * 365
int result = int(step)
// @function Produces a string corresponding to the input time in days, hours, and minutes.
// @param (series int) A time value in milliseconds to be converted to a string variable.
// @returns (string) A string variable reflecting the amount of time from the input time.
tfString(int timeInMs) =>
int s = timeInMs / 1000
int m = s / 60
int h = m / 60
int tm = math.floor(m % 60)
int th = math.floor(h % 24)
int d = math.floor(h / 24)
string result =
switch
d == 30 and th == 10 and tm == 30 => "1M"
d == 7 and th == 0 and tm == 0 => "1W"
=>
string dStr = d ? str.tostring(d) + "D " : ""
string hStr = th ? str.tostring(th) + "H " : ""
string mStr = tm ? str.tostring(tm) + "min" : ""
dStr + hStr + mStr
// }
// ———————————————————— Calculations and Plots {
// 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.")
// RVWAP + stdev bands
int timeInMs = fixedTfInput ? minsInput + hoursInput + daysInput : timeStep()
float sumSrcVol = pc.totalForTimeWhen(srcInput * volume, timeInMs, true, minBarsInput)
float sumVol = pc.totalForTimeWhen(volume, timeInMs, true, minBarsInput)
float sumSrcSrcVol = pc.totalForTimeWhen(volume * math.pow(srcInput, 2), timeInMs, true, minBarsInput)
float rollingVWAP = sumSrcVol / sumVol
float variance = sumSrcSrcVol / sumVol - math.pow(rollingVWAP, 2)
variance := math.max(0, variance)
float stDev = math.sqrt(variance)
float upperBand1 = rollingVWAP + stDev * stdevMult1
float lowerBand1 = rollingVWAP - stDev * stdevMult1
float upperBand2 = rollingVWAP + stDev * stdevMult2
float lowerBand2 = rollingVWAP - stDev * stdevMult2
float upperBand3 = rollingVWAP + stDev * stdevMult3
float lowerBand3 = rollingVWAP - stDev * stdevMult3
float upperBand4 = rollingVWAP + stDev * stdevMult4
float lowerBand4 = rollingVWAP - stDev * stdevMult4
o = open - rollingVWAP
h = high - rollingVWAP
l = low - rollingVWAP
c = close - rollingVWAP
hline(0, linestyle = hline.style_solid)
plot(show_candles == false ? close - rollingVWAP : na, "Price Line", color(#d1d4dc), style = plot.style_stepline)
plotcandle(show_candles == true ? o : na, show_candles == true ? h : na, show_candles == true ? l : na, show_candles == true ? c : na, "Candles", color = o > c ? color.new(#b2b5be, 70) : color.new(#0095bb, 70), wickcolor = o > c ? #b2b5be : #0095bb, bordercolor = o > c ? #b2b5be : #0095bb)
p0 = plot(0,editable = false, display = display.none)
p1 = plot(stdevMult1 != 0 ? upperBand1 - rollingVWAP: na, "Upper Band 1", stdevColor1)
p2 = plot(stdevMult1 != 0 ? lowerBand1 - rollingVWAP : na, "Lower Band 1", stdevColor1)
p3 = plot(stdevMult2 != 0 ? upperBand2 - rollingVWAP : na, "Upper Band 2", stdevColor2)
p4 = plot(stdevMult2 != 0 ? lowerBand2 - rollingVWAP : na, "Lower Band 2", stdevColor2)
p5 = plot(stdevMult3 != 0 ? upperBand3 - rollingVWAP : na, "Upper Band 3", stdevColor3)
p6 = plot(stdevMult3 != 0 ? lowerBand3 - rollingVWAP : na, "Lower Band 3", stdevColor3)
p7 = plot(stdevMult3 != 0 ? upperBand4 - rollingVWAP : na, "Upper Band 4", stdevColor3)
p8 = plot(stdevMult3 != 0 ? lowerBand4 - rollingVWAP : na, "Lower Band 4", stdevColor3)
fill(p1, p2, color.new(color.green, 95), "Bands Fill", display = display.none)
fill(p3, p4, color.new(color.green, 95), "Bands Fill", display = display.none)
fill(p7, p0, upperBand4 - rollingVWAP, 0, top_color = color.new(#0095bb, 75), title = "Gradient Filling")
fill(p8, p0, lowerBand4 - rollingVWAP, 0, top_color = color.new(#ff0099, 75), title = "Gradient Filling")
|
Volume Entropy | https://www.tradingview.com/script/SSjZSyYY-Volume-Entropy/ | Uldisbebris | https://www.tradingview.com/u/Uldisbebris/ | 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/
// © Uldisbebris
//@version=5
indicator("Volume Entropy", overlay = false, format=format.price, precision=2, timeframe="", timeframe_gaps=true)
//Custom function for natural logarithm using Taylor Series
naturalLog(x, terms) =>
a = x - 1.0
sum = 0.0
for i = 1 to terms
term = math.pow(a, i) / i
sum := sum + (i % 2 != 0 ? term : -term)
sum
// Entropy
len = input.int(2, 'micro_pattern_len' )
micro_pattern_len = len
entropy(data) =>
p = ta.valuewhen(data, 1, 0) / math.sum(data, micro_pattern_len)
-p * naturalLog(p, 10)
LowEntropy = entropy(volume)
// Z-score normalization
lookback = input.int(20, 'Z-score normalization lookback')
mean_entropy = ta.sma(LowEntropy, lookback)
std_entropy = ta.stdev(LowEntropy, lookback)
z_score_entropy = (LowEntropy - mean_entropy) / std_entropy
// hline
hline(1.3)
hline(-1.3)
hline(0)
/// direction change for color
Dir = ta.change(-z_score_entropy) > 0 ? 1 : -1
Col = Dir == 1 ? color.new(#06a02c, 0) : Dir == -1 ? color.new(#94060d, 0) : color.gray
volplot = plot(-z_score_entropy, title='Smoothed and Scaled EMA', color = Col, linewidth = 2)
midLinePlot = plot(0, color = na, editable = false, display = display.none)
fill(volplot, midLinePlot, 2.5, 1, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(volplot, midLinePlot, -1.0,-4.0, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")
|
Monthly Range Support & Resistance [QuantVue] | https://www.tradingview.com/script/zjwJ5WmI-Monthly-Range-Support-Resistance-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 102 | 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/
// © QuantVue
//@version=5
indicator("Monthly Range Support & Resistance [QuantVue]", overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
//-----------------------------------------------//
//runtime errors
//-----------------------------------------------//
if (timeframe.in_seconds() / 60 < timeframe.in_seconds('60') / 60)
runtime.error('Please switch to 60 minute chart or higher')
//-----------------------------------------------//
//inputs
//-----------------------------------------------//
showTable = input.bool(true, 'Show Stats on Monthly Chart', inline = '1')
yPos = input.string("Top", " ", options = ["Top", "Middle", "Bottom"], inline = '1')
xPos = input.string("Right", " ", options = ["Right","Center", "Left"], inline = '1')
statsBG = input.color(color.gray, 'Stats Table BG Color', inline = '2')
statsText = input.color(color.white, 'Stats Table Text Color', inline = '2')
averagingPerdiod = input.int(7, 'Averaging Period', minval = 3, step = 1)
multiplier = input.float(1.0, 'StDev Multiplier', minval = .25, maxval = 4, step = .25)
sLineColor = input.color(color.blue, 'Support Color', inline = '3')
rLineColor = input.color(color.rgb(255, 17, 0), 'Resistance Color', inline = '3')
showFill = input.bool(true, 'Fill', inline = '3')
showPrice = input.bool(true, 'Show Support / Resistance Prices', inline = '4')
labelTextColor = input.color(color.white, ' ', inline = '4')
showWO = input.bool(true, 'Show Monthly Open Line', inline = '5')
wOColor = input.color(color.fuchsia, ' ', inline = '5')
r1Style = input.string('Solid', 'R1 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '6')
r2Style = input.string('Solid', 'R2 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '6')
s1Style = input.string('Solid', 'S1 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '7')
s2Style = input.string('Solid', 'S2 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '7')
showPrevious = input.bool(false, 'Show Previous Levls')
//-----------------------------------------------//
//methods
//-----------------------------------------------//
method switcher(string this) =>
switch this
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
//-----------------------------------------------//
//variables
//-----------------------------------------------//
var table stats = table.new(str.lower(yPos) + '_' + str.lower(xPos), 5, 4, border_color = color.new(color.white,100), border_width = 2,
frame_color = color.new(color.white,100), frame_width = 2)
var float[] upAvgArray = array.new<float>()
var float[] downAvgArray = array.new<float>()
var line r1Line = na, var line r2Line = na, var line s1Line = na, var line s2Line = na, var line WO = na
var label r1Label = na, var label r2Label = na, var label s1Label = na, var label s2Label = na, var label WOLabel = na
var box rFill = na, var box sFill = na
var monthCount = 0, var closeAboveR1 = 0, var closeAboveR2 = 0, var closeBelowS1 = 0, var closeBelowS2 = 0
var touchR1 = 0, var touchR2 = 0, var touchS1 = 0, var touchS2 = 0
var R1 = 0.0, var R2 = 0.0, var S1 = 0.0, var S2 = 0.0
var monthIndex = 0
[monthOpen, monthHigh, monthLow, monthClose] = request.security(syminfo.tickerid, 'M',[open,high,low,close], lookahead = barmerge.lookahead_on)
newmonth = ta.change(time('M'))
idxCount = ta.barssince(newmonth)
//-----------------------------------------------//
//calculations
//-----------------------------------------------//
up = newmonth ? 100 * ((monthHigh - monthOpen) / monthClose) : na
down = newmonth ? 100 * math.abs(((monthOpen - monthLow) / monthClose)) : na
upStdev = ta.stdev(up, averagingPerdiod) * multiplier
upSD = newmonth ? upStdev[1] : na
downStdev = ta.stdev(down, averagingPerdiod) * multiplier
downSd = newmonth ? downStdev[1] : na
if newmonth
if upAvgArray.size() > averagingPerdiod
upAvgArray.pop()
upAvgArray.unshift(up)
else
upAvgArray.unshift(up)
upAvg = upAvgArray.size() > 0 ? upAvgArray.avg() : na
if newmonth
if downAvgArray.size() > averagingPerdiod
downAvgArray.pop()
downAvgArray.unshift(down)
else
downAvgArray.unshift(down)
downAvg = downAvgArray.size() > 0 ? downAvgArray.avg() : na
if newmonth
monthIndex := bar_index
R1 := newmonth ? monthOpen + (upAvg / 100) * monthOpen : R1[1]
R2 := newmonth ? monthOpen + ((upAvg + upSD) / 100) * monthOpen : R2[1]
S1 := newmonth ? monthOpen - (downAvg / 100) * monthOpen : S1[1]
S2 := newmonth ? monthOpen - ((downAvg + downSd) / 100) * monthOpen : S2[1]
//-----------------------------------------------//
//daily stats
//-----------------------------------------------//
monthCount := newmonth ? monthCount + 1 : monthCount
if monthClose > R1
closeAboveR1 += 1
if monthClose > R2
closeAboveR2 += 1
if monthClose < S1
closeBelowS1 += 1
if monthClose < S2
closeBelowS2 += 1
if monthHigh >= R1
touchR1 += 1
if monthHigh >= R2
touchR2 += 1
if monthLow <= S1
touchS1 += 1
if monthLow <= S2
touchS2 += 1
closeInsideAvg = monthCount - closeAboveR1 - closeBelowS1
closeInsideAvgPlus = monthCount - closeAboveR2 - closeBelowS2
//-----------------------------------------------//
//daily stats table
//-----------------------------------------------//
if barstate.islast and showTable and yPos == 'Top' and timeframe.ismonthly
stats.cell(0,0, ' ')
stats.cell(0, 1, 'Touch R1: ' + str.tostring(touchR1) + ' / ' + str.tostring((touchR1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 1, 'Close > R1: ' + str.tostring(closeAboveR1) + ' / ' + str.tostring((closeAboveR1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 1, 'Touch R2: ' + str.tostring(touchR2) + ' / ' + str.tostring((touchR2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 1, 'Close > R2: ' + str.tostring(closeAboveR2) + ' / ' + str.tostring((closeAboveR2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(0, 2, 'Touch S1: ' + str.tostring(touchS1) + ' / ' + str.tostring((touchS1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 2, 'Close < S1: ' + str.tostring(closeBelowS1) + ' / ' + str.tostring((closeBelowS1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 2, 'Touch S2: ' + str.tostring(touchS2) + ' / ' + str.tostring((touchS2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 2, 'Close < S2: ' + str.tostring(closeBelowS2) + ' / ' + str.tostring((closeBelowS2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(4, 3, 'Months Analyzed: ' + str.tostring(monthCount), text_color = statsText, bgcolor = statsBG)
stats.cell(4, 1, 'Total Closes Inside R1/S1: ' + str.tostring(closeInsideAvg) + ' / ' + str.tostring((closeInsideAvg/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(4, 2, 'Total Closes Inside R2/S2: ' + str.tostring(closeInsideAvgPlus) + ' / ' + str.tostring((closeInsideAvgPlus/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
else if barstate.islast and showTable and timeframe.ismonthly
stats.cell(0, 0, 'Touch R1: ' + str.tostring(touchR1) + ' / ' + str.tostring((touchR1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 0, 'Close > R1: ' + str.tostring(closeAboveR1) + ' / ' + str.tostring((closeAboveR1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 0, 'Touch R2: ' + str.tostring(touchR2) + ' / ' + str.tostring((touchR2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 0, 'Close > R2: ' + str.tostring(closeAboveR2) + ' / ' + str.tostring((closeAboveR2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(0, 1, 'Touch S1: ' + str.tostring(touchS1) + ' / ' + str.tostring((touchS1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 1, 'Close < S1: ' + str.tostring(closeBelowS1) + ' / ' + str.tostring((closeBelowS1/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 1, 'Touch S2: ' + str.tostring(touchS2) + ' / ' + str.tostring((touchS2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 1, 'Close < S2: ' + str.tostring(closeBelowS2) + ' / ' + str.tostring((closeBelowS2/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(0, 2, 'Months Analyzed: ' + str.tostring(monthCount), text_color = statsText, bgcolor = statsBG)
stats.cell(1, 2, 'Total Closes Inside R1/S1: ' + str.tostring(closeInsideAvg) + ' / ' + str.tostring((closeInsideAvg/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 2, 'Total Closes Inside R2/S2: ' + str.tostring(closeInsideAvgPlus) + ' / ' + str.tostring((closeInsideAvgPlus/monthCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
//-----------------------------------------------//
//support and resistance levels
//-----------------------------------------------//
if newmonth and (syminfo.type == 'stock' or syminfo.type == 'fund' or syminfo.type == 'index')
(r1Line[1]).delete(), (r2Line[1]).delete(), (s1Line[1]).delete(), (s2Line[1]).delete()
(r1Label[1]).delete(), (r2Label[1]).delete(), (s1Label[1]).delete(), (s2Label[1]).delete()
(WO[1]).delete()
if showWO
WO := line.new(monthIndex, monthOpen, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((8190/ (str.tonumber(timeframe.period)))) :
monthIndex + 21, monthOpen, color = wOColor, width = 3)
r1Line := line.new(monthIndex, R1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, R1, color = rLineColor, width = 2, style = r1Style.switcher())
r2Line := line.new(monthIndex, R2, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, R2, color = rLineColor, width = 2, style = r1Style.switcher())
s1Line := line.new(monthIndex, S1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, S1, color = sLineColor, width = 2, style = s1Style.switcher())
s2Line := line.new(monthIndex, S2, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, S2, color = sLineColor, width = 2, style = s2Style.switcher())
if showPrice
r1Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 : timeframe.isdaily ? monthIndex + 21 :
timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
R1, 'R1 $' + str.tostring(R1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
r2Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 : timeframe.isdaily ? monthIndex + 21 :
timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
R2, 'R2 $' + str.tostring(R2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s1Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 : timeframe.isdaily ? monthIndex + 21 :
timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
S1, 'S1 $' + str.tostring(S1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s2Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 : timeframe.isdaily ? monthIndex + 21 :
timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
S2, 'S2 $' + str.tostring(S2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
if showFill
(sFill[1]).delete(), (rFill[1]).delete()
sFill := box.new(monthIndex, S1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, S2, border_width = 0, bgcolor = color.new(sLineColor,80))
rFill := box.new(monthIndex, R1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((8190 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, R2, border_width = 0, bgcolor = color.new(rLineColor,80))
else if newmonth and (syminfo.type == 'crypto' or syminfo.type == 'forex')
(r1Line[1]).delete(), (r2Line[1]).delete(), (s1Line[1]).delete(), (s2Line[1]).delete()
(r1Label[1]).delete(), (r2Label[1]).delete(), (s1Label[1]).delete(), (s2Label[1]).delete()
(WO[1]).delete()
if showWO
WO := line.new(monthIndex, monthOpen, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) :
monthIndex + 30, monthOpen, color = wOColor, width = 3)
r1Line := line.new(monthIndex, R1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) :
monthIndex + 30, R1, color = rLineColor, width = 2, style = r1Style.switcher())
r2Line := line.new(monthIndex, R2, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) :
monthIndex + 30, R2, color = rLineColor, width = 2, style = r2Style.switcher())
s1Line := line.new(monthIndex, S1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) :
monthIndex + 30, S1, color = sLineColor, width = 2, style = s1Style.switcher())
s2Line := line.new(monthIndex, S2, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) :
monthIndex + 30, S2, color = sLineColor, width = 2, style = s2Style.switcher())
if showPrice
r1Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) : monthIndex + 30,
R1, 'R1 $' + str.tostring(R1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
r2Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) : monthIndex + 30,
R2, 'R2 $' + str.tostring(R2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s1Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) : monthIndex + 30,
S1, 'S1 $' + str.tostring(S1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s2Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) : monthIndex + 30,
S2, 'S2 $' + str.tostring(S2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
if showFill
(sFill[1]).delete(), (rFill[1]).delete()
sFill := box.new(monthIndex, S1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) :
monthIndex + 30, S2, border_width = 0, bgcolor = color.new(sLineColor,80))
rFill := box.new(monthIndex, R1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 30 : timeframe.isminutes ? monthIndex + int((43200 / (str.tonumber(timeframe.period)))) :
monthIndex + 30, R2, border_width = 0, bgcolor = color.new(rLineColor,80))
else if newmonth and syminfo.type == 'cfd'
(r1Line[1]).delete(), (r2Line[1]).delete(), (s1Line[1]).delete(), (s2Line[1]).delete()
(r1Label[1]).delete(), (r2Label[1]).delete(), (s1Label[1]).delete(), (s2Label[1]).delete()
(WO[1]).delete()
if showWO
WO := line.new(monthIndex, monthOpen, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, monthOpen, color = wOColor, width = 3)
r1Line := line.new(monthIndex, R1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, R1, color = rLineColor, width = 2, style = r1Style.switcher())
r2Line := line.new(monthIndex, R2, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, R2, color = rLineColor, width = 2, style = r2Style.switcher())
s1Line := line.new(monthIndex, S1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, S1, color = sLineColor, width = 2, style = s1Style.switcher())
s2Line := line.new(monthIndex, S2, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, S2, color = sLineColor, width = 2, style = s2Style.switcher())
if showPrice
r1Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
R1, 'R1 $' + str.tostring(R1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
r2Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
R2, 'R2 $' + str.tostring(R2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s1Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
S1, 'S1 $' + str.tostring(S1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s2Label := label.new(timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) : monthIndex + 21,
S2, 'S2 $' + str.tostring(S2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
if showFill
(sFill[1]).delete(), (rFill[1]).delete()
sFill := box.new(monthIndex, S1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, S2, border_width = 0, bgcolor = color.new(sLineColor,80))
rFill := box.new(monthIndex, R1, timeframe.ismonthly ? monthIndex + 2 : timeframe.isweekly ? monthIndex + 5 :
timeframe.isdaily ? monthIndex + 21 : timeframe.isminutes ? monthIndex + int((30600 / (str.tonumber(timeframe.period)))) :
monthIndex + 21, R2, border_width = 0, bgcolor = color.new(rLineColor,80))
if showPrevious and showFill
sFill.set_left(bar_index), rFill.set_left(bar_index)
//-----------------------------------------------//
//show historical levels
//-----------------------------------------------//
fillColor = color.new(color.white,100)
r1Plot = plot(showPrevious ? R1 : na, color = color.rgb(253, 0, 0))
r2Plot = plot(showPrevious ? R2 : na, color = color.rgb(90, 0, 0))
s1Plot = plot(showPrevious ? S1 : na, color = color.rgb(0, 174, 255))
s2Plot = plot(showPrevious ? S2 : na, color = color.rgb(0, 86, 214))
woPlot = plot(showPrevious ? monthOpen : na, color = wOColor, style = plot.style_linebr)
fill(r1Plot, r2Plot, color = showFill ? color.new(rLineColor, 80) : fillColor)
fill(s1Plot, s2Plot, color = showFill ? color.new(sLineColor, 80) : fillColor)
//-----------------------------------------------//
//alert conditions
//-----------------------------------------------//
crossR1 = ta.crossover(close,R1)
crossR2 = ta.crossover(close,R2)
crossS1 = ta.crossunder(close,S1)
crossS2 = ta.crossunder(close,S2)
alertcondition(crossR1, 'Cross Above R1', 'Price crossing above R1')
alertcondition(crossR2, 'Cross Above R2', 'Price crossing above R2')
alertcondition(crossS1, 'Cross Below S1', 'Price crossing below S1')
alertcondition(crossS2, 'Cross Below S2', 'Price crossing below S2')
|
Colored EMA | https://www.tradingview.com/script/E0Tx9siD-Colored-EMA/ | Mateus_Rapini | https://www.tradingview.com/u/Mateus_Rapini/ | 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/
// © Mateus_Rapini
//@version=5
indicator("Colored EMA", overlay = true)
//Will draw an EMA with the specified length and with specific colors depending on
//whether it's a bullish or bearish trend.
// ––––– Input
ema_length = input.int(defval = 80, title = "EMA Length")
bullishColor = input.color(defval = color.new(color.white, 10), title = "Bullish Color")
bearishColor = input.color(defval = color.red, title = "Bearish Color")
// ––––– Calculations
ema = ta.ema(close, ema_length)
emaColor = ema < close ? bullishColor : bearishColor
// ––––– Visuals
plot(ema, title = "Colored EMA", color = emaColor, linewidth = 2)
|
Initial balance 3 Session | https://www.tradingview.com/script/2VmBhYxm-Initial-balance-3-Session/ | Vanitati | https://www.tradingview.com/u/Vanitati/ | 79 | 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/
// © Vanitati
//@version=5
indicator('Initial balance 3 Sessions with retests', shorttitle='Initial balance 3S', overlay=true)
// ---- GLOBAL CONSTANTS AND VARIABLES ----
is_allowed_timeframe = timeframe.isintraday and (timeframe.multiplier == 1 or timeframe.multiplier == 5 or timeframe.multiplier == 15 or timeframe.multiplier == 30)
var alert_triggered = false
var box[] imbalancedDownBoxes = array.new_box()
var box[] imbalancedUpBoxes = array.new_box()
var int[] imbalancedDownAges = array.new_int()
var int[] imbalancedUpAges = array.new_int()
extension = extend.right
// ---- INPUTS ----
// Session Time modifiers
showNYSession = input.bool(defval=true, title='NY', group='enable/disable sessions')
showLondonSession = input.bool(defval=true, title='London', group='enable/disable sessions')
showTokyoSession = input.bool(defval=true, title='Tokyo', group='enable/disable sessions')
NY_hour = input.int(defval=15, title='NY IB', minval=0, maxval=23, group='Initial balance hour offset')
London_hour = input.int(defval=10, title='London IB', minval=0, maxval=23, group='Initial balance hour offset')
Tokyo_hour = input.int(defval=2, title='Tokyo IB', minval=0, maxval=23, group='Initial balance hour offset')
// Initial Balance Settings
extendLines = input.bool(defval=false, title='Extend Lines', group='Initial balance settings')
onlyExtendNY = input.bool(defval=true, title='Only Extend NY Hour', group='Initial balance settings')
extendMidpointOnly = input.bool(defval=true, title='Only extend mid line', group='Initial balance settings')
showVertLine = input.bool(defval=true, title='Show Vertical Line', group='Initial balance settings')
extensionHours = input.int(defval=3, title='Extension Hours', minval=0, group='Initial balance settings')
highColor = input.color(defval=color.green, title='High Line', group='Initial balance settings')
lowColor = input.color(defval=color.red, title='Low Line', group='Initial balance settings')
midColor = input.color(defval=color.rgb(120, 134, 121), title='Midpoint Line', group='Initial balance settings')
vertLineColor = input.color(defval=color.blue, title='Vertical Line', group='Initial balance settings')
// Imbalance Settings
showImbalances = input.bool(defval=true, title='Show Imbalances', group='Imbalance settings')
penetrationRatio = input.float(defval=0.001, minval=0, maxval=1, step=0.1, title="Fill ratio", group="Imbalance settings")
imbalancedDownColor = input.color(color.rgb(120,120,120,60), title="Imbalance Below", group="Imbalance settings")
imbalancedUpColor = input.color(color.rgb(120,120,120,60), title="Imbalance above", group="Imbalance settings")
//Market session settings
NYbox = input.session(title='New York Box',group="Market session settings", defval='1500-0000')
Londonbox = input.session(title='London Box',group="Market session settings", defval='1000-1500')
Tokyobox = input.session(title='Tokyo Box',group="Market session settings", defval='0200-1000')
LondonBGC = input(title='London',group="Market session settings", defval=color.new(#40f7f7, 92))
NYBGC = input(title='NY',group="Market session settings", defval=color.new(#ff412c, 92))
TokyoBGC = input(title='Tokyo',group="Market session settings", defval=color.new(#fc39ff, 92))
// ---- UTILITY FUNCTIONS ----
isWithinHour(session_hour) =>
current_hour = hour(time)
current_hour == session_hour
hourlyOpen = request.security(syminfo.tickerid, "60", open)
hourlyClose = request.security(syminfo.tickerid, "60", close)
isWithinAnySession = isWithinHour(London_hour) or isWithinHour(NY_hour) or isWithinHour(Tokyo_hour)
// ---- MAIN LOGIC FOR INITIAL BALANCE ----
draw_lines_for_hour(hour, session_name) =>
hourly_high = request.security(syminfo.tickerid, '60', high)
hourly_low = request.security(syminfo.tickerid, '60', low)
hourly_hour = request.security(syminfo.tickerid, '60', hour)
current_minute = minute(time)
is_live_bar = barstate.isrealtime
closing_selected_hour = is_live_bar ? hourly_hour == hour + 1 and hourly_hour[1] == hour : hourly_hour[1] == hour and hourly_hour[2] != hour
// Calculate the extension in candles based on timeframe
extensionCandles = extensionHours * 60 / timeframe.multiplier
if current_minute > 0 and current_minute < 60 and hourly_hour == hour + 1
na
else
var float captured_high = na
var float captured_low = na
if closing_selected_hour
captured_high := hourly_high[1]
captured_low := hourly_low[1]
midpoint = (captured_high + captured_low) / 2
endPointHighLow = extendLines and (not onlyExtendNY or (onlyExtendNY and hour == NY_hour)) ? bar_index + extensionCandles : bar_index
endPointMid = (extendLines or extendMidpointOnly) and (not onlyExtendNY or (onlyExtendNY and hour == NY_hour)) ? bar_index + extensionCandles : bar_index
if closing_selected_hour
length = timeframe.multiplier == 1 ? 61 : timeframe.multiplier == 5 ? 13 : timeframe.multiplier == 15 ? 5 : timeframe.multiplier == 30 ? 3 : 0
line.new(x1=bar_index - length + 1, y1=captured_high, x2=endPointHighLow, y2=captured_high, color=highColor, width=1)
line.new(x1=bar_index - length + 1, y1=captured_low, x2=endPointHighLow, y2=captured_low, color=lowColor, width=1)
line.new(x1=bar_index - length + 1, y1=midpoint, x2=endPointMid, y2=midpoint, color=midColor, width=1, style=line.style_dotted)
label.new(x=bar_index - length + 1, y=captured_high, text=session_name, color=color.rgb(255, 255, 255, 100), textcolor=color.rgb(255, 255, 255, 4), size=size.small)
line.new(x1=bar_index - length + 1, y1=captured_high, x2=bar_index - length + 1, y2=captured_low, color=vertLineColor, width=1, style=line.style_dotted)
line.new(x1=bar_index, y1=captured_high, x2=bar_index, y2=captured_low, color=vertLineColor, width=1, style=line.style_dotted)
// ---- MAIN LOGIC FOR IMBALANCES----
// Define age limits based on timeframe
var int age_limit = 0
if (timeframe.multiplier == 1)
age_limit := 2000
else if (timeframe.multiplier == 5)
age_limit := 500
// ---- UTILITY FUNCTIONS FOR IMBALANCES ----
drawImbalance() =>
if high[3] < low[1]
array.push(imbalancedDownBoxes, box.new(left=bar_index - 2, bottom=high[3], right=bar_index - 1, top=low[1], bgcolor=imbalancedDownColor, border_color=imbalancedDownColor, extend=extension))
array.push(imbalancedDownAges, 0)
if low[3] > high[1]
array.push(imbalancedUpBoxes, box.new(left=bar_index - 2, top=low[3], right=bar_index - 1, bottom=high[1], bgcolor=imbalancedUpColor, border_color=imbalancedUpColor, extend=extension))
array.push(imbalancedUpAges, 0)
// Imbalance session filtering within global time
if not barstate.isrealtime and showImbalances
if isWithinHour(London_hour) and showLondonSession
drawImbalance()
if isWithinHour(NY_hour) and showNYSession
drawImbalance()
if isWithinHour(Tokyo_hour) and showTokyoSession
drawImbalance()
// Imbalance Boxes Logic
if array.size(imbalancedUpBoxes) > 0
for i = array.size(imbalancedUpBoxes) - 1 to 0 by 1
imbalancedBox = array.get(imbalancedUpBoxes, i)
top = box.get_top(imbalancedBox)
bottom = box.get_bottom(imbalancedBox)
invalidationLimit = (top - bottom) * penetrationRatio
age = array.get(imbalancedUpAges, i)
if high >= bottom + invalidationLimit or high >= top or age > age_limit
box.delete(imbalancedBox)
array.remove(imbalancedUpBoxes, i)
array.remove(imbalancedUpAges, i)
else
array.set(imbalancedUpAges, i, age + 1)
if array.size(imbalancedDownBoxes) > 0
for i = array.size(imbalancedDownBoxes) - 1 to 0 by 1
imbalancedBox = array.get(imbalancedDownBoxes, i)
top = box.get_top(imbalancedBox)
bottom = box.get_bottom(imbalancedBox)
invalidationLimit = (top - bottom) * penetrationRatio
age = array.get(imbalancedDownAges, i)
if low <= top - invalidationLimit or low <= bottom or age > age_limit
box.delete(imbalancedBox)
array.remove(imbalancedDownBoxes, i)
array.remove(imbalancedDownAges, i)
else
array.set(imbalancedDownAges, i, age + 1)
//----MAIN LOGIC FOR SESSION BOXES----
is_newbar(sess) =>
t = time('D', sess)
na(t[1]) and not na(t) or t[1] < t
is_session(sess) =>
not na(time('D', sess))
processSession(sess, bgColor) =>
newbar = is_newbar(sess)
session = is_session(sess)
if session
lowValue = float(na)
lowValue := if session
if newbar
low
else
math.min(lowValue[1], low)
else
lowValue[1]
highValue = float(na)
highValue := if session
if newbar
high
else
math.max(highValue[1], high)
else
highValue[1]
startValue = int(na)
startValue := if session
if newbar
time
else
math.min(startValue[1], time)
else
na
endValue = int(na)
endValue := if session
if newbar
time_close
else
math.max(endValue[1], time_close)
else
na
sessBox = if newbar
box.new(left=startValue, bottom=lowValue, right=endValue, top=highValue, xloc=xloc.bar_time, border_style=line.style_solid, border_color=bgColor, bgcolor=bgColor)
if not newbar
box.set_right(sessBox[1], endValue)
box.set_top(sessBox[1], highValue)
box.set_bottom(sessBox[1], lowValue)
//Drawing session Boxes
if showLondonSession
processSession(Londonbox, LondonBGC)
if showNYSession
processSession(NYbox, NYBGC)
if showTokyoSession
processSession(Tokyobox, TokyoBGC)
// Drawing Session Lines
if is_allowed_timeframe
if showNYSession
draw_lines_for_hour(NY_hour, 'New York')
if showLondonSession
draw_lines_for_hour(London_hour, 'London')
if showTokyoSession
draw_lines_for_hour(Tokyo_hour, 'Tokyo') |
BDL Range Alert | https://www.tradingview.com/script/28HXt9Q5-BDL-Range-Alert/ | The_Chart_Guru | https://www.tradingview.com/u/The_Chart_Guru/ | 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/
// © The_Chart_Guru
// @version=5
indicator(title="BDL Range Alert", overlay=true)
// User input
bottomrangeBreakout = input.price(title="Set the Range Low", defval=0.0, confirm=true)
toprangeBreakout = input.price(title="Set Range High", defval=0.0, confirm=true)
// Breakout detection
bottomAlert = bottomrangeBreakout > 0 and close < bottomrangeBreakout
topAlert = toprangeBreakout > 0 and close > toprangeBreakout
// Plots
plot(bottomrangeBreakout > 0 ? bottomrangeBreakout : na, title="Bottom Range Breakout", color=color.rgb(250, 8, 8), offset=9, linewidth=2)
plot(toprangeBreakout > 0 ? toprangeBreakout : na, title="Top Range Breakout", color=color.rgb(4, 250, 13), offset=9, linewidth=2)
// The alerts
alertcondition(bottomAlert, title="Bottom Range Breakout!", message="Bottom breakout for {{ticker}}")
alertcondition(topAlert, title="Top Range Breakout!", message="Top breakout signal for {{ticker}}")
alertcondition(topAlert or bottomAlert, title="Range Breakout!", message="Breakout signal for {{ticker}}") |
Pivot Points [MisterMoTA] | https://www.tradingview.com/script/LEDYPCEi-Pivot-Points-MisterMoTA/ | MisterMoTA | https://www.tradingview.com/u/MisterMoTA/ | 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/
// @author = MisterMoTA
// © MisterMoTA
//@version=5
indicator('Pivot points [MisterMoTA]', overlay = true)
i_res = input.timeframe("D", "Choose the timeframe for pivots calculation", options=["1", "2", "3", "5", "15", "30", "45", "60", "120", "180", "240", "360", "480", "720", "D", "W", "M"], group = "Pivot Points Settings")
decimals = input.int(2, "Decimals for price displayed in Labels", maxval = 8, group = "Pivot Points Settings")
styleOption = input.string("solid (─)", title="Line Style",
options=["solid (─)", "dotted (┈)", "dashed (╌)",
"arrow left (←)", "arrow right (→)", "arrows both (↔)"], group = "Pivot Points Settings")
lineStyle = styleOption == "dotted (┈)" ? line.style_dotted :
styleOption == "dashed (╌)" ? line.style_dashed :
styleOption == "arrow left (←)" ? line.style_arrow_left :
styleOption == "arrow right (→)" ? line.style_arrow_right :
styleOption == "arrows both (↔)" ? line.style_arrow_both :
line.style_solid
hideLabels = input.bool(false, title="Show/Hide Pivot Labels", group = "Pivot Points Settings")
plotPivotPoints = input.bool(true, title = "Show Current Pivot Points", group = "Pivot Points Settings")
oldPivotPoints = input.bool(true, title = "Show Old Pivot Points", group = "Pivot Points Settings")
mainPivotColor = input.color(color.new(#1df10e, 0), "Main Pivot Color", inline="Main Pivot Color", group = "Pivot Points Settings")
r1color = input.color(color.new(#fae606, 0), "R1 Support Color", group = "Pivot Points Settings")
r2color = input.color(color.new(#41b4fc, 0), "R2 Support Color", group = "Pivot Points Settings")
r3color = input.color(color.new(#f37221, 5), "R3 Support Color", group = "Pivot Points Settings")
r4color = input.color(color.new(color.red, 0), "R4 Support Color", group = "Pivot Points Settings")
r5color = input.color(color.new(#d30755, 0), "R5 Support Color", group = "Pivot Points Settings")
s1color = input.color(color.new(#fae606, 0), "S1 Support Color", group = "Pivot Points Settings")
s2color = input.color(color.new(#41b4fc, 0), "S2 Support Color", group = "Pivot Points Settings")
s3color = input.color(color.new(#04ac0a, 0), "S3 Support Color", group = "Pivot Points Settings")
s4color = input.color(color.new(#048008, 0), "S4 Support Color", group = "Pivot Points Settings")
s5color = input.color(color.new(#025b05, 0), "S5 Support Color", group = "Pivot Points Settings")
var string decs =na
if decimals == 0
decs := "#"
else if decimals == 1
decs :="#.#"
else if decimals == 2
decs := "#.##"
else if decimals == 3
decs :="#.###"
else if decimals == 4
decs :="#.####"
else if decimals == 5
decs :="#.#####"
else if decimals == 6
decs :="#.######"
else if decimals == 7
decs :="#.#######"
else if decimals == 8
decs :="#.########"
//Pivot points
var topLine = line.new(x1=na, y1=na, x2=na, y2=na, color=color.rgb(76, 175, 79, 5), style=lineStyle, width=2)
var bottomLine = line.new(x1=na, y1=na, x2=na, y2=na, color=color.rgb(255, 82, 82, 5), style=lineStyle, width=2)
var mainPivot = line.new(x1=na, y1=na, x2=na, y2=na, color=mainPivotColor, style=lineStyle, width=1)
var sup1 = line.new(x1=na, y1=na, x2=na, y2=na, color=s1color, style=lineStyle, width=1)
var sup2 = line.new(x1=na, y1=na, x2=na, y2=na, color=s2color, style=lineStyle, width=1)
var supp3 = line.new(x1=na, y1=na, x2=na, y2=na, color=s3color, style=lineStyle, width=1)
var supp4 = line.new(x1=na, y1=na, x2=na, y2=na, color=s4color, style=lineStyle, width=1)
var supp5 = line.new(x1=na, y1=na, x2=na, y2=na, color=s5color, style=lineStyle, width=1)
var ress1 = line.new(x1=na, y1=na, x2=na, y2=na, color=r1color, style=lineStyle, width=1)
var ress2 = line.new(x1=na, y1=na, x2=na, y2=na, color=r2color, style=lineStyle, width=1)
var res3 = line.new(x1=na, y1=na, x2=na, y2=na, color=r3color, style=lineStyle, width=1)
var res4 = line.new(x1=na, y1=na, x2=na, y2=na, color=r4color, style=lineStyle, width=1)
var res5 = line.new(x1=na, y1=na, x2=na, y2=na, color=r5color, style=lineStyle, width=1)
Val_high = request.security(syminfo.tickerid, i_res, high[1])
Val_low = request.security(syminfo.tickerid, i_res, low[1])
dclose = request.security(syminfo.tickerid, i_res, close[1])
PivotPoint = (Val_high + Val_low + dclose ) / 3
R1 = PivotPoint * 2 -Val_low
R2 = PivotPoint + (Val_high -Val_low)
R3 = PivotPoint * 2 + (Val_high - 2 * Val_low)
R4 = PivotPoint * 3 + (Val_high - 3 * Val_low)
R5 = PivotPoint * 4 + (Val_high - 4 * Val_low)
S1 = PivotPoint * 2 - Val_high
S2 = PivotPoint - (Val_high -Val_low)
S3 = PivotPoint * 2 - (2 * Val_high - Val_low)
S4 = PivotPoint * 3 - (3 * Val_high - Val_low)
S5 = PivotPoint * 4 - (4 * Val_high - Val_low)
if plotPivotPoints
line.set_xy1(id=topLine, x= bar_index, y=Val_high)
line.set_xy2(id=topLine, x= bar_index+50, y=Val_high)
line.set_xy1(id=bottomLine, x=bar_index, y=Val_low)
line.set_xy2(id=bottomLine, x= bar_index+50, y=Val_low)
line.set_xy1(id=mainPivot, x= bar_index, y=PivotPoint)
line.set_xy2(id=mainPivot, x= bar_index+50, y=PivotPoint)
line.set_xy1(id=sup1, x= bar_index, y=S1)
line.set_xy2(id=sup1, x= bar_index+50, y=S1)
line.set_xy1(id=sup2, x= bar_index, y=S2)
line.set_xy2(id=sup2, x= bar_index+50, y=S2)
line.set_xy1(id=supp3, x= bar_index, y=S3)
line.set_xy2(id=supp3, x= bar_index+50, y=S3)
line.set_xy1(id=supp4, x= bar_index, y=S4)
line.set_xy2(id=supp4, x= bar_index+50, y=S4)
line.set_xy1(id=supp5, x= bar_index, y=S5)
line.set_xy2(id=supp5, x= bar_index+50, y=S5)
line.set_xy1(id=ress1, x= bar_index, y=R1)
line.set_xy2(id=ress1, x= bar_index+50, y=R1)
line.set_xy1(id=ress2, x= bar_index, y=R2)
line.set_xy2(id=ress2, x= bar_index+50, y=R2)
line.set_xy1(id=res3, x= bar_index, y=R3)
line.set_xy2(id=res3, x= bar_index+50, y=R3)
line.set_xy1(id=res4, x= bar_index, y=R4)
line.set_xy2(id=res4, x= bar_index+50, y=R4)
line.set_xy1(id=res5, x= bar_index, y=R5)
line.set_xy2(id=res5, x= bar_index+50, y=R5)
z = plot(oldPivotPoints ? PivotPoint: na, color=color.new(#1df10e, 65), style=plot.style_circles, title=' Mean Pivot', linewidth=1, display = display.pane)
x1 = plot(oldPivotPoints ? R1: na, color=r1color, style=plot.style_circles, title=' R1', linewidth=1, display = display.pane)
x2 = plot(oldPivotPoints ? S1: na, color=s1color, style=plot.style_circles, title=' S1', linewidth=1, display = display.pane)
y1 = plot(oldPivotPoints ? R2: na, color=r2color, style=plot.style_circles, title=' R2', linewidth=1, display = display.pane)
y2 = plot(oldPivotPoints ? S2: na, color=s2color, style=plot.style_circles, title=' S2', linewidth=1, display = display.pane)
y3 = plot(oldPivotPoints ? S3: na, color=s3color, style=plot.style_circles, title=' S3', linewidth=1, display = display.pane)
x3 = plot(oldPivotPoints ? R3: na, color=r3color, style=plot.style_circles, title=' R3', linewidth=1, display = display.pane)
y4 = plot(oldPivotPoints ? S4: na, color=s4color, style=plot.style_circles, title=' S4', linewidth=1, display = display.pane)
x4 = plot(oldPivotPoints ? R4: na, color=r4color, style=plot.style_circles, title='R4', linewidth=1, display = display.pane)
y5 = plot(oldPivotPoints ? S5: na, color=s5color, style=plot.style_circles, title='S5', linewidth=1, display = display.pane)
x5 = plot(oldPivotPoints ? R5: na, color=r5color, style=plot.style_circles, title='R5', linewidth=1, display = display.pane)
if hideLabels == false
l0 = label.new( bar_index+50, Val_high, str.tostring(Val_high, decs) + " is Last Candle High at " + i_res, color=#00000000, textcolor=color.green, style=label.style_label_left, size=size.normal)
l10 = label.new( bar_index+50, Val_low, str.tostring(Val_low, decs) + " is Last Candle Low at " + i_res, color=#00000000, textcolor=color.red, style=label.style_label_left, size=size.normal)
label.delete(l0[1])
label.delete(l10[1])
lm = label.new( bar_index+50, PivotPoint, 'Main Pivot : ' + str.tostring(PivotPoint, decs), color=#00000000, textcolor=mainPivotColor, style=label.style_label_left, size=size.normal)
l1 = label.new( bar_index+50, S1, 'S1 : ' + str.tostring(S1, decs), color=#00000000, textcolor=s1color, style=label.style_label_left, size=size.normal)
l2 = label.new( bar_index+50, S2, 'S2 : ' + str.tostring(S2, decs), color=#00000000, textcolor=s2color, style=label.style_label_left, size=size.normal)
l3 = label.new( bar_index+50, S3, 'S3 pivot is ' + str.tostring(S3, decs), color=#00000000, textcolor=s3color, style=label.style_label_left, size=size.normal)
l4 = label.new( bar_index+50, S4, 'S4 pivot is ' + str.tostring(S4, decs), color=#00000000, textcolor=s4color, style=label.style_label_left, size=size.normal)
l5 = label.new( bar_index+50, S5, 'S5 pivot is ' + str.tostring(S5, decs), color=#00000000, textcolor=s5color, style=label.style_label_left, size=size.normal)
r11 = label.new( bar_index+50, R1, 'R1 : ' + str.tostring(R1, decs), color=#00000000, textcolor=r1color, style=label.style_label_left,size=size.normal)
r22 = label.new( bar_index+50, R2, 'R2 : ' + str.tostring(R2, decs), color=#00000000, textcolor=r2color, style=label.style_label_left, size=size.normal)
r33 = label.new( bar_index+50, R3, 'R3 pivot is ' + str.tostring(R3, decs), color=#00000000, textcolor=r3color, style=label.style_label_left, size=size.normal)
r44 = label.new( bar_index+50, R4, 'R4 pivot is ' + str.tostring(R4, decs), color=#00000000, textcolor=r4color, style=label.style_label_left, size=size.normal)
r55 = label.new( bar_index+50, R5, 'R5 pivot is ' + str.tostring(R5, decs), color=#00000000, textcolor=r5color, style=label.style_label_left, size=size.normal)
label.delete(lm[1])
label.delete(l1[1])
label.delete(l2[1])
label.delete(l3[1])
label.delete(l4[1])
label.delete(l5[1])
label.delete(r11[1])
label.delete(r22[1])
label.delete(r33[1])
label.delete(r44[1])
label.delete(r55[1]) |
Volume HeatMap With Profile [ChartPrime] | https://www.tradingview.com/script/fASgK4y1-Volume-HeatMap-With-Profile-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 402 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Volume HeatMap With Profile [ChartPrime]",overlay = true,max_bars_back = 3000,max_boxes_count =500,max_lines_count = 500 )
string VISUAL = "➞ Visuals Settings🔸"
string CORE = "➞ Main Core Settings 🔸"
bool showVol = input.bool(false,"Show Volume",inline = "01",group = CORE)
color Bull = input.color(#1f5c03,"",inline = "01",group = CORE)
color Bear = input.color(#7a0808,"",inline = "01",group = CORE)
int levs = input.int(23," Volume Levels",tooltip = "Number of the Volume levels to check", group = CORE)
string Voldata = input.string("All",title = " Volume Type",
group = CORE,
options=["Bear","Bull","All","Points"],
tooltip = "Choose Volume Type to Show in Boxes")
bool Place = input.string("Left",title = " Placement",
group = CORE,
options=["Right","Left"],
tooltip = "Choose Volume Type to Show in Boxes") == "Left"
bool showHeat = input.bool(true,"Show HeatMap",group = CORE,inline = "!")
color Heat1Col = input.color(#13172233,"",inline = "!",group = CORE)
color Heat2Col = input.color(color.rgb(245, 127, 23, 80),"",inline = "!",group = CORE)
bool extend = input.bool(false,title = "Extend Right", group = CORE)
bool ShowPOC = input.bool(false,"Show POC",group = CORE,inline = "03")
color POCcol = input.color(#586161,"",group = CORE,inline = "03")
bool SHowVWAP = input.bool(false,"Show VWAP POC",group = CORE,inline = "04")
color VWAPcol = input.color(#586161,"",group = CORE,inline = "04")
bool showforcast = input.bool(false,"Show Forecasted Zone",group = CORE,inline = "!@")
color Forcol = input.color(color.orange,"",group = CORE,inline = "!@")
int StartTime = input.time(timestamp('01 Aug 2023 00:00 +0000'),
"Start",
confirm = true,
group = "Calculation Points")
int EndTime = input.time(timestamp('31 Dec 2080 00:00 +0000'),
"End",
confirm = true,
group = "Calculation Points")
var Start = int(na)
var End = int(na)
var COUNT = int(na)
//
type Colors
color Red
color offRed
color Green
color offGreen
color CHART
type Vol
array<float> Total
array<float> GreenV
array<float> RedV
array<float> GreenP
array<float> RedP
array<float> HIGHES
array<float> LOWS
array<float> SCR
array<float> VWAP
type Drawing
array<box> LevelsBOX
array<label> LvLabels
array<float> VPlevels
array<box> VPboxes
array<line> VPlines
array<line> Forecasting
array<linefill> Fills
Colors = Colors.new(
color.rgb(255, 82, 82, 85),
color.rgb(243, 6, 6, 50),
color.rgb(73, 241, 241, 85),
color.rgb(73, 241, 241, 50),
chart.fg_color
)
VolS = Vol.new(
array.new_float(),
array.new_float(),
array.new_float(),
array.new_float(),
array.new_float(),
array.new_float(),
array.new_float(),
array.new_float(),
array.new_float()
)
var Draw = Drawing.new(
array.new_box(5),
array.new_label(2),
array.new_float(levs+1),
array.new_box(levs+3),
array.new_line(levs),
array.new_line(),
array.new_linefill(levs)
)
method _Band(int len)=>
math.min (ta.atr (len) * 0.3, close * (0.3/100)) [20] /2
band = _Band(30)
method Volume(float Z,float X,float Q,float W)=>
GR = Z / Q
RR = X / Q
GI = int(GR * W)
RI = int(RR * W)
[GI , RI , GR , RR]
if (time == StartTime)
Start := bar_index
if (time == EndTime)
End := bar_index
ExBar = extend ? bar_index : End
ExTime = extend ? time : EndTime
COUNT:= math.abs(Start - ExBar)
if extend ? barstate.islast: bar_index == End
// max_bars_back(ExBar,3000)
// max_bars_back(COUNT,3000)
int [] Points = array.new_int(levs,0)
int [] BullP = array.new_int(levs,0)
int [] BearP = array.new_int(levs,0)
float [] Volumes = array.new_float(levs,0.0)
float [] BUllV = array.new_float(levs,0.0)
float [] BEARV = array.new_float(levs,0.0)
for i = 0 to COUNT -1
VolS.HIGHES.push(high[i])
VolS.LOWS.push(low[i])
VolS.SCR.push(close[i])
VolS.VWAP.push(ta.vwap[i])
step = (VolS.HIGHES.max()-VolS.LOWS.min() ) / levs
for i=0 to levs by 1
array.set(Draw.VPlevels,i, VolS.LOWS.min() + step * i)
if VolS.SCR.size() == 0
runtime.error("Please reconfigure the start and end points")
for i=0 to array.size(VolS.SCR) -1
for x=0 to array.size(Draw.VPlevels) - 2 by 1
//if VolS.VWAP.median() > VPlevels.get(i) and VolS.VWAP.median() < VPlevels.get(i+1)
if array.get(VolS.SCR,i)>array.get(Draw.VPlevels,x)
and
array.get(VolS.SCR,i)<array.get(Draw.VPlevels,x+1)
array.set(Points,x,array.get(Points,x)+1)
array.set(Volumes,x,array.get(Volumes,x)+volume[x])
if array.get(VolS.SCR,i) > open[i]
array.set(BUllV,x,array.get(BUllV,x)+volume[x])
if array.get(VolS.SCR,i) < open[i]
array.set(BEARV,x,array.get(BEARV,x)+volume[x])
break
if array.get(VolS.SCR,i) > open[i]
array.push(VolS.GreenV,volume[i])
if array.get(VolS.SCR,i) < open[i]
array.push(VolS.RedV,volume[i])
array.push(VolS.Total,volume[i])
//Gradient(Points)
// label.new(bar_index,low,str.tostring(Points.median()))
[GI,RI,GR,RR ] = Volume(array.sum(VolS.GreenV),
array.sum(VolS.RedV),
array.sum(VolS.Total),
array.size(VolS.SCR) -1)
if showVol
for i = 0 to array.size(Points) -1
str = ""
if array.get(Volumes,i) > 0
str := Voldata == "All" ? str.tostring(array.get(Volumes,i),format.volume)
: Voldata == "Bear" ? str.tostring(array.get(BEARV,i),format.volume):
Voldata == "Points" ? str.tostring(array.get(Points,i),format.volume) :
str.tostring(array.get(BUllV,i),format.volume)
box.delete(array.get(Draw.VPboxes,i))
array.set(Draw.VPboxes,i,
box.new(Place ? Start + array.get(Points,i) : ExBar - array.get(Points,i),
array.get(Draw.VPlevels,i+1),
Place ? Start : ExBar,
array.get(Draw.VPlevels,i),
border_color = color.from_gradient(array.get(Points,i),0,
array.max(Points),
Bear,
Bull),
bgcolor=color.from_gradient(array.get(Points,i),0,
array.max(Points),
Bear,
Bull),
text=str,
text_color=Colors.CHART,
text_size = size.normal,
text_valign = text.align_center,
text_halign = Place ? text.align_left : text.align_right
))
// for i=0 to array.size(VolS.SCR) -1
// for Z=0 to array.size(Draw.VPlevels) -2
// box.new(Start+i,Draw.VPlevels.get(Z+1),Start+i+10,Draw.VPlevels.get(Z),bgcolor = color.from_gradient(array.get(Points,Z),0,array.max(Points),Bear,Bull))
// rand = math.random(10,50)
// num = 0
// // for i=0 to int(ExBar - Start / 10) -1
// Size = (Draw.VPlevels.size() - 1 )* 2
// for Z = 0 to int(VolS.SCR.size() / (Draw.VPlevels.size() -2)) -2
// for X = 0 to Draw.VPlevels.size() -2
// box.new(Start + num,Draw.VPlevels.get(X),Start + num + 20,Draw.VPlevels.get(X+1),bgcolor = color.from_gradient(array.get(Points,X) + rand ,0,array.max(Points),Bull,Bear),border_color = color.rgb(161, 122, 24, 37),xloc = xloc.bar_index)
// num+=Size
// line.new(Start,array.get(Draw.VPlevels,4),End, array.get(Draw.VPlevels,4),color = color.red)
// line.new(Start,array.get(Draw.VPlevels,5),End, array.get(Draw.VPlevels,5),color = color.rgb(82, 255, 94))
if showforcast
sort = Points.copy()
rand = math.random(10,50)
num = 0
Size = (Draw.VPlevels.size() - 1 )* 2
for i = 0 to 10 by 2
sort.sort(order.descending)
idx = Points.indexof(sort.get(i))
// for Z = 0 to int(VolS.SCR.size() / (Draw.VPlevels.size() -2)) -2
// box.new(Start + num,Draw.VPlevels.get(idx),Start + num + 20,Draw.VPlevels.get(idx+1),bgcolor = color.from_gradient(array.get(Points,idx) + rand ,0,array.max(Points),Bull,Bear),border_color = color.rgb(161, 122, 24, 37),xloc = xloc.bar_index)
// num+=Size
// box.new(ExBar,array.get(Draw.VPlevels,idx),ExBar + 1 , array.get(Draw.VPlevels,idx+1),bgcolor = color.from_gradient(array.get(Points,idx) ,0,array.max(Points),Bull,Bear),border_color = color.rgb(161, 122, 37, 37),xloc = xloc.bar_index,extend = extend.right)
Draw.Forecasting.push(
line.new(ExBar,
array.get(Draw.VPlevels,idx),
ExBar + 1 ,
array.get(Draw.VPlevels,idx),
color = Forcol,
extend = extend.right,
style = line.style_dashed
))
if Draw.Forecasting.size() > 6
for i = 0 to 5
line.delete(Draw.Forecasting.shift())
if showHeat
for i = 0 to array.size(Points) -1
line.delete(Draw.VPlines.get(i))
Draw.VPlines.set(i,
line.new(showVol ? Start + Points.get(i): Start,
array.get(Draw.VPlevels,i),
ExBar,
array.get(Draw.VPlevels,i),
color =color.new(color.black,100)
))
for Z = 0 to Draw.VPlines.size() -2
linefill.delete(Draw.Fills.get(Z))
Draw.Fills.set(Z,
linefill.new(array.get(Draw.VPlines,Z),
array.get(Draw.VPlines,Z+1),
color= color.from_gradient(array.get(Points,Z),
0,
array.max(Points),Heat1Col,Heat2Col)
))
if ShowPOC
var box POC = na , box.delete(POC)
MaxVID = Volumes.indexof(Volumes.max())
POC:= box.new(
Start,
Draw.VPlevels.get(MaxVID),
ExBar,Draw.VPlevels.get(MaxVID+1),
color.new(POCcol,50),
border_style=line.style_solid,
bgcolor=color.new(POCcol,50),
text="POC",
text_color=Colors.CHART,
text_halign = text.align_center,
text_valign = text.align_center,
xloc=xloc.bar_index,
text_size = size.normal)
if SHowVWAP
var vwaplebel = float(na)
for i = 0 to Draw.VPlevels.size() - 2
if VolS.VWAP.median() > Draw.VPlevels.get(i)
and
VolS.VWAP.median() < Draw.VPlevels.get(i+1)
vwaplebel := Draw.VPlevels.get(i)
break
var box VWAPBox = na , box.delete(VWAPBox)
GIndex = Draw.VPlevels.indexof(vwaplebel)
VWAPBox:= box.new(
Start,
vwaplebel ,
ExBar,
Draw.VPlevels.get(GIndex+1),
color.new(VWAPcol,50),
border_style=line.style_solid,
bgcolor=color.new(VWAPcol, 70),
text="VWAP",
text_color=Colors.CHART,
text_halign = text.align_center,
text_valign = text.align_center,
xloc=xloc.bar_index,
text_size = size.normal
)
var box BOX = na , box.delete(BOX)
Draw.LevelsBOX.push(box.new(StartTime,
VolS.HIGHES.max(),
ExTime,
VolS.LOWS.min(),
bgcolor = color.new(Colors.CHART,91),
border_color = color.new(Colors.CHART,100),
xloc = xloc.bar_time
))
Draw.LevelsBOX.push(box.new(StartTime,
VolS.HIGHES.max()+ (band*4),
ExTime,
VolS.HIGHES.max(),
bgcolor = color.new(Heat2Col,85),
border_color =color.new(Heat2Col,50),
border_width = 1,xloc=xloc.bar_time
))
Draw.LevelsBOX.push(box.new(StartTime,
VolS.LOWS.min(),
ExTime,
VolS.LOWS.min()- (band*4),
bgcolor = color.new(Heat2Col,85),
border_color =color.new(Heat2Col,50),
border_width = 1,xloc=xloc.bar_time
))
Draw.LevelsBOX.push(box.new(Start,
VolS.HIGHES.max()+ (band*4),
Start + RI,
VolS.HIGHES.max(),
bgcolor = color.new(Colors.CHART,70),
border_color =color.new(Colors.CHART,50),
border_width = 1,
text = "Bear Volume", // bear
text_size = size.normal,
text_color = Colors.CHART
))
Draw.LevelsBOX.push(box.new(Start,
VolS.LOWS.min(),
Start + GI,
VolS.LOWS.min()- (band*4),
bgcolor = color.new(Colors.CHART,70),
border_color =color.new(Colors.CHART,50),
border_width = 1,
text = "Bull Volume",// Bull
text_size = size.normal,
text_color = Colors.CHART
))
Draw.LvLabels.push(
label.new(Start + ( GI + 9 ),
(VolS.LOWS.min() + VolS.LOWS.min()- (band*4)) / 2,
str.tostring(math.round(GR * 100,2)) + " %",
xloc = xloc.bar_index,
style = label.style_label_left,
textcolor= Colors.CHART,
color = color.new(color.black, 100)
))
Draw.LvLabels.push(
label.new(Start + ( RI + 9 ),
(VolS.HIGHES.max()+ (band*4) + VolS.HIGHES.max()) / 2,
str.tostring(math.round(RR * 100,2)) + " %",
xloc = xloc.bar_index,
style = label.style_label_left,
textcolor= Colors.CHART,
color = color.new(color.black, 100)
))
if array.size(Draw.LevelsBOX) > 5
for i = 0 to 4
box.delete(Draw.LevelsBOX.shift())
if array.size(Draw.LvLabels) > 2
for i = 0 to 1
label.delete(Draw.LvLabels.shift())
|
Cycles: 4x dual inputs: Swing / Time Cycles projected forward | https://www.tradingview.com/script/vag03r3a-Cycles-4x-dual-inputs-Swing-Time-Cycles-projected-forward/ | twingall | https://www.tradingview.com/u/twingall/ | 70 | 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/
// © twingall
//@version=5
indicator("Future cycles: 4x dual inputs", overlay = true, max_lines_count = 500)
var grp1 = "~~~~~~~~~ Confuence Line ~~~~~~~~~"
var grp2 = "~~~~~~~~~ Primary Cycle ~~~~~~~~~"
var grp3 = "~~~~~~~~~ Cycle 2 ~~~~~~~~~"
var grp4 = "~~~~~~~~~ Cycle 3 ~~~~~~~~~"
var grp5 = "~~~~~~~~~ Cycle 4 ~~~~~~~~~"
showConfLn = input.bool(true, "Show Confluence Line ||", group = grp1, inline = '0')
dev= input.int(0, "deviation (+/- bars)", minval = 0, group = grp1, inline = '0', tooltip = "say deviation = 'x', then each of cycle 2, 3, 4 lines (so long as they are included for confluence) must be within 'X' bars of the primary cycle line\n\nIf so, then that particular primary cycle line will be painted in the foloowing color/style")
color0 = input.color(color.purple, "color:", group = grp1, inline = '1')
linestyle0 = input.string(line.style_dashed, "style", options = [line.style_solid, line.style_dotted, line.style_dashed], group = grp1, inline = '1')
width0 = input.int(3, "width", group = grp1, inline = '1')
startDate1= input.time(timestamp("21 Jul 2021 00:00 -0400"), "Primary Cycle Start Date", confirm =true, group = grp2)
endDate1= input.time(timestamp("9 Nov 2021 00:00 -0400"), "Primary Cycle End Date", confirm = true, group = grp2)
showCycle1 = input.bool(true, "Show |", group = grp2, inline = '1')
color1 = input.color(color.red, "line color", group = grp2, inline = '1')
linestyle1 = input.string(line.style_dashed, "style", options = [line.style_solid, line.style_dotted, line.style_dashed], group = grp2, inline = '1')
width1 = input.int(1, "width", group = grp2, inline = '1')
startDate2= input.time(timestamp("28 Jan 2021 00:00 -0400"), "Start Date2", confirm =true, group = grp3, inline = '2')
endDate2= input.time(timestamp("22 Feb 2021 00:00 -0400"), "End Date2", confirm = true, group = grp3, inline = '3')
showCycle2 = input.bool(true, "Show lines |", group = grp3, inline = '5')
color2 = input.color(color.blue, "", group = grp3, inline = '5')
linestyle2 = input.string(line.style_dashed, "style", options = [line.style_solid, line.style_dotted, line.style_dashed], group = grp3, inline = '5')
width2 = input.int(1, "width", group = grp3, inline = '5')
conf2 = input.bool(true, "include in confluence calculation", group = grp3, inline = '6')
startDate3= input.time(timestamp("15 Apr 2021 00:00 -0400"), "Start Date3", confirm =true, group = grp4, inline = '6')
endDate3= input.time(timestamp("19 May 2021 00:00 -0400"), "End Date3", confirm = true, group = grp4, inline = '7')
showCycle3 = input.bool(true, "Show lines |", group = grp4, inline = '9')
color3 = input.color(color.black, "", group = grp4, inline = '9')
linestyle3 = input.string(line.style_dashed, "style", options = [line.style_solid, line.style_dotted, line.style_dashed], group = grp4, inline = '9')
width3 = input.int(1, "width", group = grp4, inline = '9')
conf3 = input.bool(true, "include in confluence calculation", group = grp4, inline = '10')
startDate4= input.time(timestamp("21 Jun 2021 00:00 -0400"), "Start Date4", confirm =true, group = grp5, inline = '10')
endDate4= input.time(timestamp("9 Nov 2021 00:00 -0400"), "End Date4", confirm = true, group = grp5, inline = '11')
showCycle4 = input.bool(true, "Show lines |", group = grp5, inline = '13')
color4 = input.color(color.green, "", group = grp5, inline = '13')
linestyle4 = input.string(line.style_dashed, "style", options = [line.style_solid, line.style_dotted, line.style_dashed], group = grp5, inline = '13')
width4 = input.int(1, "width", group = grp5, inline = '13')
conf4 = input.bool(true, "include in confluence calculation", group = grp5, inline = '14')
boxTransp= input.int(80, "box transparancy (100 = invisible)", maxval = 100, minval = 0)
cycleBoxAndLines(int _timeS, int _timeE, color _col, string _style, int _width, bool _showCycle)=>
var int strtInd = na
var int endInd = na
var array<int> lnFwdInd = array.new<int>(na)
if time>=_timeS and time[1]<=_timeS
strtInd:= bar_index-1
if time>=_timeE and time[1]<=_timeE
endInd:= bar_index-1
int len = endInd-strtInd
horizon = (last_bar_index+10000)- endInd
totLines = int(horizon/len)
midInd = int(strtInd+(len/2))
if barstate.islast and endInd>strtInd
line.new(strtInd, high, strtInd, high+1, extend = extend.both, width=1, color = color.fuchsia, style = line.style_dotted)
line.new(endInd, high, endInd, high+1, extend = extend.both, width=1, color = color.fuchsia, style = line.style_dotted)
top = math.max(high[last_bar_index-strtInd],high[last_bar_index-endInd])
bottom= math.min(low[last_bar_index-strtInd],low[last_bar_index-endInd])
box.new(strtInd,top, endInd, bottom, bgcolor = color.new(_col, boxTransp), border_color = color.new(color.white, 100), text = str.tostring(len)+ " bars", text_valign = text.align_top, text_halign = text.align_center, text_size = size.normal, text_color=color.new(_col,22))
label.new(midInd, close[last_bar_index-strtInd], style = label.style_none, size = size.normal)
for i = 1 to totLines
if endInd+(i*len) < last_bar_index+500 // TV won't let you plot lines more than 500 bars into future using bar_index as ref
if _showCycle
line.new(endInd+(i*len), high, endInd+(i*len), high+1, color = _col, extend = extend.both, style = _style, width = _width)
lnFwdInd.push(endInd+(i*len))
lnFwdInd
arrFwd1 = cycleBoxAndLines(startDate1, endDate1, color1, linestyle1, width1, showCycle1)
arrFwd2 =cycleBoxAndLines(startDate2, endDate2, color2, linestyle2, width2, showCycle2)
arrFwd3 =cycleBoxAndLines(startDate3, endDate3, color3, linestyle3, width3, showCycle3)
arrFwd4 =cycleBoxAndLines(startDate4, endDate4, color4, linestyle4, width4, showCycle4)
paintConfluence()=>
var bool result = false
if arrFwd1.size()>0
for i = 0 to arrFwd1.size()-1
ind = arrFwd1.get(i)
cond2 = false
for j= -dev to dev
if arrFwd2.includes(ind+j)
cond2:= true
cond3 = false
for j= -dev to dev
if arrFwd3.includes(ind+j)
cond3:= true
cond4 = false
for j= -dev to dev
if arrFwd4.includes(ind+j)
cond4:= true
if conf2?cond2:true
if conf3?cond3:true
if conf4?cond4:true
line.new(ind, high, ind, high+1, width = width0, color = color0, style =linestyle0, extend = extend.both)
if barstate.islast and showConfLn
paintConfluence()
|
W and M Pattern Indicator- SwaG | https://www.tradingview.com/script/lkB1fhGS-W-and-M-Pattern-Indicator-SwaG/ | swagato25 | https://www.tradingview.com/u/swagato25/ | 69 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © swagato25
//@version=5
indicator("W and M Pattern Indicator- SwaG", overlay=true)
//Inputs
upper_limit = input.int(defval = 70, title = "Upper Limit")
lower_limit = input.int(defval = 40, title = "Lower Limit")
// Get the RSI values
rsi = ta.rsi(close, 50)
// Calculate the W and M patterns
w_pattern = ( rsi<rsi[1] and rsi[10]>rsi[22] and rsi[2] < lower_limit )
m_pattern = ( rsi>rsi[9] and rsi[1]<rsi[5] and rsi[7] > upper_limit )
plotshape(w_pattern, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(m_pattern, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small) |