BO - CCI Arrow with AlertBO - CCI Arrow with Alert base on CCI indicator to get signal for trade Binary Option.
Rules of BO - CCI Arrow with Alert below:
A. Setup Menu
1. cciLength:
* Default CCI lenght = 14
2. Linear Regression Length:
* Periods to calculate Linear Regression of CCI,
* Default value = 5
3. Extreme Level:
* Default top extreme level = 100
* Default bottom extreme level = -100
4. Filter Length:
* Periods to define highest or lowest Linear Regression
* Default value = 6
B. Rule Of Alert Bar
1. Put Alert Bar
* Current Linear Regression Line created temporrary peak
* Peak of Linear Regression Line greater than Top Extreme Level (100)
* Previous Linear Regression is highest of Filter Length (6)
* Previous Linear Regression is greater than previous peak of Linear Regression Line
* Current price greater than previous low
* CCI(14) less than Linear Regression Line
2. Call Alert Bar
* Current Linear Regression Line created temporrary bottom
* Bottom of Linear Regression Line less than Bottom Extreme Level (-100)
* Previous Linear Regression is lowest of Filter Length (6)
* Previous Linear Regression is less than previous bottom of Linear Regression Line
* Current price less than previous lhigh
* CCI(14) greater than Linear Regression Line
B. Rule Of Entry Bar and Epiry.
1. Put Entry with expiry 3 bars:
* After Put Alert Bar close with signal confirmed, put Arrow appear, and after 3 bars, result label will appear to show win trade, loss trade or draw trade
2. Call Entry with expiry 3 bars:
* After Call Alert Bar close with signal confirmed, call Arrow appear, and after 3 bars, result label will appear to show win trade, loss trade or draw trade.
3. While 1 trade is opening no more any signal
C. Popup Alert/Mobile Alert
1. Signal alert: Put Alert or Call Alert will send to mobile or show popup on chart
2. Put Alert: only Put Alert will send to mobile or show popup on chart
3. Call Alert: only Call Alert will send to mobile or show popup on chart
Pesquisar nos scripts por "美元指数跌破100大关"
Point and Figure (PnF) CCIThis is live and non-repainting Point and Figure Chart Commodity Channel Index - CCI tool. The script has it’s own P&F engine and not using integrated function of Trading View.
Point and Figure method is over 150 years old. It consist of columns that represent filtered price movements. Time is not a factor on P&F chart but as you can see with this script P&F chart created on time chart.
P&F chart provide several advantages, some of them are filtering insignificant price movements and noise, focusing on important price movements and making support/resistance levels much easier to identify.
Commodity Channel Index – CCI was developed by Donalt Lambert. CCI can be used to identify overbought or oversold, a new trend or warn of extreme conditions. CCI measures the difference between a security's price change and its average price change. High positive readings indicate that prices are well above their average, which is a show of strength. Low negative readings indicate that prices are well below their average, which is a show of weakness.
The Formula for the Commodity Channel Index ( CCI ) Is:
CCI = (Typical Price – L-period SMA of TP) / (0.015 * Mean Deviation)
Mean Deviation = (SumOf 1->L ( |TP – MA| )) / L
L = Length
TP = Typical Price
If you are new to Point & Figure Chart then you better get some information about it before using this tool. There are very good web sites and books. Please PM me if you need help about resources.
Options in the Script
Box size is one of the most important part of Point and Figure Charting. Chart price movement sensitivity is determined by the Point and Figure scale. Large box sizes see little movement across a specific price region, small box sizes see greater price movement on P&F chart. There are four different box scaling with this tool: Traditional, Percentage, Dynamic (ATR), or User-Defined
4 different methods for Box size can be used in this tool.
User Defined: The box size is set by user. A larger box size will result in more filtered price movements and fewer reversals. A smaller box size will result in less filtered price movements and more reversals.
ATR: Box size is dynamically calculated by using ATR, default period is 20.
Percentage: uses box sizes that are a fixed percentage of the stock's price. If percentage is 1 and stock’s price is $100 then box size will be $1
Traditional: uses a predefined table of price ranges to determine what the box size should be.
Price Range Box Size
Under 0.25 0.0625
0.25 to 1.00 0.125
1.00 to 5.00 0.25
5.00 to 20.00 0.50
20.00 to 100 1.0
100 to 200 2.0
200 to 500 4.0
500 to 1000 5.0
1000 to 25000 50.0
25000 and up 500.0
Default value is “ATR”, you may use one of these scaling method that suits your trading strategy.
If ATR or Percentage is chosen then there is rounding algorithm according to mintick value of the security. For example if mintick value is 0.001 and box size (ATR/Percentage) is 0.00124 then box size becomes 0.001.
And also while using dynamic box size (ATR or Percentage), box size changes only when closing price changed.
Reversal : It is the number of boxes required to change from a column of Xs to a column of Os or from a column of Os to a column of Xs. Default value is 3 (most used). For example if you choose reversal = 2 then you get the chart similar to Renko chart.
Source: Closing price or High-Low prices can be chosen as data source for P&F charting.
Upper Band : as default, Upper band is 100
Lower Band : as default, Lower band is -100
There are alerts when P&F CCI moves above Upper Band or moves below Lower Band.
Double MA CCI"What is the Commodity Channel Index (CCI)?
Developed by Donald Lambert, the Commodity Channel Index (CCI) is a momentum-based oscillator used to help determine when an investment vehicle is reaching a condition of being overbought or oversold. It is also used to assess price trend direction and strength. This information allows traders to determine if they want to enter or exit a trade, refrain from taking a trade, or add to an existing position. In this way, the indicator can be used to provide trade signals when it acts in a certain way.
KEY TAKEAWAYS
• The CCI measures the difference between the current price and the historical average price.
• When the CCI is above zero it indicates the price is above the historic average. When CCI is below zero, the price is below the hsitoric average.
• High readings of 100 or above, for example, indicate the price is well above the historic average and the trend has been strong to the upside.
• Low readings below -100, for example, indicate the price is well below the historic average and the trend has been strong to the downside.
• Going from negative or near-zero readings to +100 can be used as a signal to watch for an emerging uptrend.
• Going from positive or near-zero readings to -100 may indicate an emerging downtrend.
• CCI is an unbounded indicator meaning it can go higher or lower indefinitely. For this reason, overbought and oversold levels are typically determined for each individual asset by looking at historical extreme CCI levels where the price reversed from." ----> 1
SOURCE
1: (SINCE IM NOT A "PRO" MEMBER I C'ANT POST THE SOUCRE URL..., webpage consulted at : 8:50 GMT -5 ; the 2020-01-18)
I- Added a 2nd MA length and changed the default values of the source type and switched the SMA to a MA.
II- In process to add analytic MACD histogram correlation and if possible, ploting a relative histogram between the CCI upper and lower band.
P.S.:
Don't set your moving averages lengths to far from each other... This could result in fewer convergence and divergence, also in fewer crossing MA's.
Have a good year 2020 !!
//----CODER----//
R.V.
Multi momentum indicatorScript contains couple momentum oscillators all in one pane
List of indicators:
RSI
Stochastic RSI
MACD
CCI
WaveTrend by LazyBear
MFI
Default active indicators are RSI and Stochastic RSI
Other indicators are disabled by default
RSI, StochRSI and MFI are modified to be bounded to range from 100 to -100. That's why overbought is 40 and 60 instead 70 and 80 while oversold -40 and -60 instead 30 and 20.
MACD and CCI as they are not bounded to 100 or 200 range, they are limited to 100 - -100 by default when activated (extras are simply hidden) but there is an option to show full indicator.
In settings there are couple more options like show crosses or show only histogram.
Default source for all indicators is close (except WaveTrend and MFI which use hlc3) and it could be changed but for all indicators.
There is an option for 2nd RSI which can be set for any timeframe and background calculated by Fibonacci levels.
Open Interest Rank-BuschiEnglish:
One part of the "Commitment of Traders-Report" is the Open Interest which is shown in this indicator (source: Quandl database).
Unlike my also published indicator "Open Interest-Buschi", the values here are not absolute but in a ranking system from 0 to 100 with individual time frames-
The following futures are included:
30-year Bonds (ZB)
10-year Notes ( ZN )
Soybeans (ZS)
Soybean Meal (ZM)
Soybean Oil (ZL)
Corn ( ZC )
Soft Red Winter Wheat (ZW)
Hard Red Winter Wheat (KE)
Lean Hogs (HE)
Live Cattle ( LE )
Gold ( GC )
Silver (SI)
Copper (HG)
Crude Oil ( CL )
Heating Oil (HO)
RBOB Gasoline ( RB )
Natural Gas ( NG )
Australian Dollar (A6)
British Pound (B6)
Canadian Dollar (D6)
Euro (E6)
Japanese Yen (J6)
Swiss Franc (S6)
Sugar ( SB )
Coffee (KC)
Cocoa ( CC )
Cotton ( CT )
S&P 500 E-Mini (ES)
Russell 2000 E-Mini (RTY)
Dow Jones Industrial Mini (YM)
Nasdaq 100 E-Mini (NQ)
Platin (PL)
Palladium (PA)
Aluminium (AUP)
Steel ( HRC )
Ethanol (AEZ)
Brent Crude Oil (J26)
Rice (ZR)
Oat (ZO)
Milk (DL)
Orange Juice (JO)
Lumber (LS)
Feeder Cattle (GF)
S&P 500 ( SP )
Dow Jones Industrial Average Index (DJIA)
New Zealand Dollar (N6)
Deutsch:
Ein Bestandteil des "Commitment of Traders-Report" ist das Open Interest, das in diesem Indikator dargestellt wird (Quelle: Quandl Datenbank).
Anders als in meinem ebenfalls veröffentlichten Indikator "Open Interest-Buschi" werden hier nicht die absoluten Werte dargestellt, sondern in einem Ranking-System von 0 bis 100 mit individuellen Zeitrahmen.
Folgende Futures sind enthalten:
30-jährige US-Staatsanleihen (ZB)
10-jährige US-Staatsanleihen ( ZN )
Sojabohnen(ZS)
Sojabohnen-Mehl (ZM)
Sojabohnen-Öl (ZL)
Mais( ZC )
Soft Red Winter-Weizen (ZW)
Hard Red Winter-Weizen (KE)
Magerschweine (HE)
Lebendrinder ( LE )
Gold ( GC )
Silber (SI)
Kupfer(HG)
Rohöl ( CL )
Heizöl (HO)
Benzin ( RB )
Erdgas ( NG )
Australischer Dollar (A6)
Britisches Pfund (B6)
Kanadischer Dollar (D6)
Euro (E6)
Japanischer Yen (J6)
Schweizer Franken (S6)
Zucker ( SB )
Kaffee (KC)
Kakao ( CC )
Baumwolle ( CT )
S&P 500 E-Mini (ES)
Russell 2000 E-Mini (RTY)
Dow Jones Industrial Mini (YM)
Nasdaq 100 E-Mini (NQ)
Platin (PL)
Palladium (PA)
Aluminium (AUP)
Stahl ( HRC )
Ethanol (AEZ)
Brent Rohöl (J26)
Reis (ZR)
Hafer (ZO)
Milch (DL)
Orangensaft (JO)
Holz (LS)
Mastrinder (GF)
S&P 500 ( SP )
Dow Jones Industrial Average Index (DJIA)
Neuseeland Dollar (N6)
Well Rounded Moving AverageIntroduction
There are tons of filters, way to many, and some of them are redundant in the sense they produce the same results as others. The task to find an optimal filter is still a big challenge among technical analysis and engineering, a good filter is the Kalman filter who is one of the more precise filters out there. The optimal filter theorem state that : The optimal estimator has the form of a linear observer , this in short mean that an optimal filter must use measurements of the inputs and outputs, and this is what does the Kalman filter. I have tried myself to Kalman filters with more or less success as well as understanding optimality by studying Linear–quadratic–Gaussian control, i failed to get a complete understanding of those subjects but today i present a moving average filter (WRMA) constructed with all the knowledge i have in control theory and who aim to provide a very well response to market price, this mean low lag for fast decision timing and low overshoots for better precision.
Construction
An good filter must use information about its output, this is what exponential smoothing is about, simple exponential smoothing (EMA) is close to a simple moving average and can be defined as :
output = output(1) + α(input - output(1))
where α (alpha) is a smoothing constant, typically equal to 2/(Period+1) for the EMA.
This approach can be further developed by introducing more smoothing constants and output control (See double/triple exponential smoothing - alpha-beta filter) .
The moving average i propose will use only one smoothing constant, and is described as follow :
a = nz(a ) + alpha*nz(A )
b = nz(b ) + alpha*nz(B )
y = ema(a + b,p1)
A = src - y
B = src - ema(y,p2)
The filter is divided into two components a and b (more terms can add more control/effects if chosen well) , a adjust itself to the output error and is responsive while b is independent of the output and is mainly smoother, adding those components together create an output y , A is the output error and B is the error of an exponential moving average.
Comparison
There are a lot of low-lag filters out there, but the overshoots they induce in order to reduce lag is not a great effect. The first comparison is with a least square moving average, a moving average who fit a line in a price window of period length .
Lsma in blue and WRMA in red with both length = 100 . The lsma is a bit smoother but induce terrible overshoots
ZLMA in blue and WRMA in red with both length = 100 . The lag difference between each moving average is really low while VWRMA is way more precise.
Hull MA in blue and WRMA in red with both length = 100 . The Hull MA have similar overshoots than the LSMA.
Reduced overshoots moving average (ROMA) in blue and WRMA in red with both length = 100 . ROMA is an indicator i have made to reduce the overshoots of a LSMA, but at the end WRMA still reduce way more the overshoots while being smoother and having similar lag.
I have added a smoother version, just activate the extra smooth option in the indicator settings window. Here the result with length = 200 :
This result is a little bit similar to a 2 order Butterworth filter. Our filter have more overshoots which in this case could be useful to reduce the error with edges since other low pass filters tend to smooth their amplitude thus reducing edge estimation precision.
Conclusions
I have presented a well rounded filter in term of smoothness/stability and reactivity. Try to add more terms to have different results, you could maybe end up with interesting results, if its the case share them with the community :)
As for control theory i have seen neural networks integrated to Kalman flters which leaded to great accuracy, AI is everywhere and promise to be a game a changer in real time data smoothing. So i asked myself if it was possible for a neural networks to develop pinescript indicators, if yes then i could be replaced by AI ? Brrr how frightening.
Thanks for reading :)
Quadruple Kaufman Adaptive Moving AverageFour Kaufman Adaptive Moving Averages in one script. Useful for identifying trends and setting points to add to positions / exit trades. KAMA's are great for keeping you in trending markets and avoiding sideways chops and ranges. Try them out by tweaking the fast/slow ma's and lengths to get the right set for your charts that removes the thinking about whether to be long or short and when to add to positions.
A suggested trading strategy is to tweak the ma's (often you'll want larger values) until they span the price action well on past trends. Then each time price action closes and crosses one of your KAMA lines is an opportunity to add to your position. Once all lines are cleared and you've loaded up your position, hopefully your average price of entry falls short of the highest KAMA line's value. Once this happens you don't need to get out the trade until such time as a price close crosses again that largest KAMA line. For eager profit takers, close positions once any KAMA line is crossed once you're successfully loaded up on a direction.
I use this script with a renko chart and values -> 26 length 6 fast ma 100 slow ma, 26 8 100, 26 10 100, 26 12 100 and it's good to see these moving averages, unlike regular moving averages, bend around choppy action that come when trends pause, keeping me successfully in winning trades. Give it a try.
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.
Aroon Single Line This indicator converts double lined Aroon indicator into a single line oscillator.
It is simply obtained by subtracting Aroon down from Aroon Up.
*If Oscillator points 100 value, it means there is a Strong Uptrend.
*If Oscillator points values between 100 and 40, it means there is an uptrend.
*If Oscillator points values between 20 and -20, it means no trend, it is sideways.But, when it is sideways; generally, oscillator makes FLAT LINES
between 20 and -20 values. 0 value is pointed out when the trend is downward as well, which means aroon up=aroon down.
*If Oscillator points values between -40 and -100, it means there is a downtrend.
*If Oscillator points -100 value, it means there is a Strong downtrend.
(20, 40) and (-20, -40) intervals are not mentioned, because; generally these are transition values and hard to comment, it will be more certain to
wait till values are between or at the reference values given.
CCI 0Trend Strategy (by Marcoweb) v1.0Hi guys,
I am trying to create a strategy that consists in the crossover/under of the 0 line of the Commodity Channel Index . Every time the price crosses over the 0 line in the CCI the strategy has to long getting short on the cross under and viceversa.
I have published here another script strategy (consists in a crossover/under of the Overbought/Oversold levels of the CCI) that works so I could have the opportunity to share with you the main idea that as per now is mistaken:
//@version=2
strategy(title="CCI 0Trend Strategy (by Marcoweb) v1.0", shorttitle="CCI_0T_Stra_v1.0", overlay=true)
///////////// CCI
length = input(20, minval=1)
src = input(close, title="Source")
ma = sma(src, length)
cci = (src - ma) / (0.015 * dev(src, length))
plot(cci, color=black)
band1 = hline(100, color=blue, linestyle=solid)
band0 = hline(-100, color=red, linestyle=solid)
bandl = hline(0, color=orange, linestyle=solid)
fill(band1, band0, color=olive)
p1 = plot(band0, color=red,title="-100")
p2 = plot(band1, color=blue,title="100")
p3 = plot(bandl, color=orange,title="0")
///////////// CCI 0Trend Strategy (by Marcoweb) v1.0 Strategy
if (not na(cci))
if (crossover(cci, bandl)
strategy.entry("CCI_L", strategy.long, stop=bandl, oca_type=strategy.oca.cancel, comment="CCI_L")
else
strategy.cancel(id="CCI_L")
if (crossunder(cci, bandl)
strategy.entry("CCI_S", strategy.short, stop=bandl, oca_type=strategy.oca.cancel, comment="CCI_S")
else
strategy.cancel(id="CCI_S")
//plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
With this coding I get the error : line 24 (if (crossover(cci, bandl): mismatched input '|E|' expecting RPAR
Hope you like the idea ;)
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
Indicator: Trend Trigger FactorIntroduced by M.H.Pee, Trend Trigger Factor is designed to keep the trader trading with the trend.
System rules according to the developer:
* If the 15-day TTF is above 100 (indicating an uptrend), you will want to be in long positions.
* If the 15-day TTF is below -100, you will want to be short.
* If it is between -100 and 100, you should remain with the current position.
More info:
Original Article by Mr.Pee: drive.google.com
Dynamic Equity Allocation Model"Cash is Trash"? Not Always. Here's Why Science Beats Guesswork.
Every retail trader knows the frustration: you draw support and resistance lines, you spot patterns, you follow market gurus on social media—and still, when the next bear market hits, your portfolio bleeds red. Meanwhile, institutional investors seem to navigate market turbulence with ease, preserving capital when markets crash and participating when they rally. What's their secret?
The answer isn't insider information or access to exotic derivatives. It's systematic, scientifically validated decision-making. While most retail traders rely on subjective chart analysis and emotional reactions, professional portfolio managers use quantitative models that remove emotion from the equation and process multiple streams of market information simultaneously.
This document presents exactly such a system—not a proprietary black box available only to hedge funds, but a fully transparent, academically grounded framework that any serious investor can understand and apply. The Dynamic Equity Allocation Model (DEAM) synthesizes decades of financial research from Nobel laureates and leading academics into a practical tool for tactical asset allocation.
Stop drawing colorful lines on your chart and start thinking like a quant. This isn't about predicting where the market goes next week—it's about systematically adjusting your risk exposure based on what the data actually tells you. When valuations scream danger, when volatility spikes, when credit markets freeze, when multiple warning signals align—that's when cash isn't trash. That's when cash saves your portfolio.
The irony of "cash is trash" rhetoric is that it ignores timing. Yes, being 100% cash for decades would be disastrous. But being 100% equities through every crisis is equally foolish. The sophisticated approach is dynamic: aggressive when conditions favor risk-taking, defensive when they don't. This model shows you how to make that decision systematically, not emotionally.
Whether you're managing your own retirement portfolio or seeking to understand how institutional allocation strategies work, this comprehensive analysis provides the theoretical foundation, mathematical implementation, and practical guidance to elevate your investment approach from amateur to professional.
The choice is yours: keep hoping your chart patterns work out, or start using the same quantitative methods that professionals rely on. The tools are here. The research is cited. The methodology is explained. All you need to do is read, understand, and apply.
The Dynamic Equity Allocation Model (DEAM) is a quantitative framework for systematic allocation between equities and cash, grounded in modern portfolio theory and empirical market research. The model integrates five scientifically validated dimensions of market analysis—market regime, risk metrics, valuation, sentiment, and macroeconomic conditions—to generate dynamic allocation recommendations ranging from 0% to 100% equity exposure. This work documents the theoretical foundations, mathematical implementation, and practical application of this multi-factor approach.
1. Introduction and Theoretical Background
1.1 The Limitations of Static Portfolio Allocation
Traditional portfolio theory, as formulated by Markowitz (1952) in his seminal work "Portfolio Selection," assumes an optimal static allocation where investors distribute their wealth across asset classes according to their risk aversion. This approach rests on the assumption that returns and risks remain constant over time. However, empirical research demonstrates that this assumption does not hold in reality. Fama and French (1989) showed that expected returns vary over time and correlate with macroeconomic variables such as the spread between long-term and short-term interest rates. Campbell and Shiller (1988) demonstrated that the price-earnings ratio possesses predictive power for future stock returns, providing a foundation for dynamic allocation strategies.
The academic literature on tactical asset allocation has evolved considerably over recent decades. Ilmanen (2011) argues in "Expected Returns" that investors can improve their risk-adjusted returns by considering valuation levels, business cycles, and market sentiment. The Dynamic Equity Allocation Model presented here builds on this research tradition and operationalizes these insights into a practically applicable allocation framework.
1.2 Multi-Factor Approaches in Asset Allocation
Modern financial research has shown that different factors capture distinct aspects of market dynamics and together provide a more robust picture of market conditions than individual indicators. Ross (1976) developed the Arbitrage Pricing Theory, a model that employs multiple factors to explain security returns. Following this multi-factor philosophy, DEAM integrates five complementary analytical dimensions, each tapping different information sources and collectively enabling comprehensive market understanding.
2. Data Foundation and Data Quality
2.1 Data Sources Used
The model draws its data exclusively from publicly available market data via the TradingView platform. This transparency and accessibility is a significant advantage over proprietary models that rely on non-public data. The data foundation encompasses several categories of market information, each capturing specific aspects of market dynamics.
First, price data for the S&P 500 Index is obtained through the SPDR S&P 500 ETF (ticker: SPY). The use of a highly liquid ETF instead of the index itself has practical reasons, as ETF data is available in real-time and reflects actual tradability. In addition to closing prices, high, low, and volume data are captured, which are required for calculating advanced volatility measures.
Fundamental corporate metrics are retrieved via TradingView's Financial Data API. These include earnings per share, price-to-earnings ratio, return on equity, debt-to-equity ratio, dividend yield, and share buyback yield. Cochrane (2011) emphasizes in "Presidential Address: Discount Rates" the central importance of valuation metrics for forecasting future returns, making these fundamental data a cornerstone of the model.
Volatility indicators are represented by the CBOE Volatility Index (VIX) and related metrics. The VIX, often referred to as the market's "fear gauge," measures the implied volatility of S&P 500 index options and serves as a proxy for market participants' risk perception. Whaley (2000) describes in "The Investor Fear Gauge" the construction and interpretation of the VIX and its use as a sentiment indicator.
Macroeconomic data includes yield curve information through US Treasury bonds of various maturities and credit risk premiums through the spread between high-yield bonds and risk-free government bonds. These variables capture the macroeconomic conditions and financing conditions relevant for equity valuation. Estrella and Hardouvelis (1991) showed that the shape of the yield curve has predictive power for future economic activity, justifying the inclusion of these data.
2.2 Handling Missing Data
A practical problem when working with financial data is dealing with missing or unavailable values. The model implements a fallback system where a plausible historical average value is stored for each fundamental metric. When current data is unavailable for a specific point in time, this fallback value is used. This approach ensures that the model remains functional even during temporary data outages and avoids systematic biases from missing data. The use of average values as fallback is conservative, as it generates neither overly optimistic nor pessimistic signals.
3. Component 1: Market Regime Detection
3.1 The Concept of Market Regimes
The idea that financial markets exist in different "regimes" or states that differ in their statistical properties has a long tradition in financial science. Hamilton (1989) developed regime-switching models that allow distinguishing between different market states with different return and volatility characteristics. The practical application of this theory consists of identifying the current market state and adjusting portfolio allocation accordingly.
DEAM classifies market regimes using a scoring system that considers three main dimensions: trend strength, volatility level, and drawdown depth. This multidimensional view is more robust than focusing on individual indicators, as it captures various facets of market dynamics. Classification occurs into six distinct regimes: Strong Bull, Bull Market, Neutral, Correction, Bear Market, and Crisis.
3.2 Trend Analysis Through Moving Averages
Moving averages are among the oldest and most widely used technical indicators and have also received attention in academic literature. Brock, Lakonishok, and LeBaron (1992) examined in "Simple Technical Trading Rules and the Stochastic Properties of Stock Returns" the profitability of trading rules based on moving averages and found evidence for their predictive power, although later studies questioned the robustness of these results when considering transaction costs.
The model calculates three moving averages with different time windows: a 20-day average (approximately one trading month), a 50-day average (approximately one quarter), and a 200-day average (approximately one trading year). The relationship of the current price to these averages and the relationship of the averages to each other provide information about trend strength and direction. When the price trades above all three averages and the short-term average is above the long-term, this indicates an established uptrend. The model assigns points based on these constellations, with longer-term trends weighted more heavily as they are considered more persistent.
3.3 Volatility Regimes
Volatility, understood as the standard deviation of returns, is a central concept of financial theory and serves as the primary risk measure. However, research has shown that volatility is not constant but changes over time and occurs in clusters—a phenomenon first documented by Mandelbrot (1963) and later formalized through ARCH and GARCH models (Engle, 1982; Bollerslev, 1986).
DEAM calculates volatility not only through the classic method of return standard deviation but also uses more advanced estimators such as the Parkinson estimator and the Garman-Klass estimator. These methods utilize intraday information (high and low prices) and are more efficient than simple close-to-close volatility estimators. The Parkinson estimator (Parkinson, 1980) uses the range between high and low of a trading day and is based on the recognition that this information reveals more about true volatility than just the closing price difference. The Garman-Klass estimator (Garman and Klass, 1980) extends this approach by additionally considering opening and closing prices.
The calculated volatility is annualized by multiplying it by the square root of 252 (the average number of trading days per year), enabling standardized comparability. The model compares current volatility with the VIX, the implied volatility from option prices. A low VIX (below 15) signals market comfort and increases the regime score, while a high VIX (above 35) indicates market stress and reduces the score. This interpretation follows the empirical observation that elevated volatility is typically associated with falling markets (Schwert, 1989).
3.4 Drawdown Analysis
A drawdown refers to the percentage decline from the highest point (peak) to the lowest point (trough) during a specific period. This metric is psychologically significant for investors as it represents the maximum loss experienced. Calmar (1991) developed the Calmar Ratio, which relates return to maximum drawdown, underscoring the practical relevance of this metric.
The model calculates current drawdown as the percentage distance from the highest price of the last 252 trading days (one year). A drawdown below 3% is considered negligible and maximally increases the regime score. As drawdown increases, the score decreases progressively, with drawdowns above 20% classified as severe and indicating a crisis or bear market regime. These thresholds are empirically motivated by historical market cycles, in which corrections typically encompassed 5-10% drawdowns, bear markets 20-30%, and crises over 30%.
3.5 Regime Classification
Final regime classification occurs through aggregation of scores from trend (40% weight), volatility (30%), and drawdown (30%). The higher weighting of trend reflects the empirical observation that trend-following strategies have historically delivered robust results (Moskowitz, Ooi, and Pedersen, 2012). A total score above 80 signals a strong bull market with established uptrend, low volatility, and minimal losses. At a score below 10, a crisis situation exists requiring defensive positioning. The six regime categories enable a differentiated allocation strategy that not only distinguishes binarily between bullish and bearish but allows gradual gradations.
4. Component 2: Risk-Based Allocation
4.1 Volatility Targeting as Risk Management Approach
The concept of volatility targeting is based on the idea that investors should maximize not returns but risk-adjusted returns. Sharpe (1966, 1994) defined with the Sharpe Ratio the fundamental concept of return per unit of risk, measured as volatility. Volatility targeting goes a step further and adjusts portfolio allocation to achieve constant target volatility. This means that in times of low market volatility, equity allocation is increased, and in times of high volatility, it is reduced.
Moreira and Muir (2017) showed in "Volatility-Managed Portfolios" that strategies that adjust their exposure based on volatility forecasts achieve higher Sharpe Ratios than passive buy-and-hold strategies. DEAM implements this principle by defining a target portfolio volatility (default 12% annualized) and adjusting equity allocation to achieve it. The mathematical foundation is simple: if market volatility is 20% and target volatility is 12%, equity allocation should be 60% (12/20 = 0.6), with the remaining 40% held in cash with zero volatility.
4.2 Market Volatility Calculation
Estimating current market volatility is central to the risk-based allocation approach. The model uses several volatility estimators in parallel and selects the higher value between traditional close-to-close volatility and the Parkinson estimator. This conservative choice ensures the model does not underestimate true volatility, which could lead to excessive risk exposure.
Traditional volatility calculation uses logarithmic returns, as these have mathematically advantageous properties (additive linkage over multiple periods). The logarithmic return is calculated as ln(P_t / P_{t-1}), where P_t is the price at time t. The standard deviation of these returns over a rolling 20-trading-day window is then multiplied by √252 to obtain annualized volatility. This annualization is based on the assumption of independently identically distributed returns, which is an idealization but widely accepted in practice.
The Parkinson estimator uses additional information from the trading range (High minus Low) of each day. The formula is: σ_P = (1/√(4ln2)) × √(1/n × Σln²(H_i/L_i)) × √252, where H_i and L_i are high and low prices. Under ideal conditions, this estimator is approximately five times more efficient than the close-to-close estimator (Parkinson, 1980), as it uses more information per observation.
4.3 Drawdown-Based Position Size Adjustment
In addition to volatility targeting, the model implements drawdown-based risk control. The logic is that deep market declines often signal further losses and therefore justify exposure reduction. This behavior corresponds with the concept of path-dependent risk tolerance: investors who have already suffered losses are typically less willing to take additional risk (Kahneman and Tversky, 1979).
The model defines a maximum portfolio drawdown as a target parameter (default 15%). Since portfolio volatility and portfolio drawdown are proportional to equity allocation (assuming cash has neither volatility nor drawdown), allocation-based control is possible. For example, if the market exhibits a 25% drawdown and target portfolio drawdown is 15%, equity allocation should be at most 60% (15/25).
4.4 Dynamic Risk Adjustment
An advanced feature of DEAM is dynamic adjustment of risk-based allocation through a feedback mechanism. The model continuously estimates what actual portfolio volatility and portfolio drawdown would result at the current allocation. If risk utilization (ratio of actual to target risk) exceeds 1.0, allocation is reduced by an adjustment factor that grows exponentially with overutilization. This implements a form of dynamic feedback that avoids overexposure.
Mathematically, a risk adjustment factor r_adjust is calculated: if risk utilization u > 1, then r_adjust = exp(-0.5 × (u - 1)). This exponential function ensures that moderate overutilization is gently corrected, while strong overutilization triggers drastic reductions. The factor 0.5 in the exponent was empirically calibrated to achieve a balanced ratio between sensitivity and stability.
5. Component 3: Valuation Analysis
5.1 Theoretical Foundations of Fundamental Valuation
DEAM's valuation component is based on the fundamental premise that the intrinsic value of a security is determined by its future cash flows and that deviations between market price and intrinsic value are eventually corrected. Graham and Dodd (1934) established in "Security Analysis" the basic principles of fundamental analysis that remain relevant today. Translated into modern portfolio context, this means that markets with high valuation metrics (high price-earnings ratios) should have lower expected returns than cheaply valued markets.
Campbell and Shiller (1988) developed the Cyclically Adjusted P/E Ratio (CAPE), which smooths earnings over a full business cycle. Their empirical analysis showed that this ratio has significant predictive power for 10-year returns. Asness, Moskowitz, and Pedersen (2013) demonstrated in "Value and Momentum Everywhere" that value effects exist not only in individual stocks but also in asset classes and markets.
5.2 Equity Risk Premium as Central Valuation Metric
The Equity Risk Premium (ERP) is defined as the expected excess return of stocks over risk-free government bonds. It is the theoretical heart of valuation analysis, as it represents the compensation investors demand for bearing equity risk. Damodaran (2012) discusses in "Equity Risk Premiums: Determinants, Estimation and Implications" various methods for ERP estimation.
DEAM calculates ERP not through a single method but combines four complementary approaches with different weights. This multi-method strategy increases estimation robustness and avoids dependence on single, potentially erroneous inputs.
The first method (35% weight) uses earnings yield, calculated as 1/P/E or directly from operating earnings data, and subtracts the 10-year Treasury yield. This method follows Fed Model logic (Yardeni, 2003), although this model has theoretical weaknesses as it does not consistently treat inflation (Asness, 2003).
The second method (30% weight) extends earnings yield by share buyback yield. Share buybacks are a form of capital return to shareholders and increase value per share. Boudoukh et al. (2007) showed in "The Total Shareholder Yield" that the sum of dividend yield and buyback yield is a better predictor of future returns than dividend yield alone.
The third method (20% weight) implements the Gordon Growth Model (Gordon, 1962), which models stock value as the sum of discounted future dividends. Under constant growth g assumption: Expected Return = Dividend Yield + g. The model estimates sustainable growth as g = ROE × (1 - Payout Ratio), where ROE is return on equity and payout ratio is the ratio of dividends to earnings. This formula follows from equity theory: unretained earnings are reinvested at ROE and generate additional earnings growth.
The fourth method (15% weight) combines total shareholder yield (Dividend + Buybacks) with implied growth derived from revenue growth. This method considers that companies with strong revenue growth should generate higher future earnings, even if current valuations do not yet fully reflect this.
The final ERP is the weighted average of these four methods. A high ERP (above 4%) signals attractive valuations and increases the valuation score to 95 out of 100 possible points. A negative ERP, where stocks have lower expected returns than bonds, results in a minimal score of 10.
5.3 Quality Adjustments to Valuation
Valuation metrics alone can be misleading if not interpreted in the context of company quality. A company with a low P/E may be cheap or fundamentally problematic. The model therefore implements quality adjustments based on growth, profitability, and capital structure.
Revenue growth above 10% annually adds 10 points to the valuation score, moderate growth above 5% adds 5 points. This adjustment reflects that growth has independent value (Modigliani and Miller, 1961, extended by later growth theory). Net margin above 15% signals pricing power and operational efficiency and increases the score by 5 points, while low margins below 8% indicate competitive pressure and subtract 5 points.
Return on equity (ROE) above 20% characterizes outstanding capital efficiency and increases the score by 5 points. Piotroski (2000) showed in "Value Investing: The Use of Historical Financial Statement Information" that fundamental quality signals such as high ROE can improve the performance of value strategies.
Capital structure is evaluated through the debt-to-equity ratio. A conservative ratio below 1.0 multiplies the valuation score by 1.2, while high leverage above 2.0 applies a multiplier of 0.8. This adjustment reflects that high debt constrains financial flexibility and can become problematic in crisis times (Korteweg, 2010).
6. Component 4: Sentiment Analysis
6.1 The Role of Sentiment in Financial Markets
Investor sentiment, defined as the collective psychological attitude of market participants, influences asset prices independently of fundamental data. Baker and Wurgler (2006, 2007) developed a sentiment index and showed that periods of high sentiment are followed by overvaluations that later correct. This insight justifies integrating a sentiment component into allocation decisions.
Sentiment is difficult to measure directly but can be proxied through market indicators. The VIX is the most widely used sentiment indicator, as it aggregates implied volatility from option prices. High VIX values reflect elevated uncertainty and risk aversion, while low values signal market comfort. Whaley (2009) refers to the VIX as the "Investor Fear Gauge" and documents its role as a contrarian indicator: extremely high values typically occur at market bottoms, while low values occur at tops.
6.2 VIX-Based Sentiment Assessment
DEAM uses statistical normalization of the VIX by calculating the Z-score: z = (VIX_current - VIX_average) / VIX_standard_deviation. The Z-score indicates how many standard deviations the current VIX is from the historical average. This approach is more robust than absolute thresholds, as it adapts to the average volatility level, which can vary over longer periods.
A Z-score below -1.5 (VIX is 1.5 standard deviations below average) signals exceptionally low risk perception and adds 40 points to the sentiment score. This may seem counterintuitive—shouldn't low fear be bullish? However, the logic follows the contrarian principle: when no one is afraid, everyone is already invested, and there is limited further upside potential (Zweig, 1973). Conversely, a Z-score above 1.5 (extreme fear) adds -40 points, reflecting market panic but simultaneously suggesting potential buying opportunities.
6.3 VIX Term Structure as Sentiment Signal
The VIX term structure provides additional sentiment information. Normally, the VIX trades in contango, meaning longer-term VIX futures have higher prices than short-term. This reflects that short-term volatility is currently known, while long-term volatility is more uncertain and carries a risk premium. The model compares the VIX with VIX9D (9-day volatility) and identifies backwardation (VIX > 1.05 × VIX9D) and steep backwardation (VIX > 1.15 × VIX9D).
Backwardation occurs when short-term implied volatility is higher than longer-term, which typically happens during market stress. Investors anticipate immediate turbulence but expect calming. Psychologically, this reflects acute fear. The model subtracts 15 points for backwardation and 30 for steep backwardation, as these constellations signal elevated risk. Simon and Wiggins (2001) analyzed the VIX futures curve and showed that backwardation is associated with market declines.
6.4 Safe-Haven Flows
During crisis times, investors flee from risky assets into safe havens: gold, US dollar, and Japanese yen. This "flight to quality" is a sentiment signal. The model calculates the performance of these assets relative to stocks over the last 20 trading days. When gold or the dollar strongly rise while stocks fall, this indicates elevated risk aversion.
The safe-haven component is calculated as the difference between safe-haven performance and stock performance. Positive values (safe havens outperform) subtract up to 20 points from the sentiment score, negative values (stocks outperform) add up to 10 points. The asymmetric treatment (larger deduction for risk-off than bonus for risk-on) reflects that risk-off movements are typically sharper and more informative than risk-on phases.
Baur and Lucey (2010) examined safe-haven properties of gold and showed that gold indeed exhibits negative correlation with stocks during extreme market movements, confirming its role as crisis protection.
7. Component 5: Macroeconomic Analysis
7.1 The Yield Curve as Economic Indicator
The yield curve, represented as yields of government bonds of various maturities, contains aggregated expectations about future interest rates, inflation, and economic growth. The slope of the yield curve has remarkable predictive power for recessions. Estrella and Mishkin (1998) showed that an inverted yield curve (short-term rates higher than long-term) predicts recessions with high reliability. This is because inverted curves reflect restrictive monetary policy: the central bank raises short-term rates to combat inflation, dampening economic activity.
DEAM calculates two spread measures: the 2-year-minus-10-year spread and the 3-month-minus-10-year spread. A steep, positive curve (spreads above 1.5% and 2% respectively) signals healthy growth expectations and generates the maximum yield curve score of 40 points. A flat curve (spreads near zero) reduces the score to 20 points. An inverted curve (negative spreads) is particularly alarming and results in only 10 points.
The choice of two different spreads increases analysis robustness. The 2-10 spread is most established in academic literature, while the 3M-10Y spread is often considered more sensitive, as the 3-month rate directly reflects current monetary policy (Ang, Piazzesi, and Wei, 2006).
7.2 Credit Conditions and Spreads
Credit spreads—the yield difference between risky corporate bonds and safe government bonds—reflect risk perception in the credit market. Gilchrist and Zakrajšek (2012) constructed an "Excess Bond Premium" that measures the component of credit spreads not explained by fundamentals and showed this is a predictor of future economic activity and stock returns.
The model approximates credit spread by comparing the yield of high-yield bond ETFs (HYG) with investment-grade bond ETFs (LQD). A narrow spread below 200 basis points signals healthy credit conditions and risk appetite, contributing 30 points to the macro score. Very wide spreads above 1000 basis points (as during the 2008 financial crisis) signal credit crunch and generate zero points.
Additionally, the model evaluates whether "flight to quality" is occurring, identified through strong performance of Treasury bonds (TLT) with simultaneous weakness in high-yield bonds. This constellation indicates elevated risk aversion and reduces the credit conditions score.
7.3 Financial Stability at Corporate Level
While the yield curve and credit spreads reflect macroeconomic conditions, financial stability evaluates the health of companies themselves. The model uses the aggregated debt-to-equity ratio and return on equity of the S&P 500 as proxies for corporate health.
A low leverage level below 0.5 combined with high ROE above 15% signals robust corporate balance sheets and generates 20 points. This combination is particularly valuable as it represents both defensive strength (low debt means crisis resistance) and offensive strength (high ROE means earnings power). High leverage above 1.5 generates only 5 points, as it implies vulnerability to interest rate increases and recessions.
Korteweg (2010) showed in "The Net Benefits to Leverage" that optimal debt maximizes firm value, but excessive debt increases distress costs. At the aggregated market level, high debt indicates fragilities that can become problematic during stress phases.
8. Component 6: Crisis Detection
8.1 The Need for Systematic Crisis Detection
Financial crises are rare but extremely impactful events that suspend normal statistical relationships. During normal market volatility, diversified portfolios and traditional risk management approaches function, but during systemic crises, seemingly independent assets suddenly correlate strongly, and losses exceed historical expectations (Longin and Solnik, 2001). This justifies a separate crisis detection mechanism that operates independently of regular allocation components.
Reinhart and Rogoff (2009) documented in "This Time Is Different: Eight Centuries of Financial Folly" recurring patterns in financial crises: extreme volatility, massive drawdowns, credit market dysfunction, and asset price collapse. DEAM operationalizes these patterns into quantifiable crisis indicators.
8.2 Multi-Signal Crisis Identification
The model uses a counter-based approach where various stress signals are identified and aggregated. This methodology is more robust than relying on a single indicator, as true crises typically occur simultaneously across multiple dimensions. A single signal may be a false alarm, but the simultaneous presence of multiple signals increases confidence.
The first indicator is a VIX above the crisis threshold (default 40), adding one point. A VIX above 60 (as in 2008 and March 2020) adds two additional points, as such extreme values are historically very rare. This tiered approach captures the intensity of volatility.
The second indicator is market drawdown. A drawdown above 15% adds one point, as corrections of this magnitude can be potential harbingers of larger crises. A drawdown above 25% adds another point, as historical bear markets typically encompass 25-40% drawdowns.
The third indicator is credit market spreads above 500 basis points, adding one point. Such wide spreads occur only during significant credit market disruptions, as in 2008 during the Lehman crisis.
The fourth indicator identifies simultaneous losses in stocks and bonds. Normally, Treasury bonds act as a hedge against equity risk (negative correlation), but when both fall simultaneously, this indicates systemic liquidity problems or inflation/stagflation fears. The model checks whether both SPY and TLT have fallen more than 10% and 5% respectively over 5 trading days, adding two points.
The fifth indicator is a volume spike combined with negative returns. Extreme trading volumes (above twice the 20-day average) with falling prices signal panic selling. This adds one point.
A crisis situation is diagnosed when at least 3 indicators trigger, a severe crisis at 5 or more indicators. These thresholds were calibrated through historical backtesting to identify true crises (2008, 2020) without generating excessive false alarms.
8.3 Crisis-Based Allocation Override
When a crisis is detected, the system overrides the normal allocation recommendation and caps equity allocation at maximum 25%. In a severe crisis, the cap is set at 10%. This drastic defensive posture follows the empirical observation that crises typically require time to develop and that early reduction can avoid substantial losses (Faber, 2007).
This override logic implements a "safety first" principle: in situations of existential danger to the portfolio, capital preservation becomes the top priority. Roy (1952) formalized this approach in "Safety First and the Holding of Assets," arguing that investors should primarily minimize ruin probability.
9. Integration and Final Allocation Calculation
9.1 Component Weighting
The final allocation recommendation emerges through weighted aggregation of the five components. The standard weighting is: Market Regime 35%, Risk Management 25%, Valuation 20%, Sentiment 15%, Macro 5%. These weights reflect both theoretical considerations and empirical backtesting results.
The highest weighting of market regime is based on evidence that trend-following and momentum strategies have delivered robust results across various asset classes and time periods (Moskowitz, Ooi, and Pedersen, 2012). Current market momentum is highly informative for the near future, although it provides no information about long-term expectations.
The substantial weighting of risk management (25%) follows from the central importance of risk control. Wealth preservation is the foundation of long-term wealth creation, and systematic risk management is demonstrably value-creating (Moreira and Muir, 2017).
The valuation component receives 20% weight, based on the long-term mean reversion of valuation metrics. While valuation has limited short-term predictive power (bull and bear markets can begin at any valuation), the long-term relationship between valuation and returns is robustly documented (Campbell and Shiller, 1988).
Sentiment (15%) and Macro (5%) receive lower weights, as these factors are subtler and harder to measure. Sentiment is valuable as a contrarian indicator at extremes but less informative in normal ranges. Macro variables such as the yield curve have strong predictive power for recessions, but the transmission from recessions to stock market performance is complex and temporally variable.
9.2 Model Type Adjustments
DEAM allows users to choose between four model types: Conservative, Balanced, Aggressive, and Adaptive. This choice modifies the final allocation through additive adjustments.
Conservative mode subtracts 10 percentage points from allocation, resulting in consistently more cautious positioning. This is suitable for risk-averse investors or those with limited investment horizons. Aggressive mode adds 10 percentage points, suitable for risk-tolerant investors with long horizons.
Adaptive mode implements procyclical adjustment based on short-term momentum: if the market has risen more than 5% in the last 20 days, 5 percentage points are added; if it has declined more than 5%, 5 points are subtracted. This logic follows the observation that short-term momentum persists (Jegadeesh and Titman, 1993), but the moderate size of adjustment avoids excessive timing bets.
Balanced mode makes no adjustment and uses raw model output. This neutral setting is suitable for investors who wish to trust model recommendations unchanged.
9.3 Smoothing and Stability
The allocation resulting from aggregation undergoes final smoothing through a simple moving average over 3 periods. This smoothing is crucial for model practicality, as it reduces frequent trading and thus transaction costs. Without smoothing, the model could fluctuate between adjacent allocations with every small input change.
The choice of 3 periods as smoothing window is a compromise between responsiveness and stability. Longer smoothing would excessively delay signals and impede response to true regime changes. Shorter or no smoothing would allow too much noise. Empirical tests showed that 3-period smoothing offers an optimal ratio between these goals.
10. Visualization and Interpretation
10.1 Main Output: Equity Allocation
DEAM's primary output is a time series from 0 to 100 representing the recommended percentage allocation to equities. This representation is intuitive: 100% means full investment in stocks (specifically: an S&P 500 ETF), 0% means complete cash position, and intermediate values correspond to mixed portfolios. A value of 60% means, for example: invest 60% of wealth in SPY, hold 40% in money market instruments or cash.
The time series is color-coded to enable quick visual interpretation. Green shades represent high allocations (above 80%, bullish), red shades low allocations (below 20%, bearish), and neutral colors middle allocations. The chart background is dynamically colored based on the signal, enhancing readability in different market phases.
10.2 Dashboard Metrics
A tabular dashboard presents key metrics compactly. This includes current allocation, cash allocation (complement), an aggregated signal (BULLISH/NEUTRAL/BEARISH), current market regime, VIX level, market drawdown, and crisis status.
Additionally, fundamental metrics are displayed: P/E Ratio, Equity Risk Premium, Return on Equity, Debt-to-Equity Ratio, and Total Shareholder Yield. This transparency allows users to understand model decisions and form their own assessments.
Component scores (Regime, Risk, Valuation, Sentiment, Macro) are also displayed, each normalized on a 0-100 scale. This shows which factors primarily drive the current recommendation. If, for example, the Risk score is very low (20) while other scores are moderate (50-60), this indicates that risk management considerations are pulling allocation down.
10.3 Component Breakdown (Optional)
Advanced users can display individual components as separate lines in the chart. This enables analysis of component dynamics: do all components move synchronously, or are there divergences? Divergences can be particularly informative. If, for example, the market regime is bullish (high score) but the valuation component is very negative, this signals an overbought market not fundamentally supported—a classic "bubble warning."
This feature is disabled by default to keep the chart clean but can be activated for deeper analysis.
10.4 Confidence Bands
The model optionally displays uncertainty bands around the main allocation line. These are calculated as ±1 standard deviation of allocation over a rolling 20-period window. Wide bands indicate high volatility of model recommendations, suggesting uncertain market conditions. Narrow bands indicate stable recommendations.
This visualization implements a concept of epistemic uncertainty—uncertainty about the model estimate itself, not just market volatility. In phases where various indicators send conflicting signals, the allocation recommendation becomes more volatile, manifesting in wider bands. Users can understand this as a warning to act more cautiously or consult alternative information sources.
11. Alert System
11.1 Allocation Alerts
DEAM implements an alert system that notifies users of significant events. Allocation alerts trigger when smoothed allocation crosses certain thresholds. An alert is generated when allocation reaches 80% (from below), signaling strong bullish conditions. Another alert triggers when allocation falls to 20%, indicating defensive positioning.
These thresholds are not arbitrary but correspond with boundaries between model regimes. An allocation of 80% roughly corresponds to a clear bull market regime, while 20% corresponds to a bear market regime. Alerts at these points are therefore informative about fundamental regime shifts.
11.2 Crisis Alerts
Separate alerts trigger upon detection of crisis and severe crisis. These alerts have highest priority as they signal large risks. A crisis alert should prompt investors to review their portfolio and potentially take defensive measures beyond the automatic model recommendation (e.g., hedging through put options, rebalancing to more defensive sectors).
11.3 Regime Change Alerts
An alert triggers upon change of market regime (e.g., from Neutral to Correction, or from Bull Market to Strong Bull). Regime changes are highly informative events that typically entail substantial allocation changes. These alerts enable investors to proactively respond to changes in market dynamics.
11.4 Risk Breach Alerts
A specialized alert triggers when actual portfolio risk utilization exceeds target parameters by 20%. This is a warning signal that the risk management system is reaching its limits, possibly because market volatility is rising faster than allocation can be reduced. In such situations, investors should consider manual interventions.
12. Practical Application and Limitations
12.1 Portfolio Implementation
DEAM generates a recommendation for allocation between equities (S&P 500) and cash. Implementation by an investor can take various forms. The most direct method is using an S&P 500 ETF (e.g., SPY, VOO) for equity allocation and a money market fund or savings account for cash allocation.
A rebalancing strategy is required to synchronize actual allocation with model recommendation. Two approaches are possible: (1) rule-based rebalancing at every 10% deviation between actual and target, or (2) time-based monthly rebalancing. Both have trade-offs between responsiveness and transaction costs. Empirical evidence (Jaconetti, Kinniry, and Zilbering, 2010) suggests rebalancing frequency has moderate impact on performance, and investors should optimize based on their transaction costs.
12.2 Adaptation to Individual Preferences
The model offers numerous adjustment parameters. Component weights can be modified if investors place more or less belief in certain factors. A fundamentally-oriented investor might increase valuation weight, while a technical trader might increase regime weight.
Risk target parameters (target volatility, max drawdown) should be adapted to individual risk tolerance. Younger investors with long investment horizons can choose higher target volatility (15-18%), while retirees may prefer lower volatility (8-10%). This adjustment systematically shifts average equity allocation.
Crisis thresholds can be adjusted based on preference for sensitivity versus specificity of crisis detection. Lower thresholds (e.g., VIX > 35 instead of 40) increase sensitivity (more crises are detected) but reduce specificity (more false alarms). Higher thresholds have the reverse effect.
12.3 Limitations and Disclaimers
DEAM is based on historical relationships between indicators and market performance. There is no guarantee these relationships will persist in the future. Structural changes in markets (e.g., through regulation, technology, or central bank policy) can break established patterns. This is the fundamental problem of induction in financial science (Taleb, 2007).
The model is optimized for US equities (S&P 500). Application to other markets (international stocks, bonds, commodities) would require recalibration. The indicators and thresholds are specific to the statistical properties of the US equity market.
The model cannot eliminate losses. Even with perfect crisis prediction, an investor following the model would lose money in bear markets—just less than a buy-and-hold investor. The goal is risk-adjusted performance improvement, not risk elimination.
Transaction costs are not modeled. In practice, spreads, commissions, and taxes reduce net returns. Frequent trading can cause substantial costs. Model smoothing helps minimize this, but users should consider their specific cost situation.
The model reacts to information; it does not anticipate it. During sudden shocks (e.g., 9/11, COVID-19 lockdowns), the model can only react after price movements, not before. This limitation is inherent to all reactive systems.
12.4 Relationship to Other Strategies
DEAM is a tactical asset allocation approach and should be viewed as a complement, not replacement, for strategic asset allocation. Brinson, Hood, and Beebower (1986) showed in their influential study "Determinants of Portfolio Performance" that strategic asset allocation (long-term policy allocation) explains the majority of portfolio performance, but this leaves room for tactical adjustments based on market timing.
The model can be combined with value and momentum strategies at the individual stock level. While DEAM controls overall market exposure, within-equity decisions can be optimized through stock-picking models. This separation between strategic (market exposure) and tactical (stock selection) levels follows classical portfolio theory.
The model does not replace diversification across asset classes. A complete portfolio should also include bonds, international stocks, real estate, and alternative investments. DEAM addresses only the US equity allocation decision within a broader portfolio.
13. Scientific Foundation and Evaluation
13.1 Theoretical Consistency
DEAM's components are based on established financial theory and empirical evidence. The market regime component follows from regime-switching models (Hamilton, 1989) and trend-following literature. The risk management component implements volatility targeting (Moreira and Muir, 2017) and modern portfolio theory (Markowitz, 1952). The valuation component is based on discounted cash flow theory and empirical value research (Campbell and Shiller, 1988; Fama and French, 1992). The sentiment component integrates behavioral finance (Baker and Wurgler, 2006). The macro component uses established business cycle indicators (Estrella and Mishkin, 1998).
This theoretical grounding distinguishes DEAM from purely data-mining-based approaches that identify patterns without causal theory. Theory-guided models have greater probability of functioning out-of-sample, as they are based on fundamental mechanisms, not random correlations (Lo and MacKinlay, 1990).
13.2 Empirical Validation
While this document does not present detailed backtest analysis, it should be noted that rigorous validation of a tactical asset allocation model should include several elements:
In-sample testing establishes whether the model functions at all in the data on which it was calibrated. Out-of-sample testing is crucial: the model should be tested in time periods not used for development. Walk-forward analysis, where the model is successively trained on rolling windows and tested in the next window, approximates real implementation.
Performance metrics should be risk-adjusted. Pure return consideration is misleading, as higher returns often only compensate for higher risk. Sharpe Ratio, Sortino Ratio, Calmar Ratio, and Maximum Drawdown are relevant metrics. Comparison with benchmarks (Buy-and-Hold S&P 500, 60/40 Stock/Bond portfolio) contextualizes performance.
Robustness checks test sensitivity to parameter variation. If the model only functions at specific parameter settings, this indicates overfitting. Robust models show consistent performance over a range of plausible parameters.
13.3 Comparison with Existing Literature
DEAM fits into the broader literature on tactical asset allocation. Faber (2007) presented a simple momentum-based timing system that goes long when the market is above its 10-month average, otherwise cash. This simple system avoided large drawdowns in bear markets. DEAM can be understood as a sophistication of this approach that integrates multiple information sources.
Ilmanen (2011) discusses various timing factors in "Expected Returns" and argues for multi-factor approaches. DEAM operationalizes this philosophy. Asness, Moskowitz, and Pedersen (2013) showed that value and momentum effects work across asset classes, justifying cross-asset application of regime and valuation signals.
Ang (2014) emphasizes in "Asset Management: A Systematic Approach to Factor Investing" the importance of systematic, rule-based approaches over discretionary decisions. DEAM is fully systematic and eliminates emotional biases that plague individual investors (overconfidence, hindsight bias, loss aversion).
References
Ang, A. (2014) *Asset Management: A Systematic Approach to Factor Investing*. Oxford: Oxford University Press.
Ang, A., Piazzesi, M. and Wei, M. (2006) 'What does the yield curve tell us about GDP growth?', *Journal of Econometrics*, 131(1-2), pp. 359-403.
Asness, C.S. (2003) 'Fight the Fed Model', *The Journal of Portfolio Management*, 30(1), pp. 11-24.
Asness, C.S., Moskowitz, T.J. and Pedersen, L.H. (2013) 'Value and Momentum Everywhere', *The Journal of Finance*, 68(3), pp. 929-985.
Baker, M. and Wurgler, J. (2006) 'Investor Sentiment and the Cross-Section of Stock Returns', *The Journal of Finance*, 61(4), pp. 1645-1680.
Baker, M. and Wurgler, J. (2007) 'Investor Sentiment in the Stock Market', *Journal of Economic Perspectives*, 21(2), pp. 129-152.
Baur, D.G. and Lucey, B.M. (2010) 'Is Gold a Hedge or a Safe Haven? An Analysis of Stocks, Bonds and Gold', *Financial Review*, 45(2), pp. 217-229.
Bollerslev, T. (1986) 'Generalized Autoregressive Conditional Heteroskedasticity', *Journal of Econometrics*, 31(3), pp. 307-327.
Boudoukh, J., Michaely, R., Richardson, M. and Roberts, M.R. (2007) 'On the Importance of Measuring Payout Yield: Implications for Empirical Asset Pricing', *The Journal of Finance*, 62(2), pp. 877-915.
Brinson, G.P., Hood, L.R. and Beebower, G.L. (1986) 'Determinants of Portfolio Performance', *Financial Analysts Journal*, 42(4), pp. 39-44.
Brock, W., Lakonishok, J. and LeBaron, B. (1992) 'Simple Technical Trading Rules and the Stochastic Properties of Stock Returns', *The Journal of Finance*, 47(5), pp. 1731-1764.
Calmar, T.W. (1991) 'The Calmar Ratio', *Futures*, October issue.
Campbell, J.Y. and Shiller, R.J. (1988) 'The Dividend-Price Ratio and Expectations of Future Dividends and Discount Factors', *Review of Financial Studies*, 1(3), pp. 195-228.
Cochrane, J.H. (2011) 'Presidential Address: Discount Rates', *The Journal of Finance*, 66(4), pp. 1047-1108.
Damodaran, A. (2012) *Equity Risk Premiums: Determinants, Estimation and Implications*. Working Paper, Stern School of Business.
Engle, R.F. (1982) 'Autoregressive Conditional Heteroskedasticity with Estimates of the Variance of United Kingdom Inflation', *Econometrica*, 50(4), pp. 987-1007.
Estrella, A. and Hardouvelis, G.A. (1991) 'The Term Structure as a Predictor of Real Economic Activity', *The Journal of Finance*, 46(2), pp. 555-576.
Estrella, A. and Mishkin, F.S. (1998) 'Predicting U.S. Recessions: Financial Variables as Leading Indicators', *Review of Economics and Statistics*, 80(1), pp. 45-61.
Faber, M.T. (2007) 'A Quantitative Approach to Tactical Asset Allocation', *The Journal of Wealth Management*, 9(4), pp. 69-79.
Fama, E.F. and French, K.R. (1989) 'Business Conditions and Expected Returns on Stocks and Bonds', *Journal of Financial Economics*, 25(1), pp. 23-49.
Fama, E.F. and French, K.R. (1992) 'The Cross-Section of Expected Stock Returns', *The Journal of Finance*, 47(2), pp. 427-465.
Garman, M.B. and Klass, M.J. (1980) 'On the Estimation of Security Price Volatilities from Historical Data', *Journal of Business*, 53(1), pp. 67-78.
Gilchrist, S. and Zakrajšek, E. (2012) 'Credit Spreads and Business Cycle Fluctuations', *American Economic Review*, 102(4), pp. 1692-1720.
Gordon, M.J. (1962) *The Investment, Financing, and Valuation of the Corporation*. Homewood: Irwin.
Graham, B. and Dodd, D.L. (1934) *Security Analysis*. New York: McGraw-Hill.
Hamilton, J.D. (1989) 'A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle', *Econometrica*, 57(2), pp. 357-384.
Ilmanen, A. (2011) *Expected Returns: An Investor's Guide to Harvesting Market Rewards*. Chichester: Wiley.
Jaconetti, C.M., Kinniry, F.M. and Zilbering, Y. (2010) 'Best Practices for Portfolio Rebalancing', *Vanguard Research Paper*.
Jegadeesh, N. and Titman, S. (1993) 'Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency', *The Journal of Finance*, 48(1), pp. 65-91.
Kahneman, D. and Tversky, A. (1979) 'Prospect Theory: An Analysis of Decision under Risk', *Econometrica*, 47(2), pp. 263-292.
Korteweg, A. (2010) 'The Net Benefits to Leverage', *The Journal of Finance*, 65(6), pp. 2137-2170.
Lo, A.W. and MacKinlay, A.C. (1990) 'Data-Snooping Biases in Tests of Financial Asset Pricing Models', *Review of Financial Studies*, 3(3), pp. 431-467.
Longin, F. and Solnik, B. (2001) 'Extreme Correlation of International Equity Markets', *The Journal of Finance*, 56(2), pp. 649-676.
Mandelbrot, B. (1963) 'The Variation of Certain Speculative Prices', *The Journal of Business*, 36(4), pp. 394-419.
Markowitz, H. (1952) 'Portfolio Selection', *The Journal of Finance*, 7(1), pp. 77-91.
Modigliani, F. and Miller, M.H. (1961) 'Dividend Policy, Growth, and the Valuation of Shares', *The Journal of Business*, 34(4), pp. 411-433.
Moreira, A. and Muir, T. (2017) 'Volatility-Managed Portfolios', *The Journal of Finance*, 72(4), pp. 1611-1644.
Moskowitz, T.J., Ooi, Y.H. and Pedersen, L.H. (2012) 'Time Series Momentum', *Journal of Financial Economics*, 104(2), pp. 228-250.
Parkinson, M. (1980) 'The Extreme Value Method for Estimating the Variance of the Rate of Return', *Journal of Business*, 53(1), pp. 61-65.
Piotroski, J.D. (2000) 'Value Investing: The Use of Historical Financial Statement Information to Separate Winners from Losers', *Journal of Accounting Research*, 38, pp. 1-41.
Reinhart, C.M. and Rogoff, K.S. (2009) *This Time Is Different: Eight Centuries of Financial Folly*. Princeton: Princeton University Press.
Ross, S.A. (1976) 'The Arbitrage Theory of Capital Asset Pricing', *Journal of Economic Theory*, 13(3), pp. 341-360.
Roy, A.D. (1952) 'Safety First and the Holding of Assets', *Econometrica*, 20(3), pp. 431-449.
Schwert, G.W. (1989) 'Why Does Stock Market Volatility Change Over Time?', *The Journal of Finance*, 44(5), pp. 1115-1153.
Sharpe, W.F. (1966) 'Mutual Fund Performance', *The Journal of Business*, 39(1), pp. 119-138.
Sharpe, W.F. (1994) 'The Sharpe Ratio', *The Journal of Portfolio Management*, 21(1), pp. 49-58.
Simon, D.P. and Wiggins, R.A. (2001) 'S&P Futures Returns and Contrary Sentiment Indicators', *Journal of Futures Markets*, 21(5), pp. 447-462.
Taleb, N.N. (2007) *The Black Swan: The Impact of the Highly Improbable*. New York: Random House.
Whaley, R.E. (2000) 'The Investor Fear Gauge', *The Journal of Portfolio Management*, 26(3), pp. 12-17.
Whaley, R.E. (2009) 'Understanding the VIX', *The Journal of Portfolio Management*, 35(3), pp. 98-105.
Yardeni, E. (2003) 'Stock Valuation Models', *Topical Study*, 51, Yardeni Research.
Zweig, M.E. (1973) 'An Investor Expectations Stock Price Predictive Model Using Closed-End Fund Premiums', *The Journal of Finance*, 28(1), pp. 67-78.
MA Crossover BIFTY BNF with Broker Inputs//@version=6
strategy("MA Crossover with Broker Inputs", overlay=true, margin_long=100, margin_short=100, process_orders_on_close=true)
// === BROKER & ORDER SETTINGS ===
broker = input.string("Dhan", title="Broker", options= )
orderType = input.string("MKT", title="Order Type", options= )
clientID = input.string("", title="Client ID (Optional)")
secretKey = input.string("", title="Secret Key (from JSON)")
// === INSTRUMENT SELECTION ===
instrument = input.string("BANKNIFTY", title="Select Instrument", options= )
expiryMode = input.string("Auto", title="Expiry Mode", options= )
manualExpiry = input.string("17Dec2025", title="Manual Expiry Date (if Manual Mode)")
optionType = input.string("CE", title="Option Type", options= )
strikeSel = input.string("ATM", title="Strike Selection", options= )
// === RISK MANAGEMENT ===
stopLossPts = input.int(50, title="Stop Loss (points)")
takeProfitPts = input.int(100, title="Take Profit (points)")
// === STRATEGY LOGIC: Moving Average Crossover ===
fastLength = input.int(9, title="Fast MA Length")
slowLength = input.int(18, title="Slow MA Length")
price = close
maFast = ta.sma(price, fastLength)
maSlow = ta.sma(price, slowLength)
// Crossover Long
if (ta.crossover(maFast, maSlow))
strategy.entry("Long", strategy.long, comment="MA Crossover Long")
// Crossunder Short
if (ta.crossunder(maFast, maSlow))
strategy.entry("Short", strategy.short, comment="MA Crossover Short")
// Apply SL and TP
strategy.exit("Exit Long", from_entry="Long", stop=close - stopLossPts, limit=close + takeProfitPts)
strategy.exit("Exit Short", from_entry="Short", stop=close + stopLossPts, limit=close - takeProfitPts)
// === PLOTS ===
plot(maFast, color=color.green, title="Fast MA")
plot(maSlow, color=color.red, title="Slow MA")
Universal Breakout Strategy [KedArc Quant]Description:
A flexible breakout framework where you can test different logics (Prev Day, Bollinger, Volume, ATR, EMA Trend, RSI Confirm, Candle Confirm, Time Filter) under one system.
Choose your breakout mode, and the strategy will handle entries, exits, and optional risk management (ATR stops, take-profits, daily loss guard, cooldowns).
An on-chart info table shows live mode values (like Prev High/Low, Bollinger levels, RSI, etc.) plus P&L stats for quick analysis.
Use it to compare which breakout style works best on your instrument and timeframe, whether intraday, swing, or positional trading
🔑 Why it’s useful
* Flexibility: Switch between breakout strategies without loading different indicators.
* Clarity: On-chart info table displays current mode, relevant indicator levels, and live strategy P&L stats.
* Testing efficiency: Quickly A/B test different breakout styles under the same backtest environment.
* Transparency: Every trade is rule-based and displayed with entry/exit markers.
🚀 How it helps traders
* Lets you experiment with breakout strategies quickly without loading multiple scripts.
* Helps identify which breakout method fits your instrument & timeframe.
* Gives clear on-chart visual + statistical feedback for confident decision-making.
⚙️ Input Configuration
* Breakout Mode → choose which strategy to test:
* *Prev Day* → breakouts of yesterday’s High/Low.
* *Bollinger* → Upper/Lower BB pierce.
* *Volume* → Breakout confirmed with volume above average.
* *ATR Stop* → Wide range breakout using ATR filter.
* *Time Filter* → Breakouts inside defined session hours.
* *EMA Trend* → Breakouts only in EMA fast > slow alignment.
* *RSI Confirm* → Breakouts with RSI confirmation (e.g. >55 for longs).
* *Candle Confirm* → Breakouts validated by bullish/bearish candle.
* Lookback / ATR / Bollinger inputs → adjust sensitivity.
* Intrabar mode → option to evaluate breakouts using bar highs/lows instead of closes.
* Table options → show/hide info table, show/hide P&L stats, choose corner placement.
📈 Entry & Exit Logic
* Entry → occurs when breakout condition of chosen mode is met.
* Exit → default exits via opposite signals or optional stop/target if enabled.
* Session filter → optional auto-flat at session end.
* P&L management → optional daily loss guard, cooldown between trades, and ATR-based stop/take profit.
❓ FAQ — Choosing the best setup
Q: Which strategy should I use for which chart?
* *Prev Day Breakouts*: Best on indices, FX, and liquid futures with strong daily levels.
* *Bollinger*: Works well in range-bound environments, or crypto pairs with volatility compression.
* *Volume*: Good on equities where breakout strength is tied to volume spikes.
* *ATR Stop*: Suits volatile instruments (commodities, crypto).
* *EMA Trend*: Useful in trending markets (stocks, indices).
* *RSI Confirm*: Adds momentum filter, better for swing trades.
* *Candle Confirm*: Ideal for scalpers needing visual confirmation.
* *Time Filter*: For intraday traders who want signals only in high-liquidity sessions.
Q: What timeframe should I use?
* Intraday traders → 5m to 15m (Time Filter, Candle Confirm).
* Swing traders → 1H to 4H (EMA Trend, RSI Confirm, ATR Stop).
* Position traders → Daily (Prev Day, Bollinger).
* Breakout
A trade entry condition triggered when price crosses above a resistance level (for longs) or below a support level (for shorts).
* Prev Day High/Low
Formula:
Prev High = High of (Day )
Prev Low = Low of (Day )
* Bollinger Bands
Formula:
Basis = SMA(Close, Length)
Upper Band = Basis + (Multiplier × StdDev(Close, Length))
Lower Band = Basis – (Multiplier × StdDev(Close, Length))
* Volume Confirmation
A breakout is only valid if:
Volume > SMA(Volume, Length)
* ATR (Average True Range)
Measures volatility.
Formula:
ATR = SMA(True Range, Length)
where True Range = max(High–Low, |High–Close |, |Low–Close |)
* EMA (Exponential Moving Average)
Weighted moving average giving more weight to recent prices.
Formula:
EMA = (Price × α) + (EMA × (1–α))
with α = 2 / (Length + 1)
* RSI (Relative Strength Index)
Momentum oscillator scaled 0–100.
Formula:
RSI = 100 – (100 / (1 + RS))
where RS = Avg(Gain, Length) ÷ Avg(Loss, Length)
* Candle Confirmation
Bullish candle: Close > Open AND Close > Close
Bearish candle: Close < Open AND Close < Close
Win Rate (%)
Formula:
Win Rate = (Winning Trades ÷ Total Trades) × 100
* Average Trade P&L
Formula:
Avg Trade = Net Profit ÷ Total Trades
📊 Performance Notes
The Universal Breakout Strategy is designed as a framework rather than a single-asset optimized system. Results will vary depending on the chart, timeframe, and asset chosen.
On the current defaults (15-minute, INR-denominated example), the backtest produced 132 trades over the selected period. This provides a statistically sufficient sample size.
Win rate (~35%) is relatively low, but this is balanced by a positive reward-to-risk ratio (~1.8). In practice, a lower win rate with larger wins versus smaller losses is sustainable.
The average P&L per trade is close to breakeven under default settings. This is expected, as the strategy is not tuned for a single symbol but offered as a universal breakout framework.
Commissions (0.1%) and slippage (1 tick) are included in the simulation, ensuring realistic conditions.
Risk management is conservative, with order sizing set at 1 unit per trade. This avoids over-leveraging and keeps exposure well under the 5-10% equity risk guideline.
👉 Traders are encouraged to:
Experiment with inputs such as ATR period, breakout length, or Bollinger parameters.
Test across different timeframes and instruments (equities, futures, forex, crypto) to find optimal setups.
Combine with filters (trend direction, volatility regimes, or volume conditions) for further refinement.
⚠️ Disclaimer This script is provided for educational purposes only.
Past performance does not guarantee future results.
Trading involves risk, and users should exercise caution and use proper risk management when applying this strategy.
Mongoose Compass v2 — Regime & Position SizingWhat it does
Mongoose Compass v2 is a regime‐detection dashboard and optional price-chart ribbon. It combines four market “pillars” into a 0–4 score and a suggested equity beta/position size. It is scale-independent and works on any host symbol.
Pillars (green = expansion supportive):
RS IWM/SPY – small-cap relative strength vs large caps
Credit HYG/LQD – high-yield vs investment-grade credit
Growth Cu/Au – copper vs gold (cyclical demand vs safety)
Participation – uses the first available of:
Breadth (% > 200-DMA) if you provide a symbol, else
Cboe S&P 500 Dispersion (DSPX), else
RSP/SPY equal-weight proxy
Score (0–4):
≥ 3 = Expansion
2 = Neutral
≤ 1 = Contraction
A panel shows each pillar’s normalized value (0–100), bias, total score, and a suggested size (default mapping: 0/30/60/90/100% for scores 0–4). The companion “Ribbon” script paints the price chart background by regime and displays the suggested size.
How to use
Timeframes
Weekly for regime calls (recommended anchor).
Daily for execution within the active regime (adds, trims, hedges).
Playbook
Expansion (score ≥ 3): increase risk/beta; favor cyclicals, small caps, EM; reduce hedges.
Neutral (score = 2): keep moderate beta; use relative value (e.g., quality/mega vs small caps) until RS or Cu/Au turns.
Contraction (score ≤ 1): de-risk; rotate to defensives/quality, gold/long duration; add hedges.
Alerts (included):
Expansion Regime (score ≥ 3) – risk-on trigger
Contraction Regime (score ≤ 1) – risk-off trigger
Methodology
Prices are pulled with request.security on the chosen timeframe.
Pillars are built from ratios then smoothed with an SMA (Smoothing Length, default 20).
For display/comparison, series are normalized to 0–100 within a rolling window (Normalization Length, default 60).
Bias rules:
RS / Credit / Growth: fast SMA( len ) vs slow SMA( len*2 ) of each ratio
Breadth: normalized value > 60
DSPX: normalized value < 40 (lower dispersion supports index coherence)
RSP/SPY proxy: fast > slow trend test
Score is the count of green pillars (0–4).
Suggested size is a deterministic mapping from score (editable in settings).
Notes:
Host chart scaling (log vs linear) does not affect calculations.
If a breadth series is unavailable, the script automatically falls back to DSPX, then to RSP/SPY.
Settings
Sources
Default inputs use liquid ETFs (BATS/AMEX). You may switch Copper/Gold to futures (e.g., COMEX_DL:HG1!, COMEX_DL:GC1!) if your data plan supports them.
Optional Breadth: paste a percent-above-MA series if you have one.
DSPX: uses CBOE:DSPX when breadth is blank.
If neither breadth nor DSPX resolve, the script uses RSP/SPY as a participation proxy.
Calculation
Smoothing Length (20) – higher = steadier regime, fewer flips; lower = faster reaction.
Normalization Length (60) – window for the 0–100 scaling; increase to reduce pinning at extremes.
Regime Timeframe (Ribbon only) – lock the ribbon to Weekly while viewing Daily charts.
Visual
Show/hide dashboard table, choose table position, dark/light theme, ribbon opacity.
Recommended usage
Anchor decisions on Weekly Compass; use Daily for timing.
For small-cap rotation, apply on IWM/RTY; for broad beta, use SPY/ES. Output is identical regardless of host symbol because inputs are fetched internally.
Limitations & disclaimer
This is a systematic information tool, not investment advice.
Signals can whipsaw in fast markets; confirm with your risk framework.
Data availability varies by plan (especially futures and DSPX). When a source is unavailable the scripted fallbacks apply automatically.
Market Sentiment Trend Gauge [LevelUp]Market Sentiment Trend Gauge simplifies technical analysis by mathematically combining momentum, trend direction, volatility position, and comparison against a market benchmark, into a single trend score from -100 to +100. Displayed in a separate pane below your chart, it resolves conflicting signals from RSI, moving averages, Bollinger Bands, and market correlations, providing clear insights into trend direction, strength, and relative performance.
THE PROBLEM MARKET SENTIMENT TREND GAUGE (MSTG) SOLVES
Traditional indicators often produce conflicting signals, such as RSI showing overbought while prices rise or moving averages indicating an uptrend despite market underperformance. MSTG creates a weighted composite score to answer: "What's the overall bias for this asset?"
KEY COMPONENTS AND WEIGHTINGS
The trend score combines
▪ Momentum (25%): Normalized 14-period RSI, capped at ±100.
▪ Trend Direction (35%): 10/21-period EMA relationships,
▪ Volatility Position (20%): Price position, 20-period Bollinger Bands, capped at ±100.
▪ Market Comparison (20%): Daily performance vs. SPY benchmark, capped at ±100.
Final score = Weighted sum, smoothed with 5-period EMA.
INTERPRETING THE MSTG CHART
Trend Score Ranges and Colors
▪ Bright Green (>+30): Strong bullish; ideal for long entries.
▪ Light Green (+10 to +30): Weak bullish; cautiously favorable.
▪ Gray (-10 to +10): Neutral; avoid directional trades.
▪ Light Red (-10 to -30): Weak bearish; exercise caution.
▪ Bright Red (<-30): Strong bearish; high-risk for longs, consider shorts.
Reference Lines
▪ Zero Line (Gray): Separates bullish/bearish; crossovers signal trend changes.
▪ ±30 Lines (Dotted, Green/Red): Thresholds for strong trends.
▪ ±60 Lines (Dashed, Green/Red): Extreme strength zones (not overbought/oversold); manage risk (tighten stops, partial profits) but trends may persist.
Background Colors
▪ Green Tint (>+20): Bullish environment; favorable for longs.
▪ Red Tint (<-20): Bearish environment; caution for longs.
▪ Light Gray Tint (-20 to +20): Neutral/range-bound; wait for signals.
Extreme Readings vs. Traditional Signals
MSTG ±60 indicates maximum alignment of all factors, not reversals (unlike RSI >70/<30). Use for risk management, not automatic exits. Strong trends can sustain extremes; breakdowns occur below +30 or above -30.
INFORMATION TABLE INTERPRETATION
Trend Score Symbols
▲▲ >+30 strong bullish
▲ +10 to +30
● -10 to +10 neutral
▼ -30 to -10
▼▼ <-30 strong bearish
Colors: Green (positive), White (neutral), Red (negative).
Momentum Score
+40 to +100 strong bullish
0 to +40 moderate bullish
-40 to 0 moderate bearish
-100 to -40 strong bearish
Market vs. Stock
▪ Green: Stock outperforming market
▪ Red: Stock underperforming market
Example Interpretations:
-0.45% / +1.23% (Green): Market down, stock up = Strong relative strength
+2.10% / +1.50% (Red): Both rising, but stock lagging = Relative weakness
-1.20% / -0.80% (Green): Both falling, but stock declining less = Defensive strength
UNDERSTANDING EXTREME READINGS VS TRADITIONAL OVERBOUGHT/OVERSOLD
⚠️ Critical distinctions
Traditional Overbought/Oversold Signals:
▪ Single indicator (like RSI >70 or <30) showing momentum excess
▪ Often suggests immediate reversal or pullback expected
▪ Based on "price moved too far, too fast" concept
MSTG Extreme Readings (±60):
▪ Composite alignment of 4 different factors (momentum, trend, volatility, relative strength)
▪ Indicates maximum strength in current direction
▪ NOT a reversal signal - means "all systems extremely bullish/bearish"
Key Differences:
▪ RSI >70: "Price got ahead of itself, expect pullback"
▪ MSTG >+60: "Everything is extremely bullish right now"
▪ Strong trends can maintain extreme MSTG readings during major moves
▪ Breakdowns happen when MSTG falls below +30, not at +60
Proper Usage of Extreme Readings:
▪ Risk Management: Tighten stops, take partial profits
▪ Position Sizing: Reduce new position sizes at extremes
▪ Trend Continuation: Watch for sustained extreme readings in strong markets
▪ Exit Signals: Look for breakdown below +30, not reversal from +60
TRADING WITH MSTG
Quick Assessment
1. Check trend symbol for direction.
2. Confirm momentum strength.
3. Note relative performance color.
Examples:
▲▲ 55.2 (Green), Momentum +28.4, Outperforming: Strong buy setup.
▼ -18.6 (Red), Momentum -43.2, Underperforming: Defensive positioning.
Entry Conditions
▪ Long: stock outperforming market
- Score >+30 (bright green)
- Sustained green background
- ▲▲ symbol,
▪ Short: stock underperforming market
- Score <-30 (bright red)
- Sustained red background
- ▼▼ symbol
Avoid Trading When:
▪ Gray zone (-10 to +10).
▪ Rapid color changes or frequent zero-line crosses (choppy market).
▪ Gray background (range-bound).
Risk Management:
▪ Stop Loss: Exit on zero-line crossover against position.
▪ Take Profit: Partial at ±60 for risk control.
▪ Position Sizing: Larger when signals align; smaller in extremes or mixed conditions.
KEY ADVANTAGES
▪ Unified View: Weighted composite reduces noise and conflicts.
▪ Visual Clarity: 5-color system with gradients for rapid recognition.
▪ Market Context: Relative strength vs. SPY identifies leaders/laggards.
▪ Flexibility: Works across timeframes (1-min to weekly); customizable table.
▪ Noise Reduction: EMA smoothing minimizes false signals.
EXAMPLES
Strong Bull: Trend Score 71.9, Momentum Score 76.9
Neutral: Trend Score 0.1, Momentum Score -9.2
Strong Bear: Trend Score -51.7, Momentum Score -51.5
PERFORMANCE AND LIMITATIONS
Strengths: Trend identification, noise reduction, relative performance versus market.
Limitations: Lags at turning points, less effective in extreme volatility or non-trending markets.
Recommendations: View on multiple timeframes, combine with price action and fundamentals.
VWAP Momentum Oscillator How It Works
Core Calculation Method
The oscillator combines four key market measurements into a single, normalized reading:
1. Price-VWAP Deviation: `(Close - VWAP) / VWAP × 100`
2. VWAP-MA Momentum: `(VWAP - MovingAverage) / MovingAverage × 100`
3. Anchored VWAP Strength: Average of high/low anchor deviations from rolling VWAP
4. Range Position: `(Close - PeriodLow) / (PeriodHigh - PeriodLow) × 100 - 50`
Dynamic Signal Line
The signal line uses an EMA that automatically adjusts its length based on your chart timeframe:
- Futures: Always covers 23 hours of trading (1,380 minutes)
- Stocks: Always covers 6.5 hours of trading (390 minutes)
- Examples: 276 periods on 5-min futures chart, 1,380 periods on 1-min futures chart
Trading Signals
🟢 Buy Signals
- Condition: Main oscillator crosses above signal line while below zero
- Logic: Momentum turning bullish from oversold conditions
- Visual: Green "BUY" label below price action
🔴 Sell Signals
- Condition: Main oscillator crosses below signal line while above zero
- Logic: Momentum turning bearish from overbought conditions
- Visual: Red "SELL" label above price action
⚠️ Extreme Warnings
- Extreme Overbought: Red triangle when oscillator crosses above +4.0
- Extreme Oversold: Green triangle when oscillator crosses below -4.0
- Purpose: Risk management alerts, not entry/exit signals
Oscillator Zones
Interpretation Guide
- Above +2.0: Strong bullish momentum zone (green background)
- 0 to +2.0: Mild bullish territory
- 0 to -2.0: Mild bearish territory
- Below -2.0: Strong bearish momentum zone (red background)
- Above +4.0: Extreme overbought (caution advised)
- Below -4.0: Extreme oversold (potential reversal zone)
Customization Options
Moving Average Settings
- EMA/SMA Toggle: Choose between exponential or simple moving average
- Color Customization: Adjust MA line color and width
Visual Controls
- Bullish/Bearish Colors: Customize momentum zone colors
- Signal Line: Toggle visibility and adjust color
- Line Widths: Control thickness of all plot lines
Anchor Modes
- NY Session Only: Anchors reset at NY market open (9:30 AM ET)
- 24H NY Day: Anchors reset at NY calendar day change (midnight ET)
Best Practices
Timeframe Selection
- Scalping: 1-5 minute charts for quick momentum changes
- Day Trading: 5-15 minute charts for clearer trend signals
- Swing Trading: 1-4 hour charts for major momentum shifts
Signal Confirmation
- Wait for crossovers: Don't trade on oscillator position alone
- Respect extreme levels: Exercise caution above +4 or below -4
- Use with price action: Combine with support/resistance levels
Risk Management
- Extreme zones: Reduce position size when oscillator is extended
- Failed signals: Exit quickly if momentum doesn't follow through
- Market context: Consider overall trend direction and market volatility
Technical Specifications
Calculation Components
- Base Length: 1,380 periods (futures) / 390 periods (stocks)
- Signal Line: Dynamic EMA covering one full trading day
- Smoothing: 3-period SMA on raw oscillator (adjustable)
- Update Frequency: Real-time on every price tick
Performance Notes
- Resource Efficient: Optimized calculations minimize CPU usage
- Memory Friendly: Uses incremental VWAP calculations
- Fast Loading: Minimal historical data requirements
Version History & Development
This oscillator evolved from advanced VWAP overlay strategies, transforming complex multi-line analysis into a single, actionable momentum gauge. The indicator maintains the sophistication of institutional VWAP analysis while providing the clarity needed for retail trading decisions.
Core Philosophy
Traditional VWAP indicators show where price is relative to volume-weighted averages, but they don't quantify momentum or provide clear entry/exit signals. This oscillator solves that problem by normalizing all VWAP relationships into a single, bounded indicator that works consistently across all timeframes and asset classes.
---
Open Source License: This indicator is provided free for the TradingView community. Feel free to modify and enhance according to your trading needs.
KD The ScalperWe have to take the trade when all three EMAs are pointing in the same direction (no criss-cross, no up/down, sideways). All 3 EMAs should be cleanly separated from each other with strong spacing between them; they are not tangled, sideways, or messy. This is our first filter before entering the trade. Are the EMAs stacked neatly, and is the price outside of the 25 EMA? If price pulls back and closes near or below the 25 or 50 EMA and breaks the 100 EMA, we don't trade. Use the 100 EMA as a safety net and refrain from trading if the price touches or falls below the 100 EMA.
1. Confirm the trend- All 3 EMAs must align, and they must spread
2. Watch price pull back to the 25th or the 50 EMA
3. Wait for the price to bounce - And re-approach the 25 EMA
Why is this powerful?
Removes 80% of the low-probability Trades
It keeps you out of choppy markets
Avoids Reversal Traps
Anchors us to momentum
We take the entry when the price moves up again and touches the 25 EMA from below, and then when it breaks above the 25 EMA, or even better, when a lovely green bullish candle forms. A bullish candle indicates good momentum. When a bullish candle closes in green, it means the momentum has increased significantly. This is when we enter a long trade, with the stop-loss just below the 50 EMA and the profit target being 1.5 times the stop-loss.
The same rule applies to the bearish trade.
AI Trading Alerts v6 — SL/TP + Confidence + Panel (Fixed)Overview
This Pine Script is designed to identify high-probability trading opportunities in Forex, commodities, and crypto markets. It combines EMA trend filters, RSI, and Stochastic RSI, with automatic stop-loss (SL) & take-profit (TP) suggestions, and provides a confidence panel to quickly assess the trade setup strength.
It also includes TradingView alert conditions so you can set up notifications for Long/Short setups and EMA crosses.
⚙️ Features
EMA Trend Filter
Uses EMA 50, 100, 200 for trend confirmation.
Bull trend = EMA50 > EMA100 > EMA200
Bear trend = EMA50 < EMA100 < EMA200
RSI Filter
Bullish trades require RSI > 50
Bearish trades require RSI < 50
Stochastic RSI Filter
Prevents entries during overbought/oversold extremes.
Bullish entry only if %K and %D < 80
Bearish entry only if %K and %D > 20
EMA Proximity Check
Price must be near EMA50 (within ATR × adjustable multiplier).
Signals
Continuation Signals:
Long if all bullish conditions align.
Short if all bearish conditions align.
Cross Events:
Long Cross when price crosses above EMA50 in bull trend.
Short Cross when price crosses below EMA50 in bear trend.
Automatic SL/TP Suggestions
SL size adjusts depending on asset:
Gold/Silver (XAU/XAG): 5 pts
Bitcoin/Ethereum: 100 pts
FX pairs (default): 20 pts
TP = SL × Risk:Reward ratio (default 1:2).
Confidence Score (0–4)
Based on conditions met (trend, RSI, Stoch, EMA proximity).
Labels:
Strongest (4/4)
Strong (3/4)
Medium (2/4)
Low (1/4)
Visual Panel on Chart
Shows ✅/❌ for each condition (trend, RSI, Stoch, EMA proximity, signal now).
Confidence row with color-coded strength.
Alerts
Long Setup
Short Setup
Long Cross
Short Cross
🖥️ How to Use
1. Add the Script
Open TradingView → Pine Editor.
Paste the full script.
Click Add to chart.
Save as "AI Trading Alerts v6 — SL/TP + Confidence + Panel".
2. Configure Inputs
EMA Lengths: Default 50/100/200 (works well for swing trading).
RSI Length: 14 (standard).
Stochastic Length/K/D: Default 14/3/3.
Risk:Reward Ratio: Default 2.0 (can change to 1.5, 3.0, etc.).
EMA Proximity Threshold: Default 0.20 × ATR (adjust to be stricter/looser).
3. Read the Panel
Top-right of chart, you’ll see ✅ or ❌ for:
Trend → Are EMAs aligned?
RSI → Above 50 (bull) or below 50 (bear)?
Stoch OK → Not extreme?
Near EMA50 → Close enough to EMA50?
Above/Below OK → Price position vs. EMA50 matches trend?
Signal Now → Entry triggered?
Confidence row:
🟢 Green = Strongest
🟩 Light green = Strong
🟧 Orange = Medium
🟨 Yellow = Low
⬜ Gray = None
4. Alerts Setup
Go to TradingView Alerts (⏰ icon).
Choose the script under “Condition”.
Select alert type:
Long Setup
Short Setup
Long Cross
Short Cross
Set notification method (popup, sound, email, mobile).
Click Create.
Now TradingView will notify you automatically when signals appear.
5. Example Workflow
Wait for Confidence = Strong/Strongest.
Check if market session supports volatility (e.g., XAU in London/NY).
Review SL/TP suggestions:
Long → Entry: current price, SL: close - risk_pts, TP: close + risk_pts × RR.
Short → Entry: current price, SL: close + risk_pts, TP: close - risk_pts × RR.
Adjust based on your own price action analysis.
📊 Best Practices
Use on H1 + D1 combo → align higher timeframe bias with intraday entries.
Risk only 1–2% of account per trade (position sizing required).
Filter with market sessions (Asia, Europe, US).
Strongest signals work best with trending pairs (e.g., XAUUSD, USDJPY, BTCUSD).
Anchored EMA/VWAP### Anchored EMA/VWAP Indicator
**Description:**
The **Anchored EMA/VWAP Indicator** is a powerful and versatile tool designed for traders seeking to analyze price trends and momentum from a user-defined anchor point in time. Built for TradingView using Pine Script v6, this indicator calculates and displays multiple **Exponential Moving Averages (EMAs)**, **Volume-Weighted Exponential Moving Averages (VWEMAs)**, and a **Volume-Weighted Average Price (VWAP)**, all anchored to a specific date and time chosen by the user. By anchoring these calculations, traders can focus on price action relative to significant market events, such as news releases, earnings reports, or key support/resistance levels.
The indicator supports multi-timeframe (MTF) analysis, allowing users to compute EMAs, VWEMAs, and VWAP on a higher or custom timeframe (e.g., 5-minute, 1-hour, daily) while overlaying the results on the current chart. It also includes customizable cross signals for EMA and VWEMA pairs, marked with distinct shapes (circles, diamonds, squares) to highlight potential trend changes or reversals. These features make the indicator ideal for trend-following, momentum trading, and identifying key price levels across various markets, including stocks, forex, cryptocurrencies, and commodities.
**Key Features:**
- **Anchored Calculations**: EMAs, VWEMAs, and VWAP start calculations from a user-specified anchor time, enabling analysis relative to significant market moments.
- **Multi-Timeframe Support**: Compute indicators on any timeframe (e.g., 60-minute, daily) and display them on the chart’s timeframe for flexible analysis.
- **Customizable EMAs and VWEMAs**: Four EMAs and four VWEMAs with adjustable lengths (default: 9, 21, 50, 100) and colors, with options to show or hide each.
- **Volume-Weighted Metrics**: VWAP and VWEMAs incorporate volume data, providing a more robust representation of market activity compared to standard EMAs.
- **Cross Signals**: Visual markers (circles, diamonds, squares) for crossovers between EMA and VWEMA pairs, with customizable visibility to highlight bullish (up) or bearish (down) signals.
- **User-Friendly Interface**: Organized input groups for General, EMA, VWEMA, VWAP, Arrow Settings, and Cross Visibility, with intuitive inline inputs for length and color customization.
- **Visual Clarity**: Overlaid on the price chart with distinct colors and line styles (dotted for EMAs, dashed for VWEMAs, solid for VWAP) to ensure easy interpretation.
**How to Use:**
1. **Set the Anchor Time**: Click a specific bar or enter a date/time (default: June 1, 2025) to start calculations from a significant market event.
2. **Select Timeframe**: Choose a timeframe (e.g., "5" for 5-minute, "D" for daily) to compute the indicators, allowing alignment with your trading strategy.
3. **Customize EMAs and VWEMAs**: Adjust lengths and colors for up to four EMAs and VWEMAs, and toggle their visibility to focus on relevant lines.
4. **Enable VWAP**: Display the anchored VWAP to identify volume-weighted price levels, useful as dynamic support/resistance.
5. **Monitor Cross Signals**: Enable cross visibility for specific EMA or VWEMA pairs to spot potential trend changes. Bullish crosses (e.g., shorter EMA crossing above longer EMA) are marked with green shapes below the bar, while bearish crosses are marked with red shapes above the bar.
6. **Interpret Signals**: Use EMA/VWEMA crossovers for trend confirmation, VWAP as a mean-reversion level, and volume-weighted VWEMAs for momentum analysis in high-volume markets.
**Use Cases:**
- **Trend Trading**: Identify trend direction using EMA and VWEMA crossovers, with shorter lengths (e.g., 9, 21) for faster signals and longer lengths (e.g., 50, 100) for trend confirmation.
- **Mean Reversion**: Use the anchored VWAP as a dynamic support/resistance level to trade pullbacks or breakouts.
- **Event-Based Analysis**: Anchor the indicator to significant events (e.g., earnings, economic data releases) to analyze price behavior post-event.
- **Multi-Timeframe Strategies**: Combine higher timeframe EMAs/VWAPs with lower timeframe price action for high-probability setups.
**Settings:**
- **Anchor Time**: Set the starting point for calculations (default: June 1, 2025).
- **Timeframe**: Choose the timeframe for calculations (default: 5-minute).
- **EMA/VWEMA Lengths**: Default lengths of 9, 21, 50, and 100 for both EMAs and VWEMAs, adjustable per user preference.
- **Colors**: Customizable colors with slight transparency for visual clarity.
- **Cross Visibility**: Toggle specific EMA and VWEMA cross signals (e.g., EMA1/EMA2, VWEMA1/VWEMA3) to reduce chart clutter.
- **Arrow Colors**: Green for bullish crosses, red for bearish crosses.
**Notes:**
- The indicator is overlaid on the price chart, ensuring seamless integration with price action analysis.
- VWEMAs and VWAP are volume-sensitive, making them particularly effective in markets with significant volume fluctuations.
- Ensure the anchor time is set to a valid historical or future bar to avoid calculation errors.
- Cross signals are conditional on non-NA values to prevent false positives during initialization.
**Author**: NEPOLIX
**Version**: 6 (Pine Script v6)
**Published**: For TradingView Community
This indicator is a must-have for traders looking to combine anchored, volume-weighted, and multi-timeframe analysis into a single, customizable tool. Whether you're a day trader, swing trader, or long-term investor, the Anchored EMA/VWAP Indicator provides actionable insights for informed trading decisions.
Crypto Market Dominance Stacked with LabelsA professional stacked area chart showing the dominance of major crypto market segments: BTC, ETH, Top 100 Altcoins, and #101+ Altcoins. Each layer is color-coded for clarity and includes dynamic labels with the current dominance percentage. Provides a clear visual representation of market share trends for traders, analysts, and crypto enthusiasts.
Features:
Stacked visualization of BTC, ETH, Top 100, and small-cap altcoins (#101+).
Color-coded areas for easy identification.
Dynamic labels showing each category’s current dominance percentage.
Horizontal reference lines for percentage levels.
Approximates top 100 and #101+ altcoins using TOTAL2 and TOTAL3 market cap tickers.
Use Case:
Track how market share shifts between BTC, ETH, large altcoins, and smaller altcoins over time. Ideal for analyzing trends, spotting dominance changes, and visualizing overall crypto market structure.