Daily Target & Consistency Tracker (Fixed + Win Rate)Updated this script. Realized that the suggested daily target calculations was giving the wrong number of profit to make per day to stay within the 20% or below level. Good luck to all and happy trading.
Portfolio management
The LEAP Contest - Symbol & Max Position Table TrackerDescription:
This indicator tracks the maximum contracts allowed to be traded for TradingView’s *"The Leap"* Contest. It displays a horizontal table at the bottom right of your chart showing up to 20 symbols along with their maximum allowable open contract positions.
Use case:
Designed specifically for traders participating in *The Leap* Contest on TradingView.
Users need to enter the symbol and the maximum contracts allowed for that symbol in the settings menu for each new contest.
It provides a quick reference to ensure compliance with contest rules on maximum position sizes.
How it works:
The table shows two rows: the top row displays the symbol name, and the bottom row shows the max contract limit.
If the currently loaded chart symbol matches any symbol in the list, its text color changes to yellow .
Customization:
Symbols and limits must be updated in the indicator’s settings before each contest to reflect the current rules.
Futures Margin Lookup TableThis script applies a table to the upper right corner of the screen, which provides the intraday and overnight margin requirements of the currently selected symbol.
In this indicator the user must provide the broker data in the form of specifically formatted text blocks. The data for which should be found on the broker website.
The purpose for it's creation is due to the non-standard way each individual broker may price their margins and lack of information within TradingView when connected to some (maybe all) brokers, including when paper trading, as the flat percentage rule is not accurate.
An example of information for NinjaTrader could look like this
MES;Micro S&P;$50;$2406
ES;E-Mini S&P;$500;$24,053
GC;Gold;$500;$16500
NQ;E-Mini Nasdaq;$1,000;$34,810
FDAX;Dax Index;€2,000;€44,311
Each symbol begins a new line, and the values on that line are separated by semicolons (;)
Each line consists of the following...
SYMBOL : Search string used to match to the beginning of the current chart symbol.
NAME: Human readable name
INTRA: Intraday trading margin requirement per contract
OVERNIGHT: Overnight trading margin requirement per contract
The script simply finds a matching line within your provided information using the current chart symbol.
So for example the continuous chart for NQ1! would match to the user specified line starting with NQ... as would the individual contract dates such as NQM2025, NQK2025, etc.
NOTES:
There is a possibility that symbols with similar starting characters could match.
If this is the case put the longer symbol higher in the list.
There is also a line / character limit to the text input fields within pinescript
Ensure the text you paste into them is not truncated.
If so there are 3 input fields for just this purpose.
Find the last complete line and continue the remaining symbol lines on the subsequent inputs.
Estratégia Elite Traders CriptoCRYPTO PROFITABLE AI Script (Pro Version 1.3) Completely free version with entry signals for buying and selling. Premium version under development. For more information, send a message.
My script//@version=6
indicator("Just Crossed Above 150 SMA", overlay=true)
sma150 = ta.sma(close, 150)
crossAbove = ta.crossover(close, sma150)
plot(sma150, title="SMA 150", color=color.orange) plotshape(crossAbove, title="Cross Above SMA150", location=location.belowbar, style=shape.triangleup, size=size.small, color=color.green, text="↑150")
My scriptSCREENER SMA 150
//@version=6
indicator("Just Crossed Above 150 SMA", overlay=true)
sma150 = ta.sma(close, 150)
crossAbove = ta.crossover(close, sma150)
plot(sma150, title="SMA 150", color=color.orange) plotshape(crossAbove, title="Cross Above SMA150", location=location.belowbar, style=shape.triangleup, size=size.small, color=color.green, text="↑150")
PCA Regime-Adjusted MomentumSummary
The PCA Regime-Adjusted Momentum (PCA-RAM) is an advanced market analysis tool designed to provide nuanced insights into market momentum and structural stability. It moves beyond traditional indicators by using Principal Component Analysis (PCA) to deconstruct market data into its most essential patterns.
The indicator provides two key pieces of information:
A smoothed momentum signal based on the market's dominant underlying trend.
A dynamic regime filter that gauges the stability and clarity of the market's structure, advising you when to trust or fade the momentum signals.
This allows traders to not only identify potential shifts in momentum but also to understand the context and confidence behind those signals.
Core Concepts & Methodology
The strength of this indicator lies in its sound, data-driven methodology.
1. Principal Component Analysis (PCA)
At its core, the indicator analyzes a rolling window (default 50 periods) of standardized market data (Open, High, Low, Close, and Volume). PCA is a powerful statistical technique that distills this complex, 5-dimensional data into its fundamental, uncorrelated components of variance. We focus on the First Principal Component (PC1), which represents the single most dominant pattern or "theme" driving the market's behavior in the lookback window.
2. The Momentum Signal
Instead of just looking at price, we project the current market data onto this dominant underlying pattern (PC1). This gives us a raw "projection score" that measures how strongly the current bar aligns with the historically dominant market structure. This raw score is then smoothed using two an exponential moving averages (a fast and a slow line) to create a clear, actionable momentum signal, similar in concept to a MACD.
3. The Dynamic Regime Filter
This is arguably the indicator's most powerful feature. It answers the question: "How clear is the current market picture?"
It calculates the Market Concentration Ratio, which is the percentage of total market variance explained by PC1 alone.
A high ratio indicates that the market is moving in a simple, one-dimensional way (e.g., a clear, strong trend).
A low ratio indicates the market is complex, multi-dimensional, and choppy, with no single dominant theme.
Crucially, this filter is dynamic. It compares the current concentration ratio to its own recent average, allowing it to adapt to any asset or timeframe. It automatically learns what "normal" and "choppy" look like for the specific chart you are viewing.
How to Interpret the Indicator
The indicator is displayed in a separate pane with two key visual elements:
The Momentum Lines (White & Gold)
White Line: The "Fast Line," representing the current momentum.
Gold Line: The "Slow Line," acting as the trend confirmation.
Bullish Signal: A crossover of the White Line above the Gold Line suggests a shift to positive momentum.
Bearish Signal: A crossover of the White Line below the Gold Line suggests a shift to negative momentum.
The Regime Filter (Purple & Dark Red Background)
This is your confidence gauge.
Navy Blue Background (High Concentration): The market structure is stable, simple, and trending. Momentum signals are more reliable and should be given higher priority.
Dark Red Background (Low Concentration): The market structure is complex, choppy, or directionless. Momentum signals are unreliable and prone to failure or "whipsaws." This is a signal to be cautious, tighten stops, or potentially stay out of the market.
Potential Trading Strategies
This tool is versatile and can be used in several ways:
1. Primary Signal Strategy
Condition: Wait for the background to turn Purple, confirming a stable, high-confidence regime.
Entry: Take the next crossover signal from the momentum lines (White over Gold for long, White under Gold for short).
Exit/Filter: Consider exiting positions or ignoring new signals when the background turns Navy.
2. As a Confirmation or Filter for Your Existing Strategy
Do you have a trend-following system? Only enable its long and short signals when the PCA-RAM background is Purple.
Do you have a range-trading or mean-reversion system? It might be most effective when the PCA-RAM background is Navy, indicating a lack of a clear trend.
3. Advanced Divergence Analysis
Look for classic divergences between price and the momentum lines. For example, if the price is making a new high, but the Gold Line is making a lower high, it may indicate underlying weakness in the trend, even on a Purple background. This divergence signal is more powerful because it shows that the new price high is not being confirmed by the market's dominant underlying pattern.
Correlation MA – 15 Assets + Average (Optional)This indicator calculates the moving average of the correlation coefficient between your charted asset and up to 15 user-selected symbols. It helps identify uncorrelated or inversely correlated assets for diversification, pair trading, or hedging.
Features:
✅ Compare your current chart against up to 15 assets
✅ Toggle assets on/off individually
✅ Custom correlation and MA lengths
✅ Real-time average correlation line across enabled assets
✅ Horizontal lines at +1, 0, and -1 for easy visual reference
Ideal for:
Portfolio diversification analysis
Finding low-correlation stocks
Mean-reversion & pair trading setups
Crypto, equities, ETFs
To use: set the benchmark chart (e.g. TSLA), choose up to 15 assets, and adjust settings as needed. Look for assets with correlation near 0 or negative values for uncorrelated performance.
MEDIAS MOVILES ASL//@version=5
indicator("MEDIAS MOVILES ASL",overlay=true, max_bars_back=3000)
// ======== Indicator Input Parameters =========
linew = 2 // line width for moving averages.
var string G_DAILY = "►► Daily Moving Average"
bool ma_c_enable = input(inline = "01", group = G_DAILY, defval=true, title="MM1")
string ma_c = input.string(inline = "01", group = G_DAILY, defval="ASL", title="", options= )
int len_c = input.int(inline = "01", group = G_DAILY, defval=21, minval=1, title="Length:")
color col_c = input(inline = "01", group = G_DAILY, defval=color.blue,title="")
bool ma_i_enable = input(inline = "02", group = G_DAILY, defval=true, title="MM2")
string ma_i = input.string(inline = "02", group = G_DAILY, defval="EMA", title="", options= )
int len_i = input.int(inline = "02", group = G_DAILY, defval=150, minval=1, title="Length:")
color col_i = input(inline = "02", group = G_DAILY, defval=color.red, title="")
bool ma_l_enable = input(inline = "03", group = G_DAILY, defval=true, title="MM3")
string ma_l = input.string(inline = "03", group = G_DAILY, defval="EMA", title="", options= )
int len_l = input.int(inline = "03", group = G_DAILY, defval=200, minval=1, title="Length:")
color col_l = input(inline = "03", group = G_DAILY, defval=color.orange,title="")
bool ma_a_enable = input(inline = "04", group = G_DAILY, defval=true, title="MM4")
string ma_a = input.string(inline = "04", group = G_DAILY, defval="SMA", title="", options= )
int len_a = input.int(inline = "04", group = G_DAILY, defval=30, minval=1, title="Length:")
color col_a = input(inline = "04", group = G_DAILY, defval=color.green,title="")
var string G_WEEKLY = "►► Weekly Moving Average"
bool w_ma_c_enable = input(inline = "01", group = G_WEEKLY, defval=true, title="MM1")
string w_ma_c = input.string(inline = "01", group = G_WEEKLY, defval="WMA", title="", options= )
int w_len_c = input.int(inline = "01", group = G_WEEKLY, defval=10, minval=1, title="Length:")
color w_col_c = input(inline = "01", group = G_WEEKLY, defval=color.blue,title="")
bool w_ma_i_enable = input(inline = "02", group = G_WEEKLY, defval=true, title="MM2")
string w_ma_i = input.string(inline = "02", group = G_WEEKLY, defval="WMA", title="", options= )
int w_len_i = input.int(inline = "02", group = G_WEEKLY, defval=30, minval=1, title="Length:")
color w_col_i = input(inline = "02", group = G_WEEKLY, defval=color.orange, title="")
bool w_ma_l_enable = input(inline = "03", group = G_WEEKLY, defval=true, title="MM3")
string w_ma_l = input.string(inline = "03", group = G_WEEKLY, defval="SMA", title="", options= )
int w_len_l = input.int(inline = "03", group = G_WEEKLY, defval=200, minval=1, title="Length:")
color w_col_l = input(inline = "03", group = G_WEEKLY, defval=color.green,title="")
bool w_ma_a_enable = input(inline = "04", group = G_WEEKLY, defval=true, title="MM4")
string w_ma_a = input.string(inline = "04", group = G_WEEKLY, defval="WMA", title="", options= )
int w_len_a = input.int(inline = "04", group = G_WEEKLY, defval=50, minval=1, title="Length:")
color w_col_a = input(inline = "04", group = G_WEEKLY, defval=color.red,title="")
var string G_MONTHLY = "►► Monthly Moving Average"
bool m_ma_c_enable = input(inline = "01", group = G_MONTHLY, defval=true, title="MM1")
string m_ma_c = input.string(inline = "01", group = G_MONTHLY, defval="WMA", title="", options= )
int m_len_c = input.int(inline = "01", group = G_MONTHLY, defval=12, minval=1, title="Length:")
color m_col_c = input(inline = "01", group = G_MONTHLY, defval=color.orange,title="")
bool m_ma_l_enable = input(inline = "02", group = G_MONTHLY, defval=false, title="MM2")
string m_ma_l = input.string(inline = "02", group = G_MONTHLY, defval="SMA", title="", options= )
int m_len_l = input.int(inline = "02", group = G_MONTHLY, defval=12, minval=1, title="Length:")
color m_col_l = input(inline = "02", group = G_MONTHLY, defval=color.olive,title="")
var color TBL_TXT = color.white
var color TBL_BG = #000000
var string TXT_SIZE = 'auto'
var string G_TABLE = '►► Moving Average and 2Sigma Table (Position & Size)'
bool i_table_enable = input.bool(true, inline='01', group=G_TABLE, title = "Enable? | ")
string i_tableYpos = input.string('bottom', '↕', inline='01', group=G_TABLE, options= )
string i_tableXpos = input.string('right', '↔', inline='01', group=G_TABLE, options= , tooltip='Position on the chart.')
color i_c_tableText = input.color(TBL_TXT, 'Text', inline='03', group=G_TABLE)
color i_c_tableBg = input.color(TBL_BG, 'Background', inline='03', group=G_TABLE)
string i_tableTextSize = input.string(TXT_SIZE, '', inline='03', group=G_TABLE, options= )
var string G_TABLEADD = '►► Table Additional Information'
bool unify_emas = input.bool(true, inline='01', group=G_TABLEADD, title = "Smart Unify Daily EMAS 150 & 200?", tooltip='Consolidate the two percentages in one to show the distance from close price to the long EMAS.')
cell_1 ='2σ Dispersion'
cell_2 = 'β-5Y'
cell_3 = 'Div Yield FQ'
var string G_SIGMAF = '►► 2Sigma and Bollinger Band Format'
string sigma_bb_format = input.string('0-100 inside band',inline='01', group=G_SIGMAF, title = "2σ and BB Format:", options= )
var string G_TABLEPARAM = '►► Beta & ATR Indicator Parameters'
string beta_baseline = input.string('SPY', inline='01', group=G_TABLEPARAM, title = "β Index or Benchmark:")
int beta_years = input.int(5, inline='01', group=G_TABLEPARAM, title = "Window Years:")
var color TBL_TXT2 = color.white
var color TBL_BG2 = #363A45
var string TXT_SIZE2 = 'auto'
var string COMMENT = 'EMAs = EMA(200)+EMA(150) / 2 (not adjusted by dividens) '
// ======== Functions Library =========
// ————— Function returning the leftmost `_n` characters in `_str`.
moving_avg(type, len) =>
value = type == "ASL" ? (ta.ema(close,len-1)+ta.wma(close,len))/2 : type =="EMA" ? ta.ema(close,len) : type=="WMA" ? ta.wma(close,len) : type=="HMA" ? ta.hma(close,len) : type=="L_EMAS_AVG" ? (ta.ema(close,len)+ta.ema(close,len+50))/2: ta.sma(close ,len)
txt = type + str.tostring(len,"#")
//sigma functions
// v=variation vs price
v(float x) => (close-x)/close
sigma2(x) => ta.stdev(x,bar_index > 3000 ? 3000 : (timeframe.isweekly or timeframe.ismonthly) ? 1000/5 : 1000) * 2
bg_mm(v,s) => (v > 0) ? (math.abs(v) > s) ? color.lime : color.green : (math.abs(v) > s) ? #ff0000 : #ad2323
bg_rsi(r) => r>70 ? color.red : r<30 ? color.green : r<35 ? #67Eb65 : r>65 ? #F2A09D : (r > 48 and r <52) ? color.olive : color.gray
bg_sigma2(x) => x < 0 ? #fffbbf : color.gray
fg_sigma2(x) => x < 0 ? #ff0000 : i_c_tableText
// Beta Background Color codes:
bg_beta(b) => b<0 ? color.blue : b<= 1 ? color.green : b>= 3 ? #ff0000 : b>= 1.7 ? #ad2323 : color.olive
// beta < 0 --> blue
// beta = 0 is chash no risk.
// 0 < beta <= 1 --> green
// 1 < beta <= 1.7 --> olive
// 1.7 < beta <= 3 --> dark red
// beta > 3 --> light red
// Div Yield Backgroudn
bg_div(x) => x == 0 ? color.gray : x < 3 ? color.blue : x < 5 ? color.olive : x < 10 ? color.green : color.lime
// identify ticker with operations
spread_symbol(x) =>
str.contains(x,"+") or str.contains(x,"-") or str.contains(x,"/") or str.contains(x,"*") or str.contains(x,"(")
// Table cells output.
print_cell(tbl, col, title_txt, color_txt_tit, color_bg_tit, value_txt, color_txt_val, color_bg_val,txt_size) =>
if barstate.islast
table.cell(tbl,col,0, title_txt, bgcolor = color_bg_tit , text_color = color_txt_tit,text_size = txt_size)
table.cell(tbl,col,1, value_txt, bgcolor = color_bg_val , text_color = color_txt_val,text_size = txt_size)
// formula simplified included in cells --> this function is used to setup if conditions to save execution time.
included(x,a,b,c) => x == a or x == b or x == c
// change funtion for beta
return_percent(src) => ta.change(src) * 100 / src
// bollinger band %B
bg_percentage_BB(x) => x < 0 or x > 100 ? #fffbbf : x <10 ? #30CC5A : x > 90 ? #F63538 : color.gray
fg_percentage_BB(x) => x < 0 ? color.green : x >100 ? #ff0000 : i_c_tableText
ETFs_tickers=' SPY QQQ DIA EWZ XLF XLE XLB XLV XLH XLK XLC XLY XLP XLI XLRE XLU MCHI VGLT VIG VYM VNQ SCHD IWM '
IsETF(x) => str.contains(ETFs_tickers, " " +x+" ")
// ====== End Functions Library =======
// ++++++++++++++++++ moving average calcs
= moving_avg(ma_c,len_c)
plot(timeframe.isdaily and ma_c_enable ? valmm1 : na, color=col_c, linewidth=linew)
= moving_avg(ma_i,len_i)
plot(timeframe.isdaily and ma_i_enable ? valmm2 : na, color=col_i, linewidth=linew)
= moving_avg(ma_l,len_l)
plot(timeframe.isdaily and ma_l_enable ? valmm3 : na, color=col_l,linewidth=linew)
= moving_avg(ma_a,len_a)
plot(timeframe.isdaily and ma_a_enable ? valmm4 : na, color=col_a,linewidth=linew)
if barstate.islast and timeframe.isdaily
ma_c_label = label.new(x=time, y=valmm1,
text=ma_c_enable ? txt1:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=col_c , size=size.small)
ma_i_label = label.new(x=time, y=valmm2,
text=ma_i_enable ? txt2:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=col_i, size=size.small)
ma_l_label = label.new(x=time, y=valmm3,
text=ma_l_enable ? txt3:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=col_l, size=size.small)
ma_a_label = label.new(x=time, y=valmm4,
text=ma_a_enable ? txt4:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=col_a, size=size.small)
xUpMM1 = ta.crossover(close, valmm1)
xDnMM1 = ta.crossunder(close, valmm1)
xUpEMA = ta.crossover(close, (valmm2+valmm3)/2)
xDnEMA = ta.crossunder(close, (valmm2+valmm3)/2)
if timeframe.isdaily and xUpMM1
alert(syminfo.ticker +" crossing UP ASL21 (short MA)")
if timeframe.isdaily and xDnMM1
alert(syminfo.ticker +" crossing DOWN ASL21 (short MA)")
if timeframe.isdaily and xUpEMA
alert(syminfo.ticker +" crossing UP EMAs (avg EMA150,EMA200)")
if timeframe.isdaily and xDnEMA
alert(syminfo.ticker +" crossing DOWN EMAs (avg EMA150,EMA200)")
alertcondition(xUpMM1 or xDnMM1, title="Daily Price x MA1 (ASL21)", message="Crossing ALS21")
alertcondition(xUpEMA or xDnEMA, title="Daily Price x Avg(MM2,MM3) (avg EMA150 & EMA200)",message="Crossing Big EMAs")
= moving_avg(w_ma_c,w_len_c)
plot(timeframe.isweekly and w_ma_c_enable ? w_valmm1 : na, color=w_col_c, linewidth=linew)
= moving_avg(w_ma_i,w_len_i)
plot(timeframe.isweekly and w_ma_i_enable ? w_valmm2 : na, color=w_col_i, linewidth=linew)
= moving_avg(w_ma_l,w_len_l)
plot(timeframe.isweekly and w_ma_l_enable ? w_valmm3 : na, color=w_col_l,linewidth=linew)
= moving_avg(w_ma_a,w_len_a)
plot(timeframe.isweekly and w_ma_a_enable ? w_valmm4 : na, color=w_col_a,linewidth=linew)
if barstate.islast and timeframe.isweekly
w_ma_c_label = label.new(x=time, y=w_valmm1,
text=w_ma_c_enable ? w_txt1:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=w_col_c, size=size.small)
w_ma_i_label = label.new(x=time, y=w_valmm2,
text=w_ma_i_enable ? w_txt2:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=w_col_i, size=size.small)
w_ma_l_label = label.new(x=time, y=w_valmm3,
text=w_ma_l_enable ? w_txt3:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=w_col_l, size=size.small)
w_ma_a_label = label.new(x=time, y=w_valmm4,
text=w_ma_a_enable ? w_txt4:na, xloc=xloc.bar_time, yloc=yloc.price, color=color.rgb(0, 0, 0, 100), style=label.style_label_left, textcolor=w_col_a, size=size.small)
= moving_avg(m_ma_c,m_len_c)
plot(timeframe.ismonthly and m_ma_c_enable ? m_valmm1 : na, color= m_col_c, linewidth=linew)
= moving_avg(m_ma_l,m_len_l)
plot(timeframe.ismonthly and m_ma_l_enable ? m_valmm2 : na, color=m_col_l,linewidth=linew)
// ***** TABLE SETUP AND PRINT
unify_emas := unify_emas and timeframe.isdaily and ma_i_enable and ma_l_enable and len_i == 150 and len_l == 200 and ma_i == "EMA" and ma_l == "EMA" and
math.abs(v(valmm2)-v(valmm3)) /( math.abs(v(valmm2)+v(valmm3))/2) < 0.2 and
bg_mm(v(valmm2),sigma2(v(valmm2))) == bg_mm(v(valmm3),sigma2(v(valmm3)))
total_col = 1 // 1 is RSI
total_col += timeframe.isdaily ? ((ma_c_enable ? 1 : 0) + (ma_i_enable ? 1 : 0) + (ma_l_enable ? 1 : 0) + (ma_a_enable ? 1 : 0 )) : 0
total_col += unify_emas ? -1 : 0
total_col += timeframe.isweekly ? ((w_ma_c_enable ? 1 : 0) + (w_ma_i_enable ? 1 : 0) + (w_ma_l_enable ? 1 : 0) + (w_ma_a_enable ? 1 : 0)) : 0
total_col += timeframe.ismonthly ? ((m_ma_c_enable ? 1 : 0) + (m_ma_l_enable ? 1 : 0)) : 0
// not inluding for intraday ((i_ma_c_enable ? 1 : 0) + (i_ma_i_enable ? 1 : 0)
// additional info
total_col += cell_1 == 'None' ? 0 : 1
total_col += cell_2 == 'None' ? 0 : 1
total_col += cell_3 == 'None' ? 0 : 1
border = i_tableTextSize == "tiny" ? 0 : i_tableTextSize == "small" ? 1 : i_tableTextSize == "normal" ? 2 : 3
frame = i_tableTextSize == "tiny" ? 1 : i_tableTextSize == "small" ? 2 : i_tableTextSize == "normal" ? 3 : 4
var table display = table.new(i_tableYpos + '_' + i_tableXpos, total_col, 2 ,border_width=border, frame_width = frame, frame_color = i_c_tableBg, border_color = i_c_tableBg)
// calcs
// ++++++++++++++++++++++++++ Beta
float beta = na
smooth = 1
length = timeframe.ismonthly ? 12 * beta_years + 1 : timeframe.isweekly ? 52 * beta_years + 1 : timeframe.isdaily ? 252 * beta_years + 1 : 300
instrument = not spread_symbol(syminfo.ticker) ? request.security(syminfo.tickerid, 'M', ta.ema(close, smooth)) : na
benchmark = not spread_symbol(syminfo.ticker) ? request.security(beta_baseline, 'M', ta.ema(close, smooth)) : na
inst_return = return_percent(instrument)
bench_return = return_percent(benchmark)
avg_inst_return = ta.sma(inst_return, length)
avg_bench_return = ta.sma(bench_return, length)
sum = 0.0
for idx = length to 0 by 1
inst_variance = inst_return - avg_inst_return
bench_variance = bench_return - avg_bench_return
sum += inst_variance * bench_variance
sum
covariance = sum / (length - 1)
beta := covariance / ta.variance(bench_return, length)
// Print Table with Moving Average variation vs price percentages
i=0
if timeframe.isdaily and i_table_enable
bg_mm2 = nz(bg_mm(v(valmm2),sigma2(v(valmm2))),color.gray)
bg_mm3 = nz(bg_mm(v(valmm2),sigma2(v(valmm2))),color.gray)
if ma_c_enable
print_cell(display, i, txt1, i_c_tableText, i_c_tableBg, str.tostring(v(valmm1),'#.#%'), i_c_tableText,bg_mm(v(valmm1),sigma2(v(valmm1))),i_tableTextSize)
i+=1
if ma_i_enable and not unify_emas
print_cell(display, i, txt2, i_c_tableText, i_c_tableBg, str.tostring(v(valmm2),'#.#%'), i_c_tableText,bg_mm2,i_tableTextSize)
i+=1
if ma_l_enable and not unify_emas
print_cell(display, i, txt3, i_c_tableText, i_c_tableBg, str.tostring(v(valmm3),'#.#%'), i_c_tableText,bg_mm3,i_tableTextSize)
i+=1
if unify_emas
unified_var = (valmm2 > close) ? math.max(v(valmm2), v(valmm3)) : math.min(v(valmm2),v(valmm3))
print_cell(display, i, "EMAs", i_c_tableText, i_c_tableBg, str.tostring(unified_var,'#.#%'), i_c_tableText,bg_mm2,i_tableTextSize)
i+=1
if ma_a_enable
print_cell(display, i, txt4, i_c_tableText, i_c_tableBg, str.tostring(v(valmm4),'#.#%'), i_c_tableText,bg_mm(v(valmm4),sigma2(v(valmm4))),i_tableTextSize)
i+=1
print_cell(display, i, "RSI", i_c_tableText, i_c_tableBg, str.tostring(ta.rsi(close,14),'##'), i_c_tableText,bg_rsi(ta.rsi(close,14)),i_tableTextSize)
i+=1
d = math.abs(sigma2(v(valmm1))) - math.abs(v(valmm1))
if timeframe.isweekly and i_table_enable
if w_ma_c_enable
print_cell(display, i, w_txt1, i_c_tableText, i_c_tableBg, str.tostring(v(w_valmm1),'#.#%'), i_c_tableText,bg_mm(v(w_valmm1),sigma2(v(w_valmm1))),i_tableTextSize)
i+=1
if w_ma_i_enable
print_cell(display, i, w_txt2, i_c_tableText, i_c_tableBg, str.tostring(v(w_valmm2),'#.#%'), i_c_tableText,bg_mm(v(w_valmm2),sigma2(v(w_valmm2))),i_tableTextSize)
i+=1
if w_ma_l_enable
print_cell(display, i, w_txt3, i_c_tableText, i_c_tableBg, str.tostring(v(w_valmm3),'#.#%'), i_c_tableText,bg_mm(v(w_valmm3),sigma2(v(w_valmm3))),i_tableTextSize)
i+=1
if w_ma_a_enable
print_cell(display, i, w_txt4, i_c_tableText, i_c_tableBg, str.tostring(v(w_valmm4),'#.#%'), i_c_tableText,bg_mm(v(w_valmm4),sigma2(v(w_valmm4))),i_tableTextSize)
i+=1
print_cell(display, i, "RSI", i_c_tableText, i_c_tableBg, str.tostring(ta.rsi(close,14),'##'), i_c_tableText,bg_rsi(ta.rsi(close,14)),i_tableTextSize)
i+=1
d = math.abs(sigma2(v(w_valmm1))) - math.abs(v(w_valmm1))
if timeframe.ismonthly and i_table_enable
if m_ma_c_enable
print_cell(display, i, m_txt1, i_c_tableText, i_c_tableBg, str.tostring(v(m_valmm1),'#.#%'), i_c_tableText,bg_mm(v(m_valmm1),sigma2(v(m_valmm1))),i_tableTextSize)
i+=1
if m_ma_l_enable
print_cell(display, i, m_txt2, i_c_tableText, i_c_tableBg, str.tostring(v(m_valmm2),'#.#%'), i_c_tableText,bg_mm(v(m_valmm2),sigma2(v(m_valmm2))),i_tableTextSize)
i+=1
print_cell(display, i, "RSI", i_c_tableText, i_c_tableBg, str.tostring(ta.rsi(close,14),'##'), i_c_tableText,bg_rsi(ta.rsi(close,14)),i_tableTextSize)
i+=1
d = math.abs(sigma2(v(m_valmm1))) - math.abs(v(m_valmm1))
print_cell(display, i, "2σ", i_c_tableText, i_c_tableBg, str.tostring(d ,'####.#%'), fg_sigma2(d),bg_sigma2(d),i_tableTextSize)
// ++++++++++++++++++++++++++ Yield
temp_ticker = spread_symbol(syminfo.tickerid) ? "NASDAQ:TSLA" : syminfo.tickerid // Tesla is a dummy stock to have 0 div to execute the formula.
_divYield = barstate.islast ? request.financial(temp_ticker, "DIVIDENDS_YIELD", "FQ", ignore_invalid_symbol = true) : 0.0
s1 = IsETF(syminfo.ticker) ? request.dividends(temp_ticker) : na // no se puede poner barstate.islast al preguntar por anteriores s1 +s1 +s1 +s1
dividendPeriodicity = 4 // checkear como validar la periodicidad diferente de 4 para ETFs
_divYield := IsETF(syminfo.ticker) ? (s1 +s1 +s1 +s1 ) / close * 100 : _divYield
// ++++++++++++++++++++++++++ 2sigma percentage and 0-100 like %B
float bb_2sigma = na
d = 0.0
if sigma_bb_format == '0-100 inside band'
mid2sigma =
timeframe.isdaily ? valmm1 :
timeframe.isweekly ? w_valmm1 :
timeframe.ismonthly ? m_valmm1 : na
bandwidth2sigma =
timeframe.isdaily ? sigma2(v(valmm1)) :
timeframe.isweekly ? sigma2(v(w_valmm1)) :
timeframe.ismonthly ? sigma2(v(m_valmm1)) : na
upbb2 = mid2sigma + bandwidth2sigma * close
dnbb2 = mid2sigma - bandwidth2sigma * close
bb_2sigma := (close - dnbb2) / (upbb2 - dnbb2) * 100
if sigma_bb_format == '% to up/dn band'
d := timeframe.isdaily ? math.abs(sigma2(v(valmm1))) - math.abs(v(valmm1)) :
timeframe.isweekly ? math.abs(sigma2(v(w_valmm1))) - math.abs(v(w_valmm1)) :
timeframe.ismonthly ? math.abs(sigma2(v(m_valmm1))) - math.abs(v(m_valmm1)) : na
// // ++++++++++++++++++++++++++ PRINT SELECTIONS
if i_table_enable and barstate.islast
// cell 1 - 2 sigma dispesion
if sigma_bb_format == '0-100 inside band'
if timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly
print_cell(display, i, "2σ", i_c_tableText, i_c_tableBg, str.tostring(bb_2sigma,'#'), fg_percentage_BB(bb_2sigma),bg_percentage_BB(bb_2sigma),i_tableTextSize)
i+=1
else
if timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly
print_cell(display, i, "2σ", i_c_tableText, i_c_tableBg, str.tostring(d ,'####.#%'), fg_sigma2(d),bg_sigma2(d),i_tableTextSize)
i+=1
// cell 2 - beta
beta_txt = "β-5Y"
print_cell(display, i, beta_txt , i_c_tableText, i_c_tableBg, str.tostring(beta,'#.#'), i_c_tableText,bg_beta(beta),i_tableTextSize)
i+=1
// cell 3 - div
yield_txt = "Div Yield"
print_cell(display,i, yield_txt, i_c_tableText, i_c_tableBg, str.tostring(_divYield/100,'#.#%'), i_c_tableText,bg_div(nz(_divYield,0.0)),i_tableTextSize)
i+=1
Position Size & Stop-Loss CalculatorPine Script Code for Position Size & Stop-Loss Calculator Indicator
This Pine Script indicator for TradingView will allow you to input your trading parameters and see the calculated Stop-Loss Price plotted on the chart, along with the recommended number of shares and maximum dollar risk displayed as a text label.
80-20_DCA-Alert
The idea for this indicator comes from the book “$1,000 To $1,000,000 Proven Strategies for Triple Leveraged ETF Success” by B.D. Collins. In the book, he describes a charming 80/20 DCA strategy with a stronger price weighting when prices fall in order to trade leveraged ETFs. This indicator is applied to the chart of the unleveraged (!) underlying or index of the ETF. You can then use the alarm function to receive a (daily) update on how much of the cash should currently be invested into the corresponding leveraged ETF. Depending on whether the price is above or below the freely definable levels, a different weighting is recommended. The default settings are based on B.D. Collins' original strategy and are as follows:
At the beginning of each quarter, if the price of the unleveraged underlying (index) of the ETF
- is between 0 and 15% below the ATH, 20% of the saved cash balance is invested
- between 16 and 25% below the ATH, 40% of the saved cash balance is invested
- between 26 and 35% below the ATH, 60% of the saved cash balance is invested
- greater than 35% below the ATH, 80% of the saved cash balance is invested
More details in his book.
This is not financial advice. Trading with leveraged ETFs is very risky and can lead to extreme losses
Good Luck and may the force be with us
Dr Avinash Talele momentum indicaterTrend and Volatility Metrics
EMA10, EMA20, EMA50:
Show the percentage distance of the current price from the 10, 20, and 50-period Exponential Moving Averages.
Positive values indicate the price is above the moving average (bullish momentum).
Negative values indicate the price is below the moving average (bearish or corrective phase).
Use: Helps traders spot if a stock is extended or pulling back to support.
RVol (Relative Volume):
Compares current volume to the 20-day average.
Positive values mean higher-than-average trading activity (potential institutional interest).
Negative values mean lower activity (less conviction).
Use: High RVol often precedes strong moves.
ADR (Average Daily Range):
Shows the average daily price movement as a percentage.
Use: Higher ADR = more volatility = more trading opportunities.
50D Avg. Vol & 50D Avg. Vol ₹:
The 50-day average volume (in millions) and value traded (in crores).
Use: Confirms liquidity and suitability for larger trades.
ROC (Rate of Change) Section
1W, 1M, 3M, 6M, 12M:
Show the percentage price change over the last 1 week, 1 month, 3 months, 6 months, and 12 months.
Positive values (green) = uptrend, Negative values (red) = downtrend.
Use: Quickly see if the stock is gaining or losing momentum over different timeframes.
Momentum Section
1M, 3M, 6M:
Show the percentage gain from the lowest price in the last 1, 3, and 6 months.
Use: Measures how much the stock has bounced from recent lows, helping find strong rebounds or new leaders.
52-Week High/Low Section
From 52WH / From 52WL:
Show how far the current price is from its 52-week high and low, as a percentage.
Closer to 52WH = strong uptrend; Closer to 52WL = possible value or turnaround setup.
Use: Helps traders identify stocks breaking out to new highs or rebounding off lows.
U/D Ratio
U/D Ratio:
The ratio of up-volume to down-volume over the last 50 days.
Above 1 = more buying volume (bullish), Below 1 = more selling volume (bearish).
Use: Confirms accumulation or distribution.
How This Table Helps Analysts and Traders
Instant Trend Assessment:
With EMA distances and ROC, analysts can instantly see if the stock is trending, consolidating, or reversing.
Momentum Confirmation:
ROC and Momentum sections highlight stocks with strong recent moves, ideal for momentum and breakout traders.
Liquidity and Volatility Check:
Volume and ADR ensure the stock is tradable and has enough price movement to justify a trade.
Relative Positioning:
52-week high/low stats show whether the stock is near breakout levels or potential reversal zones.
Volume Confirmation:
RVol and U/D ratio help confirm if moves are backed by real buying/selling interest.
Actionable Insights:
By combining these metrics, traders can filter for stocks with strong trends, robust momentum, and institutional backing—ideal for swing, position, or even intraday trading.
LTA - Futures Contract Size CalculatorLTA - Futures Contract Size Calculator
This indicator helps futures traders calculate the potential stop-loss (SL) value for their trades with ease. Simply input your entry price, stop-loss price, and number of contracts, and the indicator will compute the ticks moved, price movement, and total SL value in USD.
Key Features:
Supports a wide range of futures contracts, including:
Index Futures: E-mini S&P 500 (ES), Micro E-mini S&P 500 (MES), E-mini Nasdaq-100 (NQ), Micro E-mini Nasdaq-100 (MNQ)
Commodity Futures: Crude Oil (CL), Gold (GC), Micro Gold (MGC), Silver (SI), Micro Silver (SIL), Platinum (PL), Micro Platinum (MPL), Natural Gas (NG), Micro Natural Gas (MNG)
Bond Futures: 30-Year T-Bond (ZB)
Currency Futures: Euro FX (6E), Japanese Yen (6J), Australian Dollar (6A), British Pound (6B), Canadian Dollar (6C), Swiss Franc (6S), New Zealand Dollar (6N)
Displays key metrics in a clean table (bottom-right corner):
Instrument, Entry Price, Stop-Loss Price, Number of Contracts, Tick Size, Ticks Moved, Price Movement, and Total SL Value.
Automatically calculates based on the selected instrument’s tick size and tick value.
User-friendly interface with a dark theme for better visibility.
How to Use:
Add the indicator to your chart.
Select your instrument from the dropdown (ensure it matches your chart’s symbol, e.g., "NG1!" for NATURAL GAS (NG)).
Input your Entry Price, Stop-Loss Price, and Number of Contracts.
View the results in the table, including the Total SL Value in USD.
Ideal For:
Futures traders looking to quickly assess stop-loss risk.
Beginners and pros trading indices, commodities, bonds, or currencies.
Note: Ensure your chart symbol matches the selected instrument for accurate calculations. For best results, test with a few contracts and price levels to confirm the output.
This description is tailored for TradingView’s audience, providing a clear overview of the indicator’s functionality, supported instruments, and usage instructions. It also includes a note to help users avoid common pitfalls (e.g., mismatched symbols). If you’d like to adjust the tone, add more details, or include specific TradingView tags (e.g., , ), let me know!
Zen Lab Checklist - FNSThe Zen Lab Checklist - FNS is a simple yet powerful visual trading assistant designed to help traders maintain discipline and consistency in their trading routines. This provides a customizable on-screen checklist. This indicator allows traders to verify key conditions before entering a trade which will help identify trade quality and promote structured trading habits. This indicator is ideal for discretionary traders who follow a consistent set of entry rules.
✅ Key Features
Customizable Checklist Items:
Define up to 6 checklist labels with on/off toggle switches to track your trade criteria.
Visual Feedback:
Each checklist item displays a ✅ checkmark when conditions are met or a ❌ cross when not. Colors are visually distinct — green for confirmed, red for not confirmed.
Progress Tracker:
A "Trade Score" footer calculates a "trade score" percentage, helping you quickly assess the trade idea quality and readiness.
Table Position Control:
Easily adjust the table’s position on your chart (e.g., top-right, middle-center, bottom-left) using a dropdown menu.
Custom Styling Options:
- Change background and font color of checklist rows.
- Set font size (tiny to huge).
- Set the header and footer colors separately for visual contrast. (default is green background with white font)
📌 How to Use
- Open the indicator settings.
- Label your checklist items to match your personal or strategy-specific rules.
- Toggle the corresponding switches based on your trade setup conditions.
- Review the on-chart checklist and "Trade Score" to confirm your trade decision.
🎯 Why Use This?
- Discipline: Keeps you aligned with your trading plan.
- Clarity: Clear visual indicator of trade readiness.
- Efficiency: Saves time by centralizing your checklist visually on your chart.
- Custom Fit: Adapt the labels and styling to match your strategy or preferences.
⚠️ Notes
This is a manual checklist, meaning you control the toggle switches based on your judgment.
Ideal for discretionary traders who follow a consistent set of entry rules.
AsturRiskPanelIndicator Summary
ATR Engine
Length & Smoothing: Choose how many bars to use (default 14) and the smoothing method (RMA/SMA/EMA/WMA).
Median ATR: Computes a rolling median of ATR over a user-defined look-back (default 14) to derive a “scalp” target.
Scalp Target
Automatically set at ½ × median ATR, snapped to the nearest tick.
Optional rounding to whole points for simplicity.
Stop Calculation
ATR Multiplier: Scales current ATR by a user input (default 1.5) to produce your stop distance in points (and ticks when appropriate).
Distortion Handling: Switches between point-only and point + tick displays based on contract specifications.
Risk & Sizing
Risk % of account per trade (default 2 %).
Calculates dollar risk per contract and optimal contract count.
Displays all metrics (scalp, stop, risk/contract, max contracts, max risk, account size) in a customizable on-chart table.
ATR-Based Stop Placement Guidelines
Trade Context ATR Multiplier Notes
Tight Range Entry 1.0 × ATR High-conviction, precise entries. Expect more shake-outs.
Standard Trend Entry 1.5 × ATR Balanced for H2/L2, MTR, DT/DB entries.
Breakouts/Microchannels 2.0 × ATR Wide stops through chop—Brooks-style breathing room.
How to Use
Select ATR Settings
Pick an ATR length (e.g. 14) and smoothing (RMA for stability).
Adjust the median length if you want a faster/slower scalp line.
Align Multiplier with Your Setup
For tight-range entries, set ATR Multiplier ≈ 1.0.
For standard trend trades, leave at 1.5.
For breakout/pullback setups, increase to 2.0 or more.
Customize Risk Parameters
Enter your account size and desired risk % per trade (e.g. 2 %).
The table auto-calculates how many contracts you can take.
Read the On-Chart Table
Scalp shows your intraday target.
Stop gives Brooks-style stop distance in points (and ticks).
Risk/Contract is the dollar risk per contract.
Max Contracts tells you maximum position size.
Max Risk confirms total dollar exposure.
Visual Confirmation
Place your entry, then eyeball the scalp and stop levels against chart structure (e.g. swing highs/lows).
Adjust the ATR multiplier if market context shifts (e.g. volatility spikes).
By blending this sizing panel with contextual ATR multipliers, you’ll consistently give your trades the right amount of “breathing room” while keeping risk in check.
Profit Guard ProProfitGuard Pro
ProfitGuard Pro is a risk management and profit calculation tool that helps traders optimize their trades by handling position sizing, risk management, leverage, and take profit calculations. With support for both cumulative and non-cumulative take profit strategies, this versatile indicator provides the insights you need to maximize your trading strategy.
How to Use ProfitGuard Pro:
Load the Indicator: Add ProfitGuard Pro to your chart in TradingView.
Set Your Entry Position: Input your desired entry price.
Define Your Stop Loss: Enter the price at which your trade will exit to minimize losses.
Add Take Profit Levels: Input your TP1, TP2, TP3, and TP4 levels, as needed.
If you want fewer take profit levels, adjust the number of TPs in the settings menu. You can choose between 1 to 4 take profit levels based on your strategy.
Adjust Risk Settings: Specify your account size and risk percentage to calculate position size and leverage.
Choose Cumulative or Non-Cumulative Mode: Toggle cumulative profit mode to either recalculate position sizes as each take profit is hit or keep position sizes static for each TP.
Once set up, ProfitGuard Pro will automatically calculate your position size, leverage, and potential profits for each take profit level, providing a clear visual on your chart to guide your trading decisions.
Key Features:
Risk Management:
Calculate your risk percentage based on account size and stop loss.
Visualize risk in dollar terms and percentage of your account.
Position Size & Leverage:
Automatically calculate the ideal position size and leverage for your trade based on your entry, stop loss, and risk settings.
Ensure you are trading with the appropriate leverage for your account size.
Cumulative vs Non-Cumulative Profit Mode:
Cumulative Mode: Adjusts position size after each take profit is reached, recalculating for remaining contracts.
Non-Cumulative Mode: Treats each take profit as a separate calculation using the full position size.
Take Profit Levels:
Set up to 4 customizable take profit levels.
Adjust percentage values for each TP target, and visualize them on your chart with easy-to-read lines.
Profit Calculation:
Displays potential profits for each take profit level based on whether cumulative or non-cumulative mode is selected.
Calculate your risk-reward ratio dynamically at each TP.
Customizable Visuals:
Easily customize the table's size, position, and color scheme to fit your chart.
Visualize key trade details like leverage, contracts, margin, and profits directly on your chart.
Short and Long Position Support:
Automatically adjusts calculations based on whether you're trading long or short.
Value at Risk (VaR/CVaR) - Stop Loss ToolThis script calculates Value at Risk (VaR) and Conditional Value at Risk (CVaR) over a configurable T-bar forward horizon, based on historical T-bar log returns. It plots projected price thresholds that reflect the worst X% of historical return outcomes, helping set statistically grounded stop-loss levels.
A 95% 5-day VaR of −3% means: “In the worst 5% of all historical 5-day periods, losses were 3% or more.” If you're bullish, and your thesis is correct, price should not behave like one of those worst-case scenarios. So if the market starts trading below that 5-day VaR level, it may indicate that your long bias is invalidated, and a stop-loss near that level can help protect against further downside consistent with tail-risk behavior.
How it's different:
Unlike ATR or standard deviation-based methods, which measure recent volatility magnitude, VaR/CVaR incorporate both the magnitude and **likelihood** (5% chance for example) of adverse moves. This makes it better suited for risk-aware position sizing and exits grounded in actual historical return distributions.
How to use for stop placement:
- Set your holding horizon (T) and confidence level (e.g., 95%) in the inputs.
- The script plots a price level below which only the worst 5% (or chosen %) of T-bar returns have historically occurred (VaR).
- If price approaches or breaches the VaR line, your bullish/bearish thesis may be invalidated.
- CVaR gives a deeper threshold: the average loss **if** things go worse than VaR — useful for a secondary or emergency stop.
FURTHER NOTES FROM SOURCE CODE:
//======================================================================//
// If you're bullish (expecting the price to go up), then under normal circumstances, prices should not behave like they do on the worst-case days.
// If they are — you're probably wrong, or something unexpected is happening. Basically, returns shouldn't be exhibiting downside tail-like behavior if you're bullish.
// VaR(95%, T) gives the threshold below which the price falls only 5% of the time historically, over T days/bars and considering N historical samples.
// CVaR tells you the expected/average price level if that adverse move continues
// Caveats:
// For a variety of reasons, VaR underestimates volatility, despite using historical returns directly rather than making normality assumptions
// as is the case with the standard historicalvol/bollinger band/stdev/ATR approaches)
// Volatility begets volatility (volatility clustering), and VaR is not a conditional probability on recent volatility so it likely underestimates the true volatility of an adverse event
// Regieme shifts occur (bullish phase after prolonged bearish behavior), so upside/short VaR would underestimate the best-case days in the beginning of that move, depending on lookahead horizon/sampling period
// News/events happen, and maybe your sampling period doesn't contain enough event-driven returns to form reliable stats
// In general of course, this tool assumes past return distributions are reflective of forward risk (not the case in non-stationary time series)
// Thus, this tool is not predictive — it shows historical tail risk, not guaranteed outcomes.
// Also, when forming log-returns, overlapping windows of returns are used (to get more samples), but this introduces autocorrelation (if it wasn't there already). This means again, the true VaR is underestimated.
// Description:
// This script calculates and plots both Value at Risk (VaR) and
// Conditional Value at Risk (CVaR) for a given confidence level, using
// historical log returns. It computes both long-side (left tail) and
// short-side (right tail) risk, and converts them into price thresholds (red and green lines respectively).
//
// Key Concepts:
// - VaR: "There is a 95% chance the loss will be less than this value over T days. Represents the 95th-percentile worst empirical returns observed in the sampling period, over T bars.
// - CVaR: "Given that the loss exceeds the VaR, the average of those worst 5% losses is this value. (blue line)" Expected tail loss. If the worst case breached, how bad can it get on average
// - For shorts, the script computes the mirror (right-tail) equivalents.
// - Use T-day log returns if estimating risk over multiple days forward.
// - You can see instances where the VaR for time T, was surpassed historically with the "backtest" boolean
//
// Usage for Stop-Loss:
// - LONG POSITIONS:
// • 95th percentile means, 5% of the time (1 in 20 times) you'd expect to get a VaR level loss (touch the red line), over the next T bars.
// • VaR threshold = minimum price expected with (1 – confidence)% chance.
// • CVaR threshold = expected price if that worst-case zone is breached.
// → Use as potential stop-loss (VaR) or disaster stop (CVaR). If you're bullish (and you're right), price should not be exhibiting returns consistent with the worst 5% of days/T_bars historically.
//======================================================================//
1A Monthly P&L Table - Using Library1A Monthly P&L Table: Track Your Performance Month-by-Month
Overview:
The 1A Monthly P&L Table is a straightforward yet powerful indicator designed to give you an immediate overview of your asset's (or strategy's) percentage performance on a monthly basis. Displayed conveniently in the bottom-right corner of your chart, this tool helps you quickly assess historical gains and losses, making it easier to analyze trends in performance over time.
Key Features:
Monthly Performance at a Glance: Clearly see the percentage change for each past month.
Cumulative P&L: A running total of the displayed monthly P&L is provided, giving you a quick sum of performance over the selected period.
Customizable Display:
Months to Display: Choose how many past months you want to see in the table (from 1 to 60 months).
Text Size: Adjust the text size (Tiny, Small, Normal, Large, Huge) to fit your viewing preferences.
Text Color: Customize the color of the text for better visibility against your chart background.
Intraday & Daily Compatibility: The table is optimized to display on daily and intraday timeframes, ensuring it's relevant for various trading styles. (Note: For very long-term analysis on weekly/monthly charts, you might consider other tools, as this focuses on granular monthly P&L.)
How It Works:
The indicator calculates the percentage change from the close of the previous month to the close of the current month. For the very first month displayed, it calculates the P&L from the opening price of the chart's first bar to the close of that month. This data is then neatly organized into a table, updated on the last bar of the day or session.
Ideal For:
Traders and investors who want a quick, visual summary of monthly performance.
Analyzing seasonal trends or consistent periods of profitability/drawdown.
Supplementing backtesting results with a clear month-by-month breakdown.
Settings:
Text Color: Changes the color of all text within the table.
Text Size: Controls the font size of the table content.
Months to Display: Determines the number of recent months included in the table.
ZenAlgo - DominatorThis indicator provides a structured multi-ticker overview of market momentum and relative strength by analyzing short-term price behavior across selected assets in comparison with broader crypto dominance and Bitcoin/ETH performance.
Ticker and Market Data Handling
The script accepts up to 9 user-defined symbols (tickers) along with BTCUSD and ETHUSD. For each symbol:
It retrieves the current price.
It also requests the daily opening price from the "D" timeframe to compute intraday percentage change.
For BTC, ETH, and dominance (sum of BTC, USDT, and USDC dominance), daily change is calculated using this same method.
This comparison enables tracking relative performance from the daily open, which provides meaningful insight into intraday strength or weakness among different assets.
Dominance Logic
The indicator aggregates dominance data from BTC , USDT , and USDC using TradingView’s CRYPTOCAP indices. This combined dominance is used as a reference in directional and status calculations. ETH dominance is also analyzed independently.
Changes in dominance are used to infer whether market attention is shifting toward Bitcoin/stablecoins (typically indicating risk-off sentiment) or away from them (typically risk-on behavior, benefiting altcoins).
Price Direction Estimation
The script estimates directional bias using an EMA-based deviation technique:
A short EMA (user-defined lookback , default 4 bars) is calculated.
The current close is compared to the EMA to assess directional bias.
Recent candle changes are also inspected to confirm a consistent short-term trend (e.g., 3 consecutive higher closes for "up").
A small threshold is used to avoid classifying flat movements as trends.
This directionality logic is applied separately to:
The selected ticker's price
BTC price
Combined dominance
This allows the script to contextualize the movement of each asset within broader market conditions.
Market Status Evaluation
A custom function analyzes ETH and BTC dominance trends along with their relative strength to define the overall market regime:
Altseason is identified when BTC dominance is declining, ETH dominance rising, and ETH outperforms BTC.
BTC Season occurs when BTC dominance is rising, ETH dominance falling, and BTC outperforms ETH.
If neither condition is met, the state is Neutral .
This classification is shown alongside each ticker's row in the table and helps traders assess whether market conditions favor Bitcoin, Ethereum, or altcoins in general.
Ticker Status Classification
Each ticker is analyzed independently using the earlier directional logic. Its status is then determined as follows:
Full Bull : Ticker is trending up while dominance is declining or BTC is also rising.
Bullish : Ticker is trending up but not supported by broader bullish context.
Bearish : Ticker is trending down but without broader confirmation.
Full Bear : Ticker is trending down while dominance rises or BTC falls.
Neutral : No strong directional bias or conflicting context.
This classification reflects short-term momentum and macro alignment and is color-coded in the results table.
Table Display and Plotting
A configurable table is shown on the chart, which:
Displays the name and status of each selected ticker.
Optionally includes BTC, ETH, and market state.
Uses color-coding for intuitive interpretation.
Additionally, price changes from the daily open are plotted for each selected ticker, BTC, ETH, and combined dominance. These values are also labeled directly on the chart.
Labeling and UX Enhancements
Labels next to the current candle display price and percent change for each active ticker and for BTC, ETH, and combined dominance.
Labels update each bar, and old labels are deleted to avoid clutter.
Ticker names are dynamically shortened by stripping exchange prefixes.
How to Use This Indicator
This tool helps traders:
Spot early rotations between Bitcoin and altcoins.
Identify intraday momentum leaders or laggards.
Monitor which tickers align with or diverge from broader market trends.
Detect possible sentiment shifts based on dominance trends.
It is best used on lower to mid timeframes (15m–4h) to capture intraday to short-term shifts. Users should cross-reference with longer-term trend tools or structural indicators when making directional decisions.
Interpretation of Values
% Change : Measures intraday move from daily open. Strong positive/negative values may indicate breakouts or reversals.
Status : Describes directional strength relative to market conditions.
Market State : Gives a general bias toward BTC dominance, ETH strength, or altcoin momentum.
Limitations & Considerations
The indicator does not analyze liquidity or volume directly.
All logic is based on short-term movements and may produce false signals in ranging or low-volume environments.
Dominance calculations rely on external CRYPTOCAP indices, which may differ from exchange-specific flows.
Added Value Over Other Free Tools
Unlike basic % change tables or price overlays, this indicator:
Integrates dominance-based macro context into ticker evaluation.
Dynamically classifies market regimes (BTC season / Altseason).
Uses multi-factor logic to determine ticker bias, avoiding single-metric interpretation.
Displays consolidated information in a table and chart overlays for rapid assessment.
Crypto Portfolio vs BTC – Custom Blend TrackerThis tool tracks the performance of a custom-weighted crypto portfolio (SUI, BTC, SOL, DEEP, DOGE, LOFI, and Other) against BTC. Simply input your start date to anchor performance and compare your basket’s relative strength over time. Ideal for portfolio benchmarking, alt-season tracking, or macro trend validation.
Supports all timeframes. Based on BTC-relative returns (not USD). Open-source and customizable.
Risk Calculator PRO — manual lot size + auto lot-suggestionWhy risk management?
90 % of traders blow up because they size positions emotionally. This tool forces Risk-First Thinking: choose the amount you’re willing to lose, and the script reverse-engineers everything else.
Key features
1. Manual or Market Entry – click “Use current price” or type a custom entry.
2. Setup-based ₹-Risk – four presets (A/B/C/D). Edit to your workflow.
3. Lot-Size Input + Auto Lot Suggestion – you tell the contract size ⇒ script tells you how many lots.
4. Auto-SL (optional) – tick to push stop-loss to exactly 1-lot risk.
5. Instant Targets – 1 : 2, 1 : 3, 1 : 4, 1 : 5 plotted and alert-ready.
6. P&L Preview – table shows potential profit at each R-multiple plus real ₹ at SL.
7. Margin Column – enter per-lot margin once; script totals it for any size.
8. Clean Table UI – dark/light friendly; updates every 5 bars.
9. Alert Pack – SL, each target, plus copy-paste journal line on the chart.
How to use
1. Add to chart > “Format”.
2. Type the lot size for the symbol (e.g., 1250 for Natural Gas, 1 for cash equity).
3. Pick Side (Buy / Sell) & Setup grade.
4. ✅ If you want the script to place SL for you, tick Auto-SL (risk = 1 lot).
5. Otherwise type your own Stop-loss.
6. Read the table:
• Suggested lots = how many to trade so risk ≤ setup ₹.
• Risk (currency) = real money lost if SL hits.
7. Set TradingView alerts on the built-in conditions (T1_2, SL_hit, etc.) if you’d like push / email.
8. Copy the orange CSV label to Excel / Sheets for journalling.
Best practices
• Never raise risk to “fit” a trade. Lower size instead.
• Review win-rate vs. R multiple monthly; adjust setups A–D accordingly.
• Test Auto-SL in replay before going live.
Disclaimer
This script is educational. Past performance ≠ future results. The author isn’t responsible for trading losses.
CL Live lotsize ROOSTER📄 Description:
This is a utility script designed for manual futures traders who enter with market orders and want to size their positions precisely based on $ risk.
⚙️ Features:
✅ Calculates live contract size based on:
A fixed dollar risk amount (e.g. $100)
A manually set static stop-loss price
The live market price as your entry
✅ Uses a configurable risk-reward ratio (e.g. 1:3)
✅ Plots entry, stop, and target levels on the chart
✅ Displays calculated contract size as a floating label
🎯 Why this tool?
Built to support fast execution workflows , this tool helps traders who:
Enter trades at candle close or open
Want to pre-calculate their market order size before the signal
Prefer a visual, consistent, real-time R:R validation system
Avoid fumbling with the long/short position tool at the last second
🔧 Settings:
Static Stop-Loss Price: Enter the price level where you'd place your SL
Account Risk ($): How much you’re willing to risk per trade
Risk-Reward Ratio: Set your target multiplier (e.g. 3 for 3R)