Structure AnalyzerA momentum indicator that uses the highest and lowest values for price in three different lookback lengths to find the performance relative to three timeframes.
- The yellow line is the product of the price performance in three different timeframes.
- The red line is 200 EMA of the performance.
- The blue columns represent the same calculation or the volume(OBV based).
- The aqua line is the 200 EMA of the volume performance.
How to use: Whenever the performance crosses above the 200 EMA, the price is in an uptrend.
Important: When in a downtrend, the performance will stay below the 200 EMA for a long time; hence it is important o wait until the crossover.
在脚本中搜索"200亿美元是多少人民币"
Minervini Trend TemplateMinervini Trend Template
1. Stock price is above MA 150 and 200
2. MA 150 is above MA 200
3. MA 200 is trending at least 1 month(22 days)
4. MA 50 is above both MA 150 and MA 200
5. Current stock price is 25% above 52 weeks low
6. Current Price is within 25% of 52 week high
7. RS Ratings
Xiang Stoch MACD 200EMAStochastic + MACD + 200 EMA indicator
Green flag
1) MACD crossover Signal line
2) Stochastic in oversold region (=80)
3) Below 200 EMA (direction of trend)
I use 200 EMA to determine the direction of the trend, (can ignore point 3 for both flag if you got other ways).
If green flag, high possibility of market going up.
If red flag, high possibility of market going down.
ARI-DPO TrendThis is a new indicator that uses DPO (Detrended Price Oscillator) and calculating its HMA 200 and EMA 200 is able to show the current price direction.
if the line is below 0 the market is in a downtrend in the short term, otherwise, the market is in an uptrend.
if the line is red, the market is in a downtrend in the long term (bearish), otherwise, the market is in a long term uptrend (bullish)
a sequence of red/green lines means that the market is choppy
Currently, I'm using it with cryptocurrencies to assess if the short term price action.
How it works:
the indicator calculates the DPO (default 21 periods) and its HMA (default 200 periods) and EMA (default 200 periods) and shows if the DPO is above both HMA and SMA (indicator line above 0 and green), below both (indicator line below 0 and red) or between (the indicator line and the colour are not matching: e.g. red line above the zero or green line below zero). the latter is the classic situation of a choppy market or a possible short term reversal.
The aim of this indicator is to find a good entry point for long/short positions.
I'm still testing and improving it, please
let me know in the comments if you find this useful. Cheers!
GAURs Polynomial Regression ChannelsThanks to The Sweet Lord , here is the Gaur's Polynomial Regression Channel.
Its a Polynomial Regression Channel but applied a little differently. Wont go into technical details much. Overview of options is as follows-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Channel Options
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1. Degree of Polynomial: 1/2/3
Default = 3
Defines the degree of polynomials - 1,2,3. Note here, degree 1 will not be a straight line since its applied differently.
Try different degrees for different fits and market conditions.
2. Channel Length:
Default 30 (candles)
You can go beyond 100 or 200 candle lengths but smaller is the usual preference of Poly-Reg-channel traders. It all depends on market conditions and your style of trading. Do your research. I am usually comfortable with a range of 20-50 (in crypto markets).
3. Basis of Channel height/boundries: ATR/Manual
Default: ATR
ATR provides a dynamically adjusted entry/exit bounds of the channels. As ATR changes, the channel bounds also changes its height. It can also be fixed manually. Manual heights wont change automatically.
4. Basis of Y-Value: open/close/ sma / ema / wma /hilow
Default: close
Y- value is the y value of the (x,y) coordinates used while calculating the regression coefficients. Dont worry about it, its nothing serious.
5. Apply channel smoothning using sma?: Yes/No
Default: Yes
Without smoothning, the channel does not "look" good.
6. Shaded Area Height Percentage:
Its the extra margin for the channel. Its in percentage of the total height (defined 3 above) of channels. The shaded area provides an extra allowance for your entries or exits beyond the ATR or manual heights.
7. Plot RSI?: Yes/No
Default: Yes
Plots RSI (orange line in between the channel - its different from the dotted center line) considering the downbound of channels as 0 (oversold) and upbound of channels as 100 (overbought)
8. Plot 200 sma?: Yes/No
Default: Yes
It plots a 200 period fast (green) and 225 period slow (red) sma . I usually use two MAs. Its visually very easy to understand.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sample Strategy
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
You can develop your own strategy with the channels. But following is just one of the ways you can trade.
Best Application: Ranging markets. But can be happily used in volatile conditions, with a little experience.
1. SMA: -- (this condition is optional really)
If green (200) is above red (225) go only long. If red is above green go only short. Defines long term trend of the market.
2. Channel slope: -- (this stuff needs practice/experience)
Depending on the channel slope, like if its tending to go up or down, you can choose to take only short or long trades. It defines short term momentum of the market.
3. ATR based heights:
Since its ATR based, the channel height are our natural entry and exit points.
Long:
When price touches lower shaded area, consider possible long entry. Exit on price entering the upper shaded area.
Short:
Enter on upper bound shaded area, exit on lower.
4. RSI:
For additional conformations. Again note, the RSI considers the lower bound of channel as 0 and upper as 100. But since, the channel moves up and down, the RSI will also move not only as RSI but also with the channel. Meaning, say if the RSI is valued at 50, then it will be near the center of the channel but since the center changes as time and price changes, the RSI valued at 50 at different times will not be at the same horizontal level respect to the graph, although it will be at the same level (center) respect to the channel.
5. PRC Channel Percentage label:
This label is at the lower side a bit ahead of the current candle. Provides you info on what is the channel percentage. This is especially helpful in crypto markets to gauge your possible percentage profit where profits can be much higher than forex or other instruments. It can also helps you select a suitable market/instrument if the channels are based on ATR.
6. Extra indicators:
I usually use stochastic along with this setup for extra conformations.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Donate
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Use freely and donate generously if you find value. Your help will really help.
I had earlier provided BTC addresses for donations but it seems to violate TV House rules.
Hope they make TV coins redeemable in future.
- Pranav Joshi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Extra Info
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// © cpranavjoshi
// special thanks to the "Trading View" people for providing this great platform for free
// ------------------------
// MATH
// ------------------------
// special thanks to an article on the web that provided layman friendly explanation of the maths
// unfortunately i wont be able to provide the link to that article owing to TV restrictions, though i sincerely would have liked to credit the author.
// Google search this phrase, and you should be able to get it in one of the first results - "polynomialregression Mathematics of Polynomial Regression"
// my regression math calculation is a further resolution upon the generalized matrix formula given in the that article.
// the generalized matrix looks scary but in fact its much simpler than one may assume
// the summation sign things are just float numbers that can be easily found out
// so we get a matrix with number of equations equal to the number of unknowns.
// e.g. if its a 3rd degree poly, it has 4 unknowns (c0,c1,c2,c3) with 4 equations as in the generalized matrix
// it can be resolved by simple algebra
// Note: the results have been verified with excel using same input data points.
// pine was difficult for me so i coded it in python first to verify
// ------------------------
// WHY
// ------------------------
// this script was coded because Pranav badly needed Polynomial channels (had used them in mt4 earlier)
// and at the time of this coding, i could not find any readily available script in the trading view public library ( tnx public)
// the complex math was probably the hurdle
// i m not good in maths, but by the Will of the Lord, i could resolve the issue with simple algebra and logic
// ------------------------
// PINE
// ------------------------
// i am just an average (even poor probably) programmer and pine script is not my language
// this is a humble attempt to write my first pine with whatever i could do quickly
// experts - feel free to develop if needed. have used some workarounds in drawings/plottings. rectify them if possible
//
//
// - Pranav Joshi
Trading Rush Signals & AlertsThis is an unofficial script for strategies tested on TRADING RUSH Youtube channel. Over time, most successful strategies will be added with an option to set strategy-specific alerts . Trading Rush Signals & Alerts will draw signals on the chart when the entry conditions are met. You can also opt for displaying indicators .
My script is meant for beginners but can be used by veterans too. Just pick only one or two strategies, you don't want to flood your chart with conflicting signals. You may want to support your trades with a proper analysis. If a new signal occurs when there is still an open position, you are not supposed to take another.
The current version includes MACD and Donchian Channels.
MACD strategy:
►Buy, when MACD crosses below the signal line when it is negative. The price must also be above 200 EMA.
►Sell, when MACD crosses above the signal line when it is positive. The price must also be below 200 EMA.
►This strategy was tested on 30-minute charts of EURUSD and EURJPY with reward-to-risk ratio 1,5 and win rate of 62% over 100 trades .
►►►MACD has to be added to your chart separately because it needs a new window. Indicators displaying will not add this indicator to the chart.
Donchian Channels strategy:
►Buy, when the price breaches Donchian to the upside after making a new low. The price must also be above 200 EMA.
►Sell, when the price breaches Donchian to the downside after making a new high. The price must also be below 200 EMA.
►Stop-loss is Donchian bottom for long and Donchian top for shorts. Check the channel for more information.
►This strategy was tested on 30-minute charts of EURUSD with reward-to-risk ratio 1,5 and win rate of 58% over 100 trades .
►►►I programmed alerts for Donchians to come ahead of an actual breach. If you often leave the screen when trading, this will help you. The necessary downside for that is the alerts might come when the signal doesn't trigger in the end. You will see a mark on the chart if the conditions are truly met.
Bear in mind that backtesting performance doesn't guarantee future profitability. • Most systematic strategies are not suitable for any timeframe. • You should perform your own backtest to base your trades on more data & to establish confidence in the selected strategy.
New strategies will be added when I have time. If I see multiple people asking for the same new feature, I might agree to release it with a new version. I am not going to add input options in this script, it could come as a separate script though. I am in no way affiliated with the Youtubechannel , so if you find the script helpful, shot me a message or send me some TradingView coins >)
If you encounter any bug, you can report it in a message or in comments. Support it with screenshot and relevant information such as a time when it occurred and what options were on etc.
Moving average Two ColoursExponential moving average of 200 periods, which changes color according to the position of the candles.
(200 periods: default configuration Option to change periods allowed)
If the candles are on the EMA, this will have green color, otherwise red color (colors, thickness configurable).
**********************************************************************************************************************************************
Descripción en Español:
Media móvil Exponencial de 200 periodos, la cuál cambia de color según posición de las velas.
(200 periodos: configuración default. Opción de cambio de periodos permitida)
Si las velas están sobre la EMA , esta tendrá color verde, caso contrario color rojo (colores, grosor configurables).
cci based potential buy/sell signal
Commodity Channel Index Potential Buy Signal
Commodity Channel Index (CCI) is below oversold line (-200).
CCI then crosses above -100 line
Commodity Channel Index Potential Sell Signal
Commodity Channel Index (CCI) is above overbought line (+200).
CCI then crosses below +100 line.
Türkçe Açıklama;
CCI Potansiyel Al Sinyali
CCI indikatörünün -200 altında bulunduğu bölgeler aşırı satış bölgeleri,
Sonrasında aşağıdan gelerek -100 çizgisinin üzerine çıktığı yada çıkmak üzere olduğu noktalar al sinyali
CCI Potansiyel Satl Sinyali
CCI indikatörünün +200 üzerinde bulunduğu bölgeler aşırı alım bölgeleri,
Sonrasında yukarıdan inerek +100 çizgisinin altına indiği yada inmek üzere olduğu noktalar sat sinyali
Not: Tek başına kullanılması son derece hatalı sonuçlar verebilir. Sadece olabilirlik potansiyeli taşımaktadır.
Exponential Moving Average (Set of 3) [Krypt] + 13/34 EMAsI took Krypt's script and essentially added on to it.
the 20/50/100/200 EMAs should be used together as support and resistance as normal.
Wait for price to break 200 EMA
Wait for 50 EMA to cross 200 EMA
Wait for pullback to 50 EMA to open position
20 and 100 EMAs are for extra information about moving support and resistance
and 13/34 EMAs should be used in conjunction
When 13 EMA crosses 34 EMA, open position
When price gets far from 13/34, close position (because price will attempt to revert back to mean)
This is better for scalping and swing trades than the 20/50/100/200 setup.
Twitter: @AzorAhai06
ST_Trend_ReversalSTRONG TREND REVERSAL INDICATOR
The code is the percentage difference between the spot price of a given financial asset and its 200-day MA of that period. My standard setup is Daily, and I think it's got very good predictive power at that timeframe.
It can be read in two ways:
1. Values extremely above or below the 200-period MA present chances of buying/selling agains the prevailing trend.
2. Values closely above or below the 200-period MA are make-or-break market periods, where a medium-term trend becomes evident. Breaks above or below the MA are associated with strong chances of directional movements. But it's not fool-proof as false breaks have become commonplace nowadays.
Other way to use it is as confirmation of breakdowns: For example, an asset that loses its 200-day MA and then can't rally above it becomes exposed to steep losses afterwards.
It's also helpful to use in volatility trading: the closer the asset goes to its MA, the lower goes implied vol, and thus better opportiunities to be long volatility on those occasions where direction is hard to predict.
STRI = close/(200dMA)
Values over 100 indicate percentage premiums of spot vs its moving average.
Values below indicate percentage discounts of spot vs its moving average.
HeikenAshi[1]This is the alert script so you can automate this strategy using AutoView:
Make sure to use
crossing down value 0.9 once per bar (on condition) for this.
For the alert Message if you're using AutoView:
Long GBPUSD
c=order b=short
c=position b=short l=200 t=market
b=long q=0.01 l=200 t=market tp=60 sl=60
Short GBPUSD
c=order b=long
c=position b=long l=200 t=market
b=short q=0.01 l=200 t=market tp=60 sl=60
How to automate this strategy for free using a chrome extension.Hey everyone,
Recently we developed a chrome extension for automating TradingView strategies using the alerts they provide. Initially we were charging a monthly fee for the extension, but we have now decided to make it FREE for everyone. So to display the power of automating strategies via TradingView, we figured we would also provide a profitable strategy along with the custom alert script and commands for the alerts so you can easily cut and paste to begin trading for profit while you sleep.
Step 1:
You are going to need to download the Chrome Extension called AutoView. You can get the extension for free by following this link: bit.ly ( I had to shorten the link as it contains Google and TV automatically converts it to a symbol)
Step 2: Go to your chrome extension page, and under the new extension you'll see a "settings" button. In the setting you will have to connect and give permission to the exchange 1broker allowing the extension to place your orders automatically when triggered by an alert.
Step 3: Setup the strategy and custom script for the alerts in TradingView. The attached script is the strategy, you can play with the settings yourself to try and get better numbers/performance if you please.
This following script is for the custom alerts:
//@version=2
study("4All-Alert", shorttitle="Alerts")
src = close
len = input(4, minval=1, title="Length")
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsin = input(5)
sn = 100 - rsin
ln = 0 + rsin
short = crossover(rsi, sn) ? 1 : 0
long = crossunder(rsi, ln) ? 1 : 0
plot(long, "Long", color=green)
plot(short, "Short", color=red)
Now that you have the extension installed, the custom strategy and alert scripts in place, you simply need to create the alerts.
To get the alerts to communicate with the extension properly, there is a specific syntax that you will need to put in the message of the alert. You can find more details about the syntax here : gist.github.com
For this specific strategy, I use the Alerts script, long/short greater than 0.9 on close.
In the message for a long place this as your message:
Long
c=order b=short
c=position b=short l=200 t=market
b=long q=0.01 l=200 t=market tp=13 sl=25
and for the short...
Short
c=order b=long
c=position b=long l=200 t=market
b=short q=0.01 l=200 t=market tp=13 sl=25
If you'll notice in my above messages, compared to the strategy my tp and sl (take profit and stop loss) vary by a few pips. This is to cover the market opens and spread on 1broker. You can change the tp and sl in the strategy to the above and see that the overall profit will not vary much at all.
I hope this all makes sense and it is enough to not only make some people money, but to show the power of coming up with your own strategy and automating it using TradingView alerts and the free Chrome Extension AutoView.
ps. I highly recommend upgrading your TradingView account so you have access to back testing and multiple alerts.
There is really no reason you won't cover the cost and then some on a monthly basis using the tools provided.
Best of luck and happy trading.
Note: The extension currently allows for automation on 2 exchanges; 1broker and Okcoin. If you do not have accounts there, we'd appreciate you signing up using our referral links.
www.okcoin.com
1broker.com
Dynamic Equity Allocation Model//@version=6
indicator('Dynamic Equity Allocation Model', shorttitle = 'DEAM', overlay = false, precision = 1, scale = scale.right, max_bars_back = 500)
// DYNAMIC EQUITY ALLOCATION MODEL
// Quantitative framework for dynamic portfolio allocation between stocks and cash.
// Analyzes five dimensions: market regime, risk metrics, valuation, sentiment,
// and macro conditions to generate allocation recommendations (0-100% equity).
//
// Uses real-time data from TradingView including fundamentals (P/E, ROE, ERP),
// volatility indicators (VIX), credit spreads, yield curves, and market structure.
// INPUT PARAMETERS
group1 = 'Model Configuration'
model_type = input.string('Adaptive', 'Allocation Model Type', options = , group = group1, tooltip = 'Conservative: Slower to increase equity, Aggressive: Faster allocation changes, Adaptive: Dynamic based on regime')
use_crisis_detection = input.bool(true, 'Enable Crisis Detection System', group = group1, tooltip = 'Automatic detection and response to crisis conditions')
use_regime_model = input.bool(true, 'Use Market Regime Detection', group = group1, tooltip = 'Identify Bull/Bear/Crisis regimes for dynamic allocation')
group2 = 'Portfolio Risk Management'
target_portfolio_volatility = input.float(12.0, 'Target Portfolio Volatility (%)', minval = 3, maxval = 20, step = 0.5, group = group2, tooltip = 'Target portfolio volatility (Cash reduces volatility: 50% Equity = ~10% vol, 100% Equity = ~20% vol)')
max_portfolio_drawdown = input.float(15.0, 'Maximum Portfolio Drawdown (%)', minval = 5, maxval = 35, step = 2.5, group = group2, tooltip = 'Maximum acceptable PORTFOLIO drawdown (not market drawdown - portfolio with cash has lower drawdown)')
enable_portfolio_risk_scaling = input.bool(true, 'Enable Portfolio Risk Scaling', group = group2, tooltip = 'Scale allocation based on actual portfolio risk characteristics (recommended)')
risk_lookback = input.int(252, 'Risk Calculation Period (Days)', minval = 60, maxval = 504, group = group2, tooltip = 'Period for calculating volatility and risk metrics')
group3 = 'Component Weights (Total = 100%)'
w_regime = input.float(35.0, 'Market Regime Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_risk = input.float(25.0, 'Risk Metrics Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_valuation = input.float(20.0, 'Valuation Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_sentiment = input.float(15.0, 'Sentiment Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_macro = input.float(5.0, 'Macro Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
group4 = 'Crisis Detection Thresholds'
crisis_vix_threshold = input.float(40, 'Crisis VIX Level', minval = 30, maxval = 80, group = group4, tooltip = 'VIX level indicating crisis conditions (COVID peaked at 82)')
crisis_drawdown_threshold = input.float(15, 'Crisis Drawdown Threshold (%)', minval = 10, maxval = 30, group = group4, tooltip = 'Market drawdown indicating crisis conditions')
crisis_credit_spread = input.float(500, 'Crisis Credit Spread (bps)', minval = 300, maxval = 1000, group = group4, tooltip = 'High yield spread indicating crisis conditions')
group5 = 'Display Settings'
show_components = input.bool(false, 'Show Component Breakdown', group = group5, tooltip = 'Display individual component analysis lines')
show_regime_background = input.bool(true, 'Show Dynamic Background', group = group5, tooltip = 'Color background based on allocation signals')
show_reference_lines = input.bool(false, 'Show Reference Lines', group = group5, tooltip = 'Display allocation percentage reference lines')
show_dashboard = input.bool(true, 'Show Analytics Dashboard', group = group5, tooltip = 'Display comprehensive analytics table')
show_confidence_bands = input.bool(false, 'Show Confidence Bands', group = group5, tooltip = 'Display uncertainty quantification bands')
smoothing_period = input.int(3, 'Smoothing Period', minval = 1, maxval = 10, group = group5, tooltip = 'Smoothing to reduce allocation noise')
background_intensity = input.int(95, 'Background Intensity (%)', minval = 90, maxval = 99, group = group5, tooltip = 'Higher values = more transparent background')
// Styling Options
color_scheme = input.string('EdgeTools', 'Color Theme', options = , group = 'Appearance', tooltip = 'Professional color themes')
use_dark_mode = input.bool(true, 'Optimize for Dark Theme', group = 'Appearance')
main_line_width = input.int(3, 'Main Line Width', minval = 1, maxval = 5, group = 'Appearance')
// DATA RETRIEVAL
// Market Data
sp500 = request.security('SPY', timeframe.period, close)
sp500_high = request.security('SPY', timeframe.period, high)
sp500_low = request.security('SPY', timeframe.period, low)
sp500_volume = request.security('SPY', timeframe.period, volume)
// Volatility Indicators
vix = request.security('VIX', timeframe.period, close)
vix9d = request.security('VIX9D', timeframe.period, close)
vxn = request.security('VXN', timeframe.period, close)
// Fixed Income and Credit
us2y = request.security('US02Y', timeframe.period, close)
us10y = request.security('US10Y', timeframe.period, close)
us3m = request.security('US03MY', timeframe.period, close)
hyg = request.security('HYG', timeframe.period, close)
lqd = request.security('LQD', timeframe.period, close)
tlt = request.security('TLT', timeframe.period, close)
// Safe Haven Assets
gold = request.security('GLD', timeframe.period, close)
usd = request.security('DXY', timeframe.period, close)
yen = request.security('JPYUSD', timeframe.period, close)
// Financial data with fallback values
get_financial_data(symbol, fin_id, period, fallback) =>
data = request.financial(symbol, fin_id, period, ignore_invalid_symbol = true)
na(data) ? fallback : data
// SPY fundamental metrics
spy_earnings_per_share = get_financial_data('AMEX:SPY', 'EARNINGS_PER_SHARE_BASIC', 'TTM', 20.0)
spy_operating_earnings_yield = get_financial_data('AMEX:SPY', 'OPERATING_EARNINGS_YIELD', 'FY', 4.5)
spy_dividend_yield = get_financial_data('AMEX:SPY', 'DIVIDENDS_YIELD', 'FY', 1.8)
spy_buyback_yield = get_financial_data('AMEX:SPY', 'BUYBACK_YIELD', 'FY', 2.0)
spy_net_margin = get_financial_data('AMEX:SPY', 'NET_MARGIN', 'TTM', 12.0)
spy_debt_to_equity = get_financial_data('AMEX:SPY', 'DEBT_TO_EQUITY', 'FY', 0.5)
spy_return_on_equity = get_financial_data('AMEX:SPY', 'RETURN_ON_EQUITY', 'FY', 15.0)
spy_free_cash_flow = get_financial_data('AMEX:SPY', 'FREE_CASH_FLOW', 'TTM', 100000000)
spy_ebitda = get_financial_data('AMEX:SPY', 'EBITDA', 'TTM', 200000000)
spy_pe_forward = get_financial_data('AMEX:SPY', 'PRICE_EARNINGS_FORWARD', 'FY', 18.0)
spy_total_debt = get_financial_data('AMEX:SPY', 'TOTAL_DEBT', 'FY', 500000000)
spy_total_equity = get_financial_data('AMEX:SPY', 'TOTAL_EQUITY', 'FY', 1000000000)
spy_enterprise_value = get_financial_data('AMEX:SPY', 'ENTERPRISE_VALUE', 'FY', 30000000000)
spy_revenue_growth = get_financial_data('AMEX:SPY', 'REVENUE_ONE_YEAR_GROWTH', 'TTM', 5.0)
// Market Breadth Indicators
nya = request.security('NYA', timeframe.period, close)
rut = request.security('IWM', timeframe.period, close)
// Sector Performance
xlk = request.security('XLK', timeframe.period, close)
xlu = request.security('XLU', timeframe.period, close)
xlf = request.security('XLF', timeframe.period, close)
// MARKET REGIME DETECTION
// Calculate Market Trend
sma_20 = ta.sma(sp500, 20)
sma_50 = ta.sma(sp500, 50)
sma_200 = ta.sma(sp500, 200)
ema_10 = ta.ema(sp500, 10)
// Market Structure Score
trend_strength = 0.0
trend_strength := trend_strength + (sp500 > sma_20 ? 1 : -1)
trend_strength := trend_strength + (sp500 > sma_50 ? 1 : -1)
trend_strength := trend_strength + (sp500 > sma_200 ? 2 : -2)
trend_strength := trend_strength + (sma_50 > sma_200 ? 2 : -2)
// Volatility Regime
returns = math.log(sp500 / sp500 )
realized_vol_20d = ta.stdev(returns, 20) * math.sqrt(252) * 100
realized_vol_60d = ta.stdev(returns, 60) * math.sqrt(252) * 100
ewma_vol = ta.ema(math.pow(returns, 2), 20)
realized_vol = math.sqrt(ewma_vol * 252) * 100
vol_premium = vix - realized_vol
// Drawdown Calculation
running_max = ta.highest(sp500, risk_lookback)
current_drawdown = (running_max - sp500) / running_max * 100
// Regime Score
regime_score = 0.0
// Trend Component (40%)
if trend_strength >= 4
regime_score := regime_score + 40
regime_score
else if trend_strength >= 2
regime_score := regime_score + 30
regime_score
else if trend_strength >= 0
regime_score := regime_score + 20
regime_score
else if trend_strength >= -2
regime_score := regime_score + 10
regime_score
else
regime_score := regime_score + 0
regime_score
// Volatility Component (30%)
if vix < 15
regime_score := regime_score + 30
regime_score
else if vix < 20
regime_score := regime_score + 25
regime_score
else if vix < 25
regime_score := regime_score + 15
regime_score
else if vix < 35
regime_score := regime_score + 5
regime_score
else
regime_score := regime_score + 0
regime_score
// Drawdown Component (30%)
if current_drawdown < 3
regime_score := regime_score + 30
regime_score
else if current_drawdown < 7
regime_score := regime_score + 20
regime_score
else if current_drawdown < 12
regime_score := regime_score + 10
regime_score
else if current_drawdown < 20
regime_score := regime_score + 5
regime_score
else
regime_score := regime_score + 0
regime_score
// Classify Regime
market_regime = regime_score >= 80 ? 'Strong Bull' : regime_score >= 60 ? 'Bull Market' : regime_score >= 40 ? 'Neutral' : regime_score >= 20 ? 'Correction' : regime_score >= 10 ? 'Bear Market' : 'Crisis'
// RISK-BASED ALLOCATION
// Calculate Market Risk
parkinson_hl = math.log(sp500_high / sp500_low)
parkinson_vol = parkinson_hl / (2 * math.sqrt(math.log(2))) * math.sqrt(252) * 100
garman_klass_vol = math.sqrt((0.5 * math.pow(math.log(sp500_high / sp500_low), 2) - (2 * math.log(2) - 1) * math.pow(math.log(sp500 / sp500 ), 2)) * 252) * 100
market_volatility_20d = math.max(ta.stdev(returns, 20) * math.sqrt(252) * 100, parkinson_vol)
market_volatility_60d = ta.stdev(returns, 60) * math.sqrt(252) * 100
market_drawdown = current_drawdown
// Initialize risk allocation
risk_allocation = 50.0
if enable_portfolio_risk_scaling
// Volatility-based allocation
vol_based_allocation = target_portfolio_volatility / math.max(market_volatility_20d, 5.0) * 100
vol_based_allocation := math.max(0, math.min(100, vol_based_allocation))
// Drawdown-based allocation
dd_based_allocation = 100.0
if market_drawdown > 1.0
dd_based_allocation := max_portfolio_drawdown / market_drawdown * 100
dd_based_allocation := math.max(0, math.min(100, dd_based_allocation))
dd_based_allocation
// Combine (conservative)
risk_allocation := math.min(vol_based_allocation, dd_based_allocation)
// Dynamic adjustment
current_equity_estimate = 50.0
estimated_portfolio_vol = current_equity_estimate / 100 * market_volatility_20d
estimated_portfolio_dd = current_equity_estimate / 100 * market_drawdown
vol_utilization = estimated_portfolio_vol / target_portfolio_volatility
dd_utilization = estimated_portfolio_dd / max_portfolio_drawdown
risk_utilization = math.max(vol_utilization, dd_utilization)
risk_adjustment_factor = 1.0
if risk_utilization > 1.0
risk_adjustment_factor := math.exp(-0.5 * (risk_utilization - 1.0))
risk_adjustment_factor := math.max(0.5, risk_adjustment_factor)
risk_adjustment_factor
else if risk_utilization < 0.9
risk_adjustment_factor := 1.0 + 0.2 * math.log(1.0 / risk_utilization)
risk_adjustment_factor := math.min(1.3, risk_adjustment_factor)
risk_adjustment_factor
risk_allocation := risk_allocation * risk_adjustment_factor
risk_allocation
else
vol_scalar = target_portfolio_volatility / math.max(market_volatility_20d, 10)
vol_scalar := math.min(1.5, math.max(0.2, vol_scalar))
drawdown_penalty = 0.0
if current_drawdown > max_portfolio_drawdown
drawdown_penalty := (current_drawdown - max_portfolio_drawdown) / max_portfolio_drawdown
drawdown_penalty := math.min(1.0, drawdown_penalty)
drawdown_penalty
risk_allocation := 100 * vol_scalar * (1 - drawdown_penalty)
risk_allocation
risk_allocation := math.max(0, math.min(100, risk_allocation))
// VALUATION ANALYSIS
// Valuation Metrics
actual_pe_ratio = spy_earnings_per_share > 0 ? sp500 / spy_earnings_per_share : spy_pe_forward
actual_earnings_yield = nz(spy_operating_earnings_yield, 0) > 0 ? spy_operating_earnings_yield : 100 / actual_pe_ratio
total_shareholder_yield = spy_dividend_yield + spy_buyback_yield
// Equity Risk Premium (multi-method calculation)
method1_erp = actual_earnings_yield - us10y
method2_erp = actual_earnings_yield + spy_buyback_yield - us10y
payout_ratio = spy_dividend_yield > 0 and actual_earnings_yield > 0 ? spy_dividend_yield / actual_earnings_yield : 0.4
sustainable_growth = spy_return_on_equity * (1 - payout_ratio) / 100
method3_erp = spy_dividend_yield + sustainable_growth * 100 - us10y
implied_growth = spy_revenue_growth * 0.7
method4_erp = total_shareholder_yield + implied_growth - us10y
equity_risk_premium = method1_erp * 0.35 + method2_erp * 0.30 + method3_erp * 0.20 + method4_erp * 0.15
ev_ebitda_ratio = spy_enterprise_value > 0 and spy_ebitda > 0 ? spy_enterprise_value / spy_ebitda : 15.0
debt_equity_health = spy_debt_to_equity < 1.0 ? 1.2 : spy_debt_to_equity < 2.0 ? 1.0 : 0.8
// Valuation Score
base_valuation_score = 50.0
if equity_risk_premium > 4
base_valuation_score := 95
base_valuation_score
else if equity_risk_premium > 3
base_valuation_score := 85
base_valuation_score
else if equity_risk_premium > 2
base_valuation_score := 70
base_valuation_score
else if equity_risk_premium > 1
base_valuation_score := 55
base_valuation_score
else if equity_risk_premium > 0
base_valuation_score := 40
base_valuation_score
else if equity_risk_premium > -1
base_valuation_score := 25
base_valuation_score
else
base_valuation_score := 10
base_valuation_score
growth_adjustment = spy_revenue_growth > 10 ? 10 : spy_revenue_growth > 5 ? 5 : 0
margin_adjustment = spy_net_margin > 15 ? 5 : spy_net_margin < 8 ? -5 : 0
roe_adjustment = spy_return_on_equity > 20 ? 5 : spy_return_on_equity < 10 ? -5 : 0
valuation_score = base_valuation_score + growth_adjustment + margin_adjustment + roe_adjustment
valuation_score := math.max(0, math.min(100, valuation_score * debt_equity_health))
// SENTIMENT ANALYSIS
// VIX Term Structure
vix_term_structure = vix9d > 0 ? vix / vix9d : 1
backwardation = vix_term_structure > 1.05
steep_backwardation = vix_term_structure > 1.15
// Safe Haven Flows
gold_momentum = ta.roc(gold, 20)
dollar_momentum = ta.roc(usd, 20)
yen_momentum = ta.roc(yen, 20)
treasury_momentum = ta.roc(tlt, 20)
safe_haven_flow = gold_momentum * 0.3 + treasury_momentum * 0.3 + dollar_momentum * 0.25 + yen_momentum * 0.15
// Advanced Sentiment Analysis
vix_percentile = ta.percentrank(vix, 252)
vix_zscore = (vix - ta.sma(vix, 252)) / ta.stdev(vix, 252)
vix_momentum = ta.roc(vix, 5)
vvix_proxy = ta.stdev(vix_momentum, 20) * math.sqrt(252)
risk_reversal_proxy = (vix - realized_vol) / realized_vol
// Sentiment Score
base_sentiment = 50.0
vix_adjustment = 0.0
if vix_zscore < -1.5
vix_adjustment := 40
vix_adjustment
else if vix_zscore < -0.5
vix_adjustment := 20
vix_adjustment
else if vix_zscore < 0.5
vix_adjustment := 0
vix_adjustment
else if vix_zscore < 1.5
vix_adjustment := -20
vix_adjustment
else
vix_adjustment := -40
vix_adjustment
term_structure_adjustment = backwardation ? -15 : steep_backwardation ? -30 : 5
vvix_adjustment = vvix_proxy > 2.0 ? -10 : vvix_proxy < 1.0 ? 10 : 0
sentiment_score = base_sentiment + vix_adjustment + term_structure_adjustment + vvix_adjustment
sentiment_score := math.max(0, math.min(100, sentiment_score))
// MACRO ANALYSIS
// Yield Curve
yield_spread_2_10 = us10y - us2y
yield_spread_3m_10 = us10y - us3m
// Credit Conditions
hyg_return = ta.roc(hyg, 20)
lqd_return = ta.roc(lqd, 20)
tlt_return = ta.roc(tlt, 20)
hyg_duration = 4.0
lqd_duration = 8.0
tlt_duration = 17.0
hyg_log_returns = math.log(hyg / hyg )
lqd_log_returns = math.log(lqd / lqd )
hyg_volatility = ta.stdev(hyg_log_returns, 20) * math.sqrt(252)
lqd_volatility = ta.stdev(lqd_log_returns, 20) * math.sqrt(252)
hyg_yield_proxy = -math.log(hyg / hyg ) * 100
lqd_yield_proxy = -math.log(lqd / lqd ) * 100
tlt_yield = us10y
hyg_spread = (hyg_yield_proxy - tlt_yield) * 100
lqd_spread = (lqd_yield_proxy - tlt_yield) * 100
hyg_distance = (hyg - ta.lowest(hyg, 252)) / (ta.highest(hyg, 252) - ta.lowest(hyg, 252))
lqd_distance = (lqd - ta.lowest(lqd, 252)) / (ta.highest(lqd, 252) - ta.lowest(lqd, 252))
default_risk_proxy = 2.0 - (hyg_distance + lqd_distance)
credit_spread = hyg_spread * 0.5 + (hyg_volatility - lqd_volatility) * 1000 * 0.3 + default_risk_proxy * 200 * 0.2
credit_spread := math.max(50, credit_spread)
credit_market_health = hyg_return > lqd_return ? 1 : -1
flight_to_quality = tlt_return > (hyg_return + lqd_return) / 2
// Macro Score
macro_score = 50.0
yield_curve_score = 0
if yield_spread_2_10 > 1.5 and yield_spread_3m_10 > 2
yield_curve_score := 40
yield_curve_score
else if yield_spread_2_10 > 0.5 and yield_spread_3m_10 > 1
yield_curve_score := 30
yield_curve_score
else if yield_spread_2_10 > 0 and yield_spread_3m_10 > 0
yield_curve_score := 20
yield_curve_score
else if yield_spread_2_10 < 0 or yield_spread_3m_10 < 0
yield_curve_score := 10
yield_curve_score
else
yield_curve_score := 5
yield_curve_score
credit_conditions_score = 0
if credit_spread < 200 and not flight_to_quality
credit_conditions_score := 30
credit_conditions_score
else if credit_spread < 400 and credit_market_health > 0
credit_conditions_score := 20
credit_conditions_score
else if credit_spread < 600
credit_conditions_score := 15
credit_conditions_score
else if credit_spread < 1000
credit_conditions_score := 10
credit_conditions_score
else
credit_conditions_score := 0
credit_conditions_score
financial_stability_score = 0
if spy_debt_to_equity < 0.5 and spy_return_on_equity > 15
financial_stability_score := 20
financial_stability_score
else if spy_debt_to_equity < 1.0 and spy_return_on_equity > 10
financial_stability_score := 15
financial_stability_score
else if spy_debt_to_equity < 1.5
financial_stability_score := 10
financial_stability_score
else
financial_stability_score := 5
financial_stability_score
macro_score := yield_curve_score + credit_conditions_score + financial_stability_score
macro_score := math.max(0, math.min(100, macro_score))
// CRISIS DETECTION
crisis_indicators = 0
if vix > crisis_vix_threshold
crisis_indicators := crisis_indicators + 1
crisis_indicators
if vix > 60
crisis_indicators := crisis_indicators + 2
crisis_indicators
if current_drawdown > crisis_drawdown_threshold
crisis_indicators := crisis_indicators + 1
crisis_indicators
if current_drawdown > 25
crisis_indicators := crisis_indicators + 1
crisis_indicators
if credit_spread > crisis_credit_spread
crisis_indicators := crisis_indicators + 1
crisis_indicators
sp500_roc_5 = ta.roc(sp500, 5)
tlt_roc_5 = ta.roc(tlt, 5)
if sp500_roc_5 < -10 and tlt_roc_5 < -5
crisis_indicators := crisis_indicators + 2
crisis_indicators
volume_spike = sp500_volume > ta.sma(sp500_volume, 20) * 2
sp500_roc_1 = ta.roc(sp500, 1)
if volume_spike and sp500_roc_1 < -3
crisis_indicators := crisis_indicators + 1
crisis_indicators
is_crisis = crisis_indicators >= 3
is_severe_crisis = crisis_indicators >= 5
// FINAL ALLOCATION CALCULATION
// Convert regime to base allocation
regime_allocation = market_regime == 'Strong Bull' ? 100 : market_regime == 'Bull Market' ? 80 : market_regime == 'Neutral' ? 60 : market_regime == 'Correction' ? 40 : market_regime == 'Bear Market' ? 20 : 0
// Normalize weights
total_weight = w_regime + w_risk + w_valuation + w_sentiment + w_macro
w_regime_norm = w_regime / total_weight
w_risk_norm = w_risk / total_weight
w_valuation_norm = w_valuation / total_weight
w_sentiment_norm = w_sentiment / total_weight
w_macro_norm = w_macro / total_weight
// Calculate Weighted Allocation
weighted_allocation = regime_allocation * w_regime_norm + risk_allocation * w_risk_norm + valuation_score * w_valuation_norm + sentiment_score * w_sentiment_norm + macro_score * w_macro_norm
// Apply Crisis Override
if use_crisis_detection
if is_severe_crisis
weighted_allocation := math.min(weighted_allocation, 10)
weighted_allocation
else if is_crisis
weighted_allocation := math.min(weighted_allocation, 25)
weighted_allocation
// Model Type Adjustment
model_adjustment = 0.0
if model_type == 'Conservative'
model_adjustment := -10
model_adjustment
else if model_type == 'Aggressive'
model_adjustment := 10
model_adjustment
else if model_type == 'Adaptive'
recent_return = (sp500 - sp500 ) / sp500 * 100
if recent_return > 5
model_adjustment := 5
model_adjustment
else if recent_return < -5
model_adjustment := -5
model_adjustment
// Apply adjustment and bounds
final_allocation = weighted_allocation + model_adjustment
final_allocation := math.max(0, math.min(100, final_allocation))
// Smooth allocation
smoothed_allocation = ta.sma(final_allocation, smoothing_period)
// Calculate portfolio risk metrics (only for internal alerts)
actual_portfolio_volatility = smoothed_allocation / 100 * market_volatility_20d
actual_portfolio_drawdown = smoothed_allocation / 100 * current_drawdown
// VISUALIZATION
// Color definitions
var color primary_color = #2196F3
var color bullish_color = #4CAF50
var color bearish_color = #FF5252
var color neutral_color = #808080
var color text_color = color.white
var color bg_color = #000000
var color table_bg_color = #1E1E1E
var color header_bg_color = #2D2D2D
switch color_scheme // Apply color scheme
'Gold' =>
primary_color := use_dark_mode ? #FFD700 : #DAA520
bullish_color := use_dark_mode ? #FFA500 : #FF8C00
bearish_color := use_dark_mode ? #FF5252 : #D32F2F
neutral_color := use_dark_mode ? #C0C0C0 : #808080
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #1A1A00 : #FFFEF0
header_bg_color := use_dark_mode ? #2D2600 : #F5F5DC
header_bg_color
'EdgeTools' =>
primary_color := use_dark_mode ? #4682B4 : #1E90FF
bullish_color := use_dark_mode ? #4CAF50 : #388E3C
bearish_color := use_dark_mode ? #FF5252 : #D32F2F
neutral_color := use_dark_mode ? #708090 : #696969
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #0F1419 : #F0F8FF
header_bg_color := use_dark_mode ? #1E2A3A : #E6F3FF
header_bg_color
'Behavioral' =>
primary_color := #808080
bullish_color := #00FF00
bearish_color := #8B0000
neutral_color := #FFBF00
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #1A1A1A : #F8F8F8
header_bg_color := use_dark_mode ? #2D2D2D : #E8E8E8
header_bg_color
'Quant' =>
primary_color := #808080
bullish_color := #FFA500
bearish_color := #8B0000
neutral_color := #4682B4
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #0D0D0D : #FAFAFA
header_bg_color := use_dark_mode ? #1A1A1A : #F0F0F0
header_bg_color
'Ocean' =>
primary_color := use_dark_mode ? #20B2AA : #008B8B
bullish_color := use_dark_mode ? #00CED1 : #4682B4
bearish_color := use_dark_mode ? #FF4500 : #B22222
neutral_color := use_dark_mode ? #87CEEB : #2F4F4F
text_color := use_dark_mode ? #F0F8FF : #191970
bg_color := use_dark_mode ? #001F3F : #F0F8FF
table_bg_color := use_dark_mode ? #001A2E : #E6F7FF
header_bg_color := use_dark_mode ? #002A47 : #CCF2FF
header_bg_color
'Fire' =>
primary_color := use_dark_mode ? #FF6347 : #DC143C
bullish_color := use_dark_mode ? #FFD700 : #FF8C00
bearish_color := use_dark_mode ? #8B0000 : #800000
neutral_color := use_dark_mode ? #FFA500 : #CD853F
text_color := use_dark_mode ? #FFFAF0 : #2F1B14
bg_color := use_dark_mode ? #2F1B14 : #FFFAF0
table_bg_color := use_dark_mode ? #261611 : #FFF8F0
header_bg_color := use_dark_mode ? #3D241A : #FFE4CC
header_bg_color
'Matrix' =>
primary_color := use_dark_mode ? #00FF41 : #006400
bullish_color := use_dark_mode ? #39FF14 : #228B22
bearish_color := use_dark_mode ? #FF073A : #8B0000
neutral_color := use_dark_mode ? #00FFFF : #008B8B
text_color := use_dark_mode ? #C0FF8C : #003300
bg_color := use_dark_mode ? #0D1B0D : #F0FFF0
table_bg_color := use_dark_mode ? #0A1A0A : #E8FFF0
header_bg_color := use_dark_mode ? #112B11 : #CCFFCC
header_bg_color
'Arctic' =>
primary_color := use_dark_mode ? #87CEFA : #4169E1
bullish_color := use_dark_mode ? #00BFFF : #0000CD
bearish_color := use_dark_mode ? #FF1493 : #8B008B
neutral_color := use_dark_mode ? #B0E0E6 : #483D8B
text_color := use_dark_mode ? #F8F8FF : #191970
bg_color := use_dark_mode ? #191970 : #F8F8FF
table_bg_color := use_dark_mode ? #141B47 : #F0F8FF
header_bg_color := use_dark_mode ? #1E2A5C : #E0F0FF
header_bg_color
// Transparency settings
bg_transparency = use_dark_mode ? 85 : 92
zone_transparency = use_dark_mode ? 90 : 95
band_transparency = use_dark_mode ? 70 : 85
table_transparency = use_dark_mode ? 80 : 15
// Allocation color
alloc_color = smoothed_allocation >= 80 ? bullish_color : smoothed_allocation >= 60 ? color.new(bullish_color, 30) : smoothed_allocation >= 40 ? primary_color : smoothed_allocation >= 20 ? color.new(bearish_color, 30) : bearish_color
// Dynamic background
var color dynamic_bg_color = na
if show_regime_background
if smoothed_allocation >= 70
dynamic_bg_color := color.new(bullish_color, background_intensity)
dynamic_bg_color
else if smoothed_allocation <= 30
dynamic_bg_color := color.new(bearish_color, background_intensity)
dynamic_bg_color
else if smoothed_allocation > 60 or smoothed_allocation < 40
dynamic_bg_color := color.new(primary_color, math.min(99, background_intensity + 2))
dynamic_bg_color
bgcolor(dynamic_bg_color, title = 'Allocation Signal Background')
// Plot main allocation line
plot(smoothed_allocation, 'Equity Allocation %', color = alloc_color, linewidth = math.max(1, main_line_width))
// Reference lines (static colors for hline)
hline_bullish_color = color_scheme == 'Gold' ? use_dark_mode ? #FFA500 : #FF8C00 : color_scheme == 'EdgeTools' ? use_dark_mode ? #4CAF50 : #388E3C : color_scheme == 'Behavioral' ? #00FF00 : color_scheme == 'Quant' ? #FFA500 : color_scheme == 'Ocean' ? use_dark_mode ? #00CED1 : #4682B4 : color_scheme == 'Fire' ? use_dark_mode ? #FFD700 : #FF8C00 : color_scheme == 'Matrix' ? use_dark_mode ? #39FF14 : #228B22 : color_scheme == 'Arctic' ? use_dark_mode ? #00BFFF : #0000CD : #4CAF50
hline_bearish_color = color_scheme == 'Gold' ? use_dark_mode ? #FF5252 : #D32F2F : color_scheme == 'EdgeTools' ? use_dark_mode ? #FF5252 : #D32F2F : color_scheme == 'Behavioral' ? #8B0000 : color_scheme == 'Quant' ? #8B0000 : color_scheme == 'Ocean' ? use_dark_mode ? #FF4500 : #B22222 : color_scheme == 'Fire' ? use_dark_mode ? #8B0000 : #800000 : color_scheme == 'Matrix' ? use_dark_mode ? #FF073A : #8B0000 : color_scheme == 'Arctic' ? use_dark_mode ? #FF1493 : #8B008B : #FF5252
hline_primary_color = color_scheme == 'Gold' ? use_dark_mode ? #FFD700 : #DAA520 : color_scheme == 'EdgeTools' ? use_dark_mode ? #4682B4 : #1E90FF : color_scheme == 'Behavioral' ? #808080 : color_scheme == 'Quant' ? #808080 : color_scheme == 'Ocean' ? use_dark_mode ? #20B2AA : #008B8B : color_scheme == 'Fire' ? use_dark_mode ? #FF6347 : #DC143C : color_scheme == 'Matrix' ? use_dark_mode ? #00FF41 : #006400 : color_scheme == 'Arctic' ? use_dark_mode ? #87CEFA : #4169E1 : #2196F3
hline(show_reference_lines ? 100 : na, '100% Equity', color = color.new(hline_bullish_color, 70), linestyle = hline.style_dotted, linewidth = 1)
hline(show_reference_lines ? 80 : na, '80% Equity', color = color.new(hline_bullish_color, 40), linestyle = hline.style_dashed, linewidth = 1)
hline(show_reference_lines ? 60 : na, '60% Equity', color = color.new(hline_bullish_color, 60), linestyle = hline.style_dotted, linewidth = 1)
hline(50, '50% Balanced', color = color.new(hline_primary_color, 50), linestyle = hline.style_solid, linewidth = 2)
hline(show_reference_lines ? 40 : na, '40% Equity', color = color.new(hline_bearish_color, 60), linestyle = hline.style_dotted, linewidth = 1)
hline(show_reference_lines ? 20 : na, '20% Equity', color = color.new(hline_bearish_color, 40), linestyle = hline.style_dashed, linewidth = 1)
hline(show_reference_lines ? 0 : na, '0% Equity', color = color.new(hline_bearish_color, 70), linestyle = hline.style_dotted, linewidth = 1)
// Component plots
plot(show_components ? regime_allocation : na, 'Regime', color = color.new(#4ECDC4, 70), linewidth = 1)
plot(show_components ? risk_allocation : na, 'Risk', color = color.new(#FF6B6B, 70), linewidth = 1)
plot(show_components ? valuation_score : na, 'Valuation', color = color.new(#45B7D1, 70), linewidth = 1)
plot(show_components ? sentiment_score : na, 'Sentiment', color = color.new(#FFD93D, 70), linewidth = 1)
plot(show_components ? macro_score : na, 'Macro', color = color.new(#6BCF7F, 70), linewidth = 1)
// Confidence bands
upper_band = plot(show_confidence_bands ? math.min(100, smoothed_allocation + ta.stdev(smoothed_allocation, 20)) : na, color = color.new(neutral_color, band_transparency), display = display.none, title = 'Upper Band')
lower_band = plot(show_confidence_bands ? math.max(0, smoothed_allocation - ta.stdev(smoothed_allocation, 20)) : na, color = color.new(neutral_color, band_transparency), display = display.none, title = 'Lower Band')
fill(upper_band, lower_band, color = show_confidence_bands ? color.new(neutral_color, zone_transparency) : na, title = 'Uncertainty')
// DASHBOARD
if show_dashboard and barstate.islast
var table dashboard = table.new(position.top_right, 2, 20, border_width = 1, bgcolor = color.new(table_bg_color, table_transparency))
table.clear(dashboard, 0, 0, 1, 19)
// Header
header_color = color.new(header_bg_color, 20)
dashboard_text_color = text_color
table.cell(dashboard, 0, 0, 'DEAM', text_color = dashboard_text_color, bgcolor = header_color, text_size = size.normal)
table.cell(dashboard, 1, 0, model_type, text_color = dashboard_text_color, bgcolor = header_color, text_size = size.normal)
// Core metrics
table.cell(dashboard, 0, 1, 'Equity Allocation', text_color = dashboard_text_color, text_size = size.small)
table.cell(dashboard, 1, 1, str.tostring(smoothed_allocation, '##.#') + '%', text_color = alloc_color, text_size = size.small)
table.cell(dashboard, 0, 2, 'Cash Allocation', text_color = dashboard_text_color, text_size = size.small)
cash_color = 100 - smoothed_allocation > 70 ? bearish_color : primary_color
table.cell(dashboard, 1, 2, str.tostring(100 - smoothed_allocation, '##.#') + '%', text_color = cash_color, text_size = size.small)
// Signal
signal_text = 'NEUTRAL'
signal_color = primary_color
if smoothed_allocation >= 70
signal_text := 'BULLISH'
signal_color := bullish_color
signal_color
else if smoothed_allocation <= 30
signal_text := 'BEARISH'
signal_color := bearish_color
signal_color
table.cell(dashboard, 0, 3, 'Signal', text_color = dashboard_text_color, text_size = size.small)
table.cell(dashboard, 1, 3, signal_text, text_color = signal_color, text_size = size.small)
// Market Regime
table.cell(dashboard, 0, 4, 'Regime', text_color = dashboard_text_color, text_size = size.small)
regime_color_display = market_regime == 'Strong Bull' or market_regime == 'Bull Market' ? bullish_color : market_regime == 'Neutral' ? primary_color : market_regime == 'Crisis' ? bearish_color : bearish_color
table.cell(dashboard, 1, 4, market_regime, text_color = regime_color_display, text_size = size.small)
// VIX
table.cell(dashboard, 0, 5, 'VIX Level', text_color = dashboard_text_color, text_size = size.small)
vix_color_display = vix < 20 ? bullish_color : vix < 30 ? primary_color : bearish_color
table.cell(dashboard, 1, 5, str.tostring(vix, '##.##'), text_color = vix_color_display, text_size = size.small)
// Market Drawdown
table.cell(dashboard, 0, 6, 'Market DD', text_color = dashboard_text_color, text_size = size.small)
market_dd_color = current_drawdown < 5 ? bullish_color : current_drawdown < 10 ? primary_color : bearish_color
table.cell(dashboard, 1, 6, '-' + str.tostring(current_drawdown, '##.#') + '%', text_color = market_dd_color, text_size = size.small)
// Crisis Detection
table.cell(dashboard, 0, 7, 'Crisis Detection', text_color = dashboard_text_color, text_size = size.small)
crisis_text = is_severe_crisis ? 'SEVERE' : is_crisis ? 'CRISIS' : 'Normal'
crisis_display_color = is_severe_crisis or is_crisis ? bearish_color : bullish_color
table.cell(dashboard, 1, 7, crisis_text, text_color = crisis_display_color, text_size = size.small)
// Real Data Section
financial_bg = color.new(primary_color, 85)
table.cell(dashboard, 0, 8, 'REAL DATA', text_color = dashboard_text_color, bgcolor = financial_bg, text_size = size.small)
table.cell(dashboard, 1, 8, 'Live Metrics', text_color = dashboard_text_color, bgcolor = financial_bg, text_size = size.small)
// P/E Ratio
table.cell(dashboard, 0, 9, 'P/E Ratio', text_color = dashboard_text_color, text_size = size.small)
pe_color = actual_pe_ratio < 18 ? bullish_color : actual_pe_ratio < 25 ? primary_color : bearish_color
table.cell(dashboard, 1, 9, str.tostring(actual_pe_ratio, '##.#'), text_color = pe_color, text_size = size.small)
// ERP
table.cell(dashboard, 0, 10, 'ERP', text_color = dashboard_text_color, text_size = size.small)
erp_color = equity_risk_premium > 2 ? bullish_color : equity_risk_premium > 0 ? primary_color : bearish_color
table.cell(dashboard, 1, 10, str.tostring(equity_risk_premium, '##.##') + '%', text_color = erp_color, text_size = size.small)
// ROE
table.cell(dashboard, 0, 11, 'ROE', text_color = dashboard_text_color, text_size = size.small)
roe_color = spy_return_on_equity > 20 ? bullish_color : spy_return_on_equity > 10 ? primary_color : bearish_color
table.cell(dashboard, 1, 11, str.tostring(spy_return_on_equity, '##.#') + '%', text_color = roe_color, text_size = size.small)
// D/E Ratio
table.cell(dashboard, 0, 12, 'D/E Ratio', text_color = dashboard_text_color, text_size = size.small)
de_color = spy_debt_to_equity < 0.5 ? bullish_color : spy_debt_to_equity < 1.0 ? primary_color : bearish_color
table.cell(dashboard, 1, 12, str.tostring(spy_debt_to_equity, '##.##'), text_color = de_color, text_size = size.small)
// Shareholder Yield
table.cell(dashboard, 0, 13, 'Dividend+Buyback', text_color = dashboard_text_color, text_size = size.small)
yield_color = total_shareholder_yield > 4 ? bullish_color : total_shareholder_yield > 2 ? primary_color : bearish_color
table.cell(dashboard, 1, 13, str.tostring(total_shareholder_yield, '##.#') + '%', text_color = yield_color, text_size = size.small)
// Component Scores
component_bg = color.new(neutral_color, 80)
table.cell(dashboard, 0, 14, 'Components', text_color = dashboard_text_color, bgcolor = component_bg, text_size = size.small)
table.cell(dashboard, 1, 14, 'Scores', text_color = dashboard_text_color, bgcolor = component_bg, text_size = size.small)
table.cell(dashboard, 0, 15, 'Regime', text_color = dashboard_text_color, text_size = size.small)
regime_score_color = regime_allocation > 60 ? bullish_color : regime_allocation < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 15, str.tostring(regime_allocation, '##'), text_color = regime_score_color, text_size = size.small)
table.cell(dashboard, 0, 16, 'Risk', text_color = dashboard_text_color, text_size = size.small)
risk_score_color = risk_allocation > 60 ? bullish_color : risk_allocation < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 16, str.tostring(risk_allocation, '##'), text_color = risk_score_color, text_size = size.small)
table.cell(dashboard, 0, 17, 'Valuation', text_color = dashboard_text_color, text_size = size.small)
val_score_color = valuation_score > 60 ? bullish_color : valuation_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 17, str.tostring(valuation_score, '##'), text_color = val_score_color, text_size = size.small)
table.cell(dashboard, 0, 18, 'Sentiment', text_color = dashboard_text_color, text_size = size.small)
sent_score_color = sentiment_score > 60 ? bullish_color : sentiment_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 18, str.tostring(sentiment_score, '##'), text_color = sent_score_color, text_size = size.small)
table.cell(dashboard, 0, 19, 'Macro', text_color = dashboard_text_color, text_size = size.small)
macro_score_color = macro_score > 60 ? bullish_color : macro_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 19, str.tostring(macro_score, '##'), text_color = macro_score_color, text_size = size.small)
// ALERTS
// Major allocation changes
alertcondition(smoothed_allocation >= 80 and smoothed_allocation < 80, 'High Equity Allocation', 'Equity allocation reached 80% - Bull market conditions')
alertcondition(smoothed_allocation <= 20 and smoothed_allocation > 20, 'Low Equity Allocation', 'Equity allocation dropped to 20% - Defensive positioning')
// Crisis alerts
alertcondition(is_crisis and not is_crisis , 'CRISIS DETECTED', 'Crisis conditions detected - Reducing equity allocation')
alertcondition(is_severe_crisis and not is_severe_crisis , 'SEVERE CRISIS', 'Severe crisis detected - Maximum defensive positioning')
// Regime changes
regime_changed = market_regime != market_regime
alertcondition(regime_changed, 'Regime Change', 'Market regime has changed')
// Risk management alerts
risk_breach = enable_portfolio_risk_scaling and (actual_portfolio_volatility > target_portfolio_volatility * 1.2 or actual_portfolio_drawdown > max_portfolio_drawdown * 1.2)
alertcondition(risk_breach, 'Risk Breach', 'Portfolio risk exceeds target parameters')
// USAGE
// The indicator displays a recommended equity allocation percentage (0-100%).
// Example: 75% allocation = 75% stocks, 25% cash/bonds.
//
// The model combines market regime analysis (trend, volatility, drawdowns),
// risk management (portfolio-level targeting), valuation metrics (P/E, ERP),
// sentiment indicators (VIX term structure), and macro factors (yield curve,
// credit spreads) into a single allocation signal.
//
// Crisis detection automatically reduces exposure when multiple warning signals
// converge. Alerts available for major allocation shifts and regime changes.
//
// Designed for SPY/S&P 500 portfolio allocation. Adjust component weights and
// risk parameters in settings to match your risk tolerance.
View in Pine
Market Energy & Direction DashboardMarket Energy & Direction Dashboard - Daytrading
Overview
A comprehensive real-time market internals dashboard that combines NYSE TICK, NYSE Advance-Decline (ADD) momentum, VIX direction, and relative volume into a single visual traffic light system with intelligent signal synthesis. Designed for active daytraders who need instant confirmation of market direction and energy based on momentum alignment across all major internals.
What It Does
This indicator synthesizes multiple market internals using directional momentum analysis rather than static thresholds to provide clear, actionable signals:
• Traffic Light System: Single glance confirmation of market state
o Bright Green: Maximum bullish - all internals aligned (TICK + ADD rising + VIX falling + volume)
o Bright Red: Maximum bearish - all internals aligned (TICK + ADD falling + VIX rising + volume)
o Yellow: Exhaustion warning - TICK at extremes, potential reversal imminent
o Moderate Colors: Partial alignment - some confirmation but not complete
o Gray: Choppy, neutral, or conflicting signals
• Real-Time Dashboard displays:
o Current TICK value with exhaustion warnings
o Current ADD with directional momentum indicator (↑ rising = breadth improving, ↓ falling = breadth deteriorating, ± compression)
o VIX level with directional indicator (↓ declining = bullish, ↑ rising = bearish, ± compression = neutral)
o Relative volume (current vs 20-period average)
o Composite status message synthesizing all data into clear directional summary
Key Features
✓ Momentum-based analysis - all indicators show direction/change, not just levels ✓ Intelligent signal hierarchy from "Maximum" to "Moderate" based on internal alignment ✓ ADD directional momentum - catches breadth shifts early, works in all market conditions ✓ VIX directional analysis - shows if fear is increasing, decreasing, or stagnant ✓ Color-coded traffic light for instant decision making ✓ Detects TICK/ADD divergences (conflicting signals = caution) ✓ Exhaustion warnings at extreme TICK levels (±1000+) ✓ Composite status messages - "Maximum Bull", "Strong Bull", "Moderate Bull", etc. ✓ Customizable thresholds for all parameters ✓ Moveable dashboard (9 position options) ✓ Built-in alerts for all signal strengths, exhaustion, and divergences
How To Use
Setup:
1. Add indicator to your main trading chart (SPY, ES, NQ, etc.)
2. Default settings work well for most traders, but you can customize:
o TICK Extreme Level (default 1000)
o ADD Compression Threshold (default 100 - detects when breadth is stagnant)
o VIX Elevated Level (default 20)
o VIX Compression Threshold (default 2% - detects low volatility)
o Volume Threshold (default 1.5x average)
3. Position dashboard wherever convenient on your chart
Reading The Signals:
Signal Hierarchy (Strongest to Weakest):
MAXIMUM SIGNALS ⭐ (Brightest colors - All 4 internals aligned)
• "✓ MAXIMUM BULL": TICK bullish + ADD rising (↑) + VIX falling (↓) + Volume elevated
o This is the holy grail setup - all momentum aligned, highest conviction longs
• "✓ MAXIMUM BEAR": TICK bearish + ADD falling (↓) + VIX rising (↑) + Volume elevated
o Perfect storm bearish - all momentum aligned, highest conviction shorts
STRONG SIGNALS (Bright colors - Core internals aligned)
• "✓ STRONG BULL": TICK bullish + ADD rising (↑)
o Strong confirmation even without VIX/volume - breadth supporting the move
• "✓ STRONG BEAR": TICK bearish + ADD falling (↓)
o Strong confirmation - both momentum and breadth deteriorating
MODERATE SIGNALS (Faded colors - Partial confirmation)
• "MODERATE BULL": TICK bullish but ADD not confirming direction
o Proceed with caution - momentum present but breadth questionable
• "MODERATE BEAR": TICK bearish but ADD not confirming direction
o Proceed with caution - selling but breadth not fully participating
WARNING SIGNALS
• "⚠ EXHAUSTION" (Yellow): TICK at ±1000+ extremes
o Potential reversal zone - prepare to fade or take profits
o Often marks blow-off tops or capitulation bottoms
NEUTRAL/AVOID
• "CHOPPY/NEUTRAL" (Gray): Conflicting signals or low conviction
o Stay out or reduce size significantly
Individual Indicator Interpretation:
TICK:
• Green: Bullish momentum (>+300)
• Red: Bearish momentum (<-300)
• Yellow: Exhaustion (±1000+)
• Gray: Neutral
ADD (Advance-Decline):
• Green (↑): Breadth improving - more stocks participating in the move
• Red (↓): Breadth deteriorating - fewer stocks participating
• Gray (±): Breadth stagnant - no clear participation trend
VIX:
• Green (↓): Fear declining - healthy environment for rallies
• Red (↑): Fear rising - risk-off mode, supports downward moves
• Gray (±): Volatility compression - often precedes explosive moves
Volume:
• Green: High conviction (>1.5x average)
• Gray: Low conviction
Trading Strategy:
1. Wait for "MAXIMUM" or "STRONG" signals for highest probability entries
o Maximum signals = go full size with confidence
o Strong signals = good conviction, normal position sizing
2. Confirm directional alignment:
o For longs: Want ADD ↑ (rising) and VIX ↓ (falling)
o For shorts: Want ADD ↓ (falling) and VIX ↑ (rising)
3. Use exhaustion warnings (yellow) to:
o Take profits on existing positions
o Prepare counter-trend entries
o Tighten stops
4. Avoid "MODERATE" signals unless you have strong conviction from other analysis
o These work best as confirmation for existing setups
o Not strong enough to initiate new positions alone
5. Never trade "CHOPPY/NEUTRAL" signals
o Gray means stay out - preserve capital
o Wait for clear alignment
6. Watch for divergences:
o Price making new highs but ADD ↓ (falling) = distribution warning
o Price making new lows but ADD ↑ (rising) = potential bottom
o Divergence alert will notify you
Best Practices:
• Use on 1-5 minute charts for daytrading
• Combine with your price action or technical setup (support/resistance, trendlines, patterns)
• The dashboard confirms when to take your setup, not what setup to take
• Most effective during regular market hours (9:30 AM - 4:00 PM ET) when volume is present
• The strongest edge comes from "MAXIMUM" signals - wait for these for best risk/reward
• Pay special attention to ADD direction - it's the most predictive breadth indicator
• VIX compression (gray ±) often signals upcoming volatility expansion - prepare for bigger moves
Customization Option
All thresholds are adjustable in settings:
• TICK Extreme: Higher = fewer exhaustion warnings (try 1200-1500 for less sensitivity)
• ADD Compression Threshold: Change detection sensitivity
o Default 100 = balanced
o Lower (50) = more sensitive to small breadth changes
o Higher (200-300) = only shows major breadth shifts
• VIX Elevated: Adjust for current volatility regime (15-25 typical range)
• VIX Compression Threshold:
o Default 2% = balanced
o Lower (0.5-1%) = catches subtle VIX changes
o Higher (3-5%) = only shows significant VIX moves
• Volume Threshold: Lower for quieter stocks/times, higher for more confirmation
Alerts Available
• Maximum Bullish: All 4 internals aligned bullish (TICK + ADD↑ + VIX↓ + Volume)
• Maximum Bearish: All 4 internals aligned bearish (TICK + ADD↓ + VIX↑ + Volume)
• Strong Bullish: TICK bullish + ADD rising
• Strong Bearish: TICK bearish + ADD falling
• Exhaustion Warning: TICK at extreme levels
• Divergence Warning: TICK and ADD directions conflicting
Understanding the Signal Synthesis
The indicator uses intelligent logic to combine all internals:
"MAXIMUM" Signals require:
• TICK direction (bullish/bearish)
• ADD momentum (rising/falling) in same direction
• VIX direction (falling for bulls, rising for bears)
• Volume elevated (>1.5x average)
"STRONG" Signals require:
• TICK direction (bullish/bearish)
• ADD momentum (rising/falling) in same direction
• (VIX and volume are bonuses but not required)
"MODERATE" Signals:
• TICK showing direction
• But ADD not confirming or contradicting
• Weakest actionable signal
This hierarchy ensures you know exactly how much conviction the market has behind any move.
Technical Details
• Pulls real-time data from NYSE TICK (USI:TICK), NYSE ADD (USI:ADD), and CBOE VIX
• ADD direction calculated using bar-to-bar change with compression detection
• VIX direction calculated using bar-to-bar percentage change
• Volume calculation uses 20-period simple moving average
• Dashboard updates every bar
• No repainting - all calculations based on closed bar data
Who This Is For
• Active daytraders of stocks, futures (ES/NQ), and options
• Scalpers needing quick directional confirmation with multiple internal alignment
• Swing traders looking to time intraday entries with maximum confluence
• Volatility traders who monitor VIX behavior
• Market makers and professionals who trade based on breadth and internals
• Anyone who monitors market internals but wants intelligent synthesis vs raw data
Tips For Success
Trading Philosophy:
• Quality over quantity - wait for "MAXIMUM" signals for best results
• One "MAXIMUM" signal trade is worth five "MODERATE" signal trades
• Gray/neutral is not a sign of missing opportunity - it's protecting your capital
Signal Confidence Levels:
1. MAXIMUM (95%+ confidence) - Trade these aggressively with full size
2. STRONG (80-85% confidence) - Trade these with normal position sizing
3. MODERATE (60-70% confidence) - Only if confirmed by strong technical setup
4. CHOPPY/NEUTRAL - Do not trade, wait for clarity
Advanced Techniques:
• Breadth divergences: Watch for price making new highs while ADD shows ↓ (falling) = major warning
• VIX/Price divergences: Rallies with rising VIX (↑) are usually false moves
• Volume confirmation: "MAXIMUM" signals with 2x+ volume are the absolute best
• Compression zones: When both ADD and VIX show compression (±), expect explosive breakout soon
• Sequential signals: Back-to-back "MAXIMUM" signals in same direction = strong trending day
Common Patterns:
• Opening surge with "MAXIMUM BULL" that shifts to "EXHAUSTION" (yellow) = fade the high
• Selloff with "MAXIMUM BEAR" followed by ADD ↑ (rising) divergence = potential reversal
• Choppy morning followed by "MAXIMUM" signal afternoon = best trending opportunity
Example Scenarios
Perfect Bull Entry:
• Bright green signal box
• TICK: +650
• ADD: +1200 (↑)
• VIX: 18.30 (↓)
• Volume: 2.3x
• Status: "✓ MAXIMUM BULL" → ALL SYSTEMS GO - Take aggressive long positions
Strong Bull (Good Confidence):
• Green signal box (slightly less bright)
• TICK: +500
• ADD: +800 (↑)
• VIX: 19.50 (±)
• Volume: 1.2x
• Status: "✓ STRONG BULL" → Good long setup - breadth confirming even without VIX/volume
Caution Bull (Moderate):
• Faded green signal box
• TICK: +400
• ADD: +900 (↓)
• VIX: 20.10 (↑)
• Volume: 0.9x
• Status: "MODERATE BULL" → CAUTION - TICK bullish but breadth deteriorating and VIX rising = weak rally
Exhaustion Warning:
• Yellow signal box
• TICK: +1350 ⚠
• ADD: +2100 (↑)
• VIX: 17.20 (↓)
• Volume: 1.8x
• Status: "⚠ EXHAUSTION" → Take profits or prepare to fade - TICK overextended despite good internals
Divergence Setup (Potential Reversal):
• Faded green signal
• TICK: +300
• ADD: +1800 (↓)
• VIX: 21.50 (↑)
• Volume: 1.6x
• Status: "MODERATE BULL" → WARNING - Price rallying but breadth collapsing and fear rising = distribution
Perfect Bear Entry:
• Bright red signal box
• TICK: -780
• ADD: -1600 (↓)
• VIX: 24.80 (↑)
• Volume: 2.5x
• Status: "✓ MAXIMUM BEAR" → Perfect short setup - all momentum bearish with conviction
Compression (Wait Mode):
• Gray signal box
• TICK: +50
• ADD: -200 (±)
• VIX: 16.40 (±)
• Volume: 0.7x
• Status: "CHOPPY/NEUTRAL" → STAY OUT - Volatility compression, no conviction, await breakout
Performance Optimization
Best Market Conditions:
• Works excellent in trending markets (up or down)
• Particularly powerful during high-volume sessions (first/last hours)
• "MAXIMUM" signals most reliable during 9:45-11:00 AM and 2:00-3:30 PM ET
Less Effective During:
• Lunch period (11:30 AM - 1:30 PM) - lower volume reduces signal quality
• Low-volatility environments - compression signals dominate
• Major news events in first 5 minutes - wait for internals to stabilize
Recommended Use Cases:
• Scalping: Trade only "MAXIMUM" signals for quick 5-15 minute moves
• Daytrading: Use "MAXIMUM" and "STRONG" signals for position entries
• Swing entries: Use "MAXIMUM" signals for optimal intraday entry timing
• Exit timing: Use "EXHAUSTION" (yellow) warnings to take profits
________________________________________
Pro Tip: Create a dedicated workspace with this indicator on SPY/ES/NQ charts. Set alerts for "MAXIMUM BULL", "MAXIMUM BEAR", and "EXHAUSTION" signals. Most professional traders only trade the "MAXIMUM" setups and ignore everything else - this alone can dramatically improve win rates.
Smoothed Heikin Ashi + MA MTF📊 MTF Smoothed Heikin Ashi + MA Cross (SHA_MA)This indicator combines a double-smoothed Heikin Ashi (SHA) with the popular 50 and 200 Simple Moving Averages (SMAs), all wrapped in a robust Multi-Timeframe (MTF) engine.This tool is designed to help traders identify and confirm trend direction across multiple timeframes, providing cleaner signals than standard Heikin Ashi candles.
Key Features and BenefitsDouble-Smoothed Heikin Ashi (SHA):SHA candles are created by applying an Exponential Moving Average (EMA) twice to the standard Heikin Ashi calculation.This significantly filters out market noise and choppy price action, making trend reversals and continuations clearer and more reliable.Color Logic: Candles are colored green (lime) when the SHA Close is above the SHA Open (Bullish) and red when the Close is below the Open (Bearish).Multi-Timeframe (MTF) Capability:You can set the SHA candles, MA50, and MA200 to calculate on a higher timeframe (e.g., 4-Hour) while viewing your main chart on a lower timeframe (e.g., 15-Minute).This is crucial for ensuring your trades are aligned with the overall larger trend direction (top-down analysis).Self-Correction: The script automatically prevents errors by reverting the indicator to the chart's native timeframe if a timeframe lower than the chart's is mistakenly selected.Key Moving Averages:Includes the industry-standard 50 SMA (Fast) and 200 SMA (Slow).The crossover between the two MAs (Golden/Death Cross) acts as a powerful confirmation signal for the SHA trend.
⚙️ How to Use ItTrend Confirmation: Use the SHA candle color (Green/Red) to confirm the short-term trend.Long-Term Bias: Use the MA200 as the primary filter. Only look for long entries when price is above the MA200, and short entries when price is below it.MTF Alignment: Set the "Indicator Timeframe" input to a higher level (e.g., 4H or 1D) to ensure your entry timeframe is trading in the direction of the macro trend.CustomizationSettingDefault ValuePurposeIndicator TimeframeChartSet to a higher TF (e.g., 1h, 4h) for MTF analysis.SHA EMA Length 1 & 210Controls the level of smoothing applied to the candles. Higher values mean less noise but more lag.MA 50 & 200 Length50 & 200Standard Moving Average periods.\
BTC GOD — DEFINITIVE BTC MULTI INDICATORBTC GOD — The Ultimate Bitcoin Cycle Indicator (2025 Edition)
The one indicator every serious BTC holder and trader has been waiting for.
A single script that perfectly combines the 5 most powerful and accurate Bitcoin indicators ever created — all 100 % official versions:
- Official Pi Cycle Top (LookIntoBitcoin) → in 2013, 2017 & 2021 (3/3 hits)
- Official MVRV Z-Score (Glassnode / LookIntoBitcoin) → every major bottom (2015, 2018–19, 2022)
- Dynamic Bull/Bear background (red bear-market when price drops X % from cycle ATH + monthly RSI filter)
- Monthly Golden/Death Cross (50-month EMA vs 200-week EMA) → huge, unmistakable signals
- SuperTrend + 200-week EMA + 50-month EMA
- Cycle ATH/ATL tracking with flashing alert in the table when new highs/lows are made
- Exact days to/from the next halving + optimal accumulation zone (200–750 days post-halving)
- Fully customizable inputs for experienced traders
Zero repainting. Zero errors. Works on every timeframe.
This is the indicator used by people who truly understand Bitcoin’s 4-year cycles.
If you could only keep ONE Bitcoin indicator for the rest of your life… this would be it.
Save it, test it, and you’ll instantly see why it’s called BTC GOD.
Built with love and obsession for Bitcoin cycles.
Last update: November 2025
SMC BOS/CHoCH + Auto Fib (5m/any TF) durane//@version=6
indicator('SMC BOS/CHoCH + Auto Fib (5m/any TF)', overlay = true, max_lines_count = 200, max_labels_count = 200)
// --------- Inputs ----------
left = input.int(3, 'Pivot Left', minval = 1)
right = input.int(3, 'Pivot Right', minval = 1)
minSwingSize = input.float(0.0, 'Min swing size (price units, 0 = disabled)', step = 0.1)
fib_levels = input.string('0.0,0.236,0.382,0.5,0.618,0.786,1.0', 'Fibonacci levels (comma separated)')
show_labels = input.bool(true, 'Show BOS/CHoCH labels')
lookbackHighLow = input.int(200, 'Lookback for structure (bars)')
// Parse fib levels
strs = str.split(fib_levels, ',')
var array fibs = array.new_float()
if barstate.isfirst
for s in strs
array.push(fibs, str.tonumber(str.trim(s)))
// --------- Find pivot highs / lows ----------
pHigh = ta.pivothigh(high, left, right)
pLow = ta.pivotlow(low, left, right)
// store last confirmed swings
var float lastSwingHighPrice = na
var int lastSwingHighBar = na
var float lastSwingLowPrice = na
var int lastSwingLowBar = na
if not na(pHigh)
// check min size
if minSwingSize == 0 or pHigh - nz(lastSwingLowPrice, pHigh) >= minSwingSize
lastSwingHighPrice := pHigh
lastSwingHighBar := bar_index - right
lastSwingHighBar
if not na(pLow)
if minSwingSize == 0 or nz(lastSwingHighPrice, pLow) - pLow >= minSwingSize
lastSwingLowPrice := pLow
lastSwingLowBar := bar_index - right
lastSwingLowBar
// --------- Detect BOS & CHoCH (simple robust logic) ----------
var int lastBOSdir = 0 // 1 = bullish BOS (price broke above), -1 = bearish BOS
var int lastBOSbar = na
var float lastBOSprice = na
// Look for price closes beyond last structural swings within lookback
// Bullish BOS: close > recent swing high
condBullBOS = not na(lastSwingHighPrice) and close > lastSwingHighPrice and bar_index - lastSwingHighBar <= lookbackHighLow
// Bearish BOS: close < recent swing low
condBearBOS = not na(lastSwingLowPrice) and close < lastSwingLowPrice and bar_index - lastSwingLowBar <= lookbackHighLow
bosTriggered = false
chochTriggered = false
if condBullBOS
bosTriggered := true
if lastBOSdir != 1
// if previous BOS direction was -1, this is CHoCH (change of character)
chochTriggered := lastBOSdir == -1
chochTriggered
lastBOSdir := 1
lastBOSbar := bar_index
lastBOSprice := close
lastBOSprice
if condBearBOS
bosTriggered := true
if lastBOSdir != -1
chochTriggered := lastBOSdir == 1
chochTriggered
lastBOSdir := -1
lastBOSbar := bar_index
lastBOSprice := close
lastBOSprice
// --------- Plot labels for BOS / CHoCH ----------
if bosTriggered and show_labels
if chochTriggered
label.new(bar_index, high, text = lastBOSdir == 1 ? 'CHoCH ↑' : 'CHoCH ↓', style = label.style_label_up, color = color.new(color.orange, 0), textcolor = color.white, yloc = yloc.abovebar)
else
label.new(bar_index, high, text = lastBOSdir == 1 ? 'BOS ↑' : 'BOS ↓', style = label.style_label_left, color = lastBOSdir == 1 ? color.green : color.red, textcolor = color.white, yloc = yloc.abovebar)
// --------- Auto Fibonacci drawing ----------
var array fib_lines = array.new_line()
var array fib_labels = array.new_label()
var int lastFibId = na
// Function to clear previous fibs
f_clear() =>
if array.size(fib_lines) > 0
for i = 0 to array.size(fib_lines) - 1
line.delete(array.get(fib_lines, i))
if array.size(fib_labels) > 0
for i = 0 to array.size(fib_labels) - 1
label.delete(array.get(fib_labels, i))
array.clear(fib_lines)
array.clear(fib_labels)
// Decide anchors for fib: if lastBOSdir==1 (bullish) anchor from lastSwingLow -> lastSwingHigh
// if lastBOSdir==-1 (bearish) anchor from lastSwingHigh -> lastSwingLow
if lastBOSdir == 1 and not na(lastSwingLowPrice) and not na(lastSwingHighPrice)
// bullish fib: low -> high
startPrice = lastSwingLowPrice
endPrice = lastSwingHighPrice
// draw
f_clear()
for i = 0 to array.size(fibs) - 1 by 1
lvl = array.get(fibs, i)
priceLevel = startPrice + (endPrice - startPrice) * lvl
ln = line.new(x1 = lastSwingLowBar, y1 = priceLevel, x2 = bar_index, y2 = priceLevel, xloc = xloc.bar_index, extend = extend.right, color = color.new(color.green, 60), width = 1, style = line.style_solid)
array.push(fib_lines, ln)
lab = label.new(bar_index, priceLevel, text = str.tostring(lvl * 100, '#.0') + '%', style = label.style_label_right, color = color.new(color.green, 80), textcolor = color.white, yloc = yloc.price)
array.push(fib_labels, lab)
if lastBOSdir == -1 and not na(lastSwingHighPrice) and not na(lastSwingLowPrice)
// bearish fib: high -> low
startPrice = lastSwingHighPrice
endPrice = lastSwingLowPrice
f_clear()
for i = 0 to array.size(fibs) - 1 by 1
lvl = array.get(fibs, i)
priceLevel = startPrice + (endPrice - startPrice) * lvl
ln = line.new(x1 = lastSwingHighBar, y1 = priceLevel, x2 = bar_index, y2 = priceLevel, xloc = xloc.bar_index, extend = extend.right, color = color.new(color.red, 60), width = 1, style = line.style_solid)
array.push(fib_lines, ln)
lab = label.new(bar_index, priceLevel, text = str.tostring(lvl * 100, '#.0') + '%', style = label.style_label_right, color = color.new(color.red, 80), textcolor = color.white, yloc = yloc.price)
array.push(fib_labels, lab)
// --------- Optional: plot lastSwing points ----------
plotshape(not na(lastSwingHighPrice) ? lastSwingHighPrice : na, title = 'LastSwingHigh', location = location.absolute, style = shape.triangledown, size = size.tiny, color = color.red, offset = 0)
plotshape(not na(lastSwingLowPrice) ? lastSwingLowPrice : na, title = 'LastSwingLow', location = location.absolute, style = shape.triangleup, size = size.tiny, color = color.green, offset = 0)
// --------- Alerts ----------
alertcondition(bosTriggered and lastBOSdir == 1, title = 'Bullish BOS', message = 'Bullish BOS detected on {{ticker}} @ {{close}}')
alertcondition(bosTriggered and lastBOSdir == -1, title = 'Bearish BOS', message = 'Bearish BOS detected on {{ticker}} @ {{close}}')
alertcondition(chochTriggered, title = 'CHoCH Detected', message = 'CHoCH detected on {{ticker}} @ {{close}}')
// End
920 Order Flow SATY ATR//@version=6
indicator("Order-Flow / Volume Signals (No L2)", overlay=true)
//======================
// Inputs
//======================
rvolLen = input.int(20, "Relative Volume Lookback", minval=5)
rvolMin = input.float(1.1, "Min Relative Volume (× avg)", step=0.1)
wrbLen = input.int(20, "Wide-Range Lookback", minval=5)
wrbMult = input.float(1, "Wide-Range Multiplier", step=0.1)
upperCloseQ = input.float(0.60, "Close near High (0-1)", minval=0.0, maxval=1.0)
lowerCloseQ = input.float(0.40, "Close near Low (0-1)", minval=0.0, maxval=1.0)
cdLen = input.int(25, "Rolling CumDelta Window", minval=5)
useVWAP = input.bool(true, "Use VWAP Bias Filter")
showSignals = input.bool(true, "Show Long/Short OF Triangles")
//======================
// Core helpers
//======================
rng = high - low
tr = ta.tr(true)
avgTR = ta.sma(tr, wrbLen)
wrb = rng > wrbMult * avgTR
// Relative Volume
volAvg = ta.sma(volume, rvolLen)
rvol = volAvg > 0 ? volume / volAvg : 0.0
// Close location in bar (0..1)
clo = rng > 0 ? (close - low) / rng : 0.5
// VWAP (session) + SMAs
vwap = ta.vwap(close)
sma9 = ta.sma(close, 9)
sma20 = ta.sma(close, 20)
sma200= ta.sma(close, 200)
// CumDelta proxy (uptick/downtick signed volume)
tickSign = close > close ? 1.0 : close < close ? -1.0 : 0.0
delta = volume * tickSign
cumDelta = ta.cum(delta)
rollCD = cumDelta - cumDelta
//======================
// Signal conditions
//======================
volActive = rvol >= rvolMin
effortBuy = wrb and clo >= upperCloseQ
effortSell = wrb and clo <= lowerCloseQ
cdUp = ta.crossover(rollCD, 0)
cdDown = ta.crossunder(rollCD, 0)
biasBuy = not useVWAP or close > vwap
biasSell = not useVWAP or close < vwap
longOF = barstate.isconfirmed and volActive and effortBuy and cdUp and biasBuy
shortOF = barstate.isconfirmed and volActive and effortSell and cdDown and biasSell
//======================
// Plot ONLY on price chart
//======================
// SMAs & VWAP
plot(sma9, title="9 SMA", color=color.orange, linewidth=3)
plot(sma20, title="20 SMA", color=color.white, linewidth=3)
plot(sma200, title="200 SMA", color=color.black, linewidth=3)
plot(vwap, title="VWAP", color=color.new(color.aqua, 0), linewidth=3)
// Triangles with const text (no extra pane)
plotshape(showSignals and longOF, title="LONG OF",
style=shape.triangleup, location=location.belowbar, size=size.tiny,
color=color.new(color.green, 0), text="LONG OF")
plotshape(showSignals and shortOF, title="SHORT OF",
style=shape.triangledown, location=location.abovebar, size=size.tiny,
color=color.new(color.red, 0), text="SHORT OF")
// Alerts
alertcondition(longOF, title="LONG OF confirmed", message="LONG OF confirmed")
alertcondition(shortOF, title="SHORT OF confirmed", message="SHORT OF confirmed")
//────────────────────────────
// End-of-line labels (offset to the right)
//────────────────────────────
var label label9 = na
var label label20 = na
var label label200 = na
var label labelVW = na
if barstate.islast
// delete old labels before drawing new ones
label.delete(label9)
label.delete(label20)
label.delete(label200)
label.delete(labelVW)
// how far to move the labels rightward (increase if needed)
offsetBars = input.int(3)
label9 := label.new(bar_index + offsetBars, sma9, "9 SMA", style=label.style_label_left, textcolor=color.white, color=color.new(color.orange, 0))
label20 := label.new(bar_index + offsetBars, sma20, "20 SMA", style=label.style_label_left, textcolor=color.black, color=color.new(color.white, 0))
label200 := label.new(bar_index + offsetBars, sma200, "200 SMA", style=label.style_label_left, textcolor=color.white, color=color.new(color.black, 0))
labelVW := label.new(bar_index + offsetBars, vwap, "VWAP", style=label.style_label_left, textcolor=color.black, color=color.new(color.aqua, 0))
//────────────────────────────────────────────────────────────────────
//────────────────────────────────────────────
// Overnight High/Low + HOD/LOD (no POC)
//────────────────────────────────────────────
sessionRTH = input.session("0930-1600", "RTH Session (exchange tz)")
levelWidth = input.int(2, "HL line width", minval=1, maxval=5)
labelOffsetH = input.int(10, "HL label offset (bars to right)", minval=0)
isRTH = not na(time(timeframe.period, sessionRTH))
rthOpen = isRTH and not isRTH
// --- Track Overnight High/Low during NON-RTH; freeze at RTH open
// --- Track Overnight High/Low during NON-RTH; freeze at RTH open
var float onHigh = na
var float onLow = na
var int onHighBar = na
var int onLowBar = na
var float onHighFix = na
var float onLowFix = na
var int onHighFixBar = na
var int onLowFixBar = na
if not isRTH
if na(onHigh) or high > onHigh
onHigh := high
onHighBar := bar_index
if na(onLow) or low < onLow
onLow := low
onLowBar := bar_index
if rthOpen
onHighFix := onHigh
onLowFix := onLow
onHighFixBar := onHighBar
onLowFixBar := onLowBar
onHigh := na, onLow := na
onHighBar := na, onLowBar := na
// ──────────────────────────────────────────
// Candle coloring + labels for 9/20/VWAP crosses
// ──────────────────────────────────────────
showCrossLabels = input.bool(true, "Show cross labels")
// Helpers
minAll = math.min(math.min(sma9, sma20), vwap)
maxAll = math.max(math.max(sma9, sma20), vwap)
// All three lines
goldenAll = open <= minAll and close >= maxAll
deathAll = open >= maxAll and close <= minAll
// 9/20 only (exclude cases that also crossed VWAP)
dcUpOnly = open <= math.min(sma9, sma20) and close >= math.max(sma9, sma20) and not goldenAll
dcDownOnly = open >= math.max(sma9, sma20) and close <= math.min(sma9, sma20) and not deathAll
// Candle colors (priority: all three > 9/20 only)
var color cCol = na
cCol := goldenAll ? color.yellow : deathAll ? color.black :dcUpOnly ? color.lime :dcDownOnly ? color.red : na
barcolor(cCol)
// Labels
plotshape(showCrossLabels and barstate.isconfirmed and goldenAll, title="GOLDEN CROSS",
style=shape.labelup, location=location.belowbar, text="GOLDEN CROSS",
color=color.new(color.yellow, 0), textcolor=color.black, size=size.tiny)
plotshape(showCrossLabels and barstate.isconfirmed and deathAll, title="DEATH CROSS",
style=shape.labeldown, location=location.abovebar, text="DEATH CROSS",
color=color.new(color.black, 0), textcolor=color.white, size=size.tiny)
plotshape(showCrossLabels and barstate.isconfirmed and dcUpOnly, title="DC UP",
style=shape.labelup, location=location.belowbar, text="DC UP",
color=color.new(color.lime, 0), textcolor=color.black, size=size.tiny)
plotshape(showCrossLabels and barstate.isconfirmed and dcDownOnly, title="DC DOWN",
style=shape.labeldown, location=location.abovebar, text="DC DOWN",
color=color.new(color.red, 0), textcolor=color.white, size=size.tiny)
// ──────────────────────────────────────────
// Audible + alert conditions
// ──────────────────────────────────────────
alertcondition(goldenAll, title="GOLDEN CROSS", message="GOLDEN CROSS detected")
alertcondition(deathAll, title="DEATH CROSS", message="DEATH CROSS detected")
alertcondition(dcUpOnly, title="DC UP", message="Dual Cross UP detected")
alertcondition(dcDownOnly,title="DC DOWN", message="Dual Cross DOWN detected")
Asymmetric Market Momentum Channel█ OVERVIEW
"Asymmetric Market Momentum Channel" is a dynamic channel indicator that adjusts its width based on the actual strength and asymmetry of market momentum. Thanks to the asymmetric band expansion triggered by strong candles, it significantly reduces false breakouts while remaining highly sensitive to genuine moves.
█ CONCEPTS
Traditional volatility channels react too slowly or too uniformly. This indicator introduces asymmetry:
- After a strong bullish candle with a large body and long upper wick, the upper band is pushed much farther than the lower one.
- After a strong bearish candle, the lower band expands more.
As a result, the channel "remembers" the direction of the last real momentum.
- With wide bands (default base_scale 200+), it excels in contrarian (reversal) strategies – price tends to return to the midline, producing clean reversal signals.
- With narrow bands (base_scale set to 100–150), it behaves like a sensitive breakout channel – breakouts from a tight channel deliver very high-quality trend-continuation signals.
█ FEATURES
Fully adjustable asymmetric momentum channel:
- length – SMA period for midline and average range (default 30)
- base_scale – base channel width in % of average candle range (default 200%)
- strength – asymmetry intensity (higher = stronger expansion after powerful candles)
- smooth_len – EMA smoothing of the expansion (default 10)
Visualization:
- Upper band – red, lower band – green
- Midline SMA – gray
- Gradient background fill (enabled by default) – red above midline, green below; intensity controlled by Background Intensity (85 = strong, 95 = very subtle)
Signal modes:
- Contrarian (Reversal) – reversal signals on price returning inside the channel after exceeding it + confirming candle color
- Trend Continuation (Breakout) – classic breakout signals (recommended to lower base_scale to 100–150 for faster triggers)
- Both – displays both types simultaneously
Visual signals:
- Small green triangles below the bar → bullish signal
- Small red triangles above the bar → bearish signal
Alerts: Bullish Signal, Bearish Signal, Any Signal, Breakout Up, Breakout Down
█ HOW TO USE
Add the indicator to your TradingView chart and adjust the settings:
Key parameter:
- base_scale – defines the indicator’s character:
→ 200–300% → wide channel → Contrarian (reversal) mode
→ 100–150% → narrow channel → Trend Continuation (breakout) mode
- strength (default 1.0)
- length (30) – higher values = smoother, more trend-following behavior
smooth_len (10) – lower values = faster reaction to new momentum
Interpretation:
- Wide channel (base_scale ≥ 200) + Contrarian mode → mean-reversion trading
- Narrow channel (base_scale 100–150) + Breakout mode → aggressive trend-following on breakouts
- Both mode works universally – simply change base_scale to completely switch the indicator’s behavior
█ APPLICATIONS
- Scalping & daytrading – narrow channel + Breakout mode on 5–15 min
- Swing trading – narrow or wide channel + Both mode on H1–D1
- Mean-reversion – wide channel + Contrarian mode
- Trend filter – longs only above midline, shorts only below
█ NOTES
- In very strong one-sided trends, contrarian signals generate many false entries – switch exclusively to Trend Continuation (Breakout) mode with a narrow channel.
- Best performance on instruments with clear volatility and volume.
- Always match base_scale to your strategy (wide = reversal, narrow = breakout).
- Combining with volume, support/resistance levels, or indicators like MACD/RSI dramatically improves signal quality.
Sentiment Heatmap with EMA Sentiment Heatmap with EMA Let’s build a script mini-LuxAlgo-style sentiment heatmap Enhanced Simple Sentiment Heatmap + Right-Side Legend Automatic legend on the right side
Just like professional indicators:
MAX GREED
GREED
NEUTRAL
FEAR
MAX FEAR
✔ Legend stays updated on the last bar
It moves automatically as price moves.
✔ Trend EMA included (optional) 9 EMA → White
20 EMA → Red
50 EMA → Yellow
100 EMA → Blue
200 EMA → Purple Alerts (e.g., “Max Fear – Buy Zone”)
✔ Liquidity line / support-resistance auto zones Full sentiment heatmap (Greed → Fear)
✔ Right-side legend like LuxAlgo
✔ All 5 EMAs added (my colors): EMA trend cloud (9/20, 20/50, 50/200)
Buy/Sell circles based on sentiment reversals Right-side legend: MAX GREED / GREED / NEUTRAL / FEAR / MAX FEAR
5 EMAs:
9 → White
20 → Red
50 → Yellow
100 → Blue
200 → Purple
TraderDemircan Auto Fibonacci RetracementDescription:
What This Indicator Does:This indicator automatically identifies significant swing high and swing low points within a customizable lookback period and draws comprehensive Fibonacci retracement and extension levels between them. Unlike the manual Fibonacci tool that requires you to constantly redraw levels as price action evolves, this automated version continuously updates the Fibonacci grid based on the most recent major swing points, ensuring you always have current and relevant support/resistance zones displayed on your chart.Key Features:
Automatic Swing Detection: Continuously scans the specified lookback period to find the most significant high and low points, eliminating manual drawing errors
Comprehensive Level Coverage: Plots 16 Fibonacci levels including 7 retracement levels (0.0 to 1.0) and 9 extension levels (1.115 to 3.618)
Top-Down Methodology: Draws from swing high to swing low (right-to-left), following the traditional Fibonacci retracement convention where 100% is at the top
Dual Labeling System: Shows both exact price values and Fibonacci percentages for easy reference
Complete Customization: Individual toggle controls and color selection for each of the 16 levels
Flexible Display Options: Adjust line thickness (1-5), style (solid/dashed/dotted), and extension direction (left/right/both)
Visual Swing Markers: Red diamond at the swing high (starting point) and green diamond at the swing low (ending point)
Optional Trend Line: Connects the two swing points to visualize the overall price movement direction
How It Works:The indicator employs a sophisticated swing point detection algorithm that operates in two stages:Stage 1 - Find the Swing Low (Support Base):
Scans the entire lookback period to identify the lowest low, which becomes the anchor point (0.0 level in traditional retracement terms, though displayed at the bottom of the grid).Stage 2 - Find the Swing High (Resistance Peak):
After identifying the swing low, searches for the highest high that occurred after that low point, establishing the swing range. This creates a valid price movement range for Fibonacci analysis.Fibonacci Calculation Method:
The indicator uses the top-down approach where:
1.0 Level = Swing High (100% retracement, the top)
0.0 Level = Swing Low (0% retracement, the bottom)
Retracement Levels (0.236 to 0.786) = Potential support zones during pullbacks from the high
Extension Levels (1.115 to 3.618) = Potential target zones below the swing low
Formula: Price = SwingHigh - (SwingHigh - SwingLow) × FibonacciLevelThis ensures that 0.0 is at the bottom and extensions (>1.0) plot below the swing low, following standard Fibonacci retracement convention.Fibonacci Levels Explained:Retracement Levels (0.0 - 1.0):
0.0 (Gray): Swing low - the base support level
0.236 (Red): Shallow retracement, first minor support
0.382 (Orange): Moderate retracement, commonly watched support
0.5 (Purple): Psychological midpoint, significant support/resistance
0.618 (Blue - Golden Ratio): The most important retracement level, high-probability reversal zone
0.786 (Cyan): Deep retracement, last defense before full reversal
1.0 (Gray): Swing high - the initial resistance level
Extension Levels (1.115 - 3.618):
1.115 (Green): First extension, minimal downside target
1.272 (Light Green): Minor extension, common profit target
1.414 (Yellow-Green): Square root of 2, mathematical significance
1.618 (Gold - Golden Extension): Primary downside target, most watched extension level
2.0 (Orange-Red): 200% extension, psychological round number
2.382 (Pink): Secondary extension target
2.618 (Purple): Deep extension, major target zone
3.272 (Deep Purple): Extreme extension level
3.618 (Blue): Maximum extension, rare but powerful target
How to Use:For Retracement Trading (Buying Pullbacks in Uptrends):
Wait for price to make a significant move up from swing low to swing high
When price starts pulling back, watch for reactions at key Fibonacci levels
Most common entry zones: 0.382, 0.5, and especially 0.618 (golden ratio)
Enter long positions when price shows reversal signals (candlestick patterns, volume increase) at these levels
Place stop loss below the next Fibonacci level
Target: Return to swing high or higher extension levels
For Extension Trading (Profit Targets):
After price breaks below the swing low (0.0 level), use extensions as profit targets
First target: 1.272 (conservative)
Primary target: 1.618 (golden extension - most commonly reached)
Extended target: 2.618 (for strong trends)
Extreme target: 3.618 (only in powerful trending moves)
For Counter-Trend Trading (Fading Extremes):
When price reaches deep retracements (0.786 or below), look for exhaustion signals
Watch for divergences between price and momentum indicators at these levels
Enter reversal trades with tight stops below the swing low
Target: 0.5 or 0.382 levels on the bounce
For Trend Continuation:
In strong uptrends, shallow retracements (0.236 to 0.382) often hold
Use these as low-risk entry points to join the existing trend
Failure to hold 0.5 suggests weakening momentum
Breaking below 0.618 often indicates trend reversal, not just retracement
Multi-Timeframe Strategy:
Use daily timeframe Fibonacci for major support/resistance zones
Use 4H or 1H Fibonacci for precise entry timing within those zones
Confluence between multiple timeframe Fibonacci levels creates high-probability zones
Example: Daily 0.618 level aligning with 4H 0.5 level = strong support
Settings Guide:Lookback Period (10-500):
Short (20-50): Captures recent swings, more frequent updates, suited for day trading
Medium (50-150): Balanced approach, good for swing trading (default: 100)
Long (150-500): Identifies major market structure, suited for position trading
Higher values = more stable levels but slower to adapt to new trends
Pivot Sensitivity (1-20):
Controls how many candles are required to confirm a swing point
Low (1-5): More sensitive, identifies minor swings (default: 5)
High (10-20): Less sensitive, only major swings qualify
Use higher sensitivity on lower timeframes to filter noise
Individual Level Toggles:
Enable only the levels you actively trade to reduce chart clutter
Common minimalist setup: Show only 0.382, 0.5, 0.618, 1.0, 1.618, 2.618
Comprehensive setup: Enable all levels for maximum information
Visual Customization:
Line Thickness: Thicker lines (3-5) for presentation, thinner (1-2) for trading
Line Style: Solid for primary levels (0.5, 0.618, 1.618), dashed/dotted for secondary
Price Labels: Essential for knowing exact entry/exit prices
Percent Labels: Helpful for quickly identifying which Fibonacci level you're looking at
Extension Direction: Extend right for forward-looking analysis, left for historical context
What Makes This Original:While Fibonacci indicators are common on TradingView, this script's originality comes from:
Intelligent Two-Stage Detection: Unlike simple high/low finders, this uses a sequential approach (find low first, then find the high that occurred after it), ensuring logical price flow representation
Comprehensive Level Set: Includes 16 levels spanning from retracement to extreme extensions, more than most Fibonacci tools
Top-Down Methodology: Properly implements the traditional Fibonacci retracement convention (high to low) rather than the reverse
Automatic Range Validation: Only draws Fibonacci when both swing points are valid and in the correct temporal order
Dual Extension Options: Separate controls for extending lines left (historical context) and right (forward projection)
Smart Label Positioning: Places percentage labels on the left and price labels on the right for clarity
Visual Swing Confirmation: Diamond markers at swing points help users understand why levels are positioned where they are
Important Considerations:
Historical Nature: Fibonacci retracements are based on past price swings; they don't predict future moves, only suggest potential support/resistance
Self-Fulfilling Prophecy: Fibonacci levels work partly because many traders watch them, creating actual support/resistance at those levels
Not All Levels Hold: In strong trends, price may slice through multiple Fibonacci levels without pausing
Context Matters: Fibonacci works best when aligned with other support/resistance (previous highs/lows, moving averages, trendlines)
Volume Confirmation: The most reliable Fibonacci reversals occur with volume spikes at key levels
Dynamic Updates: The levels will redraw as new swing highs/lows form, so don't rely solely on static screenshots
Best Practices:
Don't Trade Blindly: Fibonacci levels are zones, not exact prices. Look for confirmation (candlestick patterns, indicators, volume)
Combine with Price Action: Watch for pin bars, engulfing candles, or doji at key Fibonacci levels
Use Stop Losses: Place stops beyond the next Fibonacci level to give trades room but limit risk
Scale In/Out: Consider entering partial positions at 0.5 and adding more at 0.618 rather than all-in at one level
Check Multiple Timeframes: Daily Fibonacci + 4H Fibonacci convergence = high-probability zone
Respect the 0.618: This golden ratio level is historically the most reliable for reversals
Extensions Need Strong Trends: Don't expect extensions to be hit unless there's clear momentum beyond the swing low
Optimal Timeframes:
Scalping (1-5 minutes): Lookback 20-30, watch 0.382, 0.5, 0.618 only
Day Trading (15m-1H): Lookback 50-100, all retracement levels important
Swing Trading (4H-Daily): Lookback 100-200, focus on 0.5, 0.618, 0.786, and extensions
Position Trading (Daily-Weekly): Lookback 200-500, all levels relevant for long-term planning
Common Fibonacci Trading Mistakes to Avoid:
Wrong Swing Selection: Choosing insignificant swings produces meaningless levels
Premature Entry: Entering as soon as price touches a Fibonacci level without confirmation
Ignoring Trend: Fighting the main trend by buying deep retracements in downtrends
Over-Reliance: Using Fibonacci in isolation without confirming with other technical factors
Static Analysis: Not updating your Fibonacci as market structure evolves
Arbitrary Lookback: Using the same lookback period for all assets and timeframes
Integration with Other Tools:Fibonacci + Moving Averages:
When 0.618 level aligns with 50 or 200 EMA, confluence creates stronger support
Price bouncing from both Fibonacci and MA simultaneously = high-probability trade
Fibonacci + RSI/Stochastic:
Oversold indicators at 0.618 or deeper retracements = strong buy signal
Overbought indicators at swing high (1.0) = potential reversal warning
Fibonacci + Volume Profile:
High-volume nodes aligning with Fibonacci levels create robust support/resistance
Low-volume areas near Fibonacci levels may see rapid price movement through them
Fibonacci + Trendlines:
Fibonacci retracement level + ascending trendline = double support
Breaking both simultaneously confirms trend change
Technical Notes:
Uses ta.lowest() and ta.highest() for efficient swing detection across the lookback period
Implements dynamic line and label arrays for clean redraws without memory leaks
All calculations update in real-time as new bars form
Extension options allow customization without modifying core code
Format.mintick ensures price labels match the symbol's minimum price increment
Tooltip on swing markers shows exact price values for precision
MTF EMA Trading SystemHere's a comprehensive description and usage guide for publishing your MTF EMA Trading System indicator on TradingView:
MTF EMA Trading System - Pro Edition
📊 Indicator Overview
The MTF EMA Trading System is an advanced multi-timeframe exponential moving average indicator designed for traders seeking high-probability setups with multiple confirmations. Unlike simple EMA crossover systems, this indicator combines trend alignment, momentum, volume analysis, and previous day confluence to generate reliable long and short signals with optimal risk-reward ratios.
✨ Key Features
1. Multi-Timeframe EMA Analysis
Configure 5 independent EMAs (default: 9, 21, 50, 100, 200)
Each EMA can pull data from ANY timeframe (5m, 15m, 1H, 4H, 1D, etc.)
Color-coded lines with customizable widths
End-of-line labels showing EMA period and timeframe (e.g., "EMA200 ")
Perfect for analyzing higher timeframe trends on lower timeframe charts
2. Advanced Signal Generation (Beyond Simple Crosses)
The system requires MULTIPLE confirmations before generating a signal:
LONG Signals Require:
✅ Price action trigger (EMA cross, bounce from key EMA, or pullback setup)
✅ Bullish EMA alignment (EMAs in proper ascending order)
✅ Volume spike confirmation (configurable threshold)
✅ RSI momentum confirmation (bullish but not overbought)
✅ Sufficient EMA separation (avoids choppy/whipsaw conditions)
✅ Price above previous day's low (confluence with support)
SHORT Signals Require:
✅ Price action trigger (EMA cross, rejection from key EMA, or pullback setup)
✅ Bearish EMA alignment (EMAs in proper descending order)
✅ Volume spike confirmation
✅ RSI momentum confirmation (bearish but not oversold)
✅ Sufficient EMA separation
✅ Price below previous day's high (confluence with resistance)
3. Real-Time Dashboard
Displays critical market conditions at a glance:
Overall trend direction (Bullish/Bearish/Neutral)
Price position relative to all EMAs
Volume status (spike or normal)
RSI momentum reading
EMA confluence strength
EMA separation quality
Current ATR value
Previous day high/low levels
Current signal status (LONG/SHORT/WAIT)
Risk-reward ratio
4. Clean Visual Design
Large, clear trade signal markers (green triangles for LONG, red triangles for SHORT)
No chart clutter - only essential information displayed
Customizable signal sizes
Professional color-coded dashboard
5. Built-In Risk Management
ATR-based calculations for stop loss placement
1:2 risk-reward ratio by default
All levels displayed in dashboard for easy reference
🎯 How to Use This Indicator
Step 1: Initial Setup
Add the indicator to your TradingView chart
Configure your preferred timeframes for each EMA:
EMA 9: Leave blank (uses chart timeframe) - Fast reaction to price
EMA 21: Leave blank or set to 15m - Key pivot level
EMA 50: Set to 1H - Intermediate trend
EMA 100: Set to 4H - Major trend filter
EMA 200: Set to 1D - Overall market bias
Adjust signal settings based on your trading style:
Conservative: Keep all confirmations enabled
Aggressive: Disable volume or momentum requirements
Scalping: Reduce min EMA separation to 0.2-0.3%
Step 2: Reading the Dashboard
Before taking any trade, check the dashboard:
Trend: Only take LONG signals in bullish trends, SHORT signals in bearish trends
Position: Confirm price is on the correct side of EMAs
Volume: Green spike = strong confirmation
RSI: Avoid extremes (>70 or <30)
Confluence: "Strong" = high probability setup
Separation: "Good" = trending market, avoid "Low" separation
Step 3: Trade Entry
For LONG Trades:
Wait for green triangle to appear below price
Verify dashboard shows:
Bullish or Neutral trend
Volume spike (preferred)
RSI between 50-70
Good separation
Enter at market or on next bar
Set stop loss at: Entry - (ATR × 2)
Set target at: Entry + (ATR × 4)
For SHORT Trades:
Wait for red triangle to appear above price
Verify dashboard shows:
Bearish or Neutral trend
Volume spike (preferred)
RSI between 30-50
Good separation
Enter at market or on next bar
Set stop loss at: Entry + (ATR × 2)
Set target at: Entry - (ATR × 4)
Step 4: Trade Management
Use the ATR values from dashboard for position sizing
Trail stops using the fastest EMA (EMA 9) as price moves in your favor
Exit partial position at 1:1 risk-reward, let remainder run to target
Exit immediately if dashboard trend changes against your position
💡 Best Practices
Timeframe Recommendations:
Scalping: 1m-5m chart with 5m, 15m, 1H, 4H, 1D EMAs
Day Trading: 5m-15m chart with 15m, 1H, 4H, 1D EMAs
Swing Trading: 1H-4H chart with 4H, 1D, 1W EMAs
Position Trading: 1D chart with 1D, 1W, 1M EMAs
Market Conditions:
Best in: Trending markets with clear direction
Avoid: Tight consolidation, low volume periods, major news events
Filter trades: Only take signals aligned with higher timeframe trend
Risk Management:
Never risk more than 1-2% per trade
Use ATR from dashboard to calculate position size
Respect the stop loss levels
Don't force trades when dashboard shows weak conditions
⚙️ Customization Options
EMA Settings (for each of 5 EMAs):
Length (period)
Timeframe (multi-timeframe capability)
Color
Line width
Show/hide toggle
Signal Settings:
Volume confirmation (on/off)
Volume spike threshold (1.0-3.0x)
Momentum confirmation (on/off)
RSI overbought/oversold levels
Minimum EMA separation percentage
ATR period and stop multiplier
Display Settings:
Show/hide EMA labels
Show/hide trade signals
Signal marker size (tiny/small/normal/large)
Show/hide dashboard
🔔 Alert Setup
The indicator includes 4 alert conditions:
LONG Signal - Fires when all long confirmations are met
SHORT Signal - Fires when all short confirmations are met
Bullish Setup - Early warning when trend aligns bullish with volume
Bearish Setup - Early warning when trend aligns bearish with volume
To set up alerts:
Right-click on chart → Add Alert
Select "MTF EMA Trading System"
Choose your desired alert condition
Configure notification method (popup, email, SMS, webhook)
📈 Performance Tips
Increase Win Rate:
Only trade in direction of higher timeframe trend
Wait for volume spike confirmation
Avoid trades during first 30 minutes and last 15 minutes of session
Skip trades when separation is "Low"
Reduce False Signals:
Increase minimum EMA separation to 0.7-1.0%
Enable all confirmation requirements
Only trade when confluence shows "Strong"
Combine with support/resistance levels
Optimize for Your Market:
Stocks: Use 9, 21, 50, 100, 200 EMAs
Forex: Consider 8, 13, 21, 55, 89 EMAs (Fibonacci)
Crypto: May need wider ATR multiplier (2.5-3.0x) for volatility
⚠️ Important Notes
This indicator is designed to reduce false signals by requiring multiple confirmations
No indicator is 100% accurate - always use proper risk management
Backtesting recommended before live trading
Market conditions change - adjust settings as needed
Works best in liquid markets with clear price action
🎓 Conclusion
The MTF EMA Trading System transforms simple moving average analysis into a sophisticated, multi-confirmation trading strategy. By combining trend alignment, momentum, volume, and confluence, it helps traders identify high-probability setups while filtering out noise and false signals. The clean interface and comprehensive dashboard make it suitable for both beginners and experienced traders across all markets and timeframes.
Daily MA — Higher-Timeframe Daily Moving Average OverlayThis indicator plots a clean, higher-timeframe daily moving average directly on any chart, so you can always see where price sits relative to the daily trend — even while trading on lower timeframes (1m, 5m, etc.).
It’s designed to be:
Simple – a single, configurable daily MA line
Consistent – always anchored to the 1D timeframe
Flexible – choose EMA or SMA and customize line width/color
⸻
What This Indicator Does
Pulls the 1-Day (1D) moving average of the current symbol, regardless of your chart timeframe.
Lets you choose between EMA (Exponential Moving Average) or SMA (Simple Moving Average).
Plots that daily MA as a smooth overlay on your current chart.
Keeps the line visually clean and continuous, making it easy to see daily trend and dynamic support/resistance.
This is not a signals/strategy script. It doesn’t generate buy/sell arrows or backtest logic. It’s a context tool for visualizing the daily trend while you execute your own strategy.
⸻
Why a Daily MA Overlay Is Useful
Traders commonly use a daily moving average to:
Anchor intraday trades to the higher-timeframe trend
Longs when price is holding above the Daily MA
Shorts or caution when price is rejecting from the Daily MA
Identify dynamic support/resistance
Price often reacts around well-watched daily MAs (e.g., 50, 100, 200)
Filter setups
Only take long setups when price is above the daily trend line
Avoid counter-trend trades when price is extended far from the Daily MA
Because this script forces the MA to always be computed on 1D, you don’t have to switch back and forth between intraday and daily charts to keep track of the bigger picture.
⸻
Inputs & Settings
MA Length
Default: 200
Any positive integer (min 1)
Common examples: 50, 100, 200 for trend structure
MA Type
EMA – reacts faster to recent price (default)
SMA – smoother, slower, more “classic” feel
Line Width
Default: 2
Range: 1 to 10
Increase if you want the Daily MA to stand out clearly against other indicators
Color
Default: Purple tone
Fully customizable – pick any color that works with your chart theme
⸻
How to Use It in Your Workflow
Intraday traders (scalpers/day-traders):
Apply the indicator to your 1m/5m/15m charts.
Use the Daily MA as a trend filter :
Only look for long scalps when price is above the Daily MA.
Be more cautious with longs or consider shorts when price is below it.
Swing traders :
Use it on 1H/4H charts to see where price sits relative to a longer-term daily trend.
Watch for:
Pullbacks to the Daily MA in an uptrend as potential demand zones.
Rejections at the Daily MA in a downtrend as potential supply zones.
Risk management & context :
Avoid chasing extended moves far from the Daily MA.
Mark confluence with other tools (support/resistance, volume profile, etc.) around the Daily MA.
⸻
Notes & Limitations
The moving average itself is calculated from daily candles , then displayed on your current timeframe.
This is a visual aid only . It does not guarantee future performance or provide financial advice.
Always combine this indicator with your own analysis, risk management, and trading plan.
⸻
Disclaimer :
This script is provided for educational and informational purposes only. It is not financial advice and does not constitute a recommendation to buy or sell any financial instrument. Always do your own research and trade at your own risk.






















